code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
#include "Node.h" #include "Production.h" Node::Node(std::string prod) { production = Production(prod); } Node::Node(Token t) { production = Production(t.getKindString() + ' ' + t.getLexeme()); } Node::~Node() { for (Node* n : children) { delete n; } } void Node::AddChild(Node* n) { children.push_front(n); } Production Node::getProduction() const { return production; } std::deque Node::getChildren() const { return children; } std::ostream& operator<< (std::ostream &strm, const Node &a) { strm << a.production << std::endl; for (Node* n : a.children) { strm << *n; } return strm; }
c++
11
0.595455
69
17.333333
36
starcoderdata
import { version } from 'process' import colorsOption from 'colors-option' import filterObj from 'filter-obj' import { validate } from 'jest-validate' import semver from 'semver' import { validateExitOn } from '../exit.js' import { applyDefaultLevels, getExampleLevels, validateLevels, } from '../level.js' import { defaultLog } from '../log.js' import { applyTesting, getExampleTesting } from './testing.js' // Validate options and assign default options export const getOptions = function ({ opts = {} }) { const optsA = filterObj(opts, isDefined) validate(optsA, { exampleConfig: EXAMPLE_OPTS }) validateOptions(optsA) const optsB = applyTesting({ opts: optsA }) const level = applyDefaultLevels({ opts: optsB }) const { colors, ...optsC } = { ...DEFAULT_OPTS, ...optsB, level } const chalk = colorsOption({ colors }) return { ...optsC, chalk } } const isDefined = function (key, value) { return value !== undefined } // Since Node 15.0.0, `unhandledRejection` makes the process exit too // TODO: remove after dropping support for Node <15.0.0 const getDefaultExitOn = function () { if (isNewExitBehavior()) { return ['uncaughtException', 'unhandledRejection'] } return ['uncaughtException'] } const isNewExitBehavior = function () { return semver.gte(version, NEW_EXIT_MIN_VERSION) } const NEW_EXIT_MIN_VERSION = '15.0.0' const DEFAULT_OPTS = { log: defaultLog, exitOn: getDefaultExitOn(), } // `validate-jest` prints the function body // eslint-disable-next-line no-empty-function const exampleFunction = function () {} const EXAMPLE_OPTS = { ...DEFAULT_OPTS, colors: true, log: exampleFunction, level: getExampleLevels(), testing: getExampleTesting(), } // Validation beyond what `jest-validate` can do const validateOptions = function ({ exitOn, level = {} }) { validateLevels({ level }) validateExitOn({ exitOn }) }
javascript
12
0.70169
69
24.594595
74
starcoderdata
package gcp import ( "github.com/pkg/errors" compute "google.golang.org/api/compute/v1" "google.golang.org/api/googleapi" ) func (o *ClusterUninstaller) listNetworks() ([]cloudResource, error) { return o.listNetworksWithFilter("items(name,selfLink),nextPageToken", o.clusterIDFilter(), nil) } // listNetworksWithFilter lists addresses in the project that satisfy the filter criteria. // The fields parameter specifies which fields should be returned in the result, the filter string contains // a filter string passed to the API to filter results. The filterFunc is a client-side filtering function // that determines whether a particular result should be returned or not. func (o *ClusterUninstaller) listNetworksWithFilter(fields string, filter string, filterFunc func(*compute.Network) bool) ([]cloudResource, error) { o.Logger.Debugf("Listing networks") ctx, cancel := o.contextWithTimeout() defer cancel() result := []cloudResource{} req := o.computeSvc.Networks.List(o.ProjectID).Fields(googleapi.Field(fields)) if len(filter) > 0 { req = req.Filter(filter) } err := req.Pages(ctx, func(list *compute.NetworkList) error { for _, item := range list.Items { if filterFunc == nil || filterFunc != nil && filterFunc(item) { o.Logger.Debugf("Found network: %s", item.Name) result = append(result, cloudResource{ key: item.Name, name: item.Name, typeName: "network", url: item.SelfLink, }) } } return nil }) if err != nil { return nil, errors.Wrapf(err, "failed to list networks") } return result, nil } func (o *ClusterUninstaller) deleteNetwork(item cloudResource) error { o.Logger.Debugf("Deleting network %s", item.name) ctx, cancel := o.contextWithTimeout() defer cancel() op, err := o.computeSvc.Networks.Delete(o.ProjectID, item.name).RequestId(o.requestID(item.typeName, item.name)).Context(ctx).Do() if err != nil && !isNoOp(err) { o.resetRequestID(item.typeName, item.name) return errors.Wrapf(err, "failed to delete network %s", item.name) } if op != nil && op.Status == "DONE" && isErrorStatus(op.HttpErrorStatusCode) { o.resetRequestID(item.typeName, item.name) return errors.Errorf("failed to delete network %s with error: %s", item.name, operationErrorMessage(op)) } if (err != nil && isNoOp(err)) || (op != nil && op.Status == "DONE") { o.resetRequestID(item.typeName, item.name) o.deletePendingItems(item.typeName, []cloudResource{item}) o.Logger.Infof("Deleted network %s", item.name) } return nil } // destroyNetworks removes all vpc network resources prefixed // with the cluster's infra ID, and deletes all of the routes. func (o *ClusterUninstaller) destroyNetworks() error { found, err := o.listNetworks() if err != nil { return err } items := o.insertPendingItems("network", found) errs := []error{} for _, item := range items { foundRoutes, err := o.listNetworkRoutes(item.url) if err != nil { errs = append(errs, err) continue } routes := o.insertPendingItems("route", foundRoutes) for _, route := range routes { err := o.deleteRoute(route) if err != nil { o.Logger.Debugf("Failed to delete route %s: %v", route.name, err) } } err = o.deleteNetwork(item) if err != nil { errs = append(errs, err) } } items = o.getPendingItems("network") return aggregateError(errs, len(items)) }
go
22
0.698225
148
33.489796
98
starcoderdata
def test_calendars(self): # generate test DataArray time_std = date_range("1991-07-01", "1993-06-30", freq="D", calendar="standard") time_365 = date_range("1991-07-01", "1993-06-30", freq="D", calendar="noleap") data_std = xr.DataArray( np.ones((time_std.size, 4)), dims=("time", "lon"), coords={"time": time_std, "lon": [-72, -71, -70, -69]}, ) # generate test start and end dates start_v = [[200, 200, np.nan, np.nan], [200, 200, 60, 60]] end_v = [[200, np.nan, 60, np.nan], [360, 60, 360, 80]] start_std = xr.DataArray( start_v, dims=("time", "lon"), coords={"time": [time_std[0], time_std[366]], "lon": data_std.lon}, attrs={"calendar": "standard", "is_dayofyear": 1}, ) end_std = xr.DataArray( end_v, dims=("time", "lon"), coords={"time": [time_std[0], time_std[366]], "lon": data_std.lon}, attrs={"calendar": "standard", "is_dayofyear": 1}, ) end_noleap = xr.DataArray( end_v, dims=("time", "lon"), coords={"time": [time_365[0], time_365[365]], "lon": data_std.lon}, attrs={"calendar": "noleap", "is_dayofyear": 1}, ) out = generic.aggregate_between_dates( data_std, start_std, end_std, op="sum", freq="AS-JUL" ) # expected output s = xc.core.calendar.doy_to_days_since(start_std) e = xc.core.calendar.doy_to_days_since(end_std) expected = e - s expected = xr.where(((s > e) | (s.isnull()) | (e.isnull())), np.nan, expected) np.testing.assert_allclose(out, expected) # check calendar convertion out_noleap = generic.aggregate_between_dates( data_std, start_std, end_noleap, op="sum", freq="AS-JUL" ) np.testing.assert_allclose(out, out_noleap)
python
13
0.51093
88
38.36
50
inline
<?php /** * Ends a sequence of * * @phpstub * * @param resource $stmt * @param int $param_nr * * @return bool */ function maxdb_stmt_close_long_data($stmt, $param_nr) { } /** * Ends a sequence of * * @phpstub * * @return bool */ function maxdb_stmt_close_long_data() { } /** * Ends a sequence of * * @phpstub-alias-of maxdb_stmt_close_long_data * @phpstub * * @param resource $stmt * @param int $param_nr * * @return bool */ function maxdb_close_long_data($stmt, $param_nr) { } /** * Ends a sequence of * * @phpstub-alias-of maxdb_stmt_close_long_data * @phpstub * * @return bool */ function maxdb_close_long_data() { }
php
5
0.622449
53
11.722222
54
starcoderdata
# coding: utf-8 import os from elasticsearch import Elasticsearch from elasticsearch_dsl.connections import connections from elasticsearch_dsl import Index, Search import utils from models import LogType, Log from connections import CustomUrllib3HttpConnection class Elasticlog(object): _instance = None def __init__(self, **kwargs): self.hosts = kwargs.get('hosts', 'localhost') self.client = Elasticsearch(self.hosts) timeout = kwargs.get('timeout', 10) os.environ['LOGGO_REQUEST_TIMEOUT'] = str(timeout) max_retries = kwargs.get('max_retries', 2) connections.create_connection(hosts=self.hosts, connection_class=CustomUrllib3HttpConnection, max_retries=max_retries) index_name = kwargs.get('index', None) self.create_index_if_not_exists(index_name) def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Elasticlog, cls).__new__(cls, *args, **kwargs) return cls._instance def create_index_if_not_exists(self, index_name): self.index = index_name idx = Index(index_name) idx.settings(number_of_shards=1, number_of_replicas=1) idx.doc_type(LogType) try: idx.create() except: pass def insert(self, **kwargs): created_at = utils.fix_date(kwargs.get('created_at')) log_type = LogType( filename = kwargs.get('filename'), level = kwargs.get('level'), message = kwargs.get('message'), created_at = created_at ) return log_type.save() def search(self, **params): index = params.get('index', self.index) search = Search(using=self.client, index=index) page = params.get('page', None) per_page = params.get('per_page', None) if page and per_page: page = page - 1 search._extra = {'from': page, 'size': per_page} sort = params.get('sort', None) if sort and sort.replace('-', '') in ['created_at', 'level']: search = search.sort(sort) date_filter = self._filter_by_date_interval(params) if date_filter: search = search.filter(date_filter) level = params.get('group_by', None) if level: search = search.query('match', level=level) hits = search.execute() format = params.get('format', 'object') if format == 'dict': return self._to_dict(hits) else: return self._to_logs(hits) def count(self): response = self.client.count(index=self.index) return response def _to_logs(self, hits): logs = [] for hit in hits: log = Log() log.id = hit.meta.id log.filename = hit.filename log.level = hit.level log.message = hit.message log.created_at = utils.to_datetime(hit.created_at, '%Y-%m-%d') logs.append(log) return logs def _to_dict(self, hits): results = [] for hit in hits: d = { 'id': hit.meta.id, 'filename': hit.filename, 'level': hit.level, 'message': hit.message, 'created_at': hit.created_at } results.append(d) return results def _filter_by_date_interval(self, params): start_date = params.get('start', None) end_date = params.get('end', None) #str(utils.today())) if start_date: d1 = utils.to_datetime(start_date) d2 = utils.to_datetime(end_date) if d1 and d2: return {'range': { 'created_at': { 'gte': str(d1).replace(' ', 'T'), 'lte': str(d2).replace(' ', 'T') } }} return None
python
20
0.550926
126
30.354839
124
starcoderdata
package org.yqj.net.nio; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Description: * * @author yaoqijun * @date 2021/5/24 * Email: */ public class NioThreadPoolFactory { public static ExecutorService buildTheadPool(String name) { ThreadFactory threadFactory = new ThreadFactory() { private final AtomicInteger threadNum = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setName(String.format("%s_%d", name, threadNum.getAndIncrement())); return thread; } }; return new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue threadFactory); } }
java
18
0.69633
127
34.16129
31
starcoderdata
/* * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */ package de.hybris.platform.sap.sapcpiorderexchange.actions; import de.hybris.platform.core.enums.ExportStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.orderprocessing.model.OrderProcessModel; import de.hybris.platform.sap.orderexchange.actions.SapSendOrderToDataHubAction; import de.hybris.platform.sap.orderexchange.constants.SapOrderExchangeActionConstants; import de.hybris.platform.sap.sapcpiadapter.service.SapCpiOutboundService; import de.hybris.platform.sap.sapcpiorderexchange.service.SapCpiOrderOutboundConversionService; import de.hybris.platform.task.RetryLaterException; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Required; import static de.hybris.platform.sap.sapcpiadapter.service.SapCpiOutboundService.*; public class SapCpiOmmOrderOutboundAction extends SapSendOrderToDataHubAction { private static final Logger LOG = Logger.getLogger(SapCpiOmmOrderOutboundAction.class); private SapCpiOutboundService sapCpiOutboundService; private SapCpiOrderOutboundConversionService sapCpiOrderOutboundConversionService; @Override public void executeAction(OrderProcessModel process) throws RetryLaterException { final OrderModel order = process.getOrder(); getSapCpiOutboundService().sendOrder(getSapCpiOrderOutboundConversionService().convertOrderToSapCpiOrder(order)).subscribe( // onNext responseEntityMap -> { if (isSentSuccessfully(responseEntityMap)) { setOrderStatus(order, ExportStatus.EXPORTED); resetEndMessage(process); LOG.info(String.format("The OMM order [%s] has been successfully sent to the SAP backend through SCPI! %n%s", order.getCode(), getPropertyValue(responseEntityMap, RESPONSE_MESSAGE))); } else { setOrderStatus(order, ExportStatus.NOTEXPORTED); LOG.error(String.format("The OMM order [%s] has not been sent to the SAP backend! %n%s", order.getCode(), getPropertyValue(responseEntityMap, RESPONSE_MESSAGE))); } final String eventName = new StringBuilder().append(SapOrderExchangeActionConstants.ERP_ORDER_SEND_COMPLETION_EVENT).append(order.getCode()).toString(); getBusinessProcessService().triggerEvent(eventName); } // onError , error -> { setOrderStatus(order, ExportStatus.NOTEXPORTED); LOG.error(String.format("The OMM order [%s] has not been sent to the SAP backend through SCPI! %n%s", order.getCode(), error.getMessage()), error); final String eventName = new StringBuilder().append(SapOrderExchangeActionConstants.ERP_ORDER_SEND_COMPLETION_EVENT).append(order.getCode()).toString(); getBusinessProcessService().triggerEvent(eventName); } ); } protected SapCpiOutboundService getSapCpiOutboundService() { return sapCpiOutboundService; } @Required public void setSapCpiOutboundService(SapCpiOutboundService sapCpiOutboundService) { this.sapCpiOutboundService = sapCpiOutboundService; } protected SapCpiOrderOutboundConversionService getSapCpiOrderOutboundConversionService() { return sapCpiOrderOutboundConversionService; } @Required public void setSapCpiOrderOutboundConversionService(SapCpiOrderOutboundConversionService sapCpiOrderOutboundConversionService) { this.sapCpiOrderOutboundConversionService = sapCpiOrderOutboundConversionService; } }
java
19
0.752019
168
41.186813
91
starcoderdata
/* * Copyright (C) 2018 - present by Dice Technology Ltd. * * Please see distribution for license. */ package technology.dice.dicefairlink.discovery.members; import java.util.Objects; import java.util.Set; public final class ClusterInfo { private final String readonlyEndpoint; private final Set replicas; public ClusterInfo(String readonlyEndpoint, Set replicas) { if ("".equals(readonlyEndpoint) || readonlyEndpoint == null) { throw new IllegalArgumentException("Read only endpoint must not be null"); } if (replicas == null) { throw new IllegalArgumentException("Set of replicas must not be mull"); } this.readonlyEndpoint = readonlyEndpoint; this.replicas = replicas; } public String getReadonlyEndpoint() { return readonlyEndpoint; } public Set getReplicas() { return replicas; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ClusterInfo)) { return false; } ClusterInfo that = (ClusterInfo) o; return Objects.equals(getReadonlyEndpoint(), that.getReadonlyEndpoint()) && Objects.equals(getReplicas(), that.getReplicas()); } @Override public int hashCode() { return Objects.hash(getReadonlyEndpoint(), getReplicas()); } }
java
11
0.69958
98
26.461538
52
starcoderdata
public TextView getTextView2() { TableRow.LayoutParams params1=new TableRow.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); TextView txt2 = new TextView(App.getInstance().getApplicationContext()); //setting the text txt2.setLayoutParams(params1); txt2.setSingleLine(false); txt2.setTextColor(Color.parseColor("#000000")); txt2.setBackgroundColor(Color.parseColor("#F1F1F1")); txt2.setTextSize(16); return txt2; }
java
10
0.644366
142
50.727273
11
inline
(function () { let width = 900, height = 500; let svg = d3.select("#dotplot") .append("svg") .attr("width", width) .attr("height", height); let text = svg.append("text") .attr("font-size","15px") d3.json("./charts/page5/data.json").then(res => { let data = res.data; let x = d3.scaleLinear() .domain([40, 150]) .range([150, 700]); let y = d3.scaleLinear() .domain([0, 1]) .range([0, 400]) svg.append("g") .attr("transform", "translate(0,400)") .call(d3.axisBottom(x)); svg.append("g") .attr("transform", "translate(150,0)") .call(d3.axisLeft(y).ticks(0)); svg.append("circle") .attr("cx", 650) .attr("cy", 40) .attr("r", 8) .style("fill", "blue"); svg.append("circle") .attr("cx", 650) .attr("cy", 65) .attr("r", 8) .style("fill", "red"); svg.append("text") .attr("x", 670) .attr("y", 40) .text("Before Vaccination (Feb 2021)") .style("font-size", "15px") .attr("alignment-baseline", "middle"); svg.append("text") .attr("x", 670) .attr("y", 65) .text("After Vaccination (Oct 2021)") .style("font-size", "15px") .attr("alignment-baseline", "middle"); let gs = svg.selectAll(".dot") .data(data) .enter() .append("g"); gs.append("line") .attr("x1", d => x(d.value[0])) .attr("x2", d => x(d.value[1])) .attr("y1", (_, i) => i * 50 + 50) .attr("y2", (_, i) => i * 50 + 50) .attr("stroke", "black"); gs.append("circle") .attr("cx", d => x(d.value[0])) .attr("cy", (_, i) => i * 50 + 50) .attr("r", 6) .attr("fill", "red") .style("cursor","pointer") .on("mouseover",function(e,d){ d3.select(this) .attr("r",8); text.text(`after vaccine:${d.value[0]}`) .attr("x",e.layerX) .attr("y",e.layerY-10); }) .on("mouseleave",function(){ d3.select(this) .attr("r",6); text.text('') }); gs.append("circle") .attr("cx", d => x(d.value[1])) .attr("cy", (_, i) => i * 50 + 50) .attr("r", 6) .attr("fill", "blue") .style("cursor","pointer") .on("mouseover",function(e,d){ d3.select(this) .attr("r",8); text.text(`before vaccine ${d.value[1]}`) .attr("x",e.layerX) .attr("y",e.layerY-10); }) .on("mouseleave",function(){ d3.select(this) .attr("r",6); text.text('') }); gs.append("text") .text(d => d.id) .attr("x", 0) .attr("y", (_, i) => i * 50 + 55); }) })()
javascript
29
0.380911
84
31.823529
102
starcoderdata
//MIT, 2015-2017, ParserApprentice using Parser.CodeDom; namespace Parser.AsmInfrastructures { public class ParserReportMsg : BuildMessage { readonly ICodeParseNode token; CompilationUnit cu; int lineNum; int columnNum; public ParserReportMsg(CompilationUnit cu, CodeErrorDescription errDescription, ICodeParseNode token, int lineNum, int columnNum) : base(errDescription) { this.token = token; this.cu = cu; this.lineNum = lineNum; this.columnNum = columnNum; } public ParserReportMsg(CompilationUnit cu, CodeErrorDescription errDescription, ICodeParseNode token, int lineNum, int columnNum, string additionalInfo) : base(errDescription, additionalInfo) { this.token = token; this.cu = cu; this.lineNum = lineNum; this.columnNum = columnNum; } public override string FileName { get { return cu.Filename; } } public override int ColumnNumber { get { return columnNum; } } public override int LineNumber { get { return lineNum; } } } public class SemanticReportMessage : BuildMessage { readonly CodeObject codeObject; CompilationUnit cu; CodeTypeReference typeref; ICodeParseNode codeSyntaxNode; public SemanticReportMessage(CompilationUnit cu, CodeErrorDescription errDescription, CodeObject codeObject) : base(errDescription) { this.codeObject = codeObject; this.cu = cu; } public SemanticReportMessage(CompilationUnit cu, CodeErrorDescription errDescription, CodeTypeReference typeref) : base(errDescription) { this.typeref = typeref; this.cu = cu; } public SemanticReportMessage(CompilationUnit cu, CodeErrorDescription errDescription, ICodeParseNode codeSyntaxNode) : base(errDescription) { this.codeSyntaxNode = codeSyntaxNode; this.cu = cu; } public override string FileName { get { if (codeObject != null) { if (!codeObject.SourceLocation.IsEmpty) { return cu.Filename; } else { return string.Empty; } } else { return string.Empty; } } } public override int ColumnNumber { get { if (codeObject != null) { if (!codeObject.SourceLocation.IsEmpty) { return codeObject.SourceLocation.BeginColumnNumber; } else { return 0; } } else { return 0; } } } public override int LineNumber { get { if (codeObject != null) { return codeObject.SourceLocation.BeginLineNumber; } else { return 0; } } } } public class ProjectSourceReportMessage : BuildMessage { public ProjectSourceReportMessage(CodeErrorDescription errDescription) : base(errDescription, null) { } public override int ColumnNumber { get { return 0; } } public override string FileName { get { return ""; } } public override int LineNumber { get { return 0; } } } public class CodeDomTransformMessage : BuildMessage { readonly CodeObject codeObject; CompilationUnit cu; public CodeDomTransformMessage(CompilationUnit cu, CodeErrorDescription errDescription, CodeObject codeObject) : base(errDescription) { this.codeObject = codeObject; this.cu = cu; } public override int ColumnNumber { get { return 0; } } public override string FileName { get { return cu.Filename; } } public override int LineNumber { get { return 0; } } } }
c#
16
0.485691
124
26.878613
173
starcoderdata
#include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<int(n);++i) #define INF 1e14 typedef complex<double> Point; typedef vector<Point> VP; #define X real() #define Y imag() const double EPS = 1e-8; const double PI = acos(-1); double dot(Point a, Point b) { return a.X*b.X + a.Y*b.Y; } double cross(Point a, Point b) { return a.X*b.Y - a.Y*b.X; } int ccw(Point a, Point b, Point c) { b -= a; c -= a; if (cross(b,c) > EPS) return +1; // counter clockwise if (cross(b,c) < -EPS) return -1; // clockwise if (dot(b,c) < -EPS) return +2; // c--a--b on line if (norm(b) < norm(c)) return -2; // a--b--c on line or a==b return 0; // a--c--b on line or a==c or b==c } bool isecSP(Point a1, Point a2, Point b) { return !ccw(a1, a2, b); } bool isecSS(Point a1, Point a2, Point b1, Point b2) { return ccw(a1, a2, b1)*ccw(a1, a2, b2) <= 0 && ccw(b1, b2, a1)*ccw(b1, b2, a2) <= 0; } Point proj(Point a1, Point a2, Point p) { return a1 + dot(a2-a1, p-a1)/norm(a2-a1) * (a2-a1); } double distSP(Point a1, Point a2, Point p) { Point r = proj(a1, a2, p); if (isecSP(a1, a2, r)) return abs(r-p); return min(abs(a1-p), abs(a2-p)); } double distSS(Point a1, Point a2, Point b1, Point b2) { if (isecSS(a1, a2, b1, b2)) return 0; return min({ distSP(a1, a2, b1), distSP(a1, a2, b2), distSP(b1, b2, a1), distSP(b1, b2, a2)}); } bool inPolygon(Point p,VP& ps){ int n = ps.size(); double sumAngle=0; rep(i,n){ double t = arg(ps[(i+1)%n]-p)-arg(ps[i]-p); while(t > +PI) t-=2*PI; while(t < -PI) t+=2*PI; sumAngle += t; } return (abs(sumAngle) > 0.1); } int main(void){ int n; while(cin>>n, n){ double sx,sy,ex,ey; cin>>sx>>sy>>ex>>ey; Point s(sx,sy); Point e(ex,ey); vector<double> d(n,INF), h(n); bool ng = false; rep(i,n){ double x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2>>h[i]; VP p = {{x1,y1},{x2,y1},{x2,y2},{x1,y2}}; if(inPolygon(s,p) || inPolygon(e,p)){ ng = true; } rep(j,4){ d[i] = min(d[i],distSS(s,e,p[j],p[(j+1)%4])); } } if(ng){ cout<<"0.0000"<<endl; continue; } double l = 0, r = 1000; rep(loop,100){ double R = (l+r)/2; bool ok = true; rep(i,n){ if(sqrt(pow(max(R-h[i],0.0),2) + pow(d[i],2)) < R){ ok = false; } } if(ok) l = R; else r = R; } printf("%.4f\n",l); } return 0; }
c++
21
0.462369
73
24.018018
111
codenet
import React from 'react' import { Dimmer, Loader, Image, Segment } from 'semantic-ui-react' const LoaderModule = ({active, text}) => ( <Loader active>{text} ) export default LoaderModule
javascript
6
0.668067
66
20.727273
11
starcoderdata
@Fuzz public void testWithInputStream(InputStream in) { try { // Create a JPEGTranscoder and set its quality hint.t JPEGTranscoder t = new JPEGTranscoder(); t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8)); // Set the transcoder input and output. TranscoderInput input = new TranscoderInput(in); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); TranscoderOutput output = new TranscoderOutput(ostream); // Perform the transcoding. t.transcode(input, output); ostream.flush(); ostream.close(); } catch(IOException e) { Assume.assumeNoException(e); } catch(TranscoderException e) { Assume.assumeNoException(e); } }
java
10
0.568672
80
39.090909
22
inline
public static void writeProperties(Properties props, DataOutput out) throws IOException { InternalDataSerializer.checkOut(out); Set<Map.Entry<Object,Object>> s; int size; if (props == null) { s = null; size = -1; } else { s = props.entrySet(); size = s.size(); } InternalDataSerializer.writeArrayLength(size, out); if (DEBUG) { InternalDataSerializer.logger.info( LocalizedStrings.DEBUG, "Writing Properties with " + size + " elements: " + props); } if (size > 0) { for (Map.Entry<Object,Object> entry: s) { // although we should have just String instances in a Properties // object our security code stores byte[] instances in them // so the following code must use writeObject instead of writeString. Object key = entry.getKey(); Object val = entry.getValue(); writeObject(key, out); writeObject(val, out); } } }
java
12
0.618653
125
32.310345
29
inline
func tagsMapEqual(expectMap map[string]interface{}, compareMap map[string]string) bool { if len(expectMap) != len(compareMap) { return false } else { for key, eVal := range expectMap { if eStr, ok := eVal.(string); !ok { // type is mismatch. return false } else { if cStr, ok := compareMap[key]; ok { if eStr != cStr { return false } } else { return false } } } } return true }
go
15
0.585812
88
19.857143
21
inline
n=int(input()) ans=set() if n%2==0: i=1 while i<n+1-i: x,y=i,n+1-i for j in range(1,n+1): if j!=x and j!=y: if (j,x) not in ans: ans.add((x,j)) if (j,y) not in ans: ans.add((y,j)) i+=1 else: i=1 while i<n-i: x,y=i,n-i for j in range(1,n+1): if j!=x and j!=y: if (j,x) not in ans: ans.add((x,j)) if (j,y) not in ans: ans.add((y,j)) i+=1 for j in range(1,n): if (j,n) not in ans: ans.add((n,j)) print(len(ans)) for i,j in ans: print(i,j)
python
16
0.354885
36
22.2
30
codenet
using DnsZone.Records; namespace DnsZone.Formatter { public class ResourceRecordWriter : IResourceRecordVisitor<DnsZoneFormatterContext, ResourceRecord> { public ResourceRecord Visit(AResourceRecord record, DnsZoneFormatterContext context) { context.WriteIpAddress(record.Address); return record; } public ResourceRecord Visit(AaaaResourceRecord record, DnsZoneFormatterContext context) { context.WriteIpAddress(record.Address); return record; } public ResourceRecord Visit(CNameResourceRecord record, DnsZoneFormatterContext context) { context.WriteAndCompressDomainName(record.CanonicalName); return record; } public ResourceRecord Visit(MxResourceRecord record, DnsZoneFormatterContext context) { context.WritePreference(record.Preference); context.WriteAndCompressDomainName(record.Exchange); return record; } public ResourceRecord Visit(CAAResourceRecord record, DnsZoneFormatterContext context) { context.WritePreference(record.Flag); context.WriteTag(record.Tag); context.WriteString(record.Value); return record; } public ResourceRecord Visit(TLSAResourceRecord record, DnsZoneFormatterContext context) { context.WritePreference(record.CertificateUsage); context.WritePreference(record.Selector); context.WritePreference(record.MatchingType); context.WriteTag(record.CertificateAssociationData); return record; } public ResourceRecord Visit(SSHFPResourceRecord record, DnsZoneFormatterContext context) { context.WritePreference(record.AlgorithmNumber); context.WritePreference(record.FingerprintType); context.WriteTag(record.Fingerprint); return record; } public ResourceRecord Visit(NsResourceRecord record, DnsZoneFormatterContext context) { context.WriteAndCompressDomainName(record.NameServer); return record; } public ResourceRecord Visit(PtrResourceRecord record, DnsZoneFormatterContext context) { context.WriteAndCompressDomainName(record.HostName); return record; } public ResourceRecord Visit(SoaResourceRecord record, DnsZoneFormatterContext context) { context.WriteAndCompressDomainName(record.NameServer); context.WriteEmail(record.ResponsibleEmail); context.WriteSerialNumber(record.SerialNumber); context.WriteTimeSpan(record.Refresh); context.WriteTimeSpan(record.Retry); context.WriteTimeSpan(record.Expiry); context.WriteTimeSpan(record.Minimum); return record; } public ResourceRecord Visit(SrvResourceRecord record, DnsZoneFormatterContext context) { context.WritePreference(record.Priority); context.WritePreference(record.Weight); context.WritePreference(record.Port); context.WriteAndCompressDomainName(record.Target); return record; } public ResourceRecord Visit(TxtResourceRecord record, DnsZoneFormatterContext context) { context.WriteString(record.Content); return record; } } }
c#
12
0.682211
105
39.870588
85
starcoderdata
public override void ConfigureContainer(ContainerBuilder builder) { // Register test event bus builder.RegisterType<TestEventBus>() .AsImplementedInterfaces().SingleInstance(); base.ConfigureContainer(builder); // Register events api configuration interface builder.RegisterType<EventsConfig>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterInstance(new AadApiClientConfig(null)) .AsImplementedInterfaces().SingleInstance(); // ... as well as signalR client (needed for api) builder.RegisterType<SignalRHubClient>() .AsImplementedInterfaces().InstancePerLifetimeScope(); // Register client events builder.RegisterType<RegistryServiceEvents>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterType<PublisherServiceEvents>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterType<TestAuthConfig>() .AsImplementedInterfaces(); }
c#
15
0.630185
70
41
27
inline
package at.xirado.interact.io; import at.xirado.interact.Interact; import at.xirado.interact.event.events.ReadyEvent; import at.xirado.interact.io.routes.InteractionRoute; import static spark.Spark.*; public class WebServer { private final Interact interact; private final String host; private final int port; public WebServer(Interact interact, String host, int port) { this.interact = interact; this.host = host; this.port = port; } public void start() { ipAddress(host); port(port); post("/interaction", new InteractionRoute(interact)); } }
java
8
0.680945
62
22.344828
29
starcoderdata
package com.offer; import java.util.ArrayList; import java.util.List; public class GetLastCommonNode { public static TreeNode getCommonNode(TreeNode root,TreeNode node1,TreeNode node2){ if(root==null||node1==null||node2==null) throw new IllegalArgumentException(); List list1=new ArrayList List list2=new ArrayList<>(); TreeNode last=null; if(findPath(root, node1, list1)&&findPath(root, node2, list2)){ int i=0; while(i<list1.size()&&i<list2.size()){ if(list1.get(i)==list2.get(i)) last=list1.get(i); i++; } } return last; } private static boolean findPath(TreeNode root,TreeNode node,List list){ if(root==node) return true; list.add(root); boolean left=false,right=false,found=false; if(root.left!=null) left=findPath(root.left, node, list); if(root.right!=null) right=findPath(root.right, node, list); found=left||right; if(!found) list.remove(list.size()-1); return found; } public static void main(String[] args) { TreeNode[] nodes=new TreeNode[6]; for(int i=0;i<6;i++) nodes[i]=new TreeNode(i); nodes[0].left=nodes[1]; nodes[0].right=nodes[4]; nodes[1].left=nodes[2]; nodes[1].right=nodes[3]; nodes[2].left=nodes[5]; System.out.println(getCommonNode(nodes[0], nodes[3], nodes[5])); } }
java
12
0.682699
83
26.313725
51
starcoderdata
def _init_params_model(): params_model = Bunch() # image and class parameters params_model.img_rows = 128 params_model.img_cols = 128 params_model.img_channels = 1 # ARCHITECTURE PARAMS # they depend exclusively on your model # the names can be changed since they will only be called by your model params_model.output_channels = 3 params_model.depth = 6 params_model.init_filt_size = 64 params_model.dropout_rate = 0.3 # LOSS # this is basically the metric for optimizing your model # this needs to be selected in accordance to the task you want to achieve params_model.keras_loss = 'binary_crossentropy' # params_model.keras_loss = 'mse' # OPTIMIZER PARAMS # these values are good starting point # you should not change them during the first runs. params_model.lr = 1e-4 params_model.beta_1 = 0.9 params_model.beta_2 = 0.999 params_model.epsilon = 1e-08 params_model.decay = 5e-05 params_model.valid_ratio = 0.2 # callbacks parameters # params_model.early_stopping = True params_model.early_stopping = False params_model.es_patience = 12 params_model.es_min_delta = 0.001 params_model.reduce_learning_rate = True params_model.lr_patience = 5 params_model.lr_factor = 0.5 params_model.lr_min_delta = 0.001 params_model.lr_cooldown = 2 params_model.tensorboard = True params_model.tb_write_grads = True return params_model
python
7
0.615713
81
32.530612
49
inline
package org.magcode.sunricher.api; public class Constants { public static final byte[] DATA_OFF; public static final byte[] DATA_ON; public static final byte[] DATA_BRIGHT; public static final byte[] DATA_RGB_360; public static final byte[] DATA_RGB_R; public static final byte[] DATA_RGB_G; public static final byte[] DATA_RGB_B; public static final byte[] DATA_RGB_W; public static final byte[] DATA_RGB_PRG_ON; public static final byte[] DATA_RGB_PRG_OFF; public static final byte[] DATA_RGB_PRG_SPEED; public static final byte[] DATA_RGB_BRIGHT; public static final byte[] DATA_ROOM1_OFF; public static final byte[] DATA_ROOM1_ON; public static final byte[] DATA_ROOM2_OFF; public static final byte[] DATA_ROOM2_ON; public static final byte[] DATA_ROOM3_OFF; public static final byte[] DATA_ROOM3_ON; public static final byte[] DATA_ROOM4_OFF; public static final byte[] DATA_ROOM4_ON; public static final byte[] DATA_ROOM5_OFF; public static final byte[] DATA_ROOM5_ON; public static final byte[] DATA_ROOM6_OFF; public static final byte[] DATA_ROOM6_ON; public static final byte[] DATA_ROOM7_OFF; public static final byte[] DATA_ROOM7_ON; public static final byte[] DATA_ROOM8_OFF; public static final byte[] DATA_ROOM8_ON; public static final String AT_OK = "+ok"; public static final String AT_ASSIST = "HF-A11ASSISTHREAD"; public static final int TCP_PORT = 8899; public static final int UDP_PORT = 48899; static { DATA_OFF = new byte[] { (byte) 2, (byte) 18, (byte) -87 }; DATA_ON = new byte[] { (byte) 2, (byte) 18, (byte) -85 }; DATA_ROOM1_OFF = new byte[] { 2, 10, -110 }; DATA_ROOM2_OFF = new byte[] { 2, 10, -107 }; DATA_ROOM3_OFF = new byte[] { 2, 10, -104 }; DATA_ROOM4_OFF = new byte[] { 2, 10, -101 }; DATA_ROOM5_OFF = new byte[] { 2, 10, -98 }; DATA_ROOM6_OFF = new byte[] { 2, 10, -95 }; DATA_ROOM7_OFF = new byte[] { 2, 10, -92 }; DATA_ROOM8_OFF = new byte[] { 2, 10, -89 }; DATA_ROOM1_ON = new byte[] { 2, 10, -109 }; DATA_ROOM2_ON = new byte[] { 2, 10, -106 }; DATA_ROOM3_ON = new byte[] { 2, 10, -103 }; DATA_ROOM4_ON = new byte[] { 2, 10, -100 }; DATA_ROOM5_ON = new byte[] { 2, 10, -97 }; DATA_ROOM6_ON = new byte[] { 2, 10, -94 }; DATA_ROOM7_ON = new byte[] { 2, 10, -91 }; DATA_ROOM8_ON = new byte[] { 2, 10, -88 }; DATA_BRIGHT = new byte[] { 8, 56, 0 }; DATA_RGB_360 = new byte[] { 8, 54, 0 }; // unused DATA_RGB_R = new byte[] { 8, 72, 0 }; DATA_RGB_G = new byte[] { 8, 73, 0 }; DATA_RGB_B = new byte[] { 8, 74, 0 }; DATA_RGB_W = new byte[] { 8, 75, 0 }; DATA_RGB_PRG_SPEED = new byte[] { 8, 34, 0 }; DATA_RGB_PRG_ON = new byte[] { 2, 78, 21 }; DATA_RGB_PRG_OFF = new byte[] { 2, 79, 21 }; DATA_RGB_BRIGHT = new byte[] { 8, 35, 0 }; } }
java
9
0.63969
80
39.614286
70
starcoderdata
<?php if(!$this->session->userdata('user')) { redirect('home'); } ?> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Tambah Pengunjung <div class="panel panel-default"> <div class="panel-heading"> Form Tambah Pengunjung <!-- /.panel-heading --> <div class="panel-body"> <ul class="nav nav-tabs"> <li class="active"> <a href="#upddata" data-toggle="tab" aria-expanded="true">Edit Data Pengunjung <a href="#updkartu" data-toggle="tab" aria-expanded="true">Edit Data Kartu Sehat <div class="tab-content"> <div class="tab-pane fade active in" id="upddata"> <div class="col-md-9 col-sm-9 col-xs-9 col-lg-9"> <form method="post" action="<?php echo base_url('index.php/home/update_pengunjung');?>" enctype="multipart/form-data"> <div class="panel-body"> <?php if($this->session->flashdata('notifg')) { echo '<div class="alert alert-danger">'; echo $this->session->flashdata('notifg'); echo ' }elseif($this->session->flashdata('pendnotifs')){ echo '<div class="alert alert-success">'; echo $this->session->flashdata('pendnotifs'); echo ' }elseif($this->session->flashdata('notifw')){ echo '<div class="alert alert-warning">'; echo $this->session->flashdata('notifw'); echo ' } ?> <div class="form-group"> Pengunjung <input type="text" class="form-control" name="nik_pengunjung" value="<?php echo $pengunjung->nik_pengunjung;?>" readonly> <div class="form-group"> <input type="text" class="form-control" name="nama_pengunjung" value="<?php echo $pengunjung->nama_pengunjung;?>"> <div class="form-group"> Tanggal Lahir <input type="text" class="form-control" name="ttl_pengunjung" value="<?php echo $pengunjung->ttl_pengunjung;?>"> <div class="form-group"> <input type="text" class="form-control" name="alamat_pengunjung" value="<?php echo $pengunjung->alamat_pengunjung;?>"> <div class="form-group"> <?php if($pengunjung->role_pengunjung == 'elder'){ ?> <select class="form-control" name="role_pengunjung" > <option value="<?php echo $pengunjung->role_pengunjung;?>"><?php echo $pengunjung->role_pengunjung;?> <option value="Member">Member <?php }else{ ?> <select class="form-control" name="role_pengunjung" > <option value="<?php echo $pengunjung->role_pengunjung;?>"><?php echo $pengunjung->role_pengunjung;?> <option value="Elder">Elder <?php } ?> <div class="form-group"> Kelamin <?php if($pengunjung->jk_pengunjung == 'Laki-laki'){ ?> <select class="form-control" name="jk_pengunjung" > <option value="<?php echo $pengunjung->jk_pengunjung;?>"><?php echo $pengunjung->jk_pengunjung;?> <option value="Perempuan">Perempuan <?php }else{ ?> <select class="form-control" name="jk_pengunjung" > <option value="<?php echo $pengunjung->jk_pengunjung;?>"><?php echo $pengunjung->jk_pengunjung;?> <option value="Laki-laki">Laki-laki <?php } ?> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg" value="submit" name="submit_petugas"> <div class="col-md-3 col-sm-3 col-xs-3 col-lg-3"> <div id="foto-petugas"> <img src="<?php echo base_url('assets/img/pengunjung/').$pengunjung->foto_pengunjung;?>" style="width: 170px;height: 230px;margin-top: 20px"> <div class="tab-pane fade" id="updkartu"> <div class="col-md-9 col-sm-9 col-xs-9 col-lg-9"> <form method="post" action="<?php echo base_url('index.php/home/update_kartu');?>" enctype="multipart/form-data"> <div class="panel-body"> <?php if($this->session->flashdata('notifg')) { echo '<div class="alert alert-danger">'; echo $this->session->flashdata('notifg'); echo ' }elseif($this->session->flashdata('pendnotifs')){ echo '<div class="alert alert-success">'; echo $this->session->flashdata('pendnotifs'); echo ' }elseif($this->session->flashdata('notifw')){ echo '<div class="alert alert-warning">'; echo $this->session->flashdata('notifw'); echo ' } ?> <div class="form-group"> Pengunjung <input type="text" class="form-control" name="nik_pengunjung" value="<?php echo $pengunjung->nik_pengunjung;?>" readonly> <div class="form-group"> <input type="text" class="form-control" name="nama_pengunjung" value="<?php echo $pengunjung->nama_pengunjung;?>" readonly> <div class="form-group"> Kartu <input type="number" class="form-control" name="no_kartu" value="<?php echo $kartu->no_kartu;?>"> <div class="form-group"> Tingak1 <input type="text" class="form-control" name="faskes_t1" value="<?php echo $kartu->faskes_t1;?>"> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg" value="submit" name="submit_petugas"> <div class="col-md-3 col-sm-3 col-xs-3 col-lg-3"> <div id="foto-petugas"> <img src="<?php echo base_url('assets/img/pengunjung/').$pengunjung->foto_pengunjung;?>" style="width: 170px;height: 230px;margin-top: 20px">
php
9
0.402846
157
51.923529
170
starcoderdata
/******************************************************************************* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.examples.analysis.dataflow; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.dataflow.IFDS.ISupergraph; import com.ibm.wala.dataflow.IFDS.TabulationResult; import com.ibm.wala.dataflow.graph.BitVectorSolver; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cfg.BasicBlockInContext; import com.ibm.wala.ipa.cfg.ExplodedInterproceduralCFG; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.analysis.ExplodedControlFlowGraph; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.config.AnalysisScopeReader; import com.ibm.wala.util.config.FileOfClasses; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; /** * Tests of various flow analysis engines. */ public class DataflowTest extends WalaTestCase { private static AnalysisScope scope; private static IClassHierarchy cha; // more aggressive exclusions to avoid library blowup // in interprocedural tests private static final String EXCLUSIONS = "java\\/awt\\/.*\n" + "javax\\/swing\\/.*\n" + "sun\\/awt\\/.*\n" + "sun\\/swing\\/.*\n" + "com\\/sun\\/.*\n" + "sun\\/.*\n" + "org\\/netbeans\\/.*\n" + "org\\/openide\\/.*\n" + "com\\/ibm\\/crypto\\/.*\n" + "com\\/ibm\\/security\\/.*\n" + "org\\/apache\\/xerces\\/.*\n" + "java\\/security\\/.*\n" + ""; @BeforeClass public static void beforeClass() throws Exception { scope = AnalysisScopeReader.readJavaScope(TestConstants.WALA_TESTDATA, null, DataflowTest.class.getClassLoader()); scope.setExclusions(new FileOfClasses(new ByteArrayInputStream(EXCLUSIONS.getBytes(StandardCharsets.UTF_8)))); try { cha = ClassHierarchyFactory.make(scope); } catch (ClassHierarchyException e) { throw new Exception(e); } } /* * (non-Javadoc) * * @see junit.framework.TestCase#tearDown() */ @AfterClass public static void afterClass() throws Exception { scope = null; cha = null; } @Test public void testIntraproc1() { IAnalysisCacheView cache = new AnalysisCacheImpl(); final MethodReference ref = MethodReference.findOrCreate(ClassLoaderReference.Application, "Ldataflow/StaticDataflow", "test1", "()V"); IMethod method = cha.resolveMethod(ref); IR ir = cache.getIRFactory().makeIR(method, Everywhere.EVERYWHERE, SSAOptions.defaultOptions()); ExplodedControlFlowGraph ecfg = ExplodedControlFlowGraph.make(ir); IntraprocReachingDefs reachingDefs = new IntraprocReachingDefs(ecfg, cha); BitVectorSolver<IExplodedBasicBlock> solver = reachingDefs.analyze(); for (IExplodedBasicBlock ebb : ecfg) { if (ebb.getNumber() == 4) { IntSet out = solver.getOut(ebb).getValue(); Assert.assertEquals(1, out.size()); Assert.assertTrue(out.contains(1)); } } } @Test public void testIntraproc2() { IAnalysisCacheView cache = new AnalysisCacheImpl(); final MethodReference ref = MethodReference.findOrCreate(ClassLoaderReference.Application, "Ldataflow/StaticDataflow", "test2", "()V"); IMethod method = cha.resolveMethod(ref); IR ir = cache.getIRFactory().makeIR(method, Everywhere.EVERYWHERE, SSAOptions.defaultOptions()); ExplodedControlFlowGraph ecfg = ExplodedControlFlowGraph.make(ir); IntraprocReachingDefs reachingDefs = new IntraprocReachingDefs(ecfg, cha); BitVectorSolver<IExplodedBasicBlock> solver = reachingDefs.analyze(); for (IExplodedBasicBlock ebb : ecfg) { if (ebb.getNumber() == 10) { IntSet out = solver.getOut(ebb).getValue(); Assert.assertEquals(2, out.size()); Assert.assertTrue(out.contains(0)); Assert.assertTrue(out.contains(2)); } } } @Test public void testContextInsensitive() throws IllegalArgumentException, CallGraphBuilderCancelException { Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(scope, cha, "Ldataflow/StaticDataflow"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraphBuilder<InstanceKey> builder = Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha, scope); CallGraph cg = builder.makeCallGraph(options, null); ExplodedInterproceduralCFG icfg = ExplodedInterproceduralCFG.make(cg); ContextInsensitiveReachingDefs reachingDefs = new ContextInsensitiveReachingDefs(icfg, cha); BitVectorSolver<BasicBlockInContext<IExplodedBasicBlock>> solver = reachingDefs.analyze(); for (BasicBlockInContext<IExplodedBasicBlock> bb : icfg) { if (bb.getNode().toString().contains("testInterproc")) { IExplodedBasicBlock delegate = bb.getDelegate(); if (delegate.getNumber() == 4) { IntSet solution = solver.getOut(bb).getValue(); IntIterator intIterator = solution.intIterator(); List<Pair<CGNode, Integer>> applicationDefs = new ArrayList<>(); while (intIterator.hasNext()) { int next = intIterator.next(); final Pair<CGNode, Integer> def = reachingDefs.getNodeAndInstrForNumber(next); if (def.fst.getMethod().getDeclaringClass().getClassLoader().getReference().equals(ClassLoaderReference.Application)) { System.out.println(def); applicationDefs.add(def); } } Assert.assertEquals(2, applicationDefs.size()); } } } } @Test public void testContextSensitive() throws IllegalArgumentException, CancelException { Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(scope, cha, "Ldataflow/StaticDataflow"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraphBuilder<InstanceKey> builder = Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha, scope); CallGraph cg = builder.makeCallGraph(options, null); ContextSensitiveReachingDefs reachingDefs = new ContextSensitiveReachingDefs(cg); TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> result = reachingDefs.analyze(); ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> supergraph = reachingDefs.getSupergraph(); for (BasicBlockInContext<IExplodedBasicBlock> bb : supergraph) { if (bb.getNode().toString().contains("testInterproc")) { IExplodedBasicBlock delegate = bb.getDelegate(); if (delegate.getNumber() == 4) { IntSet solution = result.getResult(bb); IntIterator intIterator = solution.intIterator(); List<Pair<CGNode, Integer>> applicationDefs = new ArrayList<>(); while (intIterator.hasNext()) { int next = intIterator.next(); final Pair<CGNode, Integer> def = reachingDefs.getDomain().getMappedObject(next); if (def.fst.getMethod().getDeclaringClass().getClassLoader().getReference().equals(ClassLoaderReference.Application)) { System.out.println(def); applicationDefs.add(def); } } Assert.assertEquals(1, applicationDefs.size()); } } } } }
java
21
0.708452
132
41.995305
213
research_code
package de.adorsys.psd2.sandbox.tpp.rest.server.service; import com.fasterxml.jackson.core.type.TypeReference; import de.adorsys.psd2.sandbox.tpp.cms.api.domain.AisConsent; import de.adorsys.psd2.sandbox.tpp.rest.api.domain.UserTransaction; import de.adorsys.psd2.sandbox.tpp.rest.server.model.DataPayload; import org.junit.Test; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; public class ParseServiceTest { private final ResourceLoader resourceLoader = new DefaultResourceLoader(); private final ParseService parseService = new ParseService(resourceLoader); @Test public void getDataFromFile_Consents() throws IOException { MultipartFile multipartFile = resolveMultipartFile("consents_template.yml"); Optional data = parseService.getDataFromFile(multipartFile, new TypeReference { }); assertThat(data.isPresent()).isTrue(); data.get().forEach(this::assertNoNullFields); } @Test public void convertMultiPartToFile() throws IOException { List transactions = parseService.convertFileToTargetObject(resolveMultipartFile("transactions_template.csv"), UserTransaction.class); assertThat(transactions).isNotEmpty(); assertThat(transactions.get(0)).isEqualToComparingFieldByField(buildSingleUserTransaction()); } private UserTransaction buildSingleUserTransaction() { UserTransaction transaction = new UserTransaction(); transaction.setId("50405667"); transaction.setPostingDate("30.01.2017"); transaction.setValueDate("30.01.2017"); transaction.setText("Lohn/Gehalt"); transaction.setUsage("Gehalt Teambank"); transaction.setPayer(" transaction.setAccountNumber("7807800780"); transaction.setBlzCode("VOHADE2HXXX"); transaction.setAmount("2116.17"); transaction.setCurrency("EUR"); return transaction; } @Test public void getDataFromFile_DataPayload() throws IOException { MultipartFile multipartFile = resolveMultipartFile("data_payload_template.yml"); Optional data = parseService.getDataFromFile(multipartFile, new TypeReference { }); validateDataPayload(data); } private MultipartFile resolveMultipartFile(String fileName) throws IOException { Resource resource = resourceLoader.getResource(fileName); return new MockMultipartFile("file", resource.getFile().getName(), "text/plain", resource.getInputStream()); } private void validateDataPayload(Optional data) { assertThat(data.isPresent()).isTrue(); DataPayload payload = data.get(); assertThat(payload.getBranch() == null).isTrue(); assertThat(payload.getGeneratedIbans().size() == 0).isTrue(); assertThat(payload.getUsers().size() == 1).isTrue(); assertThat(payload.getAccounts().size() == 1).isTrue(); assertThat(payload.getBalancesList().size() == 1).isTrue(); assertThat(payload.getPayments().size() == 1).isTrue(); } private void assertNoNullFields(AisConsent consent) { assertThat(consent).hasNoNullFieldsOrProperties(); assertThat(consent.getPsuInfo()).hasNoNullFieldsOrProperties(); assertThat(consent.getTppInfo()).hasNoNullFieldsOrProperties(); consent.getAccess().getAccounts().forEach(a -> assertThat(a).hasNoNullFieldsOrProperties()); consent.getAccess().getBalances().forEach(a -> assertThat(a).hasNoNullFieldsOrProperties()); consent.getAccess().getTransactions().forEach(a -> assertThat(a).hasNoNullFieldsOrProperties()); } }
java
14
0.728031
158
44.266667
90
starcoderdata
bool SvdLLS::solve_aux() { { float* ap = _fa.data(); for_int(j, _n) for_int(i, _m) *ap++ = _a[i][j]; } { float* bp = _fb.data(); for_int(d, _nd) for_int(i, _m) *bp++ = _b[d][i]; } float rcond = 1.f/k_float_cond_max; if (0) rcond = -1.f; // use machine precision to determine rank lapack_int irank, lwork = _work.num(), info; lapack_int lm = _m, ln = _n, lnd = _nd; sgelss_(&lm, &ln, &lnd, _fa.data(), &lm, _fb.data(), &lm, _s.data(), &rcond, &irank, _work.data(), &lwork, &info); assertx(info>=0); if (info>0) return false; if (irank<_n) return false; // _s contains singular values in decreasing order. assertx(_s[_n-1]); float cond = _s[0]/_s[_n-1]; if (cond>k_float_cond_warning) { HH_SSTAT(Ssvdlls_cond, cond); } { float* bp = _fb.data(); for_int(d, _nd) { for_int(j, _n) { _x[d][j] = *bp++; } bp += (_m-_n); } } return true; }
c++
13
0.496855
118
38.791667
24
inline
using System; using NSpec; using NUnit.Framework; namespace Coypu.Drivers.Tests { public class When_finding_buttons : DriverSpecs { internal override void Specs() { it["finds a particular button by its text"] = () => { driver.FindButton("first button").Id.should_be("firstButtonId"); driver.FindButton("second button").Id.should_be("secondButtonId"); }; it["finds a particular button by its id"] = () => { driver.FindButton("firstButtonId").Text.should_be("first button"); driver.FindButton("thirdButtonId").Text.should_be("third button"); }; it["finds a particular button by its name"] = () => { driver.FindButton("secondButtonName").Text.should_be("second button"); driver.FindButton("thirdButtonName").Text.should_be("third button"); }; it["finds a particular input button by its value"] = () => { driver.FindButton("first input button").Id.should_be("firstInputButtonId"); driver.FindButton("second input button").Id.should_be("secondInputButtonId"); }; it["finds a particular input button by its id"] = () => { driver.FindButton("firstInputButtonId").Value.should_be("first input button"); driver.FindButton("thirdInputButtonId").Value.should_be("third input button"); }; it["finds a particular input button by id ends with"] = () => { driver.FindButton("rdInputButtonId").Value.should_be("third input button"); }; it["finds a particular input button by id before finding by id ends with"] = () => { driver.FindButton("otherButtonId").Id.should_be("otherButtonId"); }; it["finds a particular input button by its name"] = () => { driver.FindButton("secondInputButtonId").Value.should_be("second input button"); driver.FindButton("thirdInputButtonName").Value.should_be("third input button"); }; it["finds a particular submit button by its value"] = () => { driver.FindButton("first submit button").Id.should_be("firstSubmitButtonId"); driver.FindButton("second submit button").Id.should_be("secondSubmitButtonId"); }; it["finds a particular submit button by its id"] = () => { driver.FindButton("firstSubmitButtonId").Value.should_be("first submit button"); driver.FindButton("thirdSubmitButtonId").Value.should_be("third submit button"); }; it["finds a particular submit button by its name"] = () => { driver.FindButton("secondSubmitButtonName").Value.should_be("second submit button"); driver.FindButton("thirdSubmitButtonName").Value.should_be("third submit button"); }; it["finds image buttons"] = () => { driver.FindButton("firstImageButtonId").Value.should_be("first image button"); driver.FindButton("secondImageButtonId").Value.should_be("second image button"); }; it["does not find text inputs"] = () => { Assert.Throws => driver.FindButton("firstTextInputId")); }; it["does not find hidden inputs"] = () => { Assert.Throws => driver.FindButton("firstHiddenInputId")); }; it["does not find invisible inputs"] = () => { Assert.Throws => driver.FindButton("firstInvisibleInputId")); }; it["finds img elements with role='button' by alt text"] = () => { Assert.That(driver.FindButton("I'm an image with the role of button").Id, Is.EqualTo("roleImageButtonId")); }; it["finds any elements with role='button' by text"] = () => { Assert.That(driver.FindButton("I'm a span with the role of button").Id, Is.EqualTo("roleSpanButtonId")); }; it["finds an image button with both types of quote in my value"] = () => { var button = driver.FindButton("I'm an image button with \"both\" types of quote in my value"); Assert.That(button.Id, Is.EqualTo("buttonWithBothQuotesId")); }; } } }
c#
20
0.54895
123
41.210526
114
starcoderdata
def __init__(self, args): super(InferenceOnDataset, self).__init__() # load config self.print_update("Loading and setting config") config = self.load_and_set_config(args) # set logging set_logger(join(config.log_dir, 'inference.log')) # load optimal threshold for val set on this epoch epoch_val_logs = self.load_epoch_logs(config.log_dir, args.epoch) if args.threshold is None: if epoch_val_logs is None: assert args.threshold is not None, \ color( "args.threshold cannot be None when model logs do not exist.", "red" ) args.threshold = epoch_val_logs['threshold'] # load data self.print_update("Loading data") dataloader = self.load_data(config, args) # load model self.print_update("Loading model") model = self.load_model(config) # forward pass self.print_update("Running forward pass") results = self.forward_pass(model, dataloader, args.mode, args.threshold) # save logs: individual predictions self.save_logs(results, config.log_dir_inference, args.mode, fname=f"{args.epoch}.pt") # individual level aggregation self.print_update("individual level aggregation") ila_results = self.results_post_aggregation( model, results, epoch_val_logs, args.agg_method, args.mode, at=args.at, agg_th=args.threshold ) # save logs: individual predictions post aggregation fname = f"{args.epoch}_{args.agg_method}_aggregated.pt" self.save_logs(ila_results, config.log_dir_inference, args.mode, fname=fname)
python
11
0.603184
105
39.930233
43
inline
<?php namespace App\Repositories\Booking_Date; interface Booking_DateRepositoryInterface { public function showall(); public function paginate(); public function showallBooking_DateonRoom($id); public function showallBooking_DateonUser($id); public function showBooking_Date($booking); public function destroyBooking_Date($booking); public function restoreBooking_Date($booking); public function cancel($booking,$user); }
php
7
0.757515
51
26.722222
18
starcoderdata
<?php $__env->startSection('content'); ?> coach Stuart Dew has landed in hot water after being videoed urinating outside a Gold Coast nightclub, in another embarrassing moment for the league in the state. 41, was videoed outside the Miami Tavern Shark Bar urinating against a wall at a drink with fellow senior members of the Gold Coast Suns staff. is not known exactly when the video was shot, but it surfaced just a hours after his side's final game of the severely interrupted 2020 season. was reportedly filmed urinating by his colleague before the video was shared to a WhatsApp group and eventually wound up online, The Courier Mail reports. morning after the video was shot the staffer reportedly realised his mistake and asked anyone in the WhatsApp group to delete it - but it was already too late. coach Stuart Dew has landed in hot water after being videoed urinating outside a Gold Coast nightclub, in another embarrassing moment for the league in the state turns to the camera after finishing relieving himself and smiles awkwardly. Queensland law, anyone caught urinating in public faces a fine of $533.80. Coast Suns chief executive confirmed the incident when contacted by The Courier Mail, but refused to comment further. the background of the video Dew can be heard by his fellow colleagues, including one who asks: 'Do you play for the Canterbury Bulldogs?' NRL side has landed in hot water repeatedly in recent years for off-field dramas. former Port Adelaide and Hawthorn champion took over as coach of the battling team at the beginning of 2019 and has widely been praised for developing the side.  is not known exactly when the video was shot, but it surfaced just a hours after his side's final game of the severely interrupted 2020 season on Sunday AFL players have been sent home from Queensland for breaching COVID-19 rules  players and their families were holed up at the league's hotel hub under increasingly strict conditions (pictured, AFL stars and WAGs relaxing by the pool at the Mercure Resort on the Gold Coast) premier Annastacia Palaszczuk has come under fire for allowing the AFL to set up private hubs in the state she controls, after a number of players and officials were involved in scandals. pair Sydney Stack and were sent home and banned for 10 weeks after getting into a fight outside a strip club. AFL is also currently investigating for a potential breach of strict COVID-19 rules that were agreed upon so the league could set up in the state. have been similar issues in other hubs around the country, including in Perth where Sydney Swans star was caught sneaking his then girlfriend into his team's private hotel accommodation. have since charged Taylor with domestic violence offences after an alleged incident involving he and the same woman, his now ex-girlfriend,    <?php $__env->stopSection(); ?> <?php echo $__env->make('_layouts.post', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
php
12
0.768996
214
78.95122
41
starcoderdata
def write_all(self, force=False, **kwargs): """ Write all the data in this DataStore """ for key, handle in self.items(): local_kwargs = kwargs.get(key, {}) if handle.is_written and not force: continue handle.write(**local_kwargs)
python
10
0.553691
52
41.714286
7
inline
fn myprettyfailure_0002_option() { let err = err1().unwrap_err(); // your failure let result = myprettyfailure_option(MyPrettyFailurePrint { head: "🔔 error".to_string(), separator: "---------------------------------------------------------".to_string(), causedby: "context".to_string() }, &err); // this indent to upd to 100% coverage assert!(result == r#"🔔 error --------------------------------------------------------- a long err1 --------------------------------------------------------- ▶ context: a very long err2 ▶ context: an another deep err3 ---------------------------------------------------------"#); }
rust
12
0.406728
91
45.785714
14
inline
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import autobind from '../../utils/autobind'; import ImageForm from '../image-form/image-form'; import * as imageActions from '../../actions/image'; const defaultState = { title: '', titleDirty: false, titleError: '', description: '', }; class PostForm extends React.Component { constructor(props) { super(props); this.state = this.props.post ? this.props.post : defaultState; autobind.call(this, PostForm); } handleChange(event) { const { name, value } = event.target; this.setState({ [name]: value }); } handleSubmit(event) { event.preventDefault(); const id = this.props.selectedEvent._id; if (!this.state.titleError) { if (this.props.type === 'announcement') { this.props.onComplete({ ...this.state, isAnnouncement: true, type: this.props.type }, id); this.setState(this.props.post ? this.state : defaultState); this.props.handleClose(); } else if (this.props.type === 'photo') { this.props.onComplete({ ...this.state, imageUrl: '' }); this.setState(this.props.post ? this.state : defaultState); this.props.handleClose(); } else { this.props.onComplete({ ...this.state, type: this.props.type }, id); this.setState(this.props.post ? this.state : defaultState); this.props.handleClose(); } } else { this.setState({ titleDirty: true, descriptionDirty: true, }); } } handleValidation(name, value) { if (!value) { this.setState({ [`${name}Dirty`]: true, [`${name}Error`]: `Must provide ${name}`, }); } } render() { const { type } = this.props; const buttonText = this.props.post ? 'Update' : 'Add'; const nonImagePostJSX = <form onSubmit={this.handleSubmit}> <input type='text' name='title' placeholder='Title' onChange={this.handleChange} onBlur={() => this.handleValidation('title', this.state.title)} value={this.state.title} /> {this.state.titleDirty && this.state.titleError } <textarea placeholder='enter text here' name='description' onChange={this.handleChange} value={this.state.description} /> <button type='submit'> {buttonText} return ( { type === 'photo' ? <ImageForm show={true} showCaption={true} event={this.props.selectedEvent} onComplete={this.props.pPostImageRequest} /> : nonImagePostJSX } ); } } PostForm.propTypes = { type: PropTypes.string, post: PropTypes.object, onComplete: PropTypes.func, selectedEvent: PropTypes.object, pPostImageRequest: PropTypes.func, handleClose: PropTypes.func, }; const mapStatetoProps = state => ({ selectedEvent: state.selectedEvent, }); const mapDispatchToProps = dispatch => ({ pPostImageRequest: (image, event) => dispatch(imageActions.createRequest(image, event)), }); export default connect(mapStatetoProps, mapDispatchToProps)(PostForm);
javascript
19
0.600978
98
27.46087
115
starcoderdata
// Copyright (c) 2019, The Emergent Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package popcode import ( "sort" "github.com/goki/mat32" ) type PopCodes int const ( // GaussBump = gaussian bump, with value = weighted average of tuned unit values GaussBump PopCodes = iota // Localist = each unit represents a distinct value; intermediate values represented by graded activity of neighbors; overall activity is weighted-average across all units Localist ) // popcode.OneD provides encoding and decoding of population // codes, used to represent a single continuous (scalar) value // across a population of units / neurons (1 dimensional) type OneD struct { Code PopCodes `desc:"how to encode the value"` Min float32 `desc:"minimum value representable -- for GaussBump, typically include extra to allow mean with activity on either side to represent the lowest value you want to encode"` Max float32 `desc:"maximum value representable -- for GaussBump, typically include extra to allow mean with activity on either side to represent the lowest value you want to encode"` Sigma float32 `def:"0.2" viewif:"Code=GaussBump" desc:"sigma parameter of a gaussian specifying the tuning width of the coarse-coded units, in normalized 0-1 range"` Clip bool `desc:"ensure that encoded and decoded value remains within specified range"` Thr float32 `def:"0.1" desc:"threshold to cut off small activation contributions to overall average value (i.e., if unit's activation is below this threshold, it doesn't contribute to weighted average computation)"` MinSum float32 `def:"0.2" desc:"minimum total activity of all the units representing a value: when computing weighted average value, this is used as a minimum for the sum that you divide by"` } func (pc *OneD) Defaults() { pc.Code = GaussBump pc.Min = -0.5 pc.Max = 1.5 pc.Sigma = 0.2 pc.Clip = true pc.Thr = 0.1 pc.MinSum = 0.2 } // SetRange sets the min, max and sigma values func (pc *OneD) SetRange(min, max, sigma float32) { pc.Min = min pc.Max = max pc.Sigma = sigma } const ( // Add is used for popcode Encode methods, add arg -- indicates to add values // to any existing values in the target vector / tensor: // used for encoding additional values (see DecodeN for decoding). Add = true // Set is used for popcode Encode methods, add arg -- indicates to set values // in any existing values in the target vector / tensor: // used for encoding first / only values. Set = false ) // Encode generates a pattern of activation of given size to encode given value. // n must be 2 or more. pat slice will be constructed if len != n. // If add == false (use Set const for clarity), values are set to pattern // else if add == true (Add), then values are added to any existing, // for encoding additional values in same pattern. func (pc *OneD) Encode(pat *[]float32, val float32, n int, add bool) { if len(*pat) != n { *pat = make([]float32, n) } if pc.Clip { val = mat32.Clamp(val, pc.Min, pc.Max) } rng := pc.Max - pc.Min gnrm := 1 / (rng * pc.Sigma) incr := rng / float32(n-1) for i := 0; i < n; i++ { trg := pc.Min + incr*float32(i) act := float32(0) switch pc.Code { case GaussBump: dist := gnrm * (trg - val) act = mat32.Exp(-(dist * dist)) case Localist: dist := mat32.Abs(trg - val) if dist > incr { act = 0 } else { act = 1.0 - (dist / incr) } } if add { (*pat)[i] += act } else { (*pat)[i] = act } } } // Decode decodes value from a pattern of activation // as the activation-weighted-average of the unit's preferred // tuning values. // must have 2 or more values in pattern pat. func (pc *OneD) Decode(pat []float32) float32 { n := len(pat) if n < 2 { return 0 } rng := pc.Max - pc.Min incr := rng / float32(n-1) avg := float32(0) sum := float32(0) for i, act := range pat { if act < pc.Thr { act = 0 } trg := pc.Min + incr*float32(i) avg += trg * act sum += act } sum = mat32.Max(sum, pc.MinSum) avg /= sum return avg } // Values sets the vals slice to the target preferred tuning values // for each unit, for a distribution of given size n. // n must be 2 or more. // vals slice will be constructed if len != n func (pc *OneD) Values(vals *[]float32, n int) { if len(*vals) != n { *vals = make([]float32, n) } rng := pc.Max - pc.Min incr := rng / float32(n-1) for i := 0; i < n; i++ { trg := pc.Min + incr*float32(i) (*vals)[i] = trg } } // DecodeNPeaks decodes N values from a pattern of activation // using a neighborhood of specified width around local maxima, // which is the amount on either side of the central point to // accumulate (0 = localist, single points, 1 = +/- 1 point on // either side, etc). // Allocates a temporary slice of size pat, and sorts that: relatively expensive func (pc *OneD) DecodeNPeaks(pat []float32, nvals, width int) []float32 { n := len(pat) if n < 2 { return nil } rng := pc.Max - pc.Min incr := rng / float32(n-1) type navg struct { avg float32 idx int } avgs := make([]navg, n) for i := range pat { sum := float32(0) ns := 0 for d := -width; d <= width; d++ { di := i + d if di < 0 || di >= n { continue } act := pat[di] if act < pc.Thr { continue } sum += pat[di] ns++ } avgs[i].avg = sum / float32(ns) avgs[i].idx = i } // sort highest to lowest sort.Slice(avgs, func(i, j int) bool { return avgs[i].avg > avgs[j].avg }) vals := make([]float32, nvals) for i := range vals { avg := float32(0) sum := float32(0) mxi := avgs[i].idx for d := -width; d <= width; d++ { di := mxi + d if di < 0 || di >= n { continue } act := pat[di] if act < pc.Thr { act = 0 } trg := pc.Min + incr*float32(di) avg += trg * act sum += act } sum = mat32.Max(sum, pc.MinSum) vals[i] = avg / sum } return vals }
go
14
0.654051
220
27.159624
213
starcoderdata
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Linq; using static System.Console; using static System.Math; namespace abc_91_c { class Program { static void Main(string[] args) { int n = int.Parse(ReadLine()); int[][] red = new int[n][]; int[][] blue = new int[n][]; for(int i = 0; i<n; i++) { int[] input = ReadLine().Split().Select(int.Parse).ToArray(); red[i] = input; } for(int i = 0; i<n; i++) { int[] input = ReadLine().Split().Select(int.Parse).ToArray(); blue[i] = input; } red = red.OrderByDescending(a => a[1]).ToArray(); blue = blue.OrderBy(a => a[0]).ToArray(); int count=0; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(red[j] == null) continue; if(red[j][0] < blue[i][0] && red[j][1] < blue[i][1]) { count++; red[j] = null; break; } } } WriteLine(count); } } }
c#
21
0.397626
77
24.45283
53
codenet
<?php namespace fd; use pocketmine\plugin\PluginBase; class Loader extends PluginBase{ public function onEnable() : void{ } }
php
6
0.655405
38
13.8
10
starcoderdata
namespace device_sync { // Holds information for a key managed by CryptAuth or an ephemeral key, such as // a Diffie-Hellman key-pair. class CryptAuthKey { public: // Specified by CryptAuth in the Enrollment protocol by // SyncKeysResponse::SyncSingleKeyResponse::KeyAction or // SyncKeysResponse::SyncSingleKeyResponse::KeyCreation. kActive denotes that // the key should be used. kInactive denotes that the key should be retained // for possible future activation but not used. For ephemeral keys not managed // by CryptAuth but used locally for intermediate cryptographic operations, // this status is meaningless. enum Status { kActive, kInactive }; static base::Optional<CryptAuthKey> FromDictionary(const base::Value& dict); // Constructor for symmetric keys. CryptAuthKey(const std::string& symmetric_key, Status status, cryptauthv2::KeyType type, const base::Optional<std::string>& handle = base::nullopt); // Constructor for asymmetric keys. Note that |public_key| should be a // serialized securemessage::GenericPublicKey proto. CryptAuthKey(const std::string& public_key, const std::string& private_key, Status status, cryptauthv2::KeyType type, const base::Optional<std::string>& handle = base::nullopt); CryptAuthKey(const CryptAuthKey&); ~CryptAuthKey(); bool IsSymmetricKey() const; bool IsAsymmetricKey() const; Status status() const { return status_; } cryptauthv2::KeyType type() const { return type_; } const std::string& symmetric_key() const { DCHECK(IsSymmetricKey()); return symmetric_key_; } const std::string& public_key() const { DCHECK(IsAsymmetricKey()); return public_key_; } const std::string& private_key() const { DCHECK(IsAsymmetricKey()); return private_key_; } const std::string& handle() const { return handle_; } void set_status(Status status) { status_ = status; } // Converts CryptAuthKey to a dictionary-type Value of the form // { // "handle": <handle_> // "status": <status_ as int> // "symmetric_key": <symmetric_key_> // "type": <type_ as int> // } base::Value AsSymmetricKeyDictionary() const; // Converts CryptAuthKey to a dictionary-type Value of the form // { // "handle": <handle_> // "private_key" : <private_key_> // "public_key" : <public_key_> // "status": <status_ as int> // "type": <type_ as int> // } base::Value AsAsymmetricKeyDictionary() const; bool operator==(const CryptAuthKey& other) const; bool operator!=(const CryptAuthKey& other) const; private: std::string symmetric_key_; std::string public_key_; std::string private_key_; Status status_; cryptauthv2::KeyType type_; std::string handle_; }; } // namespace device_sync }
c
14
0.665627
80
31.077778
90
inline
package com.packagename.myapp; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import com.packagename.myapp.control.ManageUserController; import com.packagename.myapp.model.base.JsonModel; import com.packagename.myapp.model.base.User; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.Grid.SelectionMode; import com.vaadin.flow.component.html.H5; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.select.Select; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.binder.Binder; import com.vaadin.flow.data.binder.ValidationException; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; @PageTitle("ManageUser | Vaadin CRM") //Child of MainLayout Right side of Main Page //Which has the path localhost:8080/dashboard @Route(value = "manageUser", layout = MainLayout.class) public class ManageUser extends VerticalLayout { public ManageUser() { Binder binder = new Binder(ManageUserController.class); H5 UserManagement = new H5("User Management"); add(UserManagement); //Make a form layout for the adding user FormLayout form = new FormLayout(); //create the column for the display form.setResponsiveSteps( new ResponsiveStep("20em",1), new ResponsiveStep("25em",2), new ResponsiveStep("35em",3), new ResponsiveStep("50em", 4), new ResponsiveStep("65em", 5), new ResponsiveStep("80em", 6)); //create text field for the name input TextField userName = new TextField(); userName.setLabel("Name"); //creates the binder to get data easier from the user.json file binder.forField(userName) .asRequired() .bind(User::getName, User::setName); //textfield for password TextField password = new TextField(); password.setLabel("Password"); binder.forField(password) .asRequired() .bind(User::getPassword, User::setPassword); //select drop down for the different types Select userType = new Select(); userType.setLabel("User Type"); userType.setValue("Editor"); userType.setItems("Editor","Reviewer","Researcher","Admin"); binder.forField(userType) .asRequired() .bind(User::getUserType, User::setUserType); //text field for the email input TextField email = new TextField(); email.setLabel("Email"); binder.forField(email) .asRequired() .bind(User::getEmail, User::setEmail); //text field for the user id input TextField UserId = new TextField(); UserId.setLabel("UserId"); binder.forField(UserId) .asRequired() .bind(User::getUserID, User::setUserID); //textfield for the field of the user works in TextField field = new TextField(); field.setLabel("field"); binder.forField(field) .asRequired() .bind(User::getField, User::setField); form.add(UserId,userName,password,userType, field,email); //Add dialog Dialog removed = new Dialog(); Dialog added = new Dialog(); Dialog edited = new Dialog(); //Prompt removed.add(new Label("Selected user have been removed.")); added.add(new Label("Added selected user.")); edited.add(new Label("Selected user have been edited")); ArrayList userList; try{ userList = new ArrayList<>(JsonModel.getUserData().values()); } catch(IOException e){ e.printStackTrace(); userList = new ArrayList<>(); } //Create new grid Grid userGrid = new Grid<>(); //Add the userList items to the grid. userGrid.setItems(userList); //Add columns to the grid userGrid.addColumn(User::getUserID).setHeader("UserID"); userGrid.addColumn(User::getName).setHeader("Name"); userGrid.addColumn(User::getPassword).setHeader("Password"); userGrid.addColumn(User::getUserType).setHeader("User Type"); userGrid.addColumn(User::getField).setHeader("Field"); userGrid.addColumn(User::getEmail).setHeader("User Email"); //Allow admin to select multiple objects from the grid userGrid.setSelectionMode(SelectionMode.SINGLE); userGrid.addSelectionListener(e ->{ User select = e.getFirstSelectedItem().orElse(null); if(select == null){ select = new User(null, null, null, null, null, null); }else{ binder.readBean(select); } }); //Label for adding new users. H5 newUser = new H5("Add New User"); //Button to go back. Button back = new Button("Back", e -> UI.getCurrent().navigate("admin")); //Button to add a user and rund the code to add the user. Button add = new Button("Add User", e -> { if(UserId.getValue() == null || userName.getValue() == null || password.getValue() == null || field.getValue() == null || ((String)userType.getValue()) == null || email.getValue() == null){ Dialog invalid = new Dialog(); invalid.add(new Label("Please fill out all of the fields")); invalid.open(); userGrid.getDataProvider().refreshAll(); } else{ HashMap<String, User> addNewUser = new HashMap<String, User>(); User temp = new User(UserId.getValue(), password.getValue(), userName.getValue(), email.getValue(), field.getValue(), (String) userType.getValue()); try { addNewUser = JsonModel.getUserData(); } catch(IOException e2){ e2.printStackTrace(); } addNewUser.put(UserId.getValue(),temp); try { JsonModel.setUserData(addNewUser); }catch(IOException e1){ e1.printStackTrace(); } added.open(); UI.getCurrent().getPage().reload(); } }); //Edit the user data ArrayList finalUserList = userList; Button edit = new Button("Edit User", e ->{ Set select = userGrid.getSelectedItems(); User[] selectedInfo = new User [1]; select.toArray(selectedInfo); try { binder.writeBean(selectedInfo[0]); HashMap <String, User> selected = new HashMap<String, User>(); for(User temp: finalUserList){ selected.put(temp.getUserID(), temp); } try { JsonModel.setUserData(selected); }catch(IOException e5){ e5.printStackTrace(); } }catch(ValidationException e4){ e4.printStackTrace(); } edited.open(); userGrid.getDataProvider().refreshAll(); }); //Button to remove a user. Button remove = new Button("Remove Selected User(s)", e ->{ //Grabs all of the user data in the user.json file and put it in a Hashmap HashMap <String, User> allUser; try{ allUser = JsonModel.getUserData(); }catch(IOException error){ error.printStackTrace(); allUser = new HashMap<>(); } Set select = userGrid.getSelectedItems(); User[] selectedInfo = new User [1]; select.toArray(selectedInfo); allUser.remove(selectedInfo[0].getUserID()); try { JsonModel.setUserData(allUser); } catch(IOException e3){ e3.printStackTrace(); } removed.open(); UI.getCurrent().getPage().reload(); }); //Set the buttons to the left side of the page. setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.START); back.addThemeVariants(ButtonVariant.LUMO_PRIMARY); //add the grid, remove button, add button, edit button, and back button add(userGrid,remove,form,add, edit, back); } }
java
21
0.703694
152
28.478764
259
starcoderdata
/* Copyright 2019 HAProxy Technologies Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package parsers import ( "strings" "github.com/haproxytech/config-parser/v4/common" "github.com/haproxytech/config-parser/v4/errors" "github.com/haproxytech/config-parser/v4/types" ) type HTTPCheckV2 struct { data []types.HTTPCheckV2 preComments []string // comments that appear before the the actual line } func (h *HTTPCheckV2) parse(line string, parts []string, comment string) (*types.HTTPCheckV2, error) { if len(parts) < 2 { return nil, &errors.ParseError{Parser: "HttpCheck", Line: line} } hc := &types.HTTPCheckV2{ Comment: comment, Type: parts[1], } if len(parts) == 2 { return hc, nil } if len(parts) > 3 { if parts[2] == "!" { hc.ExclamationMark = true hc.Match = parts[3] hc.Pattern = strings.Join(parts[4:], " ") return hc, nil } hc.Match = parts[2] hc.Pattern = strings.Join(parts[3:], " ") return hc, nil } return nil, &errors.ParseError{Parser: "HttpCheck", Line: line} } func (h *HTTPCheckV2) Result() ([]common.ReturnResultLine, error) { if len(h.data) == 0 { return nil, errors.ErrFetch } result := make([]common.ReturnResultLine, len(h.data)) for index, c := range h.data { var sb strings.Builder sb.WriteString("http-check") if c.Type != "" { sb.WriteString(" ") sb.WriteString(c.Type) } if c.ExclamationMark { sb.WriteString(" !") } if c.Match != "" { sb.WriteString(" ") sb.WriteString(c.Match) } if c.Pattern != "" { sb.WriteString(" ") sb.WriteString(c.Pattern) } result[index] = common.ReturnResultLine{ Data: sb.String(), Comment: c.Comment, } } return result, nil }
go
13
0.681299
102
23.573034
89
starcoderdata
@Override public void drawPanel(int mx, int my, float partialTick) { IGuiRect bounds = this.getTransform(); GlStateManager.pushMatrix(); GlStateManager.color(1F, 1F, 1F, 1F); int curState = !isActive()? 0 : (bounds.contains(mx, my)? 2 : 1); if(curState == 2 && pendingRelease && Mouse.isButtonDown(0)) { curState = 0; } IGuiTexture t = texStates[curState]; if(t != null) // Support for text or icon only buttons in one or more states. { t.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); } if(texIcon != null) { int isz = Math.min(bounds.getHeight() - icoPadding, bounds.getWidth()- icoPadding); if(isz > 0) { if(colIcon != null) { texIcon.drawTexture(bounds.getX() + (bounds.getWidth() / 2) - (isz / 2), bounds.getY() + (bounds.getHeight() / 2) - (isz / 2), isz, isz, 0F, partialTick, colIcon); } else { texIcon.drawTexture(bounds.getX() + (bounds.getWidth() / 2) - (isz / 2), bounds.getY() + (bounds.getHeight() / 2) - (isz / 2), isz, isz, 0F, partialTick); } } } if(btnText != null && btnText.length() > 0) { drawCenteredString(Minecraft.getMinecraft().fontRenderer, btnText, bounds.getX() + bounds.getWidth()/2, bounds.getY() + bounds.getHeight()/2 - 4, colStates[curState].getRGB(), txtShadow); } GlStateManager.popMatrix(); }
java
18
0.626705
190
31.418605
43
inline
@GetMapping("/activityList") // load activity list page public String activityList(Model model){ model.addAttribute("loggerName", indexLoginBO.getEmployeeByIdNo(SuperController.idNo)); List<EmployeeDTO> p = manageBO.findAllUser(); // find all employees model.addAttribute("loadAllUsers", p); // load employee details List<ActivityListDTO> p1 = humanResourceBO.findAllActivity(); model.addAttribute("listAllActivity", p1); return "activityList"; }
java
9
0.703777
95
49.4
10
inline
int(input()) num = input().split() i = 1 ok = True for n in num: if n != "mumble" and i != int(n): ok = False i += 1 print("makes sense" if ok else "something is fishy")
python
8
0.576037
52
17.166667
12
starcoderdata
import os import fnmatch class SourceFile: def __init__(self): self.extensions = ['*.c', '*.h', '*.C', '*.H', '*.c++', '*.cc', '*.cp', '*.cpp', '*.cxx', '*.h++', '*.hh', '*.hp', '*.hpp', '*.hxx'] def locate(self, root): '''Locate all C/C++ files matching extensions attribute. ''' for path, dirs, files in os.walk(os.path.relpath(root)): for extension in self.extensions: for filename in fnmatch.filter(files, extension): yield os.path.join(os.path.relpath(path), filename)
python
18
0.478964
71
37.625
16
starcoderdata
int read_temp_sensor(uint32_t *temp) { xSemaphoreTake(s_temp_i2c_mutex, portMAX_DELAY); int rv = i2c_read_temp(temp); if (rv == -1) { // BUG: Semaphore should have been released here! return rv; } xSemaphoreGive(s_temp_i2c_mutex); return 0; }
c
7
0.656489
53
25.3
10
inline
package ch.heigvd.amt.gamyval.service.daos; import ch.heigvd.amt.gamyval.models.entities.Account; import ch.heigvd.amt.gamyval.models.entities.Role; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.persistence.NoResultException; @Stateless public class AccountDAO extends GenericDAO<Account, Long> implements AccountDAOLocal { @EJB RoleDAOLocal roleDAO; @Override public Account authenticate(String email, String password) { try { return (Account) em.createNamedQuery("Account.authenticate") .setParameter("email", email) .setParameter("password", password) .getSingleResult(); } catch (NoResultException e) { return null; } } @Override public void addRole(String email, String role) { Account account = getFromEmail(email); Role r = roleDAO.getFromNameCreate(role); account.addRole(r); } @Override public Account getFromEmail(String email) { try { return (Account) em.createNamedQuery("Account.getFromEmail") .setParameter("email", email) .getSingleResult(); } catch (NoResultException e) { return null; } } }
java
13
0.642556
127
29.956522
46
starcoderdata
using System; using System.IO; using System.Threading.Tasks; using FlaUI.Core; using FlaUI.Core.Capturing; using FlaUI.Core.Logging; using FlaUI.Core.Tools; using NUnit.Framework; using NUnit.Framework.Interfaces; namespace FlaUI.TestUtilities { /// /// Base class for ui tests with some helper methods. /// This class allows recording videos, taking screen shots on failed tests and /// starts and stops the application under test for each test or fixture. /// public abstract class FlaUITestBase { /// /// Member which holds the current video recorder. /// private VideoRecorder _recorder; /// /// The name of the current test method. Used for the video recorder. /// private string _testMethodName; /// /// Instance of the current used automation object. /// protected AutomationBase Automation { get; private set; } /// /// Instance of the current running application. /// protected Application Application { get; set; } /// /// Specifies the starting mode of the application to test. /// Defaults to OncePerTest. /// protected virtual ApplicationStartMode ApplicationStartMode => ApplicationStartMode.OncePerTest; /// /// Flag to indicate if videos should be kept even if the test did not fail. /// Defaults to false. /// protected virtual bool KeepVideoForSuccessfulTests => false; /// /// Specifies the mode of the video recorder. /// Defaults to OnePerTest. /// protected virtual VideoRecordingMode VideoRecordingMode => VideoRecordingMode.OnePerTest; /// /// Path of the directory for the screenshots and videos for the tests. /// Defaults to c:\temp\testsmedia. /// protected virtual string TestsMediaPath => @"c:\temp\testsmedia"; /// /// Gets the automation instance that should be used. /// protected abstract AutomationBase GetAutomation(); /// /// Starts the application which should be tested. /// protected abstract Application StartApplication(); /// /// Setup method for the test fixture. /// [OneTimeSetUp] public virtual async Task UITestBaseOneTimeSetUp() { Logger.Default = new NUnitProgressLogger(); Automation = GetAutomation(); if (VideoRecordingMode == VideoRecordingMode.OnePerFixture) { await StartVideoRecorder(SanitizeFileName(TestContext.CurrentContext.Test.FullName)); } if (ApplicationStartMode == ApplicationStartMode.OncePerFixture) { Application = StartApplication(); } } /// /// Teardown method of the test fixture. /// [OneTimeTearDown] public virtual async Task UITestBaseOneTimeTearDown() { if (VideoRecordingMode == VideoRecordingMode.OnePerFixture) { StopVideoRecorder(); } if (ApplicationStartMode == ApplicationStartMode.OncePerFixture) { CloseApplication(); } if (Automation != null) { Automation.Dispose(); Automation = null; } } /// /// Setup method for each test. /// [SetUp] public virtual async Task UITestBaseSetUp() { // Due to the recorder running in an own thread, it is necessary to save the current method name for that thread _testMethodName = TestContext.CurrentContext.Test.MethodName; if (VideoRecordingMode == VideoRecordingMode.OnePerTest) { await StartVideoRecorder(SanitizeFileName(TestContext.CurrentContext.Test.FullName)); } if (ApplicationStartMode == ApplicationStartMode.OncePerTest) { Application = StartApplication(); } } /// /// Teardown method for each test. /// [TearDown] public virtual async Task UITestBaseTearDown() { if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed) { TakeScreenShot(TestContext.CurrentContext.Test.FullName); } if (ApplicationStartMode == ApplicationStartMode.OncePerTest) { CloseApplication(); } if (VideoRecordingMode == VideoRecordingMode.OnePerTest) { StopVideoRecorder(); } _testMethodName = null; } /// /// Closes and starts the application. /// protected void RestartApplication() { CloseApplication(); Application = StartApplication(); } /// /// Closes the application. /// private void CloseApplication() { if (Application != null) { Application.Close(); Retry.WhileFalse(() => Application.HasExited, TimeSpan.FromSeconds(2), ignoreException: true); Application.Dispose(); Application = null; } } /// /// Method which captures the image for the video and screen shots. /// By default captures the main screen. /// protected virtual CaptureImage CaptureImage() { return Capture.MainScreen(); } /// /// Method which allows customizing the settings for the video recorder. /// By default downloads ffmpeg and sets the path to ffmpeg. /// protected virtual async Task AdjustRecorderSettings(VideoRecorderSettings videoRecorderSettings) { // Download FFMpeg var ffmpegPath = await VideoRecorder.DownloadFFMpeg(@"C:\temp"); videoRecorderSettings.ffmpegPath = ffmpegPath; } /// /// Starts the video recorder. /// /// <param name="videoName">The unique name of the video file. private async Task StartVideoRecorder(string videoName) { // Refresh all the system information SystemInfo.RefreshAll(); // Start the recorder var videoRecorderSettings = new VideoRecorderSettings { VideoFormat = VideoFormat.xvid, VideoQuality = 6, TargetVideoPath = Path.Combine(TestsMediaPath, $"{SanitizeFileName(videoName)}.avi") }; await AdjustRecorderSettings(videoRecorderSettings); _recorder = new VideoRecorder(videoRecorderSettings, r => { var testName = TestContext.CurrentContext.Test.ClassName + "." + (_testMethodName ?? "[SetUp]"); var img = CaptureImage(); img.ApplyOverlays(new InfoOverlay(img) { RecordTimeSpan = r.RecordTimeSpan, OverlayStringFormat = @"{rt:hh\:mm\:ss\.fff} / {name} / CPU: {cpu} / RAM: {mem.p.used}/{mem.p.tot} ({mem.p.used.perc}) / " + testName }, new MouseOverlay(img)); return img; }); await Task.Delay(500); } /// /// Stops the video recorder. /// private void StopVideoRecorder() { if (_recorder != null) { _recorder.Stop(); if (!KeepVideoForSuccessfulTests && TestContext.CurrentContext.Result.FailCount == 0) { File.Delete(_recorder.TargetVideoPath); } _recorder.Dispose(); _recorder = null; } } /// /// Takes a screen shot. /// private void TakeScreenShot(string testName) { var imageName = SanitizeFileName(testName) + ".png"; imageName = imageName.Replace("\"", String.Empty); var imagePath = Path.Combine(TestsMediaPath, imageName); try { Directory.CreateDirectory(TestsMediaPath); CaptureImage().ToFile(imagePath); } catch (Exception ex) { Logger.Default.Warn("Failed to save screen shot to directory: {0}, filename: {1}, Ex: {2}", TestsMediaPath, imagePath, ex); } } /// /// Replaces all invalid characters with underlines. /// private string SanitizeFileName(string fileName) { fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars())); return fileName; } } }
c#
23
0.554618
153
33.238267
277
starcoderdata
n, k = map(int, input().split()) v = list(map(int, input().split())) ans = 0 for a in range(min(n, k)+1): for b in range(min(n, k)-a+1): bag = [] bag += v[:a] bag += v[len(v)-b:] bag.sort() if len(bag) > 0: for c in range(k-a-b): if bag[0] < 0: bag.pop(0) if len(bag) == 0: break ans = max(ans, sum(bag)) print(ans)
python
14
0.451282
35
20.722222
18
codenet
const { BackboneElementSchema } = require('./BackboneElement'); const { CodeableConceptSchema } = require('./allSchemaHeaders.js'); const { SubstanceSourceMaterialPartDescriptionSchema } = require('./allSchemaHeaders.js'); SubstanceSourceMaterialPartDescriptionSchema.add(BackboneElementSchema); SubstanceSourceMaterialPartDescriptionSchema.remove('id'); SubstanceSourceMaterialPartDescriptionSchema.add({ part: CodeableConceptSchema, partLocation: CodeableConceptSchema, }); module.exports.SubstanceSourceMaterialPartDescriptionSchema = SubstanceSourceMaterialPartDescriptionSchema;
javascript
6
0.845763
107
48.166667
12
starcoderdata
def get_message_headers(message: pypff.message) -> Optional[str]: """Takes a pypff.message object and returns its headers Args: message: A pypff.message object Returns: A string """ return message.transport_headers
python
6
0.594306
65
24.636364
11
inline
from sympy import I, symbols, Matrix from sympy.physics.quantum.commutator import Commutator as Comm from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.tensorproduct import TensorProduct as TP from sympy.physics.quantum.tensorproduct import tensor_product_simp from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.qubit import Qubit, QubitBra from sympy.physics.quantum.operator import OuterProduct from sympy.physics.quantum.density import Density from sympy.core.trace import Tr A, B, C = symbols('A,B,C', commutative=False) x = symbols('x') mat1 = Matrix([[1, 2*I], [1 + I, 3]]) mat2 = Matrix([[2*I, 3], [4*I, 2]]) def test_tensor_product_dagger(): assert Dagger(TensorProduct(I*A, B)) == \ -I*TensorProduct(Dagger(A), Dagger(B)) assert Dagger(TensorProduct(mat1, mat2)) == \ TensorProduct(Dagger(mat1), Dagger(mat2)) def test_tensor_product_abstract(): assert TP(x*A, 2*B) == x*2*TP(A, B) assert TP(A, B) != TP(B, A) assert TP(A, B).is_commutative is False assert isinstance(TP(A, B), TP) assert TP(A, B).subs(A, C) == TP(C, B) def test_tensor_product_expand(): assert TP(A + B, B + C).expand(tensorproduct=True) == \ TP(A, B) + TP(A, C) + TP(B, B) + TP(B, C) def test_tensor_product_commutator(): assert TP(Comm(A, B), C).doit().expand(tensorproduct=True) == \ TP(A*B, C) - TP(B*A, C) assert Comm(TP(A, B), TP(B, C)).doit() == \ TP(A, B)*TP(B, C) - TP(B, C)*TP(A, B) def test_tensor_product_simp(): assert tensor_product_simp(TP(A, B)*TP(B, C)) == TP(A*B, B*C) def test_issue_2824(): # most of the issue regarding sympification of args has been handled # and is tested internally by the use of args_cnc through the quantum # module, but the following is a test from the issue that used to raise. assert TensorProduct(1, Qubit('1')*Qubit('1').dual) == \ TensorProduct(1, OuterProduct(Qubit(1), QubitBra(1))) def test_eval_trace(): # This test includes tests with dependencies between TensorProducts #and density operators. Since, the test is more to test the behavior of #TensorProducts it remains here A, B, C, D, E, F = symbols('A B C D E F', commutative=False) # Density with simple tensor products as args t = TensorProduct(A, B) d = Density([t, 1.0]) tr = Tr(d) assert tr.doit() == 1.0*Tr(A*Dagger(A))*Tr(B*Dagger(B)) ## partial trace with simple tensor products as args t = TensorProduct(A, B, C) d = Density([t, 1.0]) tr = Tr(d, [1]) assert tr.doit() == 1.0*A*Dagger(A)*Tr(B*Dagger(B))*C*Dagger(C) tr = Tr(d, [0, 2]) assert tr.doit() == 1.0*Tr(A*Dagger(A))*B*Dagger(B)*Tr(C*Dagger(C)) # Density with multiple Tensorproducts as states t2 = TensorProduct(A, B) t3 = TensorProduct(C, D) d = Density([t2, 0.5], [t3, 0.5]) t = Tr(d) assert t.doit() == (0.5*Tr(A*Dagger(A))*Tr(B*Dagger(B)) + 0.5*Tr(C*Dagger(C))*Tr(D*Dagger(D))) t = Tr(d, [0]) assert t.doit() == (0.5*Tr(A*Dagger(A))*B*Dagger(B) + 0.5*Tr(C*Dagger(C))*D*Dagger(D)) #Density with mixed states d = Density([t2 + t3, 1.0]) t = Tr(d) assert t.doit() == ( 1.0*Tr(A*Dagger(A))*Tr(B*Dagger(B)) + 1.0*Tr(A*Dagger(C))*Tr(B*Dagger(D)) + 1.0*Tr(C*Dagger(A))*Tr(D*Dagger(B)) + 1.0*Tr(C*Dagger(C))*Tr(D*Dagger(D))) t = Tr(d, [1] ) assert t.doit() == ( 1.0*A*Dagger(A)*Tr(B*Dagger(B)) + 1.0*A*Dagger(C)*Tr(B*Dagger(D)) + 1.0*C*Dagger(A)*Tr(D*Dagger(B)) + 1.0*C*Dagger(C)*Tr(D*Dagger(D)))
python
16
0.594616
76
34.065421
107
starcoderdata
public bool IsActionPressed(Node source, string actionName) { if (!NetworkExt.IsNetworkEnabled(GetTree())) { return Input.IsActionPressed(actionName); } else { var myId = source.GetNetworkMaster(); if (myId == 1) { // Do not handle server input return false; } if (_PlayerInputs.ContainsKey(myId)) { return _PlayerInputs[myId].IsActionPressed(actionName); } else { return false; } } }
c#
14
0.509804
71
32.058824
17
inline
void TxUCMCollector::setCurrLogFile () { TRY { #ifdef FUTURE // // Read the status properties file, if it exists, to get // the last file that was not processed completely or was // not archived // if (new File (statusFile).exists ()) { Properties properties = new Properties(); properties.load (new FileInputStream (statusFile)); currLogFile = properties.getProperty (statusFileName); if (currLogFile != null) { const char * strTime = properties.getProperty (statusFileModTime); long longTime = (new Long (strTime)).longValue (); currLogFilePos = (new Long (properties.getProperty (statusFilePos))).longValue (); // Sleep if the file being processed has not changed if (new File (currLogFile).exists ()) { while (true) { if (new File (currLogFile).lastModified () == longTime) { System.out.println ("Waiting for " + currLogFile + " to be updated..."); log->info ("Waiting for " + currLogFile + " to be updated..."); Thread.sleep (sleepTime * 1000); } else { break; } } } // Seems like the status file is outdated. Delete it else { new File (statusFile).delete (); } } } // // Look at the logs dir for new files // currLogFile = ""; currLogFilePos = 0; File logFileDir = new File (logsDir); while (true) { FilenameFilter filter = new FilenameFilter() { boolean accept (File file, const char * name) { return name.endsWith (".log"); } }; File[] logFiles = logFileDir.listFiles (filter); System.out.println ("Found " + logFiles.length + " log files in " + logsDir); log->info ("Found " + logFiles.length + " log files in " + logsDir); // If there are log files available to be processed, // find the oldest one and continue processing it. if (logFiles.length > 0) { File file = logFiles [0]; for (int i = 1; i < logFiles.length; i++) { if (file.lastModified () > logFiles [i].lastModified ()) { file = logFiles [i]; } } // oldest .log file in the logs dir is set to be processed currLogFile = file.toString (); break; } // If there are no log files available in the // directory, sleep for a while and check again else { System.out.println ("Waiting for new log files in " + logsDir); log->info ("Waiting for new log files in " + logsDir); Thread.sleep (sleepTime * 1000); } } #endif }
c++
20
0.4384
100
40.86747
83
inline
from functools import lru_cache from typing import List, Union from pydantic import AnyHttpUrl, BaseSettings, validator from pydantic.fields import Field class Settings(BaseSettings): API_V1_STR: str = "/api/v1" BACKEND_CORS_ORIGINS: Union[str, List[AnyHttpUrl]] = Field( default=[ "http://localhost", "http://localhost:8080", "https://localhost", ] ) PROJECT_NAME: str = "face-authentication" SQLDB_URI: str = "sqlite:///sqlite3.db" FACE_API_ENDPOINT: str = "" FACE_API_KEY: str = "" FACE_API_GROUP: str = "" OAUTH_AUTH_URL: str = "/api/v1/authorize" OAUTH_TOKEN_URL: str = "/api/v1/token" AUTH_ALGORITHM: str = "HS256" AUTH_SECRET_KEY: str = " AUTH_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 class Config: case_sensitive = True @validator("BACKEND_CORS_ORIGINS", pre=True) @classmethod def _assemble_cors_origins(cls, cors_origins): if isinstance(cors_origins, str): return [item.strip() for item in cors_origins.split(",")] return cors_origins @lru_cache() def get_settings() -> Settings: return Settings()
python
14
0.622354
69
25.840909
44
starcoderdata
console.log("in url reducer"); export default(state = [], payload) => { switch(payload.type){ case 'concat': return payload.url; default: return state; } };
javascript
9
0.453782
40
15.142857
14
starcoderdata
// // CodeGenerator.h // // Library: CodeGeneration // Package: CodeGeneration // Module: CodeGenerator // // Definition of the CodeGenerator class. // // Copyright (c) 2006-2014, Applied Informatics Software Engineering GmbH. // All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // #ifndef CodeGeneration_CodeGenerator_INCLUDED #define CodeGeneration_CodeGenerator_INCLUDED #include "Poco/CodeGeneration/CodeGeneration.h" #include "Poco/CppParser/Struct.h" #include "Poco/CppParser/Variable.h" #include "Poco/CppParser/TypeDef.h" #include #include namespace Poco { namespace CodeGeneration { class CodeGeneration_API CodeGenerator /// A CodeGenerator defines an interface for code generators. { public: struct FwdDecl { std::string includeFile; std::string className; std::string fullNameSpace; FwdDecl(const std::string& inc, const std::string& cN, const std::string& ns); bool operator<(const FwdDecl& other) const; /// Must guarantee that the primary order is by namespace, then by class }; typedef std::set IncludeSet; typedef std::map<std::string, std::string> Properties; /// Maps a property name to its value. typedef std::set FwdDecls; CodeGenerator(const std::string& nameSpace, const std::string& libraryName, bool usePocoIncludeStyle, const std::string& copyright); /// Creates the CodeGenerator. The nameSpace declares in which nameSpace the generated class will be, /// the library name contaisn the name of the project virtual ~CodeGenerator(); /// Destroys the CodeGenerator. virtual void addIncludeFile(const std::string& incFile); /// Adds an include file to the CodeGenerator. A call to this method is only meaningful until structStart was not called. /// Duplicate includes will be ignored. Contains the include path only, e.g. "include/MyClass.h" (without enclosing ") virtual void addSrcIncludeFile(const std::string& incFile); /// Include file which will be written to an implementation file. virtual void addSystemIncludeFile(const std::string& incFile); /// Adds a system include file virtual void addFwdDecl(const std::string& inclFile, const std::string& className, const std::string namespacePrefix); /// Adds a fwd decl. virtual void writeIncludes(); /// Convenience Functions which calls for all include files writeInclude, also writes fwdDecls. virtual void writeDefaultHeader(const Poco::CppParser::Struct* pStruct, const std::string& className, const std::string& libraryName, const std::string& package) = 0; /// Writes the default header, e.g. copyright notice, no include namespace open or anything else is written /// This is always the first method that is called! virtual void endFile() = 0; /// Closes the file. virtual void writeInclude(const std::string& include, bool toHeader) = 0; /// Writes the include either to the header or the src file. virtual void writeSystemInclude(const std::string& include) = 0; /// Writes the system include file to the header. virtual void writeNameSpaceBegin(const std::string& fullNameSpace) = 0; /// Writes the enclosing namespace virtual void writeFwdDecls(const FwdDecls& decl) = 0; /// Writes the fwd decl to the header file and the include file to the src file. virtual void writeNameSpaceEnd(const std::string& fullNameSpace) = 0; /// Closes the namespace virtual void structStart(const Poco::CppParser::Struct* pStruct, const CodeGenerator::Properties& properties) = 0; /// Writes the class declaration. virtual void structEnd() = 0; /// Closes the class declaration. virtual void methodStart(const Poco::CppParser::Function* pFunc, const CodeGenerator::Properties& properties) = 0; /// Writes the method header. Properties contains the properties found in the functions docuementation and in the class documentation. virtual void writeMethodImplementation(const std::string& code) = 0; /// Only valid when inside a method. Simply forwards the code lines to the implementation file. virtual void writeImplementation(const std::string& code) = 0; /// Writes other non-method code. virtual void methodEnd(const Poco::CppParser::Function* pFunc, const CodeGenerator::Properties& properties) = 0; /// Closes the method. virtual void variablesStart() = 0; /// Indicates that variables wil be written. virtual void variable(const Poco::CppParser::Variable* pVar) = 0; /// Writes a single variable. virtual void writeTypeDef(const Poco::CppParser::TypeDef* pType) = 0; /// Writes a single typedef virtual void variablesEnd() = 0; /// Ends variable definitions. virtual const CodeGenerator::IncludeSet& includes() const; /// Returns all includes that the CodeGenerator consists of. virtual const CodeGenerator::IncludeSet& systemIncludes() const; /// Returns all system includes that the CodeGenerator consists of. virtual const std::string& nameSpace() const; /// The namespace of the file virtual const std::string& libraryName() const; /// The prefix assigned to the namespace. virtual bool usePocoIncludeStyle() const; /// Returns which include style should be used virtual const std::string& copyright() const; /// Returns the copyright notice, can be empty. private: std::string _nameSpace; std::string _libraryName; bool _usePocoIncludeStyle; std::string _copyright; IncludeSet _includes; IncludeSet _systemIncludes; IncludeSet _srcIncludes; FwdDecls _fwdDecls; }; inline void CodeGenerator::addIncludeFile(const std::string& incFile) { _includes.insert(incFile); } inline void CodeGenerator::addSrcIncludeFile(const std::string& incFile) { _srcIncludes.insert(incFile); } inline void CodeGenerator::addSystemIncludeFile(const std::string& incFile) { _systemIncludes.insert(incFile); } inline const CodeGenerator::IncludeSet& CodeGenerator::includes() const { return _includes; } inline const CodeGenerator::IncludeSet& CodeGenerator::systemIncludes() const { return _systemIncludes; } inline const std::string& CodeGenerator::nameSpace() const { return _nameSpace; } inline const std::string& CodeGenerator::libraryName() const { return _libraryName; } inline bool CodeGenerator::usePocoIncludeStyle() const { return _usePocoIncludeStyle; } inline const std::string& CodeGenerator::copyright() const { return _copyright; } } } // namespace Poco::CodeGeneration #endif // CodeGeneration_CodeGenerator_INCLUDED
c
12
0.750233
167
29.140187
214
starcoderdata
'use strict'; module.exports = { packageWarningMsg: packageWarningMsg, isHaveChecked: isHaveChecked, inTripletExpressionHaveChecked: inTripletExpressionHaveChecked, inIfStatementHaveChecked: inIfStatementHaveChecked, isLogicalRightExpression: isLogicalRightExpression, isLeftExpressionHaveChecked: isLeftExpressionHaveChecked, isArgumentsHit: isArgumentsHit, getObjectFirstName: getObjectFirstName, isInWhiteList: isInWhiteList }; function packageWarningMsg(object) { var msg = ''; if (object.object.name && object.property.name) { msg = object.object.name + '.' + object.property.name + ' could be null, would cause NullReferenceException error'; } return msg; } function getObjectFirstName(node) { if (!node.object) { return node.type === 'ThisExpression' ? 'this' : node.name; } var tNode = node; while (!tNode.name && tNode.object) { if (!tNode.object) { tNode = { name: tNode.type === 'ThisExpression' ? 'this' : '' }; break; } else { tNode = tNode.object; } } return tNode.type === 'ThisExpression' ? 'this' : tNode.name;; } function getObjectSecondName(node) { if (!node.object) { return node.name; } var tNode = node; while (tNode.object && tNode.object.type !== 'ThisExpression' && tNode.object.type !== 'Identifier') { tNode = tNode.object; if (!tNode) { tNode = { name: '' }; break; } } return tNode.property ? tNode.property.name : ''; } function isInWhiteList(whiteList, node) { var result = false; if (whiteList.includes(getObjectFirstName(node.object))) { result = true; } else if (whiteList.filter(function (x) { return x.includes('.').length; })) { var deepWhite = whiteList.filter(function (x) { return x.includes('.'); }); deepWhite.forEach(function (target) { var first = target.split('.')[0]; var second = target.split('.')[1]; var targetName = first + '.' + second; if (first === getObjectFirstName(node) && getObjectSecondName(node) === second) { result = true; } }); } return result; } function isHaveChecked(parent, node) { return inTripletExpressionHaveChecked(parent, node) || inIfStatementHaveChecked(parent, node) || inUnaryOrBinaryExpressionHaveChecked(parent, node); } function inUnaryOrBinaryExpressionHaveChecked(parent, node) { var result = false; var types = ['UnaryExpression', 'BinaryExpression']; if (types.includes(node.parent.type) && node.parent.parent.right === node.parent) { var hitLintObjectName = getObjectNameDeeply(node); result = isLeftExpressionHaveChecked(parent, node.parent, hitLintObjectName); } return result; } function inTripletExpressionHaveChecked(rootparent, node) { var result = false; if (node.parent.type === 'ConditionalExpression') { var test = node.parent.test; if (test && test.object && test.property) { var testObjectName = getObjectNameDeeply({ object: test }); var hitLintObjectName = getObjectNameDeeply(node); result = testObjectName === hitLintObjectName; } else if (test && test.left && test.right) { return isLeftExpressionHaveChecked(rootparent, test.right); } } return result; } function inIfStatementHaveChecked(rootparent, node) { var result = false; var findCount = 0; var parent = node.parent; while (!result && parent.parent && findCount < 3) { parent = findBlockParentNodeRecursively(parent); result = unitIfExpressionChecked(rootparent, parent, node); findCount++; if (parent) { parent = parent.parent; } else { parent = null; break; } } return result; } function findBlockParentNodeRecursively(parent) { while (parent.type !== 'BlockStatement') { parent = parent.parent; if (!parent) break; } return parent; } function unitIfExpressionChecked(rootparent, parent, node) { var result = false; if (parent && parent.parent && parent.parent.type === 'IfStatement' && parent.parent.test && parent.parent.alternate !== parent) { var testObjectName = ''; var hitLintObjectName = getObjectNameDeeply(node); var testNode = parent.parent.test; if (testNode.left && testNode.right) { var right = testNode.right; var left = testNode.left; if (right.object && right.property) { testObjectName = getObjectNameDeeply(right); if (testObjectName !== hitLintObjectName && testNode.left.left) { return isLeftExpressionHaveChecked(rootparent, testNode.right, hitLintObjectName); } } else if (right.left) { testObjectName = getObjectNameDeeply(right.left); } else if (right.right) { testObjectName = getObjectNameDeeply(right.right); } else { testObjectName = getObjectNameDeeply(left); } if (testObjectName !== hitLintObjectName) { if (left.left && left.left.object && getObjectNameDeeply(left.left) === hitLintObjectName) { testObjectName = getObjectNameDeeply(left.left); } else if (left.right && left.right.object && getObjectNameDeeply(left.right) === hitLintObjectName) { testObjectName = getObjectNameDeeply(left.right); } } } else if (testNode.object) { testObjectName = testNode.object.name + '.' + testNode.property.name; } result = testObjectName === hitLintObjectName; } return result; } function isLeftExpressionHaveChecked(rootparent, node, hitName) { var result = false; var hitLintObjectName = hitName ? hitName : getObjectNameDeeply(node); var testObjectName = ''; if (node.parent && node.parent.left) { var leftNode = node.parent.left; if (!leftNode.left && leftNode.object && leftNode.property) { testObjectName = getObjectNameDeeply({ object: leftNode }); result = testObjectName === hitLintObjectName; } else if (!leftNode.left && leftNode.argument && leftNode.argument.object && leftNode.argument.property) { testObjectName = getObjectNameDeeply({ object: leftNode.argument }); result = testObjectName === hitLintObjectName; } else { if (leftNode.right && leftNode.right.type === 'MemberExpression' && leftNode.right.object && leftNode.right.property) { testObjectName = getObjectNameDeeply({ object: leftNode.right }); if (testObjectName === hitLintObjectName) { result = true; return result; } } var tempLeft = leftNode.left; while (tempLeft && tempLeft.left) { tempLeft = tempLeft.left; if (tempLeft) { var tempRight = tempLeft.parent.right; if (tempRight.object && tempRight.property) { testObjectName = getObjectNameDeeply({ object: tempRight }); if (testObjectName === hitLintObjectName) { result = true; break; } } } else { tempLeft = tempLeft.parent; break; } } if (!result && tempLeft && tempLeft.object && tempLeft.property) { testObjectName = getObjectNameDeeply({ object: tempLeft }); result = testObjectName === hitLintObjectName; } } } return result; } // TODO: use traverseTree to make code clean // function traverseLogicalTree (node) { // if (node.left) { // traverseLogicalTree(node.left); // traverseLogicalTree(node.right); // } else { // console.log (node) // } // } function isLogicalRightExpression(parent, node) { if (node.parent.type === 'LogicalExpression' && node.parent.right === node) { return isLeftExpressionHaveChecked(parent, node); } else { var checkNode = node.parent.parent; while (checkNode.type !== 'LogicalExpression') { checkNode = checkNode.parent; if (!checkNode.parent) { checkNode = null; break; } } if (checkNode && checkNode.right) { return isLeftExpressionHaveChecked(parent, checkNode.right); } return false; } } function isArgumentsHit(node) { var result = false; if (node.parent && node.parent.arguments && node.parent.arguments[0] && node.parent.arguments[0] === node) { result = true; } return result; } function getObjectNameDeeply(node) { var name = ''; if (node.object && node.object.name && node.property && node.property.name) { name = node.object.name + '.' + node.property.name; } else { var target = node.object; if (target && target.object && target.property && target.object.name && target.property.name) { name = target.object.name + '.' + target.property.name; } else if (target && target.object && !target.object.name && target.object.type === 'ThisExpression') { name = 'this.' + target.property.name; } else if (target && target.object && !target.object.name && target.object.object && target.object.property) { name = target.object.object.name + '.' + target.object.property.name; } } return name; }
javascript
22
0.585283
152
36.605263
266
starcoderdata
import React from "react"; import { Switch, Route, Redirect } from "react-router-dom"; import SignIn from "./components/Auth Pages/SignIn"; import HomePageLayout from "./layouts/HomePageLayout"; import SignUp from "./components/Auth Pages/SignUp"; import Settings from "./components/Settings Page/Settings"; import NewPost from "./components/NewPost"; import Profile from "./components/Profile Page/Profile"; import ArticleDisplay from "./components/Article Pages/ArticleDisplay"; import PrivateRoute from "./PrivateRoute"; import NavBar from "./components/NavBar"; function Routes() { return ( <> <NavBar /> <Route exact path="/signin" component={SignIn} /> <Route exact path="/signup" component={SignUp} /> <PrivateRoute path="/settings"> <Settings /> <PrivateRoute exact path="/newpost"> <NewPost /> <Route exact path="/profile/:username"> <Profile /> <Route exact path="/articles/:slug" component={ArticleDisplay} /> <Route exact path="/"> <Redirect to="/globalfeed" /> <Route component={HomePageLayout} /> ); } export default Routes;
javascript
11
0.643021
73
31.775
40
starcoderdata
import { graphql, useStaticQuery } from "gatsby" // import {TransitionLink} from 'gatsby-plugin-transition-link' import AniLink from "gatsby-plugin-transition-link/AniLink" import "./scss/_partials/grids.scss" import React from "react" const BlogList = () => { const { allMdx } = useStaticQuery( graphql` query bloglistQuery { allMdx(filter: {frontmatter: {isBlog: {eq: true}}}) { edges { node { fields { slug } frontmatter { blogTitle blogSubtitle title date } id excerpt(pruneLength: 50) } } } } ` ) // console.log(allMdx) return ( <> <div className="wrap-1 sf-1"> <section className="landing-work_list"> <h2 className="vis-hide">Work <div className="display"> {/* something */} {/* Start generative code here */} {allMdx.edges.map(({ node }) => ( <div key={node.id} className="blog-item"> <AniLink cover to={node.fields.slug} direction="down" bg="#ffffff" duration={1.5} className="blog-link" > <h3 className="blog-title"> {node.frontmatter.title}{" "} <span className="blog-date"> - {node.frontmatter.date} ))} {/* End generative code */} ) } export default BlogList
javascript
22
0.342438
69
34.550725
69
starcoderdata
def download_bedroom(download_path): """ This code is partially borrowed from https://github.com/fyu/lsun/blob/master/download.py """ import lmdb category = 'bedroom' set_name = 'train' data_dir = os.path.join(download_path, category) num_total_images = 3033042 if os.path.exists(data_dir): if len(glob(os.path.join(data_dir, "*.webp"))) == 3033042: print('Bedroom was downloaded.') return else: print('Bedroom was downloaded but some files are missing.') else: os.mkdir(data_dir) if not os.path.exists("bedroom_train_lmdb/"): url = 'http://lsun.cs.princeton.edu/htbin/download.cgi?tag={}' \ '&category={}&set={}'.format('latest', category, set_name) cmd = ['curl', url, '-o', 'bedroom.zip'] print('Downloading', category, set_name, 'set') subprocess.call(cmd) print('Unzipping') cmds = [['unzip', 'bedroom.zip'], ['rm', 'bedroom.zip']] for cmd in cmds: subprocess.call(cmd) else: print("lmdb files are downloaded and unzipped") # export the lmdb file to data_dir print("Extracting .webp files from lmdb file") env = lmdb.open('bedroom_train_lmdb', map_size=1099511627776, max_readers=100, readonly=True) count = 0 with env.begin(write=False) as txn: cursor = txn.cursor() for key, val in cursor: try: image_out_path = os.path.join(data_dir, key + '.webp') with open(image_out_path, 'w') as fp: fp.write(val) except: image_out_path = os.path.join(data_dir, key.decode() + '.webp') with open(image_out_path, 'wb') as fp: fp.write(val) count += 1 if count % 1000 == 0: print('Finished {}/{} images'.format(count, num_total_images)) cmd = ['rm', '-rf', 'bedroom_train_lmdb'] subprocess.call(cmd)
python
17
0.551061
79
36.555556
54
inline
package stubidp.test.utils.httpstub; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; import java.util.Optional; public abstract class StubHandler extends AbstractHandler { protected void respondWith(Request baseRequest, HttpServletResponse response, RegisteredResponse registeredResponse) { response.setStatus(registeredResponse.status()); for (Map.Entry<String, String> headerEntry : registeredResponse.headers().entrySet()) { response.setHeader(headerEntry.getKey(), headerEntry.getValue()); } response.setContentType(registeredResponse.contentType()); try { response.getWriter().append(registeredResponse.body()); } catch (IOException e) { throw new RuntimeException(e); } baseRequest.setHandled(true); } @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response){ RecordedRequest recordedRequest = new RecordedRequest(baseRequest); recordRequest(recordedRequest); findResponse(recordedRequest).ifPresent(requestAndResponse -> { requestAndResponse.addCall(); respondWith(baseRequest, response, requestAndResponse.getResponse()); }); } protected abstract Optional findResponse(ReceivedRequest recordedRequest); protected abstract void recordRequest(RecordedRequest recordedRequest); }
java
15
0.73821
122
40.35
40
starcoderdata
package org.jboss.resteasy.jsapi; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; import org.jboss.resteasy.core.ResourceMethodRegistry; import org.jboss.resteasy.jsapi.i18n.LogMessages; import org.jboss.resteasy.jsapi.i18n.Messages; import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; import org.jboss.resteasy.spi.ResteasyDeployment; import org.jboss.resteasy.spi.ResteasyProviderFactory; /** * @author */ public class JSAPIServlet extends HttpServlet { //corresponding to RFC 4329 this is the right MEDIA_TYPE private static final String JS_MEDIA_TYPE = "application/javascript"; private static final long serialVersionUID = -1985015444704126795L; private Map<String, ServiceRegistry> services; private JSAPIWriter apiWriter = new JSAPIWriter(); @Override public void init(ServletConfig config) throws ServletException { super.init(config); if (LogMessages.LOGGER.isDebugEnabled()) LogMessages.LOGGER.info(Messages.MESSAGES.loadingJSAPIServlet()); try { scanResources(); } catch (Exception e) { throw new ServletException(e); } if (LogMessages.LOGGER.isDebugEnabled()) LogMessages.LOGGER.debug(Messages.MESSAGES.jsapiServletLoaded()); // make it possible to get to us for rescanning ServletContext servletContext = config.getServletContext(); servletContext.setAttribute(getClass().getName(), this); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String uri = req.getRequestURL().toString(); uri = uri.substring(0, uri.length() - req.getServletPath().length()); if (LogMessages.LOGGER.isDebugEnabled()) { LogMessages.LOGGER.debug(Messages.MESSAGES.serving(pathInfo)); LogMessages.LOGGER.debug(Messages.MESSAGES.query(req.getQueryString())); } if (this.services == null) try { scanResources(); } catch (Exception e) { resp.sendError(503, Messages.MESSAGES.thereAreNoResteasyDeployments()); // FIXME should return internal error } if (this.services == null) { resp.sendError(503, Messages.MESSAGES.thereAreNoResteasyDeployments()); } resp.setContentType(JS_MEDIA_TYPE); this.apiWriter.writeJavaScript(uri, req, resp, services); } public void scanResources() throws Exception { ServletConfig config = getServletConfig(); ServletContext servletContext = config.getServletContext(); Map<String, ResteasyDeployment> deployments = (Map<String, ResteasyDeployment>) servletContext.getAttribute(ResteasyContextParameters.RESTEASY_DEPLOYMENTS); if (deployments == null) return; synchronized (this) { services = new HashMap<String, ServiceRegistry>(); for (Map.Entry<String, ResteasyDeployment> entry : deployments.entrySet()) { ResourceMethodRegistry registry = (ResourceMethodRegistry) entry.getValue().getRegistry(); ResteasyProviderFactory providerFactory = (ResteasyProviderFactory) entry.getValue().getProviderFactory(); ServiceRegistry service = new ServiceRegistry(null, registry, providerFactory, null); services.put(entry.getKey(), service); } } } }
java
15
0.693507
162
34.231481
108
starcoderdata
import defineVisitSet from './defineSets/defineVisitSet'; import defineVisitStatusSet from './defineSets/defineVisitStatusSet'; import defineLegendSet from './defineSets/defineLegendSet'; import defineDefaultSet from './defineSets/defineDefaultSet'; export default function defineSets() { [ 'site_col', 'id_col', 'id_status_col', 'visit_col', // with visit_order_col 'visit_status_col' // with visit_status_order_col, visit_status_color_col, and visit_status_description_col ].forEach(col => { switch (col) { case 'visit_col': defineVisitSet.call(this); break; case 'visit_status_col': defineVisitStatusSet.call(this); defineLegendSet.call(this); break; default: defineDefaultSet.call(this, col); break; } }); }
javascript
13
0.593555
115
33.357143
28
starcoderdata
public boolean performFinish() { // Saving the dialog settings page.saveDialogSettings(); // Getting the schemas to be exported and where to export them final Schema[] selectedSchemas = page.getSelectedSchemas(); final String exportDirectory = page.getExportDirectory(); try { getContainer().run( false, false, new IRunnableWithProgress() { public void run( IProgressMonitor monitor ) { monitor.beginTask( Messages.getString( "ExportSchemasAsOpenLdapWizard.ExportingSchemas" ), selectedSchemas.length ); //$NON-NLS-1$ for ( Schema schema : selectedSchemas ) { monitor.subTask( schema.getSchemaName() ); try { BufferedWriter buffWriter = new BufferedWriter( new FileWriter( exportDirectory + "/" //$NON-NLS-1$ + schema.getSchemaName() + ".schema" ) ); //$NON-NLS-1$ buffWriter.write( OpenLdapSchemaFileExporter.toSourceCode( schema ) ); buffWriter.close(); } catch ( IOException e ) { PluginUtils .logError( NLS .bind( Messages.getString( "ExportSchemasAsOpenLdapWizard.ErrorSavingSchema" ), new String[] { schema.getSchemaName() } ), //$NON-NLS-1$ e ); ViewUtils .displayErrorMessageDialog( Messages.getString( "ExportSchemasAsOpenLdapWizard.Error" ), NLS.bind( Messages.getString( "ExportSchemasAsOpenLdapWizard.ErrorSavingSchema" ), new String[] { schema.getSchemaName() } ) ); //$NON-NLS-1$ //$NON-NLS-2$ } monitor.worked( 1 ); } monitor.done(); } } ); } catch ( InvocationTargetException e ) { // Nothing to do (it will never occur) } catch ( InterruptedException e ) { // Nothing to do. } return true; }
java
26
0.452429
252
43.5
56
inline
// Gameover screen demo.gameover = function(){}; demo.gameover.prototype = { preload: function(){ // loadImages(); var tilemap_height = 650; game.world.setBounds(0, 0, 1000, tilemap_height); }, create: function(){ death_count += 1; // console.log(death_count); game.add.text(400,400,"Death Count: " + death_count); add_game_bg('bg2'); game.stage.backgroundColor = "#ffffff"; game.physics.startSystem(Phaser.Physics.Arcade); var style = {boundsAlignH: "center", boundsAlignV: "middle" } var gameovertext = game.add.sprite(500, 150, "game_over_txt"); gameovertext.anchor.setTo(0.5, 0.5); gameovertext.scale.setTo(1.2, 1.2); game.add.text(400,400,"Death Count: " + death_count); game.sound.stopAll(); disappointed.play('','',0.6); var style = {font: "30px Arial", fill: "Black"} var main_menu_option = game.add.sprite(300, 300, "main_menu_txt"); main_menu_option.anchor.setTo(0.5, 0.5); main_menu_option.inputEnabled = true; main_menu_option.events.onInputUp.add( function(){ game.state.start('menu'); } ); main_menu_option.events.onInputOver.add( function() { main_menu_option.scale.setTo(1.2, 1.2); } ); main_menu_option.events.onInputOut.add( function () { main_menu_option.scale.setTo(1, 1); } ); var style = {font: "30px Arial", fill: "Black"} var retry_pause_option = game.add.sprite(700, 300, "try_again_txt"); retry_pause_option.anchor.setTo(0.5, 0.5); retry_pause_option.inputEnabled = true; retry_pause_option.events.onInputUp.add( function(){ game.state.start(restart_state); } ); retry_pause_option.events.onInputOver.add( function() { retry_pause_option.scale.setTo(1.2, 1.2); } ); retry_pause_option.events.onInputOut.add( function () { retry_pause_option.scale.setTo(1, 1); } ); }, update: function(){ } };
javascript
15
0.519116
76
30.824324
74
starcoderdata
func downsampleBatch(data []sample, resolution int64, add func(int64, *aggregator)) int64 { var ( aggr aggregator nextT = int64(-1) lastT = data[len(data)-1].t ) // Fill up one aggregate chunk with up to m samples. for _, s := range data { if value.IsStaleNaN(s.v) { continue } if s.t > nextT { if nextT != -1 { add(nextT, &aggr) } aggr.reset() nextT = currentWindow(s.t, resolution) // Limit next timestamp to not go beyond the batch. A subsequent batch // may overlap in time range otherwise. // We have aligned batches for raw downsamplings but subsequent downsamples // are forced to be chunk-boundary aligned and cannot guarantee this. if nextT > lastT { nextT = lastT } } aggr.add(s.v) } // Add the last sample. add(nextT, &aggr) return nextT }
go
13
0.657283
91
24.5625
32
inline
int main(){ ios::sync_with_stdio(0); cin.tie(0); int arr[10]={0,1,2,3,4,5,6,7,8,9}; for(int x:arr){ //we read it as "for each x in arr." cout<<x<<"\n"; //here x refers to the values in arr, not the index. } cout<<"\n\n"; for (int x : arr) //here in each iteration x gets the copy of the value in the array. so, even if we do ++x the original values in the array aren't changed { cout << ++x << "\n"; } cout << "\n\n"; cout << "original array:\n"; for (int x : arr) { cout << x << "\n"; } cout << "\n\n"; for (int &x : arr) //if we want to change the actual values in array, we can use references for that. { cout << ++x << "\n"; } cout << "\n\n"; cout << "original array:\n"; for (int x : arr) { cout << x << "\n"; } return 0; }
c++
9
0.449522
159
26.705882
34
inline
import React from "react"; import util from "../util"; import CsrfInput from "../util/csrf-input"; import UpvoteTopicItem from "./upvote-topic-item"; export default class TopicsListItem extends React.Component { constructor (props) { super(props); this.state = { user: _pageData.user }; } renderUpvote () { const user = _pageData.user; if (!user) { return ""; } return <UpvoteTopicItem upvoted={this.upvoted} toggleVote={this.toggleVote.bind(this)} {...this.props} user={user}/> } get upvoted () { return this.props.votes.includes(this.state.user._id) } toggleVote (e) { util.post(`${this.props.url}/toggle-vote`, { topic: this.props._id }); e.preventDefault(); } renderAdminInfo () { if (window._pageData.isAdmin) { return <span className="post-info-section"> HackType: <span className="hack-type-name">{this.props.metadata.hack_type} } } renderEdit () { if (window._pageData.isAdmin || this.props.author._id === window._pageData.user._id) { return <span className="post-info-section"> <a href={`${this.props.url}/edit`}>Edit } return ""; } onDeleteIntent (e) { if (!confirm('Are you sure you wish to delete?')) { return e.preventDefault(); } } renderDelete () { if (window._pageData.isAdmin || this.props.author._id === window._pageData.user._id) { return <form onSubmit={this.onDeleteIntent} action={`${this.props.url}/delete`} method="post" className="inline-block"> <CsrfInput /> <button className="btn btn-small btn-delete">Delete } return ""; } render () { let itemNumber = this.props.itemNumber ? <div className="item-number">{this.props.itemNumber} : ""; let commentsCount = this.props.comments.length; return <div className={`post-item ${this.props.sticky ? "topic-sticky" : "topic-not-sticky"}`}> {itemNumber} {this.renderUpvote()} <div className="topic-content"> <a href={this.props.url} className="post-item-title"> {this.props.title} <div className="post-info"> <span className="post-info-section"> <a href={`/users/${this.props.author.username}`}> <span className="post-info-section"> <span className={this.upvoted ? "post-upvoted" : "post-not-upvoted"} onClick={this.toggleVote.bind(this)}>{this.props.votes.length} <i className="fa fa-heart" aria-hidden="true"> {" | "} <span className="post-info-section"> {this.props.created_at.fromNow()} <span className="hide-xs"> {" | "} <span className="post-info-section"> {commentsCount} Comment{commentsCount!== 1 ? "s" : ""} {this.renderEdit()} {this.renderDelete()} {this.renderAdminInfo()} <div className="comments-count"> <i className="fa fa-comment-o" aria-hidden="true"> <span className="comments-number">{commentsCount} } }
javascript
20
0.491913
213
36.560748
107
starcoderdata
$(document).ready( function () { $('.ch').click(function(){ var a = 0; for (var i = 1; i <= 12; i++) { if($('#ch' + i).prop('checked')) { a += parseInt($('#ch' + i).val()) } } $('#num').text(a); }); });
javascript
25
0.326241
49
24.727273
11
starcoderdata
function() { // mouse moving over canvas var mouse = d3.mouse(this); // vertical ruler d3.select(".mouse-line") .attr("d", function(){ yRange = mainYScale.range(); // range of y-axis var xCoor = d3.mouse(this)[0]; // mouse position in x return "M"+ xCoor +"," + yRange[0] + "L" + xCoor + "," + yRange[1]; }); // circles and text var selectText = function(s, c) { d3.selectAll(s) .attr("transform", function(d, i) { var xYear = mainXScale.invert(mouse[0]), bisect = d3.bisector(function(d) { return d.year; }).right; var line = document.getElementsByClassName(c)[0]; if(line != null){ var beginning = 0, end = line.getTotalLength(), target = null; while (true){ target = Math.floor((beginning + end) / 2); pos = line.getPointAtLength(target); if ((target === end || target === beginning) && pos.x !== mouse[0]) { break; } if (pos.x > mouse[0]) end = target; else if (pos.x < mouse[0]) beginning = target; else break; } d3.select(this).select('text') .text(mainYScale.invert(pos.y).toFixed(perHead ? 4 : 0)); return "translate(" + mouse[0] + "," + pos.y +")"; } }); }; selectText(".mouse-circle-mean", "mean"); selectText(".mouse-circle-median", "median"); selectText(".mouse-circle-selected", "selected"); }
javascript
24
0.371673
101
41.959184
49
inline
if(window.customElements.get('thing-') === undefined) { customElements.define('thing-', class extends HTMLElement { //static get observedAttributes() { return ['identifier']; } constructor(...args) { super(...args); this.root = false; if(document.body.querySelectorAll('*').length === 1) { this.root = true; } } connectedCallback() { this.identifier = this.getAttribute('identifier'); /* gun.get(this.identifier).map().on((value, key) => { // We only want to render child nodes here if(typeof(value) === 'object') { this.render(value, key) } else { key !== this.identifier ? this.setAttribute(key, value) : null; } */ this.render() /*let id = typeof(value) !== 'object' ? MD5(identifier+value) : Gun.node.soul(value), parent = document.getElementById(identifier), type = typeof(value) !== 'object' ? 'property' : 'thing'; typeof(value) === 'object' ? children.push({id, type, key, value:value, attributes }) : null; hyper(parent)`${ children.map(thing => wire(thing)`${ { thing: { id: thing.id, type: thing.type, key: key, value: thing.value, attributes: thing.attributes } } }`) }` */ // }) } render() { console.log('test') //return 'test' /*this.hyper`${ children.map(thing => wire(thing)`${ { thing: { id: thing.id, type: thing.type, key: key, value: thing.value, attributes: thing.attributes } } }`) }` */ // attribute-focused /*Object.keys(result).filter(key => attributes.includes(key)).map((key, index) => { this.setAttribute(key, result[key]); }) console Object.keys(this.attributes).map(index => { console.log(this.attributes.item(index), this.attributes.item(index).value, 'index') }) Context: ${identifier} ${Object.keys(this.attributes).map(index => wire()`${{ id:index, html: `<br /> <input disabled value="${this.attributes.item(index).value}" /> `}} `)} */ //console.log(root,'THEROOT') } } ) } /* class SubContainer extends Component { constructor(thing) { super().thing = thing; } render() { return this.html` <section id=${this.item.identifier}> <summary onclick=${this}> Type: refType)} /> Identifier: ${this.item.text} ${new Context(this.item.identifier, false)} } } class Container extends Component { constructor(identifier, children) { super(); this.concepts = children.concepts; this.relations = children.relations; this.arcs = children.arcs; this.identifier = identifier; } render() { return this.html` <section id="${this.identifier}"> href=${'/?id='+this.identifier}>Link to ${this.identifier} Object.keys(this.concepts) .filter(identifier => identifier !== '_') .map(c => SubContainer.for({identifier:c}, c)) } Object.keys(this.relations) .filter(identifier => identifier !== '_') .map(c => SubContainer.for({identifier:c}, c)) } Object.keys(this.arcs) .filter(identifier => identifier !== '_') .map(c => SubContainer.for({identifier:c}, c)) } } } */
javascript
16
0.342903
129
39.458065
155
starcoderdata
/* * @@name @@version * @@repository.url * * * Copyright @@year @@copyright * Released under the @@licenses * * Author: @@author * Date: @@date */ (function (global) { var TIMEOUT = 300, THRESHOLD = 0.5; //cm var tap = { cancel: this.up, up: function (pointer, eventData) { var downEvt = pointer.events.down[0], props; if (downEvt) { if ((global.math.duration(downEvt.timeStamp, eventData.timeStamp) > TIMEOUT) || // check for max time (eventData.target !== downEvt.target) || // same start/end target (global.gesture.getPointerOnTarget(downEvt.target).length > 1) || // check for multiple pointers => not a tap (pointer.hasMoved(THRESHOLD))) { // check for unallowed movement return; } props = global.gesture.cloneProperties(downEvt, global.gesture.DEFAULT_PROPERTIES); global.gesture.trigger(eventData.target, 'tap', props); // todo check for double tap } } }; global.gesture.register(tap); }(window.polyTouch));
javascript
25
0.550607
129
25.847826
46
starcoderdata
/* *┌──────────────────────────────────────────────────────────────┐ *│ 描 述: *│ 作 者:xuXin *│ 版 本:1.0.0 *│ 创建时间:2019/7/2 14:08:02 *└──────────────────────────────────────────────────────────────┘ */ using System.Collections.Generic; using SsitEngine.Unity; using SsitEngine.Unity.Resource; using UnityEngine; namespace Framework.Tip { public class TagTipManager : SingletonMono { private const string TIP_PATH = "UI/TagTip/UITagTip"; private Transform canvasRoot; private List tips = new List public override void OnSingletonInit() { tips = new List } public void Awake() { if (Instance != this) Debug.LogError("Tag tip instance is exception"); } public void LateUpdate() { for (var i = 0; i < tips.Count; i++) { var tt = tips[i]; if (tt.isInUse) { if (tt.root == null) { tt.isInUse = false; gameObject.SetActive(false); //也可以移除画布外 continue; } if (tt.IsInView(tt.root.transform.position)) { tt.gameObject.SetActive(true); tt.OnShow(); } else { tt.gameObject.SetActive(false); } } } } public TagTip GetTip() { tips.RemoveAll(tip => { return tip == null; }); foreach (var hud in tips) { if (hud.isInUse) continue; return hud; } var tmp = CreateTip(); if (tmp != null) tips.Add(tmp); return tmp; } private TagTip CreateTip() { TagTip tip = null; //access:资源加载 ResourcesManager.Instance.LoadAsset false, prefab => { if (prefab != null) { //prefab = Instantiate(prefab); if (canvasRoot == null) canvasRoot = transform; if (canvasRoot == null) { Debug.LogError("Can Not Find Canvas!!!"); } else { prefab.transform.SetParent(canvasRoot); //prefab.transform.localPosition = Vector3.one; prefab.transform.localScale = Vector3.one; } tip = prefab.GetComponent } }); return tip; } private void ClearTip() { if (tips != null) { foreach (var tagTip in tips) Destroy(tagTip); tips.Clear(); } } public void Destory() { tips.Clear(); tips = null; } #region 消息处理 private void OnEnable() { } private void OnDisable() { } #endregion } }
c#
22
0.374148
86
26.294574
129
starcoderdata
#!/usr/bin/env python3 """ Created on 2021-11-27 09:52 @author: johannes """ import os from pathlib import Path import yaml import sqlite3 import pandas as pd DAYS_MAPPER = { 'day': 1, 'days3': 3, 'week': 7, 'month': 30, 'quartile': 90, 'halfyear': 180, 'fullyear': 365, } def get_db_conn(): """Doc.""" return sqlite3.connect(os.getenv('TSTWEATHERDB')) def get_start_time(period, time_zone=None): """Doc.""" today = pd.Timestamp.today(tz=time_zone or 'Europe/Stockholm') if period == 'thisyear': return pd.Timestamp(f'{today.year}0101').strftime('%Y-%m-%d %H:%M:%S') elif period in DAYS_MAPPER: return (today - pd.Timedelta(days=DAYS_MAPPER.get(period)) ).strftime('%Y-%m-%d %H:%M:%S') else: # Return according to "day". return (today - pd.Timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') class DataBaseHandler: """Doc.""" def __init__(self, time_zone=None): self.time_zone = time_zone or 'Europe/Stockholm' base = Path(__file__).parent with open(base.joinpath('resources/parameters.yaml').resolve()) as fd: data = yaml.load(fd, Loader=yaml.FullLoader) self.db_fields = set(data.get('db_fields')) self._start_time = None self._end_time = None self._app_timing = None def post(self, **kwargs): """Doc.""" df = pd.DataFrame( {field: item for field, item in kwargs.items() if field in self.db_fields} ) conn = get_db_conn() df.to_sql('weather', conn, if_exists='append', index=False) def get_data_for_time_period(self): """Doc.""" conn = get_db_conn() return pd.read_sql( """select * from weather where timestamp between '"""+self.start_time+"""%' and '"""+self.end_time+"""%'""", conn ) def get_parameter_data_for_time_period(self, *args, time_period='day'): """Return dataframe based on parameter list. Args: args (str): iterable of parameters. Eg. ('timestamp', 'outtemp', 'winsp') time_period (str): period according to TIMING_OPTIONS (eg. "day", "week" or "month"). """ para_list = ', '.join(args) start_time = get_start_time(time_period, time_zone=self.time_zone) end_time = pd.Timestamp.today(tz=self.time_zone).strftime('%Y-%m-%d %H:%M:%S') conn = get_db_conn() return pd.read_sql( f"""select {para_list} from weather where timestamp between '"""+start_time+"""' and '"""+end_time+"""'""", conn ) @staticmethod def get(): """Doc.""" conn = get_db_conn() return pd.read_sql('select * from weather', conn) @staticmethod def get_time_log(): """Doc.""" conn = get_db_conn() query = """select timestamp from weather""" return pd.read_sql(query, conn).timestamp.to_list() def get_recent_time_log(self): """Doc.""" conn = get_db_conn() return pd.read_sql( """select timestamp from weather where (timestamp like '"""+self.date_today+"""%' or timestamp like '"""+self.date_yesterday+"""%')""", conn ).timestamp.to_list() @staticmethod def get_last_timestamp(): """Doc.""" conn = get_db_conn() try: return pd.read_sql( 'select timestamp from weather order by rowid desc limit 1', conn )['timestamp'][0] except IndexError: return None @staticmethod def get_last_parameter_value(parameter): """Doc.""" conn = get_db_conn() try: return pd.read_sql( f'select {parameter} from weather order by rowid desc limit 1', conn )[parameter][0] except IndexError: return None @property def today(self): """Return pandas TimeStamp for today.""" return pd.Timestamp.today(tz=self.time_zone) @property def date_today(self): """Return date string of today.""" return self.today.strftime('%Y-%m-%d') @property def date_yesterday(self): """Return date string of yesterday.""" return (self.today - pd.Timedelta(days=1)).strftime('%Y-%m-%d') @property def start_time(self): """Return start of time window (pandas.Timestamp)""" return self._start_time @start_time.setter def start_time(self, period): if period == 'day': self._start_time = (self.today - pd.Timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') elif period == 'days3': self._start_time = (self.today - pd.Timedelta(days=3)).strftime('%Y-%m-%d %H:%M:%S') elif period == 'week': self._start_time = (self.today - pd.Timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S') elif period == 'month': self._start_time = (self.today - pd.Timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S') elif period == 'quartile': self._start_time = (self.today - pd.Timedelta(days=90)).strftime('%Y-%m-%d %H:%M:%S') elif period == 'halfyear': self._start_time = (self.today - pd.Timedelta(days=180)).strftime('%Y-%m-%d %H:%M:%S') elif period == 'fullyear': self._start_time = (self.today - pd.Timedelta(days=365)).strftime('%Y-%m-%d %H:%M:%S') elif period == 'thisyear': self._start_time = pd.Timestamp(f'{self.today.year}0101').strftime('%Y-%m-%d %H:%M:%S') @property def end_time(self): """Return end of time window (pandas.Timestamp)""" return self._end_time @end_time.setter def end_time(self, period): if period == 'now': self._end_time = pd.Timestamp.today(tz=self.time_zone).strftime('%Y-%m-%d %H:%M:%S') else: self._end_time = pd.Timestamp(period).strftime('%Y-%m-%d %H:%M:%S') @property def app_timing(self): """Return app time spec.""" return self._app_timing @app_timing.setter def app_timing(self, timing): self._app_timing = timing def get_forecast_db_conn(): """Doc.""" return sqlite3.connect(os.getenv('FORECASTDB')) class ForecastHandler: """Get weather forecast based SMHI model 'PMP3g' (grid size: 2.8 km). Data from SMHI:s open API. https://www.smhi.se/data/utforskaren-oppna-data/meteorologisk-prognosmodell-pmp3g-2-8-km-upplosning-api """ def __init__(self, time_zone=None): self.time_zone = time_zone or 'Europe/Stockholm' def get_parameter_data_for_time_period(self, *args, time_period='day'): """Return dataframe based on parameter list. Args: args (str): iterable of parameters. Eg. ('timestamp', 'outtemp', 'winsp') time_period (str): period according to TIMING_OPTIONS (eg. "day", "days3"). """ para_list = ', '.join(args) start_time = get_start_time(time_period, time_zone=self.time_zone) end_time = self.get_endtime(time_period) conn = get_forecast_db_conn() return pd.read_sql( f"""select {para_list} from forecast where timestamp between '"""+start_time+"""' and '"""+end_time+"""'""", conn ) def get_endtime(self, time_period): """Doc.""" if time_period == 'day': return (self.today + pd.Timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') elif time_period == 'days3': return (self.today + pd.Timedelta(days=3)).strftime('%Y-%m-%d %H:%M:%S') @property def today(self): """Return pandas TimeStamp for today.""" return pd.Timestamp.today(tz=self.time_zone)
python
19
0.547505
107
31.793388
242
starcoderdata
""" Explore 4D interpolation on the computational grid (or mildly aggregated form thereof) """ import numpy as np import pandas as pd import logging log=logging.getLogger(__name__) from .. import utils from ..grid import unstructured_grid from ..model import unstructured_diffuser ## def interp_to_time_per_ll(df,tstamp,lat_col='latitude',lon_col='longitude', value_col='value'): """ interpolate each unique src/station to the given tstamp, and include a time_offset """ assert np.all(np.isfinite(df[value_col].values)) tstamp=utils.to_dnum(tstamp) def interp_col(grp): # had been dt64_to_dnum dns=utils.to_dnum(grp.time.values) value=np.interp( tstamp,dns,grp[value_col] ) dist=np.abs(tstamp-dns).min() return pd.Series([value,dist], [value_col,'time_offset']) # for some reason, using apply() ignores as_index result=df.groupby([lat_col,lon_col],as_index=False).apply(interp_col).reset_index() assert np.all(np.isfinite(result[value_col].values)) return result def weighted_grid_extrapolation(g,samples,alpha=1e-5, x_col='x',y_col='y',value_col='value',weight_col='weight', cell_col=None, edge_depth=None,cell_depth=None, return_weights=False): """ g: instance of UnstructuredGrid samples: DataFrame, with fields x,y,value,weight (or other names given by *_col) if cell_col is specified, this gives 0-based indices to the grid's cells, and speeds up the process. if x_col is None, or samples doesn't have x_col, point-data will be used from the grid geometry. alpha: control spatial smoothing. Lower value is smoother returns extrapolated data in array of size [Ncells] """ if x_col not in samples.columns: x_col=None y_col=None D=unstructured_diffuser.Diffuser(g,edge_depth=edge_depth,cell_depth=cell_depth) D.set_decay_rate(alpha) Dw=unstructured_diffuser.Diffuser(g,edge_depth=edge_depth,cell_depth=cell_depth) Dw.set_decay_rate(alpha) for i in range(len(samples)): if i%1000==0: log.info("%d/%d samples"%(i,len(samples))) rec=samples.iloc[i] if weight_col is None: weight=1.0 else: weight=rec[weight_col] assert weight>0.0 if x_col is not None: xy=rec[[x_col,y_col]].values else: xy=None if cell_col is not None: cell=int(rec[cell_col]) else: cell=D.grid.point_to_cell(xy) or D.grid.select_cells_nearest(xy) if xy is None: xy=D.grid.cells_centroid([cell])[0] D.set_flux(weight*rec[value_col],cell=cell,xy=xy) Dw.set_flux(weight,cell=cell,xy=xy) log.info("Construct 1st linear system") D.construct_linear_system() log.info("Solve 1st linear system") D.solve_linear_system(animate=False) log.info("Construct 2nd linear system") Dw.construct_linear_system() log.info("Solve 2nd linear system") Dw.solve_linear_system(animate=False) C=D.C_solved W=Dw.C_solved assert np.all(np.isfinite(C)) assert np.all(np.isfinite(W)) assert np.all(W>0) T=C / W if return_weights: return T,W else: return T
python
14
0.59795
90
28.762712
118
starcoderdata
package loglang.lang; import loglang.lang.Operator.Kind; /** * Created by skgchxngsxyz-osx on 15/10/06. */ public class OperatorTable { // unary op @Operator(Kind.PLUS) public static int plus(int right) { return right; } @Operator(Kind.PLUS) public static float plus(float right) { return right; } @Operator(Kind.MINUS) public static int minus(int right) { return -right; } @Operator(Kind.MINUS) public static float minus(float right) { return -right; } @Operator(Kind.NOT) public static boolean not(boolean right) { return !right; } @Operator(Kind.NOT) public static int not(int right) { return ~right; } // binary op // ADD @Operator(Kind.ADD) public static int add(int left, int right) { return left + right; } @Operator(Kind.ADD) public static float add(float left, float right) { return left + right; } @Operator(Kind.ADD) public static String add(String left, Object right) { return left + right; } // SUB @Operator(Kind.SUB) public static int sub(int left, int right) { return left - right; } @Operator(Kind.SUB) public static float sub(float left, float right) { return left - right; } // MUL @Operator(Kind.MUL) public static int mul(int left, int right) { return left * right; } @Operator(Kind.MUL) public static float mul(float left, float right) { return left * right; } // DIV @Operator(Kind.DIV) public static int div(int left, int right) { return left / right; } @Operator(Kind.DIV) public static float div(float left, float right) { return left / right; } // MOD @Operator(Kind.MOD) public static int mod(int left, int right) { return left % right; } // EQ @Operator(Kind.EQ) public static boolean eq(int left, int right) { return left == right; } @Operator(Kind.EQ) public static boolean eq(float left, float right) { return left == right; } @Operator(Kind.EQ) public static boolean eq(boolean letf, boolean right) { return letf == right; } @Operator(Kind.EQ) public static boolean eq(String left, String right) { return left.equals(right); } // NE @Operator(Kind.NE) public static boolean ne(int left, int right) { return left != right; } @Operator(Kind.NE) public static boolean ne(float left, float right) { return left != right; } @Operator(Kind.NE) public static boolean ne(boolean letf, boolean right) { return letf != right; } @Operator(Kind.NE) public static boolean ne(String left, String right) { return !left.equals(right); } // LT @Operator(Kind.LT) public static boolean lt(int left, int right) { return left < right; } @Operator(Kind.LT) public static boolean lt(float left, float right) { return left < right; } @Operator(Kind.LT) public static boolean lt(String left, String right) { return left.compareTo(right) < 0; } // GT @Operator(Kind.GT) public static boolean gt(int left, int right) { return left > right; } @Operator(Kind.GT) public static boolean gt(float left, float right) { return left > right; } @Operator(Kind.GT) public static boolean gt(String left, String right) { return left.compareTo(right) > 0; } // LE @Operator(Kind.LE) public static boolean le(int left, int right) { return left <= right; } @Operator(Kind.LE) public static boolean le(float left, float right) { return left <- right; } @Operator(Kind.LE) public static boolean le(String left, String right) { return left.compareTo(right) <= 0; } // GE @Operator(Kind.GE) public static boolean ge(int left, int right) { return left >= right; } @Operator(Kind.GE) public static boolean ge(float left, float right) { return left >= right; } @Operator(Kind.GE) public static boolean ge(String left, String right) { return left.compareTo(right) >= 0; } // AND @Operator(Kind.AND) public static int and(int left, int right) { return left & right; } // OR @Operator(Kind.OR) public static int or(int left, int right) { return left | right; } // XOR @Operator(Kind.XOR) public static int xor(int left, int right) { return left ^ right; } }
java
9
0.609166
78
24.558011
181
starcoderdata
//MIT License //Copyright(c) 2019 "Skarredghost") //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. using System; using System.Security.Cryptography.X509Certificates; using TMPro; using UnityEngine; namespace Ntw.CurvedTextMeshPro { /// /// Class for drawing a Text Pro text following a circle arc /// [ExecuteInEditMode] public class TextProOnACircle : TextProOnACurve { /// /// The radius of the text circle arc /// [SerializeField] [Tooltip("The radius of the text circle arc.")] private float _radius = 10.0f; [SerializeField] [Tooltip("The Y offset of the text circle center.")] private float _yOffset; [SerializeField] [Tooltip("Change Y Offset in accordance with radius considering font size.")] private bool _compensateRadius; /// /// Limits distance between symbols whatever to keep symbols together. /// [Tooltip("Keep symbols together.")] [SerializeField] private bool _fixedLetterSpacing; /// /// Some multiplier to adjust text size to circle dimensions. /// [SerializeField] private float _letterSpacingMultiplier = 30; /// /// How much degrees the text arc should span /// [SerializeField] [Tooltip("How much degrees the text arc should span")] private float _arcDegrees = 90.0f; /// /// The angular offset at which the arc should be centered, in degrees. /// -90 degrees means that the text is centered on the highest point /// [SerializeField] [Tooltip("The angular offset at which the arc should be centered, in degrees")] private float _angularOffset = -90; /// /// How many maximum degrees per letters should be. For instance, if you specify /// 10 degrees, the distance between the letters will never be superior to 10 degrees. /// It is useful to create text that gracefully expands until it reaches the full arc, /// without making the letters to sparse when the string is short /// [SerializeField] [Tooltip("The maximum angular distance between letters, in degrees")] private int _maxDegreesPerLetter = 360; private new void Update() { TextComponent ??= gameObject.GetComponent if (_compensateRadius) _yOffset = -_radius; base.Update(); } /// /// Computes the transformation matrix that maps the offsets of the vertices of each single character from /// the character's center to the final destinations of the vertices so that the text follows a curve /// /// <param name="charMidBaselinePos">Position of the central point of the character /// <param name="zeroToOnePos">Horizontal position of the character relative to the bounds of the box, in a range [0, 1] /// <param name="text">Information on the text that we are showing /// <param name="charIdx">Index of the character we have to compute the transformation for /// matrix to be applied to all vertices of the text protected override Matrix4x4 ComputeTransformationMatrix(Vector3 charMidBaselinePos, float zeroToOnePos, int charIdx) { float letterDegrees = _fixedLetterSpacing ? (180 * TextComponent.fontSize / _letterSpacingMultiplier) / (Mathf.PI * _radius) : _maxDegreesPerLetter; //calculate the actual degrees of the arc considering the maximum distance between letters float actualArcDegrees = Mathf.Min(_arcDegrees, (float)TextComponent.textInfo.characterCount / TextComponent.textInfo.lineCount * letterDegrees); //compute the angle at which to show this character. //We want the string to be centered at the top point of the circle, so we first convert the position from a range [0, 1] //to a [-0.5, 0.5] one and then add m_angularOffset degrees, to make it centered on the desired point float angle = ((zeroToOnePos - 0.5f) * actualArcDegrees + _angularOffset) * Mathf.Deg2Rad; //we need radians for sin and cos //compute the coordinates of the new position of the central point of the character. Use sin and cos since we are on a circle. //Notice that we have to do some extra calculations because we have to take in count that text may be on multiple lines float x0 = Mathf.Cos(angle); float y0 = Mathf.Sin(angle); float radiusForThisLine = _radius - TextComponent.textInfo.lineInfo[0].lineExtents.max.y * TextComponent.textInfo.characterInfo[charIdx].lineNumber; var newMidBaselinePos = new Vector2(x0 * radiusForThisLine, -y0 * radiusForThisLine); //actual new position of the character //compute the transformation matrix: move the points to the just found position, then rotate the character to fit the angle of the curve //(-90 is because the text is already vertical, it is as if it were already rotated 90 degrees) return Matrix4x4.TRS(new Vector3(newMidBaselinePos.x, newMidBaselinePos.y + _yOffset, 0), Quaternion.AngleAxis(-Mathf.Atan2(y0, x0) * Mathf.Rad2Deg - 90, Vector3.forward), Vector3.one); } } }
c#
17
0.671956
160
48.955556
135
starcoderdata
static const char *test_websocket_endpoint(void) { struct mg_mgr mgr; struct mg_connection *nc; const char *local_addr = "127.0.0.1:7798"; char buf[20] = "", buf2[20] = "0"; mg_mgr_init(&mgr, NULL); /* mgr.hexdump_file = "-"; */ ASSERT((nc = mg_bind(&mgr, local_addr, cb3)) != NULL); mg_set_protocol_http_websocket(nc); nc->user_data = buf2; mg_register_http_endpoint(nc, "/boo", cbwep MG_UD_ARG(NULL)); /* Websocket request */ ASSERT((nc = mg_connect(&mgr, local_addr, cb4)) != NULL); mg_set_protocol_http_websocket(nc); nc->user_data = buf; mg_send_websocket_handshake(nc, "/boo", NULL); poll_until(&mgr, 1, c_str_ne, buf, (void *) ""); /* Check that test buffer has been filled by the callback properly. */ ASSERT_STREQ(buf, "0RDF|hi"); /* Test handshake failure */ ASSERT((nc = mg_connect(&mgr, local_addr, cb4)) != NULL); mg_set_protocol_http_websocket(nc); buf[0] = '\0'; buf2[0] = '1'; buf2[1] = '\0'; nc->user_data = buf; mg_send_websocket_handshake(nc, "/boo", NULL); poll_until(&mgr, 1, c_str_ne, buf, (void *) ""); ASSERT_STREQ(buf, "code 403"); mg_mgr_free(&mgr); return NULL; }
c
12
0.612121
72
30.243243
37
inline
# Maior e Menor from time import sleep print('=*'*100) n1 = int(input('Valor 1:')) n2 = int(input('Valor 2:')) n3 = int(input('Valor 3:')) numeros = [n1, n2, n3] #mixagem dos valores print('=*'*100) print('Analisando dados...') sleep(5)#Espera de 5segundos #Simplificação print('O maior valor digitado foi {}'.format(max(numeros))) print('O menor numero digitado foi {}'.format(min(numeros))) if n1 == n2 or n2 == n3 or n1 == n3: print('{}, {} e {} SÃO IGUAIS'.format(n1, n2, n3)) #Forma extensa '''#Quando for os maiores valores if n1 > n2 and n1 > n3: print('{} foi o MAIOR VALOR DIGITADO'.format(n1)) if n2 > n1 and n2 > n3: print('{} foi o MAIOR VALOR DIGITADO'.format(n2)) if n3 > n1 and n3 > n2: print('{} foi o MAIOR VALOR DIGITADO'.format(n3)) #Quando for os menores valores if n1 < n2 and n1 < n3: print('{} foi o MENOR VALOR DIGITADO'.format(n1)) if n2 < n1 and n2 < n3: print('{} foi o MENOR VALOR DIGITADO'.format(n2)) if n3 < n1 and n3 < n2: print('{} foi o MAIOR VALOR DIGITADO'.format(n3)) #Quando for os mesmos valores if n1 == n2 or n2 == n3 or n1 == n3: print('{}, {} e {} SÃO IGUAIS'.format(n1, n2, n3)) print('\n\nThanks to use our service.') '''
python
9
0.616186
60
17.641791
67
starcoderdata
package pl.cwanix.opensun.authserver.packet.c2s.auth; import lombok.Getter; import pl.cwanix.opensun.authserver.packet.AuthServerPacketOPCode; import pl.cwanix.opensun.commonserver.packets.Packet; import pl.cwanix.opensun.commonserver.packets.annotations.IncomingPacket; import pl.cwanix.opensun.utils.bytes.ByteRange; import pl.cwanix.opensun.utils.datatypes.FixedLengthField; @Getter @IncomingPacket(category = AuthServerPacketOPCode.Auth.CATEGORY, operation = AuthServerPacketOPCode.Auth.Ask.SRV_SELECT) public class C2SAskSrvSelectPacket implements Packet { private static final ByteRange SERVER_INDEX_RANGE = ByteRange.of(0); private static final ByteRange CHANNEL_INDEX_RANGE = ByteRange.of(1); private final FixedLengthField serverIndex; private final FixedLengthField channelIndex; public C2SAskSrvSelectPacket(final byte[] value) { this.serverIndex = new FixedLengthField(SERVER_INDEX_RANGE, value); this.channelIndex = new FixedLengthField(CHANNEL_INDEX_RANGE, value); } }
java
14
0.806338
120
44.44
25
starcoderdata
const assert = require('assert'); const fs = require('fs'); const toggleCase = (char) => { if (char === char.toUpperCase()) { return char.toLowerCase(); } return char.toUpperCase(); }; const reduce = (input) => { const { string, left } = input.split('').reduce(({ string, left }, right) => { if (left && right === toggleCase(left)) { const [ newLeft, ...newString ] = string; return { string: newString, left: newLeft }; } return { string: [ left, ...string ], left: right }; }, { string: '', left: null }); return [ left, ...string ] .filter(Boolean) .reverse() .join(''); }; const length = (input) => reduce(input).length; const uniqueChars = (input) => Object.keys(input.split('').reduce((acc, it) => ({ ...acc, [it.toLowerCase()]: (acc[it.toLowerCase()] || 0) + 1 }), {})); const improve = (input) => (char) => { const improved = input.replace(new RegExp(`${char}`, 'ig'), ''); const improvedLength = length(improved); return { char, length: improvedLength }; }; const getImprovedLengths = (input) => uniqueChars(input).map(improve(input)); const getMostImproved = (improved) => improved.slice().sort(({ length: a }, { length: b }) => a < b ? -1 : a > b ? 1 : 0)[0]; (() => { const input = 'dabAcCaCBAcCcaDA'; const expected = 'dabCBAcaDA'; assert.equal(length(input),expected.length); // { char: 'c', length: 4 } assert.equal(getMostImproved(getImprovedLengths(input)).length, 4); })(); const input = fs.readFileSync(`${__dirname}/input`, 'utf-8'); console.log(reduce(input).length); console.log(getMostImproved(getImprovedLengths(input)));
javascript
21
0.59192
125
24.117647
68
starcoderdata
<?php /** * 主播魅力点变化记录数据访问层 * * the last known user to change this file in the repository <$LastChangedBy: hexin $> * @author * @version $Id: DoteyCharmRecordsModel.php 16624 2013-11-20 05:51:03Z hexin $ * @package model * @subpackage consume */ class DoteyCharmRecordsModel extends PipiActiveRecord { public function tableName(){ return '{{dotey_charm_records}}'; } /** * @param string $className * @return DoteyCharmPointsRecordsModel */ public static function model($className = __CLASS__){ return parent::model($className); } public function getDbConnection(){ return Yii::app()->db_consume_records; } /** * @author supeng * @param array $condition * @param unknown_type $offset * @param unknown_type $pageSize * @param unknown_type $isLimit */ public function getCharmAwardByCondition(Array $condition = array(),$offset = 0, $pageSize = 10,$isLimit = true){ $result = array(); $result['count'] = 0; $result['list'] = array(); $criteria = $this->getDbCriteria(); $criteria->compare('source', SOURCE_SENDS); $criteria->compare('sub_source', SUBSOURCE_SENDS_ADMIN); $criteria->compare('client', CLIENT_ADMIN); //是否取得明细 if (!empty($condition['record_id'])){ if (is_array($condition['record_id'])){ $criteria->addInCondition('record_id',$condition['record_id']); }else{ $criteria->addCondition('record_id='.intval($condition['record_id'])); } $result['list'] = $this->findAll($criteria); return $result; } //是否已经被撤销 if (!empty($condition['target_id'])){ if (is_array($condition['target_id'])){ $criteria->addInCondition('target_id',$condition['target_id']); }else{ $criteria->addCondition('target_id='.intval($condition['target_id'])); } $result['list'] = $this->findAll($criteria); return $result; } $criteria->addCondition('target_id=0'); if (!empty($condition['create_time_on'])){ $criteria->addCondition('create_time>='.strtotime($condition['create_time_on'])); } if (!empty($condition['create_time_end'])){ $criteria->addCondition('create_time<'.strtotime($condition['create_time_end'])); } if (!empty($condition['uid'])){ if (is_array($condition['uid'])){ $criteria->addInCondition('uid', $condition['uid']); }else{ $criteria->addCondition('uid='.intval($condition['uid'])); } } $result['count'] = $this->count($criteria); if ($isLimit){ $criteria->limit = $pageSize; $criteria->offset = $offset; } $criteria->order = 'create_time DESC'; $result['list'] = $this->findAll($criteria); return $result; } /** * @author supeng * @param array $condition * @param unknown_type $offset * @param unknown_type $pageSize * @param unknown_type $isLimit */ public function getCharmByCondition(Array $condition = array(),$offset = 0, $pageSize = 10,$isLimit = true){ $result = array(); $result['count'] = 0; $result['list'] = array(); $criteria = $this->getDbCriteria(); if (!empty($condition['source'])){ $criteria->compare('source', $condition['source']); } if (!empty($condition['sub_source'])){ $criteria->compare('sub_source', $condition['sub_source']); } if(isset($condition['source_arr']) && is_array($condition['source_arr'])){ $criteria->addInCondition('source', $condition['source_arr']); } if (!empty($condition['client'])){ $criteria->compare('client', $condition['client']); } //是否取得明细 if (!empty($condition['record_id'])){ $criteria->compare('record_id', $condition['record_id']); } if (!empty($condition['create_time_on'])){ $criteria->addCondition('create_time>='.strtotime($condition['create_time_on'])); } if (!empty($condition['create_time_end'])){ $criteria->addCondition('create_time<'.strtotime($condition['create_time_end'])); } if (!empty($condition['uid'])){ $criteria->compare('uid', $condition['uid']); } $result['count'] = $this->count($criteria); if ($isLimit){ $criteria->limit = $pageSize; $criteria->offset = $offset; } $criteria->order = 'create_time DESC'; $result['list'] = $this->findAll($criteria); return $result; } /** * 获取主播fans的魅力值贡献统计 * @author guoshaobo * @param int $dotey_id * @param int $offset * @param int $limit * @return array */ public function countDoteyCharmBuSendUid($dotey_id, $offset, $limit) { $criteria = $this->getDbCriteria(); $criteria->select = ' sender_uid, sum(`charm`) as points'; $criteria->condition = ' uid=:uid'; $criteria->params = array(':uid'=>$dotey_id); $criteria->order = 'points desc'; $criteria->group = 'sender_uid'; $count = $this->count($criteria); $criteria->offset = $offset; $criteria->limit = $limit; $list = $this->getCommandBuilder()->createFindCommand($this->tableName(),$criteria)->queryAll(); return array('count'=>$count, 'list'=>$list); } /** * @author supeng * @param unknown_type $doteyIds * @param unknown_type $condition * @return mixed */ public function getDoteyCharmRecords($doteyIds,$condition) { $criteria = $this->getDbCriteria(); $criteria->select = ' uid, sum(charm) charm'; if(isset($condition['stime']) && $condition['stime']>=0){ $criteria->condition .= ' create_time>=:stime'; $criteria->params += array(':stime'=>$condition['stime']); } if(isset($condition['etime']) && $condition['etime']>=0){ $criteria->condition .= ' and create_time<=:etime'; $criteria->params += array(':etime'=>$condition['etime']); } //按月的范围统计 if(isset($condition['monthTime'])){ $stime = strtotime($condition['monthTime']); $criteria->addCondition('create_time >='.$stime); $etime = strtotime('+1 months',$stime); $criteria->addCondition('create_time <'.$etime); } $criteria->addInCondition('uid', $doteyIds); $criteria->group = 'uid'; return $this->getCommandBuilder()->createFindCommand($this->tableName(),$criteria)->queryAll(); } } ?>
php
20
0.633133
114
26.5
218
starcoderdata
import cadquery as cq # Parameter definitions p_outerWidth = 100.0 # Outer width of box enclosure p_outerLength = 150.0 # Outer length of box enclosure p_outerHeight = 50.0 # Outer height of box enclosure p_thickness = 3.0 # Thickness of the box walls p_sideRadius = 10.0 # Radius for the curves around the sides of the bo p_topAndBottomRadius = 2.0 # Radius for the curves on the top and bottom edges p_screwpostInset = 12.0 # How far in from the edges the screwposts should be p_screwpostID = 4.0 # Inner diameter of the screwpost holes, should be roughly screw diameter not including threads p_screwpostOD = 10.0 # Outer diameter of the screwposts. Determines overall thickness of the posts p_boreDiameter = 8.0 # Diameter of the counterbore hole, if any p_boreDepth = 1.0 # Depth of the counterbore hole, if p_countersinkDiameter = 0.0 # Outer diameter of countersink. Should roughly match the outer diameter of the screw head p_countersinkAngle = 90.0 # Countersink angle (complete angle between opposite sides, not from center to one side) p_lipHeight = 1.0 # Height of lip on the underside of the lid. Sits inside the box body for a snug fit. # Outer shell oshell = cq.Workplane("XY").rect(p_outerWidth, p_outerLength) \ .extrude(p_outerHeight + p_lipHeight) # Weird geometry happens if we make the fillets in the wrong order if p_sideRadius > p_topAndBottomRadius: oshell.edges("|Z").fillet(p_sideRadius) oshell.edges("#Z").fillet(p_topAndBottomRadius) else: oshell.edges("#Z").fillet(p_topAndBottomRadius) oshell.edges("|Z").fillet(p_sideRadius) # Inner shell ishell = oshell.faces("<Z").workplane(p_thickness, True)\ .rect((p_outerWidth - 2.0 * p_thickness), (p_outerLength - 2.0 * p_thickness))\ .extrude((p_outerHeight - 2.0 * p_thickness), False) # Set combine false to produce just the new boss ishell.edges("|Z").fillet(p_sideRadius - p_thickness) # Make the box outer box box = oshell.cut(ishell) # Make the screwposts POSTWIDTH = (p_outerWidth - 2.0 * p_screwpostInset) POSTLENGTH = (p_outerLength - 2.0 * p_screwpostInset) postCenters = box.faces(">Z").workplane(-p_thickness)\ .rect(POSTWIDTH, POSTLENGTH, forConstruction=True)\ .vertices() for v in postCenters.all(): v.circle(p_screwpostOD / 2.0).circle(p_screwpostID / 2.0)\ .extrude((-1.0) * ((p_outerHeight + p_lipHeight) - (2.0 * p_thickness)), True) # Split lid into top and bottom parts (lid, bottom) = box.faces(">Z").workplane(-p_thickness - p_lipHeight).split(keepTop=True, keepBottom=True).all() # Translate the lid, and subtract the bottom from it to produce the lid inset lowerLid = lid.translate((0, 0, -p_lipHeight)) cutlip = lowerLid.cut(bottom).translate((p_outerWidth + p_thickness, 0, p_thickness - p_outerHeight + p_lipHeight)) # Compute centers for counterbore/countersink or counterbore topOfLidCenters = cutlip.faces(">Z").workplane().rect(POSTWIDTH, POSTLENGTH, forConstruction=True).vertices() # Add holes of the desired type if p_boreDiameter > 0 and p_boreDepth > 0: topOfLid = topOfLidCenters.cboreHole(p_screwpostID, p_boreDiameter, p_boreDepth, (2.0) * p_thickness) elif p_countersinkDiameter > 0 and p_countersinkAngle > 0: topOfLid = topOfLidCenters.cskHole(p_screwpostID, p_countersinkDiameter, p_countersinkAngle, (2.0) * p_thickness) else: topOfLid= topOfLidCenters.hole(p_screwpostID, 2.0 * p_thickness) # Return the combined result result = topOfLid.combineSolids(bottom) # Displays the result of this script show_object(result)
python
12
0.727836
119
45.142857
77
starcoderdata
#!/usr/bin/env python ''' # # Neural networks is a supervised learning algorithm, which utilizes neurons (which is a mathematical functions which accepts weighted values, and gives an output using an activation function) inorder to learn a problem and # then to evaluate and predict the outcomes for data which has not yet been seen. # # Problem : We have been given a train data set which contains the correct orientations of around 36000 images, using this we have to train our program. # We then have to predict/assign an orientation for the images in the test-data set # # Formulation : We utilize the pixels of the image, representing an unique feature, which is fed into the neural network, which results in a model file post training. # The model file contains the weights and biases which are to be fed into the input, hidden and output layer. # # Citation : 1. Discussed with and # 2. Understanding the whole process of back propagation neural network: # https://www.youtube.com/watch?v=aircAruvnKk&list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi # 3. Used as a reference to check the working of code with a small sample input and expected output data & # Understanding the implementation of batch gradient descent & bias matrix and also learnt about the keepdims parameter used for numpy.sum: # https://www.analyticsvidhya.com/blog/2017/05/neural-network-from-scratch-in-python-and-r/ # 4. Referred for understanding the mathematical formulas and its working: # 1. https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/ # 2. http://neuralnetworksanddeeplearning.com/chap2.html # # Code-Descrption : The class file present here is called from orient.py based on the input provided # # NOTE: please provide extension .npz for the model file instead of .txt # # Training: # orient.py train train_file.txt mddel_file.npz nearest # NOTE: please provide extension .npz for the model file instead of .txt # Initialize with random weights between -1 to 1, for input to hidden, hidden to output, hidden bias and output bias. This auto-corrects itself by evaluating itself against the training data via feed forward. # We compute the error rate, on the basis of mis-classification, and use to reduce the error rate via back-propogation. We again update the bias and the weights. This continues for the number of iterations we # defined. We evaluate the error rate for each iteration by computing the root means square error for each iteration. Output bias is the sum of all the delta output times the learning rate, and bias hidden layer # is the sum of delta of hidden layer for each image. Finally, we store the weights and bias into the model file. # # Testing: # orient.py test test_file.txt mddel_file.npz nearest # NOTE: please provide extension .npz for the model file instead of .txt # We initialize all the weights and biases as per the model file. Then we perform feed forward to compute the predicted orientation of the test-image. We provide the accurace based on the correctly identified images # over the total images. # # # Problems(P), Assumptions(A), Simplifications (S), Design Decisions (DD): # Experimented with the learning rates to get better output (DD) # Experimented with the hidden layer to get better output (DD) # Stochastic gradient descent takes a lot of time for computation (P) # Implemented batch gradient descent, to get better performance (DD) # Store the model file as a default file format supported by numpy, instead of txt (DD) # # Analysis : # We evaluated the implementation for various values of epochs and hidden layer, with a constant learning rate of 0.0001 # It takes approx 15 minutes for training and approx 5 mins for the test process, on the whole set. # We had multiple values but decided to go with the following to show our process, we came to 564 after much analysis. # # hidden layer size | epochs | Accuracy | # ------------------------------------------------------------------ # 20 | 1000 | 69.88 | # 20 | 2000 | 68.82 | # 20 | 500 | 70.41 | # 10 | 1000 | 67.97 | # 10 | 2000 | 69.35 | # 10 | 5000 | 66.38 | # 8 | 1000 | 70.94 | # 8 | 2000 | 69.03 | # 8 | 5000 | 68.08 | # 8 | 1500 | 68.39 | # 8 | 6000 | 69.67 | # 6 | 2000 | 70.837 | # 6 | 1000 | 69.56 | # 6 | 4377 | 71.36 | # ------------------------------------------------------------------ ''' import os import numpy as np np.warnings.filterwarnings('ignore') class NNet: # Variable Initialization def __init__(self): self.input_layer_size = 192 self.hidden_layer_size = 6 #Hidden layer size self.output_layer_size = 4 self.epoch_iterations = 4377 #Training iterations self.alpha = 0.0001 # Learning rate # self.epoch_iterations = 100 self.possible_output = [0, 90, 180, 270] #Different orientation types ''' This function returns the orientation value to output layer formats 0 90 180 270 ''' def returnBinForm(self,orientation): single_output = [0,0,0,0] single_output[self.possible_output.index(int(orientation))]=1 return single_output # Sigmoid Function def sigmoid(self,xx): return 1 / (1 + np.exp(-xx)) # Derivative of Sigmoid Function def d_sigmoid(self,xx): return xx * (1 - xx) #Train file needs the train_file.txt and the model file name without any file format extension #as numpy saves the model in npz format' def train(self,trainFile, modelFile): input_text_size = sum(1 for line in open(trainFile)) input_data = np.zeros(shape=(input_text_size, self.input_layer_size)) #a numpy matrix of 36976 x 192 output_data = np.zeros(shape=(input_text_size, self.output_layer_size)) i = -1 with open(trainFile) as f: for line in f: i = i + 1 item = line.split() for j in range(len(item) - 2): input_data[i][j] = int(item[j + 2]) output_data[i] = self.returnBinForm(item[1]) random_start = -1 random_end = +1 np.random.seed(1) input_to_hidden = np.random.uniform(random_start, random_end, size=(self.input_layer_size, self.hidden_layer_size)) bias_hidden_layer = np.random.uniform(random_start, random_end, size=(self.hidden_layer_size)) hidden_to_output = np.random.uniform(random_start, random_end, size=(self.hidden_layer_size, self.output_layer_size)) output_bias = np.random.uniform(random_start, random_end, size=(self.output_layer_size)) for i in range(self.epoch_iterations + 1): #Feed Forward network hidden_layer = self.sigmoid(np.dot(input_data, input_to_hidden) + bias_hidden_layer) actual_output = self.sigmoid(np.dot(hidden_layer, hidden_to_output) + output_bias) #Back Propogation network error_value = output_data - actual_output delta_output = error_value * self.d_sigmoid(actual_output) delta_hidden_layer = np.dot(delta_output, (np.transpose(hidden_to_output))) * self.d_sigmoid(hidden_layer) hidden_to_output += np.dot(np.transpose(hidden_layer), delta_output) * self.alpha input_to_hidden += np.dot(np.transpose(input_data), delta_hidden_layer) * self.alpha output_bias += np.sum(delta_output, axis=0) * self.alpha bias_hidden_layer += np.sum(delta_hidden_layer, axis=0) * self.alpha RMSError= np.sum(np.square(error_value))*0.5 #print str(i)+" RMS= "+str(RMSError) np.savez_compressed(modelFile, input_to_hidden=input_to_hidden, hidden_to_output=hidden_to_output, bias_hidden_layer=bias_hidden_layer, output_bias=output_bias) def test(self,modelFile, testFile, outputFile): #Save data to model test_file_lines = sum(1 for line in open(testFile)) test_X = np.zeros(shape=(test_file_lines, self.input_layer_size)) test_correct_orientation = np.zeros(shape=(test_file_lines)) #Load data from model modelData = np.load(modelFile) input_to_hidden = modelData['input_to_hidden'] hidden_to_output = modelData['hidden_to_output'] bias_hidden_layer = modelData['bias_hidden_layer'] output_bias = modelData['output_bias'] test_label=dict() i = -1 with open(testFile) as f: for line in f: i = i + 1 x = line.split() for j in range(len(x) - 2): test_X[i][j] = x[j + 2] test_correct_orientation[i] = x[1] test_label[i] = x[0] correct_track_counter = 0 total_track_counter = 0 if os.path.isfile(outputFile): os.remove(outputFile) for i_counter in range(len(test_X)): hidden_layer = self.sigmoid(np.dot(test_X, input_to_hidden) + bias_hidden_layer) actual_output = self.sigmoid(np.dot(hidden_layer, hidden_to_output) + output_bias) predicted_test_out = self.possible_output[np.argmax(actual_output[i_counter])] if predicted_test_out == int(test_correct_orientation[i_counter]): correct_track_counter += 1 total_track_counter += 1 with open(outputFile, 'a') as outs: output_line = test_label[i_counter] + " " + str(predicted_test_out) + "\n" outs.write(output_line) # print "Results = ", str(self.epoch_iterations) + " == " + str((correct_track_counter * 100.0) / len(test_X)) print "Accuracy: " + str((correct_track_counter * 100.0) / len(test_X)) # train("train-data.txt", "nnet_model") # test("nnet_model.npz","test-data.txt","output.txt")
python
17
0.586169
233
54.786802
197
starcoderdata
package cli import ( "context" "net" "net/http" "os" "os/signal" "sync" "syscall" "time" "github.com/cloudflare/tableflip" "github.com/urfave/cli" "github.com/ziyan/gatewaysshd/auth" "github.com/ziyan/gatewaysshd/db" "github.com/ziyan/gatewaysshd/gateway" ) func run(c *cli.Context) error { caPublicKeys, err := parseCaPublicKeys(c) if err != nil { log.Errorf("failed to parse certificate authority public key from file \"%s\": %s", c.String("ca-public-key"), err) return err } hostSigner, err := parseHostSigner(c) if err != nil { log.Errorf("failed to host key from file \"%s\" and \"%s\": %s", c.String("host-private-key"), c.String("host-public-key"), err) return err } idleTimeout, err := parseIdleTimeout(c) if err != nil { log.Errorf("failed to parse idle timeout \"%s\": %s", c.String("idle-timeout"), err) return err } // set up upgrader upgrader, err := tableflip.New(tableflip.Options{ PIDFile: c.String("pid-file"), }) if err != nil { log.Errorf("failed to create upgrader: %s", err) return err } defer upgrader.Stop() // ssh listener log.Debugf("listening ssh endpoint: %s", c.String("listen-ssh")) sshListener, err := upgrader.Fds.Listen("tcp", c.String("listen-ssh")) if err != nil { log.Errorf("failed to listen on %s: %s", c.String("listen-ssh"), err) return err } // http listener var httpListener net.Listener if c.String("listen-http") != "" { log.Debugf("listening http endpoint: %s", c.String("listen-http")) httpListener, err = upgrader.Fds.Listen("tcp", c.String("listen-http")) if err != nil { log.Errorf("failed to listen on %s: %s", c.String("listen-http"), err) return err } } // open database database, err := db.Open(c.String("postgres-host"), uint16(c.Uint("postgres-port")), c.String("postgres-user"), c.String("postgres-password"), c.String("postgres-dbname")) if err != nil { log.Errorf("failed to open database: %s", err) return err } defer func() { if err := database.Close(); err != nil { log.Errorf("failed to close database: %s", err) } }() if err := database.Migrate(); err != nil { log.Errorf("failed to migrate database: %s", err) return err } // create ssh auth config sshConfig, err := auth.NewConfig(database, caPublicKeys, c.String("geoip-database")) if err != nil { log.Errorf("failed to create ssh config: %s", err) return err } sshConfig.ServerVersion = c.String("server-version") sshConfig.AddHostKey(hostSigner) // create gateway gateway, err := gateway.Open(database, sshConfig, &gateway.Settings{ Version: c.App.Version, }) if err != nil { log.Errorf("failed to create ssh gateway: %s", err) return err } defer gateway.Close() // tell parent that we are ready // need to get all the inheritted fds before calling this if err := upgrader.Ready(); err != nil { log.Errorf("failed to send ready to parent: %s", err) return err } // wait until parent exit before continuing if err := upgrader.WaitForParent(context.Background()); err != nil { log.Errorf("failed to wait for parent to shutdown: %s", err) return err } // run var waitGroup sync.WaitGroup defer waitGroup.Wait() // signal to quit quit := false // accept all connections sshRunning := make(chan struct{}) waitGroup.Add(1) go func() { defer waitGroup.Done() defer close(sshRunning) var waitGroup2 sync.WaitGroup defer waitGroup2.Wait() log.Debugf("running and serving ssh") for { socket, err := sshListener.Accept() if err != nil { if !quit { log.Errorf("failed to accept incoming tcp connection: %s", err) } break } waitGroup2.Add(1) go func() { defer waitGroup2.Done() gateway.HandleConnection(socket) }() } log.Debugf("stop serving ssh") }() // serve http var httpServer *http.Server httpRunning := make(chan struct{}) if c.String("listen-http") != "" { httpServer = &http.Server{ Addr: c.String("listen-http"), Handler: newHttpHandler(gateway, c.Bool("debug-pprof")), } waitGroup.Add(1) go func() { defer waitGroup.Done() defer close(httpRunning) log.Debugf("running and serving http") if err := httpServer.Serve(httpListener); err != nil && err != http.ErrServerClosed { log.Errorf("http server exited with error: %s", err) } log.Debugf("stop serving http") }() } // wait till exit signaling := make(chan os.Signal, 1) signal.Notify(signaling, syscall.SIGINT, syscall.SIGTERM) upgrading := make(chan os.Signal, 1) signal.Notify(upgrading, syscall.SIGHUP) for !quit { select { case <-upgrading: log.Noticef("upgrading ...") if err := upgrader.Upgrade(); err != nil { log.Errorf("failed to upgrade: %s", err) } case <-signaling: quit = true case <-sshRunning: quit = true case <-httpRunning: quit = true case <-time.After(10 * time.Second): gateway.ScavengeConnections(idleTimeout) case <-upgrader.Exit(): quit = true } } // make sure there is a deadline on shutting down time.AfterFunc(30*time.Second, func() { log.Fatalf("graceful shutdown server timed out") os.Exit(1) }) // shutdown server, this will block until all connections are closed log.Noticef("shutting down") waitGroup.Add(1) go func() { defer waitGroup.Done() if err := sshListener.Close(); err != nil { log.Errorf("failed to close ssh listener: %s", err) } gateway.Close() }() if httpServer != nil { waitGroup.Add(1) go func() { defer waitGroup.Done() if err := httpServer.Shutdown(context.Background()); err != nil { log.Errorf("failed to shutdown http server: %s", err) } }() } return nil }
go
17
0.658838
172
23.621739
230
starcoderdata
<?php namespace Admin\Action; use Think\Action; class CountSczylAction extends CommonAction { /** * 获得统计数据 * * @param string $qishu 期数:201707 * @param string $sid 学校id:school 中的id * @return array */ public function getSczylbData($qishu='201810',$sid='15'){ $id = $this->getQishuId($qishu,$sid,1); $xyxxb = $this->checkFenbiao($id,'xyxxb');//判断是否是分表 $school_name = M('school')->where(array('id'=>$sid))->getField('name'); $where = "suoshudd =$id and xuehao != '' and (zhuangtai = '在读' or zhuangtai = '休学') and xiaoqu ='$school_name'";// 下面$arr获取数据的查询条件 $schools = M($xyxxb)->field('jiuduxx,nianji,count(*) as count')->where($where)->group('jiuduxx,nianji')->order('id')->select(); //获取分校公立学校规模数 $guimo = M("gonglixx")->where("sid = $sid")->select(); $guimo_arr = array(); foreach ($guimo as $g){ $guimo_arr[$g['xuexiao']] = $g['xuexiaogms']; } $data = array(); $nianji_arr = array("幼儿园"=>"youeryuan","一年级"=>"yinianji","二年级"=>"ernianji","三年级"=>"sannianji","四年级"=>"sinianji","五年级"=>"wunianji","六年级"=>"liunianji","初一"=>"chuyi","初二"=>"chuer","初二以上"=>"chuerys"); $p = 1; foreach($schools as $k=>$v){ if ($v['jiuduxx'] == ''){ $v['jiuduxx'] = '空'.$p;$p++; } switch($v['nianji']){ case '小班': case '中班': case '大班': $data[$v['jiuduxx']]['幼儿园'] += $v['count']; break; case '一年级': case '二年级': case '三年级': case '四年级': case '五年级': case '六年级': case '初一': case '初二': $data[$v['jiuduxx']][$v['nianji']] += $v['count']; break; default: $data[$v['jiuduxx']][$v['初二以上']] += $v['count']; break; } } $arr = array(); $i = 1; foreach ($data as $k=>$v){ if(mb_substr($k,0,1,'utf-8') == '空'){ $k = ''; } $arr[$i]['xuhao'] = $i; $arr[$i]['gonglixx'] = $k; $heji = 0; foreach ($nianji_arr as $m=>$n){ if (array_key_exists($m,$v)){ $arr[$i][$n] = $v[$m]; $heji += $v[$m]; }else{ $arr[$i][$n] = 0; } } $arr[$i]['heji'] = $heji; $arr[$i]['xuexiaogms'] = $guimo_arr[$k]?$guimo_arr[$k]:0; if($arr[$i]['xuexiaogms'] ==0){ $arr[$i]['zhaoyoulv'] = 0; }else{ $arr[$i]['zhaoyoulv'] = round($heji/$arr[$i]['xuexiaogms'],4); } $i++; } return $arr; } public function getSczylbData_bak($qishu,$sid){ $where['qishu'] = $qishu;// 获取期数 $where['sid'] = $sid;// 获取学校id $where['tid'] = 3;// 从班级学员信息表获取信息,它的tid是3 $id = M('qishu_history')->where($where)->getField('id');// 获取对应qishu_history的id,也就是bjxyxxb里面的suoshudd的订单号 // ------------以下所有数据都根据suoshudd的id号查询出------------ // $heji是每个年级对应的合计数 // $data是每个公立学校对应的每个年级的合计数 // $res是返回的数据,$res = ['data'=>$data,'heji'=>$heji]; // $heji unset($where); $bjxyxxb = $this->checkFenbiao($id,'bjxyxxb');//判断是否是分表 $where = 'suoshudd ='.$id.' and ((xuehao !="" and beizhu = "") or banji = "停读" or banji = "未进班")';// 下面$arr获取数据的查询条件 $arr = M($bjxyxxb)->field('count(*) as count,nianji')->where($where)->group('nianji')->select(); $heji = $this->getHeji($arr); // $data $schools = M($bjxyxxb)->field('gonglixx')->where($where)->group('gonglixx')->select();// 得出所有公立学校的数组 foreach($schools as $k=>$v){ $temp = M($bjxyxxb)->field('count(*) as count,nianji,gonglixx')->where('gonglixx ="'.$v['gonglixx'].'" and suoshudd ='.$id.' and ((xuehao !="" and beizhu = "") or banji = "停读" or banji = "未进班")')->group('nianji')->select(); $youeryuan = 0; $count = 0; foreach($temp as $v1){ $count += $v1['count']; switch($v1['nianji']){ case '小班': case '中班': case '大班': $data[$k+1]['youeryuan'] += $v1['count']; break; case '一年级': case '二年级': case '三年级': case '四年级': case '五年级': case '六年级': case '初一': case '初二': $data[$k+1][$this->encode($v1['nianji'],'all')] = $v1['count']; break; // case '一年级': // $data[$k+1]['yinianji'] = $v1['count']; // break; // case '二年级': // $data[$k+1]['ernianji'] = $v1['count']; // break; // case '三年级': // $data[$k+1]['sannianji'] = $v1['count']; // break; // case '四年级': // $data[$k+1]['sinianji'] = $v1['count']; // break; // case '五年级': // $data[$k+1]['wunianji'] = $v1['count']; // break; // case '六年级': // $data[$k+1]['liunianji'] = $v1['count']; // break; // case '初一': // $data[$k+1]['chuyi'] = $v1['count']; // break; // case '初二': // $data[$k+1]['chuer'] = $v1['count']; // break; default: $data[$k+1]['chuerys'] += $v1['count']; break; } $data[$k+1]['gonglixx'] = $v1['gonglixx']; } $data[$k+1]['heji'] = $count; } $res = ['data'=>$data,'heji'=>$heji]; return $res; } }
php
20
0.386635
235
37.545455
165
starcoderdata
import React from 'react'; import TextInput from './TextInput'; //import { Link } from 'react-router-dom'; class HomePage extends React.Component { constructor(props) { super(props); this.state ={ teste: ' ' }, this.list ={ "games":[ { "title":"Hotline Miami", "price":4.24, "rating":"-", "discount":"-75%", "path":"/app/219150/", "id":219150, "url":"https://steamdb.info/app/219150/", "imageUrl":"https://steamdb.info/static/camo/apps/219150/header.jpg" }, { "title":"Hotline Miami 2: Wrong Number", "price":6.24, "rating":"-", "discount":"-75%", "path":"/app/274170/", "id":274170, "url":"https://steamdb.info/app/274170/", "imageUrl":"https://steamdb.info/static/camo/apps/274170/header.jpg" }, this.teste = '', ] } } render(){ //const {list} = this.props; console.log(this.list); return ( <div class="row align-items-start"> <div class="col-3"> <div class="col-4"> <TextInput name="Email" value={this.state.teste}/> <div class="col-1"> <button type="button" className="btn btn-outline-primary">Buscar <table className="table"> <thead className="thead-dark"> <th scope="col"># <th scope="col">Nome <th scope="col">Preço <th scope="col">Preço Original <th scope="col">Loja <th scope="col">Id Loja <th scope="col">URL <th scope="col">Ação {this.list.games.map((game) => ( type="button" class="btn btn-warning">Favoritar ))} ); } } export default HomePage;
javascript
19
0.435928
88
27.146067
89
starcoderdata
/** * Created by lukepowell on 10/4/17. * @fileoverview Block to allow arbitrary JavaScript code to be run by advanced students * @author ( * @copyright DigiPen Institute of Technology 2017 */ 'use strict'; goog.provide('Blockly.JavaScript.eval'); goog.require('Blockly.JavaScript'); Blockly.JavaScript['javascript_eval'] = function(block){ const evalStr = block.getFieldValue('EVAL'); return `${evalStr}\n`; }; Blockly.JavaScript['javascript_eval_output'] = function(block){ const evalStr = block.getFieldValue('EVAL'); return [`${evalStr}`, Blockly.JavaScript.ORDER_FUNCTION_CALL]; };
javascript
8
0.719821
88
29.5
22
starcoderdata
import React, { Component } from 'react'; import Link from 'next/link' import Button from '../node_modules/react-bootstrap/Button'; import 'bootstrap/dist/css/bootstrap.min.css'; export default class Groupregistration extends Component { constructor(props) { super(props); this.handlesubmit = this.handlesubmit.bind(this); } handlesubmit(e){ e.preventDefault(); const method = "POST"; const body = JSON.stringify({name: information.name.value,email_address: information.email_address.value,password: information.limit.value,}); //console.log(body); fetch('https://9dlsqbzy25.execute-api.eu-west-1.amazonaws.com/register_place/register_place',{method: "POST",body: body}) .then((response) => response.json()) .then((responseJson) => { //console.log(responseJson); if(responseJson.result == 2){ window.alert("あなたのトークンは"+responseJson.password_token+"です。必ずメモをとってください。") }else{ window.alert("あなたの団体は登録済みです。ログインしてください。") } location.href = "/group_log_in"; }) .catch((error) =>{ window.alert("登録時にエラーが起きました。もう一度入力してください。") location.href = "/group_registration" //console.error('error'); }); } render(){ return(<div className='text-center'> registration   Appへようこそ id="information" onSubmit={this.handlesubmit}>  <input type="text" name="name" placeholder="Name" required>  <input type="email" name="email_address" placeholder="Email" required>  <input type="text" name="password" minLength="5" placeholder="Password" required>  <input type="number" name="limit" min="1" placeholder="Limit" required> <Button variant='info' type="submit">新規登録 <Link href = "/group_log_in"> <Link href = "/"> Home } }
javascript
21
0.533915
168
39.360656
61
starcoderdata
<?php use Illuminate\Support\Facades\Route; function copyRecursive($source, $destiny, $mode = 0755) { $info = pathinfo($destiny); if (!file_exists($info['dirname'])) { mkdir($info['dirname'], $mode, true); } return copy($source, $destiny); } if (!function_exists('formatPrice')) { /** * Format integer to a price * @param integer $price * @return string */ function formatPrice($price) { return 'R$' . number_format((float)$price, 2, ',', '.'); } } if (! function_exists('activeMenu')) { function activeMenu($routes) { return in_array(Route::currentRouteName(), explode('|', $routes)) ? 'active' : ''; } }
php
14
0.573066
90
20.84375
32
starcoderdata
console.info("Hot reloader enabled..."); const elem = document.createElement("div"); elem.innerText = "Rebuilding..."; elem.style.position = "fixed"; elem.style.width = "250px"; elem.style.height = "65px"; elem.style.background = "blue"; elem.style.color = "white"; elem.style.top = "0"; elem.style.left = "calc(50% - 125px)"; elem.style.zIndex = "99999"; elem.style.lineHeight = "65px"; elem.style.textAlign = "center"; elem.style.fontFamily = '"Inconsolata", monospace'; elem.style.fontSize = "18pt"; elem.style.borderRadius = "0 0 30px 30px"; let rebuilding = false; let path = window.location.pathname.slice(1); if (path.indexOf(".") === -1) { if (path.length > 0) { path += "/index.html"; } else { path += "index.html"; } } async function poller() { let latestVersion; try { latestVersion = await fetch("/get_revision", { method: "POST", cache: "no-cache", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ path }), }); } catch { latestVersion = { ok: false }; } let data = null; if (latestVersion.ok) { data = await latestVersion.json(); } if (data == null || data.manualVersion !== manualVersion) { // a manual make invocation has taken place // disable auto-reload document.body.appendChild(elem); elem.style.background = "red"; elem.innerText = "Refresh to update"; clearInterval(interval); return; } if (data.pubVersion !== data.srcVersion) { document.body.appendChild(elem); if (!rebuilding) { const resp = await fetch("/rebuild_path", { method: "POST", cache: "no-cache", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ path }), }); if (resp.ok) { rebuilding = true; } } } if (data.pubVersion !== version) { window.location.reload(); } } const interval = setInterval(poller, 700);
javascript
13
0.612014
65
25.038462
78
starcoderdata
// Copyright (c) All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Pihrtsoft.Snippets; using static Pihrtsoft.Text.RegularExpressions.Linq.Patterns; namespace Snippetica.CodeGeneration.Commands { public class GenerateAlternativeShortcutCommand : SnippetCommand { private static readonly Regex _regex = AssertBack(LetterLower()).Assert(LetterUpper()).ToRegex(); public override CommandKind Kind => CommandKind.AlternativeShortcut; public override Command ChildCommand => CommandUtility.SuffixFileNameWithUnderscoreCommand; protected override void Execute(ExecutionContext context, Snippet snippet) { snippet.Shortcut = CreateAlternativeShortcut(snippet); snippet.AddTag(KnownTags.NonUniqueTitle); } private static string CreateAlternativeShortcut(Snippet snippet) { IEnumerable values = _regex.Split(snippet.Shortcut) .Select(f => f.Substring(0, 1) + f.Substring(f.Length - 1, 1)) .Select(f => f.ToLower(CultureInfo.InvariantCulture)); return string.Concat(values); } } }
c#
23
0.711355
155
36.916667
36
starcoderdata
package su.sold.playersgeo.listener; import fr.xephi.authme.events.LoginEvent; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.json.JSONObject; import su.sold.playersgeo.Database; import su.sold.playersgeo.Plugin; import su.sold.playersgeo.util.Geo; import java.io.IOException; import java.util.Objects; public class AuthMeListener implements Listener { private Plugin plugin; public AuthMeListener(Plugin p){ plugin = p; } @EventHandler(priority = EventPriority.NORMAL) public void onLogin(LoginEvent event) throws IOException { final Player ply = event.getPlayer(); new Thread(new Runnable() { @Override public void run() { JSONObject data = null; try { data = Geo.getGeoIPData(Objects.requireNonNull(ply.getAddress()).getAddress().getHostAddress()); } catch (IOException e) { e.printStackTrace(); } if(data!=null) { Plugin.log.info("§c[§ePlayers§6Geo§c] §f"+ply.getName()+ " §e from §l"+data.getString("geoplugin_city")+", "+data.getString("geoplugin_countryCode")); Geo.notifyOnPlayerJoin(ply.getName()+ "§e from §l"+data.getString("geoplugin_city")+", "+data.getString("geoplugin_countryCode")); plugin.db.add(ply.getName(), data.getString("geoplugin_city"), data.getString("geoplugin_countryName"), data.getString("geoplugin_countryCode"), data.getString("geoplugin_latitude"), data.getString("geoplugin_longitude")); }else{ Plugin.log.info("§c[§ePlayers§6Geo§c] §cGeo data not found for §e" +ply.getName()); } } }).start(); } }
java
25
0.632853
242
37.84
50
starcoderdata
private void OnReorderObject(SerializedProperty sect, int i1, int i2) { // reorder objs var objs = sect.serializedObject.FindProperty("objs"); objs.MoveArrayElement(i1, i2); sect.serializedObject.ApplyModifiedProperties(); // reorder visibility element var switches = sect.serializedObject.FindProperty("switches"); for (int i = 0; i < switches.arraySize; ++i) { var s = switches.GetArrayElementAtIndex(i); var visibility = s.FindPropertyRelative("visibility"); if (sect.propertyPath != visibility.propertyPath) { visibility.MoveArrayElement(i1, i2); } } sect.serializedObject.ApplyModifiedProperties(); }
c#
14
0.561758
74
41.15
20
inline
const rootPatterns = [{ // rxjs/operator/map regex: /^rxjs\/operator\//, root: ['Rx', 'Observable', 'prototype'] }, { // rxjs/observable/interval regex: /^rxjs\/observable\/[a-z]/, root: ['Rx', 'Observable'] }, { // rxjs/observable/MulticastObservable regex: /^rxjs\/observable\/[A-Z]/, root: 'Rx' }, { // rxjs/scheduler/asap regex: /^rxjs\/scheduler\/[a-z]/, root: ['Rx', 'Scheduler'] }, { // rxjs/scheduler/VirtualTimeScheduler regex: /^rxjs\/scheduler\/[A-Z]/, root: 'Rx' }]; function rootForRequest(path) { const match = rootPatterns.find(pattern => path.match(pattern.regex)); if (match) { return match.root; } return 'Rx'; } function rxjsExternalsFactory() { return function rxjsExternals(context, request, callback) { if (request.startsWith('rxjs/')) { return callback(null, { root: rootForRequest(request), commonjs: request, commonjs2: request, amd: request }); } callback(); }; } module.exports = rxjsExternalsFactory;
javascript
15
0.613833
72
19.019231
52
starcoderdata
const fs = require('fs'); function prepareHTML(employeeArray){ generateHTML() for (let index = 0; index < employeeArray.length; index++) { if (employeeArray.length>0) { appendEmployee(employeeArray[index]); } else { closeHTML() } }} // for loop to loop through each employee in the array // use appendHTML for each employee in the for loop // once all employees appended close HTMl function generateHTML() { let html = `<!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="Description" content="Enter your description here" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css"> Profiles <div class="min-vh-100 p-5 bg-dark text-black"> <div class="container-fluid"> <h1 class="text-white text-center">Welcome to the Team! <div class="d-flex justify-content-around pt-2">` fs.writeFile('./dist/output.html', html, (err) => err ? console.error(err) : console.log('Your team profile is ready in ./dist/output.html') ) } function appendEmployee(employee) { return new Promise(function(resolve, reject) { const name = employee.getName(); const role = employee.getRole(); const id = employee.getId(); const email = employee.getEmail(); let data = ''; if (role === 'Manager') { const officeNumber = employee.getOfficeNumber() data = `<div class="card mb-2 " style="max-width: 25rem"> <div class="card-body text-white bg-primary "> <h5 class="card-title">${name} <h6 class="card-subtitle">${role} <ul class="list-group list-group-flush"> <li class="list-group-item">Member ID: ${id} <li class="list-group-item">Email: <a href="mailto:${email}">${email} <li class="list-group-item">Office Number: ${officeNumber} } else if (role === 'Engineer') { const GitHub = employee.getGithub() data = `<div class="card mb-2" style="max-width: 25rem"> <div class="card-body text-white bg-primary "> <h5 class="card-title">${name} <h6 class="card-subtitle">${role} <ul class="list-group list-group-flush"> <li class="list-group-item">Member ID: ${id} <li class="list-group-item">Email: <a href="mailto:${email}">${email} <li class="list-group-item">Github: <a target="_blank" href="https://github.com/${GitHub}">${GitHub} } else { const school = employee.getSchool() data = `<div class="card mb-2" style="max-width: 25rem"> <div class="card-body text-white bg-primary "> <h5 class="card-title">${name} <h6 class="card-subtitle">${role} <ul class="list-group list-group-flush"> <li class="list-group-item">Member ID: ${id} <li class="list-group-item">Email: <a href="mailto:${email}">${email} <li class="list-group-item">School: ${school} fs.appendFile('./dist/output.html', data, function (err) { if (err) { return reject(err); }; return resolve(); }); }); } function closeHTML() { const html = ` fs.appendFile("./dist/output.html", html, function (err) { if (err) { console.log(err); }; }); } module.exports = prepareHTML
javascript
17
0.526026
125
33.078125
128
starcoderdata
import subprocess import re class Wifi: @staticmethod def do(action,data:dict): obj = Wifi() if(action=='add'): return obj.addwifi(data) elif(action=='delete'): return obj.removewifi(data['ssid']) elif(action=='edit'): return obj.editWifi(data) else: return {'error':True,'msg':'Invalid Operation'} def addwifi(self,info:dict): network = self.__newNetwork(info) data = self.__readInterfaceFile(); networks = data['networks'] if self.__exists(info['ssid'],networks): return {'error':True,'msg':'SSID already exist'} newData = self.__formatNetworks(networks); newData.append(network) newData.insert(0,data['title']); self.__writeInterfaceFile(newData) return {'error':False} def editWifi(self,info:dict): data = self.__readInterfaceFile(); networks = data['networks'] net = None for x in range(0, len(networks)): if re.match(r'.*#app.*', networks[x]) and re.match(r'.*' + info['oldssid'] + '.*', networks[x]): del networks[x] net = self.__newNetwork(info) break newData = self.__formatNetworks(networks) if(net != None): newData.append(net) newData.insert(0, data['title']) self.__writeInterfaceFile(newData) return {'error': False} def removewifi(self,ssid): data = self.__readInterfaceFile(); networks = data['networks'] for x in range(0,len(networks)): if re.match(r'.*#app.*',networks[x]) and re.match(r'.*'+ssid+'.*',networks[x]): del networks[x] break newData = self.__formatNetworks(networks) newData.insert(0,data['title']) self.__writeInterfaceFile(newData) return {'error':False} def __exists(self,ssid,networks:list): for net in networks: if re.match('.*' + ssid + '.*', net): return True return False def __formatNetworks(self,networks:list): formatted = [] length = len(networks) for i in range(0,length): sp = '\n\t' fm = re.sub('\s+',sp,networks[i]) indx = fm.rindex(sp) n_str = fm[0:indx]+'\n'+fm[indx+2:]+'\n\n' formatted.append(n_str) return formatted def __newNetwork(self,info:dict): if(info['password'] != ''): return 'network={\n\tssid="'+ info['ssid'] + '"\n\tpsk="'+info['password']+'"\n\t#app="true"\n}\n\n' return 'network={\n\tssid="' + info['ssid'] + '"\n\t#app="true"\n}\n\n' def __readInterfaceFile(self): f = open('/etc/wpa_supplicant/wpa_supplicant.conf','r') original = f.read(); data = re.sub(r'\s',' ',original) f.close() networks = re.findall(r'network[=][{].*?[}]',data); others = original[0:original.index('network')] configs = []; #for x in networks: #configs.append(re.sub(r'network[=][{]|[}]','',x)) return {'networks':networks,'title':others} def __writeInterfaceFile(self,data:list): f = open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w+') f.writelines(data); f.close()
python
15
0.529982
112
26.007937
126
starcoderdata
def added(self, nodename, nodeid): "Tell all plugins this node has been added." for p in self.plugins: try: p.added(nodename, nodeid) except: self.logError(p)
python
11
0.672316
46
21.25
8
inline
#include "pf/basic/string.h" #include "pf/support/helpers.h" #include "pf/console/input_definition.h" using namespace pf_console; // Sets the definition of the input. void InputDefinition::set_definition( const std::vector<InputParameter *> &defines) { std::vector options; std::vector arguments; for (InputParameter *define : defines) { if (instanceof(define, InputOption)) { InputOption option = *dynamic_cast<InputOption *>(define); options.emplace_back(option); } else { InputArgument argument = *dynamic_cast<InputArgument *>(define); arguments.emplace_back(argument); } } set_options(options); set_arguments(arguments); } // Sets the InputArgument objects. void InputDefinition::set_arguments( const std::vector &arguments) { arguments_.clear(); required_count_ = 0; has_optional_ = false; has_an_array_argument_ = false; add_arguments(arguments); } // Adds an array of InputArgument objects. void InputDefinition::add_arguments( const std::vector &arguments) { for (InputArgument argument : arguments) { add_argument(argument); } } // Add an argument. void InputDefinition::add_argument(const InputArgument &argument) { if (arguments_.find(argument.name()) != arguments_.end()) { std::string msg{""}; msg = "An argument with name '" + argument.name() + "' already exists."; AssertEx(false, msg.c_str()); return; } if (has_an_array_argument_) { AssertEx(false, "Cannot add an argument after an array argument."); return; } if (argument.is_required() && has_optional_) { AssertEx(false, "Cannot add a required argument after an optional one."); return; } if (argument.is_array()) { has_an_array_argument_ = true; } if (argument.is_required()) { ++required_count_; } else { has_optional_ = true; } argument_names_.emplace_back(argument.name()); arguments_[argument.name()] = argument; } // Sets an argument. void InputDefinition::set_argument(const InputArgument &argument) { if (arguments_.find(argument.name()) == arguments_.end()) { AssertEx(false, "Cannot set a not exists argument."); return; } arguments_[argument.name()] = argument; } // Get an argument by name. InputArgument InputDefinition::get_argument(const std::string &name) { InputArgument r; if (!has_argument(name)) { std::string msg{""}; msg = "The " +name+ " argument does not exist."; AssertEx(false, msg.c_str()); return r; } r = arguments_[name]; return r; } // Get an argument by position. InputArgument InputDefinition::get_argument(uint32_t pos) { InputArgument r; if (pos < argument_names_.size()) r = arguments_[argument_names_[pos]]; return r; } // Returns true if an InputArgument object exists by name. bool InputDefinition::has_argument(const std::string &name) { return arguments_.find(name) != arguments_.end(); } // Returns true if an InputArgument object exists by position. bool InputDefinition::has_argument(uint32_t pos) { return pos < argument_names_.size(); } // Gets the array of InputArgument objects. std::map<std::string, InputArgument> InputDefinition::get_arguments() { return arguments_; } // Returns the number of InputArguments. size_t InputDefinition::get_argument_count() const { return arguments_.size(); } // Returns the number of required InputArguments. size_t InputDefinition::get_argument_require_count() const { return static_cast } // Gets the default values. std::map<std::string, std::string> InputDefinition::get_argument_defaults() { std::map<std::string, std::string> r; for (auto it = arguments_.begin(); it != arguments_.end(); ++it) { r[it->first] = it->second.get_default(); } return r; } // Sets the InputOption objects. void InputDefinition::set_options(const std::vector &options) { options_.clear(); shortcuts_.clear(); add_options(options); } // Adds an array of InputOption objects. void InputDefinition::add_options(const std::vector &options) { for (const InputOption &option : options) { add_option(option); } } // Add an option. void InputDefinition::add_option(const InputOption &option) { using namespace pf_support; if (options_.find(option.name()) != options_.end() && option.equals(&options_.find(option.name())->second)) { std::string msg{""}; msg = "An option named " + option.name() + " already exists."; AssertEx(false, msg.c_str()); return; } auto shortcuts = option.shortcut(); // std::cout << "name: " << option.name() << " shortcuts: " << shortcuts << std::endl; if ("" != shortcuts) { for (auto &shortcut : explode("|", shortcuts)) { if (shortcuts_.find(shortcut.data) != shortcuts_.end() && option.equals(&options_.find(shortcuts_[shortcut.data])->second)) { std::string msg{""}; msg = "An option with shortcut "+shortcut.data+" already exists."; AssertEx(false, msg.c_str()); return; } } } options_[option.name()] = option; if ("" != shortcuts) { for (auto &shortcut : explode("|", shortcuts)) { shortcuts_[shortcut.data] = option.name(); } } } // Returns an InputOption by name. InputOption InputDefinition::get_option(const std::string &name) { InputOption r; if (!has_option(name)) { std::string msg{""}; msg = "The '--" + name + "' option does not exist."; AssertEx(false, msg.c_str()); return r; } r = options_[name]; return r; } // Returns true if an InputOption object exists by name. bool InputDefinition::has_option(const std::string &name) const { return options_.find(name) != options_.end(); } // Gets the array of InputOption objects. std::map<std::string, InputOption> InputDefinition::get_options() { return options_; } // Returns true if an InputOption object exists by shortcut. bool InputDefinition::has_shortcut(const std::string &name) { return shortcuts_.find(name) != shortcuts_.end(); } // Gets an InputOption by shortcut. InputOption InputDefinition::get_option_for_shortcut( const std::string &shortcut) { return get_option(shortcut_toname(shortcut)); } // Gets an array of default values. std::map<std::string, std::string> InputDefinition::get_option_defaults() { std::map<std::string, std::string> r; for (auto it = options_.begin(); it != options_.end(); ++it) r[it->first] = it->second.get_default(); return r; } // Returns the InputOption name given a shortcut. std::string InputDefinition::shortcut_toname(const std::string &shortcut) { if (shortcuts_.find(shortcut) == shortcuts_.end()) { std::string msg{""}; msg = "The -" +shortcut+ " option does not exist."; AssertEx(false, msg.c_str()); return ""; } return shortcuts_[shortcut]; } // Gets the synopsis. std::string InputDefinition::get_synopsis(bool _short) { using namespace pf_support; std::vector elements; if (_short && !options_.empty()) { elements.emplace_back("[options]"); } else if (!_short) { for (auto it = options_.begin(); it != options_.end(); ++it) { std::string value{""}; if (it->second.accept_value()) { auto temp = pf_basic::string::toupper(it->second.name()); value = value + " " + (it->second.is_optional() ? "[" : "") + temp + (it->second.is_optional() ? "[" : ""); } std::string _shortcut = it->second.shortcut(); std::string shortcut{""}; if (_shortcut != "") shortcut = shortcut + "-" + _shortcut + "|"; std::string element{"["}; element += shortcut + "--" + it->second.name() + value + "]"; elements.emplace_back(element); } } if (elements.size() > 0 && arguments_.size() > 0) { elements.emplace_back("[--]"); } std::string tail{""}; for (auto it = arguments_.begin(); it != arguments_.end(); ++it) { std::string element = "<" + it->second.name() + ">"; if (it->second.is_array()) { element += "..."; } if (!it->second.is_required()) { element = "[" + element; tail += "]"; } elements.emplace_back(element); } return implode(" ", elements) + tail; }
c++
21
0.642572
88
28.974638
276
starcoderdata