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
package app_test import ( _ "embed" "fmt" "net/http" "os" "github.com/gin-gonic/gin" "github.com/iver-wharf/wharf-core/pkg/app" ) // The version.yaml file should be populated by a CI pipeline build step just // before building the binary for this application. // // For example, assuming you have BUILD_VERSION, BUILD_GIT_COMMIT, and BUILD_REF // environment variables set before running the following script: // // #!/bin/sh // // cat <<EOF > version.yaml // version: ${BUILD_VERSION} // buildGitCommit: ${BUILD_GIT_COMMIT} // buildDate: $(date '+%FT%T%:z') // buildRef: ${BUILD_REF} // EOF // go:embed version.yaml var versionFile []byte // AppVersion is the type holding metadata about this application's version. var AppVersion app.Version // getVersionHandler godoc // @summary Returns the version of this API // @tags meta // @success 200 {object} app.Version // @router /version [get] func getVersionHandler(c *gin.Context) { c.JSON(http.StatusOK, AppVersion) } func ExampleVersion_ginEndpoint() { if err := app.UnmarshalVersionYAML(versionFile, &AppVersion); err != nil { fmt.Println("Failed to read embedded version.yaml file:", err) os.Exit(1) } // If you use swaggo then you can set the API version like so: // // docs.SwaggerInfo.Version = AppVersion.Version // // More info: https://github.com/swaggo/swag#how-to-use-it-with-gin r := gin.Default() r.GET("/version", getVersionHandler) _ = r.Run() }
go
9
0.697736
80
24.033333
60
starcoderdata
import { Subject } from 'rxjs'; const subject = new Subject(); export const paymentService = { paymentInitiated: payload => subject.next({ event: 'PAYMENT_INITIATED', payload: payload }), paymentProcessed: (payload) => subject.next({ event: 'PAYMENT_PROCESSED', payload: payload }), getService: () => subject.asObservable() };
javascript
11
0.655914
80
28.125
16
starcoderdata
package io.qameta.htmlelements.handler; import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.MethodInvocationException; import io.qameta.htmlelements.exception.NotImplementedException; import io.qameta.htmlelements.extension.MethodHandler; import io.qameta.htmlelements.extension.MethodParameters; import io.qameta.htmlelements.extension.Retry; import io.qameta.htmlelements.extension.TargetModifier; import io.qameta.htmlelements.extension.Timeout; import io.qameta.htmlelements.statement.ListenerStatement; import io.qameta.htmlelements.statement.RetryStatement; import io.qameta.htmlelements.statement.Statement; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.UndeclaredThrowableException; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import static io.qameta.htmlelements.util.ReflectionUtils.getMethodsNames; public class WebBlockMethodHandler implements InvocationHandler { private final Supplier targetProvider; private final Context context; private final Class[] targetClasses; public WebBlockMethodHandler(Context context, Supplier targetProvider, Class... targetClasses) { this.targetProvider = targetProvider; this.targetClasses = targetClasses; this.context = context; } private Class[] getTargetClasses() { return targetClasses; } private Supplier getTargetProvider() { return this.targetProvider; } private Context getContext() { return context; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Class[] targetClass = getTargetClasses(); Statement base; // web element proxy if (getMethodsNames(targetClass, "equals", "hashCode").contains(method.getName())) { base = () -> safeInvokeTargetMethod(targetProvider, method, args); } else { MethodHandler handler = getContext().getRegistry().getHandler(method) .orElseThrow(() -> new NotImplementedException(method)); base = () -> handler.handle(getContext(), proxy, method, args); } ListenerStatement statement = prepareListenerStatement(method, args); RetryStatement retry = prepareRetryStatement(method, args); try { return statement.apply(retry.apply(base)).evaluate(); } catch (MethodInvocationException e) { throw e.getCause(); } } @SuppressWarnings("unchecked") private ListenerStatement prepareListenerStatement(Method method, Object[] args) { String description = getContext().getStore().get(Context.DESCRIPTION_KEY, String.class).get(); ListenerStatement statement = new ListenerStatement(description, method, args); getContext().getStore().get(Context.LISTENERS_KEY, List.class).ifPresent(statement::withListeners); return statement; } private RetryStatement prepareRetryStatement(Method method, Object[] args) { Properties properties = getContext().getStore().get(Context.PROPERTIES_KEY, Properties.class).get(); RetryStatement retry = new RetryStatement(properties) .ignoring(Throwable.class); if (method.isAnnotationPresent(Retry.class)) { Retry retryAnnotation = method.getAnnotation(Retry.class); retry.withTimeout(retryAnnotation.timeoutInSeconds(), TimeUnit.SECONDS) .pollingEvery(retryAnnotation.poolingInMillis(), TimeUnit.MILLISECONDS) .ignoring(retryAnnotation.ignoring()); } MethodParameters parameters = new MethodParameters(method, args); parameters.getParameter(Timeout.class, Long.class) .ifPresent(timeout -> retry.withTimeout(timeout, TimeUnit.SECONDS)); return retry; } @SuppressWarnings("unchecked") private Object safeInvokeTargetMethod(Supplier targetProvider, Method method, Object[] args) throws Throwable { try { Object target = targetProvider.get(); for (TargetModifier modifier : getContext().getRegistry().getExtensions(TargetModifier.class)) { target = modifier.modify(getContext(), target); } return method.invoke(target, args); } catch (InvocationTargetException | IllegalAccessException e) { throw new MethodInvocationException(e); } } public Object getUnwrappedObject() { return targetProvider.get(); } }
java
13
0.707363
116
38.396694
121
starcoderdata
package controllers; import models.entity.Gyudon; import models.form.GyudonForm; //import models.repository.GyudonRepository; import models.repository.GyudonRepository; import play.data.Form; import play.db.jpa.Transactional; import play.db.jpa.JPA; import play.mvc.*; import views.html.*; import java.util.Date; import static play.data.Form.form; import static play.db.jpa.JPA.em; public class Application extends Controller { //@Transactional(value="default",readOnly=true) @Transactional(value = "default") public static Result index() { Gyudon firstGyudon = em().find(Gyudon.class, 1L); if(firstGyudon == null){ Gyudon gyudon = new Gyudon(); gyudon.id = 1L; //gyudon.id = GyudonRepository.getMaxId().getId() + 1L; gyudon.name = "hogehuga"; gyudon.create_at = new Date(); gyudon.update_at = new Date(); em().persist(gyudon); firstGyudon = gyudon; } System.out.println(firstGyudon.getId() + ":" + firstGyudon.getName() + ":" + firstGyudon.getUpdate_at()); //firstGyudon.name = "betumei"; //JPA.em().persist(firstGyudon); //JPA.em().remove(firstGyudon); //List gyudons = (List GyudonRepository.findById(0L); GyudonRepository gyudonRepo = new GyudonRepository(); return ok(index.render("今までにチーズ牛丼中盛りツユダクを食べた人は " + gyudonRepo.findAll().size() +" 人です", form(GyudonForm.class))); } @Transactional(value = "default") public static Result send() { Form f = form(GyudonForm.class).bindFromRequest(); if (!f.hasErrors()) { GyudonForm data = f.get(); if (data.action.equals("insert")){ Gyudon gyudon = new Gyudon(); gyudon.id = data.id; //gyudon.id = GyudonRepository.getMaxId().getId() + 1L; gyudon.name = data.name; gyudon.create_at = new Date(); em().persist(gyudon); }else if (data.action.equals("update")){ Gyudon gyudon = em().find(Gyudon.class, data.id); gyudon.name = data.name; gyudon.update_at = new Date(); em().merge(gyudon); }else if (data.action.equals("delete")){ Gyudon gyudon = em().find(Gyudon.class, data.id); em().remove(gyudon); } String msg = "you gyudoned: " + data.name + "さんがチーズ牛丼中盛りツユダクを" + data.action; return ok(index.render(msg, f)); }else{ return badRequest(index.render("ERRER", form(GyudonForm.class))); } } }
java
14
0.683248
115
28.4
80
starcoderdata
import time import sys def currentTime(): return int(time.time()), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) def checkPythonVersion(minRequired=3,minSubRequired=0): if sys.version_info < (minRequired,minSubRequired): print("ERROR: Please use python version {0}.{1}+".format(minRequired,minSubRequired)) exit(0) else: return True
python
11
0.668421
93
26.142857
14
starcoderdata
/** * @author */ function showHidePages(showPage, hidePage ){ showPage.height = Ti.UI.SIZE; showPage.show(); hidePage.hide(); hidePage.height = 0; hidePage = null; } function showView(ele){ ele.height = Ti.UI.SIZE; ele.show(); } function hideView(ele){ ele.hide(); ele.height = 0; ele = null; } var style; if (Ti.Platform.name === 'iPhone OS'){ style = Ti.UI.iPhone.ActivityIndicatorStyle.BIG; }else{ style = Ti.UI.ActivityIndicatorStyle.PLAIN; } var activityIndicator = Ti.UI.createActivityIndicator({ width: 'auto', height: 'auto', message: 'Loading...', color: '#FFF', id: 'activityIndicator', style: style }); function showActivityIndicator(win){ activityIndicator.show(); win.add(activityIndicator); } function hideActivityIndicator(win){ activityIndicator.hide(); win.remove(activityIndicator); activityIndicator = null; } function padIntRight(num){ var str = num.toString(), strArray = str.split("."); if (str === '' || strArray.length === 1) { return ''; } if( strArray[1].length < 2){ strArray[1] += '0'; console.log(strArray[1]); } return strArray[0] + '.' + strArray[1]; }
javascript
10
0.626926
55
15.44
75
starcoderdata
package org.studierstube.opentracker; import org.studierstube.opentracker.OT_CORBA.EventAttribute; import org.studierstube.opentracker.OT_CORBA.EventHelper; import org.studierstube.opentracker.OT_CORBA.FloatVectorHelper; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; import org.omg.CORBA.ORB; import org.omg.CORBA.Any; /** * Multimodal OpenTracker Event. * * @author * @author jfn */ public class OTEvent extends HashMap<String, Any> { /** * */ private static final long serialVersionUID = -6849795742997397981L; private ORB orb; public OTEvent(ORB _orb) { orb = _orb; } public OTEvent(ORB _orb, EventAttribute[] atts) { this(_orb); for (int i = 0; i < atts.length; i++) { System.out.println("name of event attribute is " + atts[i].name); put(atts[i].name, atts[i].value); } } public Vector3f getPosition() { return new Vector3f(FloatVectorHelper.extract(get("position"))); } public void setPosition(Vector3f pos) { Any value = orb.create_any(); float fv[] = {pos.x, pos.y, pos.y}; FloatVectorHelper.insert(value, fv); put("position", value); } public Vector4f getOrientation() { return new Vector4f(FloatVectorHelper.extract(get("orientation"))); } public void setOrientation(Vector4f ori) { Any value = orb.create_any(); float fv[] = {ori.x, ori.y, ori.z, ori.w}; FloatVectorHelper.insert(value, fv); put("orientation", value); } public float getTimestamp() { return get("timestamp").extract_float(); } public void setTimestamp(float timestamp) { Any value = orb.create_any(); value.insert_float(timestamp); put("timestamp", value); } public void setButton(short button) { Any value = orb.create_any(); value.insert_short(button); put("button", value); } public short getButton() { return get("button").extract_short(); } public EventAttribute[] getEventAttributes() { Set atts = new HashSet Set keys = keySet(); for (String key : keys) { EventAttribute att = new EventAttribute(); att.name = key; att.value = get(key); atts.add(att); } return (EventAttribute[]) atts.toArray(new EventAttribute[atts.size()]); } public Any asAny() { Any ret = orb.create_any(); EventHelper.insert(ret, getEventAttributes()); return ret; } }
java
11
0.69341
74
22.728155
103
starcoderdata
using System; using BookLovers.Base.Infrastructure.Commands; namespace BookLovers.Readers.Application.Commands.Timelines { internal class AddBookToBookcaseActivityInternalCommand : ICommand { public Guid ReaderGuid { get; private set; } public Guid BookGuid { get; private set; } public DateTime Date { get; private set; } private AddBookToBookcaseActivityInternalCommand() { } public AddBookToBookcaseActivityInternalCommand(Guid readerGuid, Guid bookGuid, DateTime date) { ReaderGuid = readerGuid; BookGuid = bookGuid; Date = date; } } }
c#
10
0.667622
102
25.884615
26
starcoderdata
def getOauthCredentials(): """ Get Oauth credentials from local config file """ credentials = {} with open("oauth-credentials", "r") as fin: credentials['clientId'] = fin.readline().strip() credentials['clientSecret'] = fin.readline().strip() return credentials
python
11
0.617363
60
27.363636
11
inline
package api import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/bdavs3/worker/server/auth" "github.com/bdavs3/worker/worker" ) func TestAPIRequest(t *testing.T) { w := worker.NewWorker() o := auth.NewOwners() handler := NewHandler(w, o) var tests = []struct { comment string job worker.Job want int }{ { comment: "well-formed request to /jobs/run", job: worker.Job{Command: "echo", Args: []string{"hello"}}, want: http.StatusOK, }, { comment: "poorly-formed request to /jobs/run", job: worker.Job{Command: "", Args: []string{}}, want: http.StatusBadRequest, }, } for _, test := range tests { rec := httptest.NewRecorder() t.Run(test.comment, func(t *testing.T) { requestBody, err := json.Marshal(test.job) if err != nil { t.Errorf("Error marshalling job as JSON: %v", err) } req, err := http.NewRequest( http.MethodPost, "/jobs/run", bytes.NewBuffer(requestBody), ) if err != nil { t.Errorf("Error forming request: %v", err) } http.HandlerFunc(handler.PostJob).ServeHTTP(rec, req) if rec.Code != test.want { t.Errorf("got %d, want %d", rec.Code, test.want) } }) } }
go
20
0.611156
65
19.278689
61
starcoderdata
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the Shuup Commerce Inc - # SELF HOSTED SOFTWARE LICENSE AGREEMENT executed by Shuup Commerce Inc, DBA as SHUUP® # and the Licensee. import shuup.apps class AppConfig(shuup.apps.AppConfig): name = "shuup_api_test_app" label = "shuup_api_test_app" verbose_name = "Shuup API Test App" required_installed_apps = ("shuup_api",) provides = { "api_populator": [ "shuup_api_test_app.api.populate_api", ] }
python
9
0.655844
86
27
22
starcoderdata
/* * Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.ui.grid; import ucar.nc2.ui.gis.AbstractGisFeature; import ucar.nc2.ui.gis.GisPart; import java.util.*; // for Iterator and ArrayList import java.awt.geom.*; // for Point2D.Double /** * An AbstractGisFeature derived class for contour lines. * * Created: * * @author wier */ public class ContourFeature extends AbstractGisFeature { private int numparts, npts; private ArrayList lines; // arrayList of ContourLines private double contourValue; /** * constructor */ public ContourFeature(ArrayList conLines) { // set how many GisParts there are numparts = conLines.size(); // save the input ContourLines as member data lines = new ArrayList(conLines); // save the single contour value for all lines here as member data if (conLines.size() > 0) contourValue = ((ContourLine) (lines.get(0))).getContourLevel(); else contourValue = 0.0; // using every line, add together how many points on all the lines int np, count = 0; for (int i = 0; i < numparts; i++) { GisPart cl = (GisPart) (conLines.get(i)); np = cl.getNumPoints(); count += np; // error if contour values not all the same if (((ContourLine) (lines.get(i))).getContourLevel() != contourValue) System.out.println(" Mismatch: all contour levels" + " in one ContourFeature should be the same."); } npts = count; } // end cstr /** * Get the value of the contour level for all the contour lines * in this object. * * @return double value */ public double getContourValue() { return contourValue; } ; // implement GisFeature methods: public java.awt.geom.Rectangle2D getBounds2D() { // Get the bounding box for this feature. from java.awt.geom.Rectangle2D double x0 = (((ContourLine) (lines.get(0))).getX())[0]; double y0 = (((ContourLine) (lines.get(0))).getY())[0]; double xMaxInd = x0, xmin = x0, yMaxInd = y0, ymin = y0; for (int i = 0; i < lines.size(); i++) { GisPart cline = (ContourLine) (lines.get(i)); double[] xpts = cline.getX(); double[] ypts = cline.getY(); for (int j = 0; j < cline.getNumPoints(); j++) { if (xpts[j] < xmin) xmin = xpts[j]; else if (xpts[j] > xMaxInd) xMaxInd = xpts[j]; if (ypts[j] < ymin) ymin = ypts[j]; else if (ypts[j] > yMaxInd) yMaxInd = ypts[j]; } } // Rectangle2D.Double(double x, double y, double width, double height) Rectangle2D.Double rect = new Rectangle2D.Double(xmin, ymin, xMaxInd - xmin, yMaxInd - ymin); return rect; } public java.util.Iterator getGisParts() { return lines.iterator(); } public int getNumParts() { return numparts; } public int getNumPoints() { return npts; } } // ContourFeature
java
16
0.623826
82
25.62931
116
starcoderdata
""" Movable AABBs in space. Classes: Body """ from __future__ import annotations # NOTE: This is necessary below Python 3.10 from .aabb import AABB from .collision import (CollisionData, get_axis_collision_distances, get_axis_collision_times, get_collision_normals) from .object2d import Object2D from .space import Space from pyglet.math import Vec2 from typing import Optional class Body(AABB): """ A moving bounding box in 2D space. Contains some helper methods for finding the nearest collision in the space, and resolving the collision. """ def __init__( self, x: float, # From `Object2D` y: float, # From `Object2D` w: float, # From `AABB` h: float, # From `AABB` layer: int = AABB.DEFAULT_LAYER, # From `AABB` mask: int = AABB.DEFAULT_LAYER, # Use our default layer from before parent: Optional[Object2D] = None # From `Object2D` ): super().__init__(x, y, w, h, layer, parent) # Initialise AABB fields self.mask = mask def get_collision_data(self, other: AABB, velocity: Vec2) -> CollisionData: """ Get the collision data between this and another bounding box, using a given velocity. """ # Get Collision Distances x_entry_dist, x_exit_dist = get_axis_collision_distances( self.global_x, self.w, velocity.x, other.global_x, other.w ) y_entry_dist, y_exit_dist = get_axis_collision_distances( self.global_y, self.h, velocity.y, other.global_y, other.h ) entry_distances = Vec2(x_entry_dist, y_entry_dist) # Get Collision Times x_entry_time, x_exit_time = get_axis_collision_times( x_entry_dist, x_exit_dist, velocity.x ) y_entry_time, y_exit_time = get_axis_collision_times( y_entry_dist, y_exit_dist, velocity.y ) entry_times = Vec2(x_entry_time, y_entry_time) # Use closest entry and furthest exit entry_time = max(x_entry_time, y_entry_time) exit_time = min(x_exit_time, y_exit_time) # Was there a collision? collided = not ( # No motion entry_time > exit_time # Or collision already happened or exit_time <= 0 # Or collision happens further than 1 time step away or entry_time > 1 ) # Get collision normals normals = get_collision_normals( entry_times, entry_distances, ) if collided else Vec2(0, 0) # Return data return CollisionData( collided, # Use whichever is nearest to resolve ongoing collisions in the # neatest manner. entry_time if abs(entry_time) < abs(exit_time) else exit_time, normals, ) def get_nearest_collision( self, space: Space, velocity: Vec2, ) -> Optional[CollisionData]: """ Finds the nearest collision in the space, if any. """ broad_phase = self.get_broad_phase(velocity) closest_data: Optional[CollisionData] = None # Loop over every box in the space for other in space: # Check if a collision is possible if other is not self and self.mask & other.layer and broad_phase.is_colliding_aabb(other): # Get data data = self.get_collision_data(other, velocity) if ( # No collision yet closest_data is None # New collision is nearer or data.collision_time < closest_data.collision_time ) and data.collided: # Check there actually was a collision closest_data = data return closest_data def move(self, space: Space, velocity: Vec2) -> Vec2: """ Moves as far as possible in one iteration, returning the remaining velocity calculated using the slide method. """ nearest_collision = self.get_nearest_collision(space, velocity) if nearest_collision is None: self.position += velocity # Move all the way new_velocity = Vec2(0, 0) # No more velocity left over else: # Move to point of collision self.x += velocity.x * nearest_collision.collision_time self.y += velocity.y * nearest_collision.collision_time # Calculate dot product of normals and velocity dot_product = ( velocity.x * nearest_collision.normals.y + velocity.y * nearest_collision.normals.x ) * (1-nearest_collision.collision_time) # Determine new velocity new_velocity = Vec2( dot_product * nearest_collision.normals.y, dot_product * nearest_collision.normals.x ) return new_velocity def move_and_slide( self, space: Space, velocity: Vec2, max_bounce: int = 3, ): """ Repeatedly moves with the given velocity until it equals 0 or the maximum bounces in one frame have been reached. """ counter = 0 # Move until velocity is zero while velocity != Vec2(0, 0) and counter < max_bounce: velocity = self.move(space, velocity) counter += 1 # Increment max bounces counter
python
16
0.574161
102
33
163
starcoderdata
<?php namespace Ayumila\Classes; use Ayumila\Exceptions\AyumilaException; use Ayumila\Traits\CreateStandard; use Exception; use Propel\Runtime\Collection\ObjectCollection; use Propel\Runtime\Connection\StatementWrapper; use \Propel\Runtime\Propel AS PropelRunTime; class Propel { use CreateStandard; private ?StatementWrapper $stmt = null; /** * @param ObjectCollection $collection * @return bool * @throws AyumilaException */ public function automaticGroupDelete(ObjectCollection $collection): bool { $objectHelper = $this->getTableDataFromObjectCollection($collection); if(!$objectHelper->getPrimaryKeyNames()) { throw new AyumilaException('automaticGroupDelete can\'t find PrimaryKeys'); } $queryHeader = 'DELETE FROM '.$objectHelper->getTableName().' '; $queryWhere = ''; $sqlDelete = array(); $addSqlDelete = function ($query) use(&$sqlDelete) { $sqlDelete[] = $query.';'; }; foreach ($collection AS $item) { $queryWhere .= $queryWhere ? 'OR (' : 'WHERE ('; foreach ($objectHelper->getPrimaryKeyNames() AS $keyName) { $queryWhere .= $keyName['name'].' = \''.$item->getByName($keyName['phpName']).'\' '; } $queryWhere .= ') '; if(strlen($queryHeader.$queryWhere) > 300000) { $addSqlDelete($queryHeader.$queryWhere); $queryWhere = ''; } } if($queryWhere) $addSqlDelete($queryHeader.$queryWhere); $this->customQuery($sqlDelete); return true; } /** * @param array|string $sqlQueries * @return bool */ public function customQuery(array|string $sqlQueries): bool { $sqlQueries = is_string($sqlQueries) ? [$sqlQueries] : $sqlQueries; foreach ($sqlQueries AS $query) { if(is_string($query)) { $connection = PropelRunTime::getConnection(); $stmt = $connection->prepare($query); try{ $stmt->execute(); $this->stmt = $stmt; }catch (Exception $ex) { return false; } }else{ return false; } } return true; } /** * requires one call to customQuery * @return mixed */ public function fetchAll(): mixed { return $this->stmt->fetchAll(); } /** * @throws AyumilaException */ public function getTableDataFromObjectCollection(ObjectCollection $collection): PropelObjectHelper { $tableMap = $collection->getTableMapClass(); if( class_exists($tableMap) && method_exists($tableMap,'getTableMap') ){ $tableMap = $tableMap::getTableMap(); $primaryKeyNames = array(); foreach($tableMap->getPrimaryKeys() AS $key) { $primaryKeyNames[] = [ 'name' => $key->getName(), 'phpName' => $key->getPhpName(), ]; } $objectHelper = new PropelObjectHelper(); $objectHelper->setTableName($tableMap::getTableMap()->getName()); $objectHelper->setPrimaryKeyNames($primaryKeyNames); return $objectHelper; } throw new AyumilaException('getTableDataFromObjectCollection can\'t find the Propel:TableMap or Propel:TableMap Method getTableMap'); } } class PropelObjectHelper { private string $tableName = ''; private array $primaryKeyNames = array(); /** * @return string */ public function getTableName(): string { return $this->tableName; } /** * @param string $tableName */ public function setTableName(string $tableName): void { $this->tableName = $tableName; } /** * @return array */ public function getPrimaryKeyNames(): array { return $this->primaryKeyNames; } /** * @param array $primaryKeyNames */ public function setPrimaryKeyNames(array $primaryKeyNames): void { $this->primaryKeyNames = $primaryKeyNames; } }
php
18
0.547717
141
24.614035
171
starcoderdata
public String getTextWithoutMask() { if (chars.length() == 0) { return ""; } String str = chars.toString(); if (isMaskedEdit) { if (mode == CURRENCY) { if (!hasSignificantDigits()) { if (str.indexOf('.') < 0 && str.indexOf(',') < 0) { str = Convert.toString(0d, decimalPlaces);//"0"; } } else { if (decimalPlaces > 0) // for currency mode, remove the , and . and put it in Java's format (xxxx.yy) { int k = str.length() - decimalPlaces; // get the number of decimal places if (k <= 0) { str = "0.".concat(Convert.zeroPad(str, decimalPlaces)); } else { str = str.substring(0, k) + "." + str.substring(k); } } if (isNegative) { str = "-".concat(str); } } } else { StringBuffer sbuf = new StringBuffer(str.length()); if (mask.length == str.length()) // totally formatted? faster algorithm { // 25/03/1970 -> 25031970 for (int i = 0; i < mask.length; i++) { if (mask[i] == '9') { sbuf.append(chars.charAt(i)); } } } else { // 25031970 -> 25031970 int max = chars.length(); for (int i = 0, j = 0; i < mask.length; i++) { if ('0' <= mask[i] && mask[i] <= '9' && j < max) { sbuf.append(chars.charAt(j++)); } } } str = sbuf.toString(); } } return str; }
java
19
0.438408
111
31.326531
49
inline
function marg1(){ var slider = document.querySelector('#slider'); slider.style.marginLeft = '-100%'; function marg2(){ var slider = document.querySelector('#slider'); slider.style.marginLeft = '-200%'; function marg2(){ var slider = document.querySelector('#slider'); slider.style.marginLeft = '0'; setTimeout(marg1, 8000); } setTimeout(marg0, 8000); } setTimeout(marg2, 8000); } setInterval(slid , 7500); setInterval(para , 7200); setInterval(head , 7200); setInterval(line , 7300); setTimeout(marg1, 8000); setInterval(slid2 , 8500); setInterval(head2 , 8700); setInterval(para2 , 8700); setInterval(line2 , 8600); function slid(){ var s = document.querySelectorAll('.slid'); var i ; for(i=0;i<s.length;i++){ s[i].style.transform = 'scale(.8)'; } } function slid2(){ var s = document.querySelectorAll('.slid'); var i ; for(i=0;i<s.length;i++){ s[i].style.transform = 'scale(1)'; } } function head(){ var h = document.querySelectorAll('h1'); var i ; for(i=0;i<h.length;i++){ h[i].style.top = '70px'; } } function head2(){ var h = document.querySelectorAll('h1'); var i ; for(i=0;i<h.length;i++){ h[i].style.top = '0'; } } function para(){ var p = document.querySelectorAll('p'); var i ; for(i=0;i<h.length;i++){ p[i].style.bottom = '40px'; } } function para2(){ var p = document.querySelectorAll('p'); var i ; for(i=0;i<h.length;i++){ p[i].style.bottom = '0'; } } function line(){ var l = document.querySelector('.line'); for(i=0;i<s.length;i++){ s[i].style.transform = 'scale(0)'; } } function line2(){ var l = document.querySelector('.line'); l.style.transform = 'scale(1)'; } function scrollAppear(){ var sectiononeh1 = document.querySelector('.sectiononeh1'); var sectiononeh1Post = sectiononeh1.getBoundingClientRect().top; var screenpos = window.innerHeight; if(sectiononeh1Post < screenpos){ sectiononeh1.classList.add('sectiononeh1-appear'); } } window.addEventListener('scroll',scrollAppear); var slideIndex = 1; showSlides(slideIndex); // Next/previous controls function plusSlides(n) { showSlides(slideIndex += n); } // Thumbnail image controls function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("demo"); var captionText = document.getElementById("caption"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active"; captionText.innerHTML = dots[slideIndex-1].alt; }
javascript
12
0.614706
68
22.728682
129
starcoderdata
package com.ardic.android.iot.hwnodeapptemplate.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import com.ardic.android.iot.hwnodeapptemplate.listener.CompatibilityListener; import com.ardic.android.iot.hwnodeapptemplate.manager.WifiNodeManager; import com.ardic.android.iotignite.callbacks.ConnectionCallback; import com.ardic.android.iotignite.exceptions.UnsupportedVersionException; import com.ardic.android.iotignite.nodes.IotIgniteManager; import com.ardic.android.utilitylib.interfaces.TimeoutListener; import com.ardic.android.utilitylib.timer.TimeoutTimer; /** * Created by yavuz.erzurumlu on 02.11.2016. */ public class WifiNodeService extends Service implements ConnectionCallback, TimeoutListener { private static final String TAG = WifiNodeService.class.getSimpleName(); private static final long IGNITE_RESTART_INTERVAL = 10000L; private static WifiNodeService serviceInstance; private IotIgniteManager.Builder igniteBuilder; private IotIgniteManager iotContext; private TimeoutTimer igniteTimer; private WifiNodeManager wifiNodeManager; private boolean isIgniteConnected; private static CompatibilityListener compatibilityListener; public static WifiNodeService getInstance() { return serviceInstance; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); serviceInstance = this; igniteTimer = new TimeoutTimer(this); igniteBuilder = new IotIgniteManager.Builder().setContext(getApplicationContext()) .setConnectionListener(this).setLogEnabled(true); rebuildIgnite(); } @Override public void onConnected() { Log.d(TAG, "Ignite connected"); isIgniteConnected = true; igniteTimer.cancelTimer(); wifiNodeManager = WifiNodeManager.getInstance(getApplicationContext(), iotContext); startManagement(); wifiNodeManager.sendIgniteConnectionChanged(true); } @Override public void onDisconnected() { Log.d(TAG, "Ignite disconnected"); isIgniteConnected = false; stopManagement(); igniteTimer.startTimer(IGNITE_RESTART_INTERVAL); if (wifiNodeManager != null) { wifiNodeManager.sendIgniteConnectionChanged(false); } } @Override public void onTimerTimeout() { rebuildIgnite(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } public void startManagement() { if (wifiNodeManager != null) { wifiNodeManager.startManagement(); } } public void stopManagement() { if (wifiNodeManager != null) { wifiNodeManager.stopManagement(); } } public void restartManagement() { if (wifiNodeManager != null) { wifiNodeManager.restartManagement(); } } private void rebuildIgnite() { igniteTimer.startTimer(IGNITE_RESTART_INTERVAL); try { iotContext = igniteBuilder.build(); } catch (UnsupportedVersionException e) { Log.i(TAG, "Unsupported version exception : " + e); if(compatibilityListener!=null){ compatibilityListener.onUnsupportedVersionExceptionReceived(e); } } } @Override public void onDestroy() { wifiNodeManager.stopManagement(); super.onDestroy(); serviceInstance = null; } public boolean isIgniteConnected() { return isIgniteConnected; } public static void setCompatibilityListener(CompatibilityListener listener){ compatibilityListener = listener; } }
java
13
0.690368
93
29.05303
132
starcoderdata
def create_event( event_session_id, event_id, event_type, timestamp=None, device_id=None ): """Create an EventMessage for a single event type.""" if not timestamp: timestamp = dt_util.now() event_data = { event_type: { "eventSessionId": event_session_id, "eventId": event_id, }, } return create_event_message(event_data, timestamp, device_id=device_id)
python
10
0.608491
75
31.692308
13
inline
private void createWorkaroundFile(@NotNull String file, @NotNull String content) { try { createDummyFiles(file); } catch (Exception e) { e.printStackTrace(); } // build pseudo file with block final VirtualFile relativeFile = VfsUtil.findRelativeFile(getProject().getBaseDir(), file.split("/")); ApplicationManager.getApplication().runWriteAction(() -> { try { relativeFile.setBinaryContent(content.getBytes()); } catch (IOException e2) { e2.printStackTrace(); } relativeFile.refresh(false, false); }); }
java
15
0.571001
110
34.263158
19
inline
// Package runtime contains BloxOne DDI API helper // runtime abstractions for internal client use. package runtime import ( "fmt" "github.com/go-openapi/runtime" "io" "io/ioutil" "path" "strings" ) // TrimIDPrefix removes app ID and resource type prefixes from the ID property. // // If no prefix is found, TrimIDPrefix will return the original id value. // // More about BloxOne DDI resource IDs: // https://github.com/infobloxopen/atlas-app-toolkit/tree/v1.1.2/rpc/resource#resource func TrimIDPrefix(pathPattern string, id string) string { if !path.IsAbs(id) { id = "/" + id } prefix := pathPattern for !strings.HasPrefix(id, prefix) { prefix = prefix[0 : len(prefix)-1] if len(prefix) == 0 { return strings.TrimPrefix(id, "/") } } if strings.HasPrefix(pathPattern, prefix+"{id}") { return strings.TrimPrefix(id, prefix) } else { return strings.TrimPrefix(id, "/") } } // NewAPIHTTPError creates a new API HTTP error. func NewAPIHTTPError(opName string, payload io.Reader, code int) *APIHTTPError { body, err := ioutil.ReadAll(payload) if err != nil { body = []byte("Failed to read response") } return &APIHTTPError{ runtime.APIError{ OperationName: opName, Response: string(body), Code: code, }, } } // APIHTTPError wraps runtime.APIError, and modifies response processing logic. type APIHTTPError struct { runtime.APIError } // Error method prints APIHTTPError error message. func (a *APIHTTPError) Error() string { return fmt.Sprintf("%s (status %d): \n%s", a.OperationName, a.Code, a.Response) }
go
15
0.700317
86
24.403226
62
starcoderdata
#include "stdafx.h" #include ".\mainwnd.h" CMainWnd::CMainWnd(void) : CKuiDialogImpl "IDR_DLG_MAIN" ) { } CMainWnd::~CMainWnd(void) { } void CMainWnd::OnDestroy() { PostQuitMessage(0); } void CMainWnd::OnBkBtnMax() { if (WS_MAXIMIZE == (GetStyle() & WS_MAXIMIZE)) { SendMessage(WM_SYSCOMMAND, SC_RESTORE | HTCAPTION, 0); } else { SendMessage(WM_SYSCOMMAND, SC_MAXIMIZE | HTCAPTION, 0); } } void CMainWnd::OnBkBtnMin() { SendMessage(WM_SYSCOMMAND, SC_MINIMIZE | HTCAPTION, 0); } void CMainWnd::OnBkBtnClose() { DestroyWindow(); }
c++
10
0.633943
69
13.461538
39
starcoderdata
/* * Copyright (c) 2010-2022. Axon Framework * * 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 org.axonframework.spring.messaging.unitofwork; import org.axonframework.common.Assert; import org.axonframework.common.transaction.Transaction; import org.axonframework.common.transaction.TransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import javax.annotation.Nonnull; /** * TransactionManager implementation that uses a {@link org.springframework.transaction.PlatformTransactionManager} as * underlying transaction manager. * * @author * @since 2.0 */ public class SpringTransactionManager implements TransactionManager { private final PlatformTransactionManager transactionManager; private final TransactionDefinition transactionDefinition; /** * @param transactionManager The transaction manager to use * @param transactionDefinition The definition for transactions to create */ public SpringTransactionManager(PlatformTransactionManager transactionManager, TransactionDefinition transactionDefinition) { Assert.notNull(transactionManager, () -> "transactionManager may not be null"); this.transactionManager = transactionManager; this.transactionDefinition = transactionDefinition; } /** * Initializes the SpringTransactionManager with the given {@code transactionManager} and the default * transaction definition. * * @param transactionManager the transaction manager to use */ public SpringTransactionManager(PlatformTransactionManager transactionManager) { this(transactionManager, new DefaultTransactionDefinition()); } @Nonnull @Override public Transaction startTransaction() { TransactionStatus status = transactionManager.getTransaction(transactionDefinition); return new Transaction() { @Override public void commit() { commitTransaction(status); } @Override public void rollback() { rollbackTransaction(status); } }; } /** * Commits the transaction with given {@code status} if the transaction is new and not completed. * * @param status The status of the transaction to commit */ protected void commitTransaction(TransactionStatus status) { if (status.isNewTransaction() && !status.isCompleted()) { transactionManager.commit(status); } } /** * Rolls back the transaction with given {@code status} if the transaction is new and not completed. * * @param status The status of the transaction to roll back */ protected void rollbackTransaction(TransactionStatus status) { if (status.isNewTransaction() && !status.isCompleted()) { transactionManager.rollback(status); } } }
java
13
0.720179
139
36.683168
101
starcoderdata
RTCrX509AttributeTypeAndValue_MatchAsRdnByRfc5280(PCRTCRX509ATTRIBUTETYPEANDVALUE pLeft, PCRTCRX509ATTRIBUTETYPEANDVALUE pRight) { if (RTAsn1ObjId_Compare(&pLeft->Type, &pRight->Type) == 0) { /* * Try for perfect match in case we get luck. */ #ifdef DEBUG_bird /* Want to test the complicated code path first */ if (pLeft->Value.enmType != RTASN1TYPE_STRING || pRight->Value.enmType != RTASN1TYPE_STRING) #endif if (RTAsn1DynType_Compare(&pLeft->Value, &pRight->Value) == 0) return true; /* * If both are string types, we can compare them according to RFC-5280. */ if ( pLeft->Value.enmType == RTASN1TYPE_STRING && pRight->Value.enmType == RTASN1TYPE_STRING) { size_t cchLeft; const char *pszLeft; int rc = RTAsn1String_QueryUtf8(&pLeft->Value.u.String, &pszLeft, &cchLeft); if (RT_SUCCESS(rc)) { size_t cchRight; const char *pszRight; rc = RTAsn1String_QueryUtf8(&pRight->Value.u.String, &pszRight, &cchRight); if (RT_SUCCESS(rc)) { /* * Perform a simplified RFC-5280 comparsion. * The algorithm as be relaxed on the following counts: * 1. No unicode normalization. * 2. Prohibited characters not checked for. * 3. Bidirectional characters are not ignored. */ pszLeft = rtCrX509CanNameStripLeft(pszLeft, &cchLeft); pszRight = rtCrX509CanNameStripLeft(pszRight, &cchRight); while (*pszLeft && *pszRight) { RTUNICP ucLeft = rtCrX509CanNameGetNextCpWithMapping(&pszLeft, &cchLeft); RTUNICP ucRight = rtCrX509CanNameGetNextCpWithMapping(&pszRight, &cchRight); if (ucLeft != ucRight) { ucLeft = RTUniCpToLower(ucLeft); ucRight = RTUniCpToLower(ucRight); if (ucLeft != ucRight) return false; } } return cchRight == 0 && cchLeft == 0; } } } } return false; }
c++
19
0.484314
102
42.237288
59
inline
// CKEDITOR.replace('message'); var base_url = "<?= base_url() ?>"; var token = "<?php echo $_SESSION['account']['token'] ?>"; var active_user = "<?php echo $_SESSION['account']['details']['id'] ?>"; var user_is_expert = "<?php echo $_SESSION['account']['details']['is_expert'] ?>"; var expert_table = $('#experts_table').DataTable({ "pageLength": 10, "responsive": true }); var inquiries_table = $('#inquiries_table').DataTable({ "pageLength": 10, "responsive": true }); if ($(".myBox").length == 1) { $('.myBox').scrollTop($(".myBox")[0].scrollHeight); } get_conversations(); function get_conversations() { if (user_is_expert == 1) { $.ajax({ type: "get", url: base_url + "api/messaging/Conversations/" + active_user, headers: { "Authorization": "Bearer " + token }, dataType: "json", success: function(res) { console.log(res); if (res.success) { experts = res.success.data; var counter = 1; expert_table.clear().draw(); experts.forEach(element => { expert_table.row.add([ element.sender_name, element.sender_email, element.sender_contact, '<a href="' + base_url + 'Subscribers_FE/ask_the_experts_message/' + element.sender_id + '" class="btn btn-small light-blue darken-2"><span class="fa fa-envelope"> ]).draw(false); }); } else { expert_table.clear().draw(); } } }); } else { $.ajax({ type: "get", url: base_url + "api/user/Users", headers: { "Authorization": "Bearer " + token }, dataType: "json", success: function(res) { console.log(res); if (res.success) { experts = res.success.data; var counter = 1; expert_table.clear().draw(); experts.forEach(element => { if (element.is_expert == 1 && element.id != active_user) { expert_table.row.add([ element.fullname, element.id, element.field_study, '<a href="' + base_url + 'Subscribers_FE/ask_the_experts_message/' + element.id + '" class="btn btn-small light-blue darken-2"><span class="fa fa-envelope"> ]).draw(false); } }); } else { expert_table.clear().draw(); } } }); } } function send_message(sender, receiver) { console.log({ 'message': $('#message').val(), 'sender': sender, 'receiver': receiver, 'convo_id': $('#convo_id').val(), }); $.ajax({ type: "POST", url: base_url + "api/messaging/Messages", data: { 'message': $('#message').val(), 'sender': sender, 'receiver': receiver, 'convo_id': $('#convo_id').val(), }, dataType: "JSON", headers: { "Authorization": "Bearer " + token }, success: function(res) { if (!res.success) { Swal.fire( 'Warning!', res.error.message, 'warning' ) } else { window.location.replace(base_url + "Subscribers_FE/ask_the_experts_message/" + receiver); } } }); }
php
6
0.382005
207
35.289256
121
starcoderdata
void read_flow_sensor(uint32_t sample_ms) { // FLOW // Units for flowrate are slm * 1000, or milliliters per minute. float raw_flow = -999.0; raw_flow = flow_sensor.readFlow(); if (flow_sensor.checkRange(raw_flow)) { if (raw_flow > 0) { output_meta_event( (char *) ((SENSOR_INSTALLED_BACKWARD) ? flow_too_low : flow_too_high), sample_ms); } else { output_meta_event( (char *) ((SENSOR_INSTALLED_BACKWARD) ? flow_too_high : flow_too_low), sample_ms); } } float flow = (SENSOR_INSTALLED_BACKWARD) ? -raw_flow : raw_flow; signed long flow_milliliters_per_minute = (signed long) (flow * 1000); output_measurement('M', 'F', 'A', 0, sample_ms, flow_milliliters_per_minute); }
c++
15
0.634615
107
40.941176
17
inline
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; use App\T1; use Illuminate\Support\Str; use App\Http\Requests\TodosRequest; class Todocontroller extends Controller { // public function __construct() // { // $this->middleware('Auth')->except('readTable'); // } public function readTable() { $data = T1::all(); return view('todo_index', ['data' => $data]); } public function update(TodosRequest $update) { // $userToken = $update->cookie('userToken'); // $user = Admin::where('remember_token', "$userToken")->first('admin')->admin; $user = Auth::user()->name; $id = $update->input('no'); $item = $update->input('item'); T1::find($id)->update(['item' => "$item", 'update_user' => 'admin', 'update_user' => $user]); //return redirect()->back()->with('message', 'please login'); //return 'please login'; return redirect('todolist'); // return $update; } public function delete(Request $delete) { $id = $delete->input('id'); T1::find($id)->delete(); return redirect('todolist'); // return $delete; } public function create(TodosRequest $create) { // $userToken = $create->cookie('userToken'); // $user = Admin::where('remember_token', "$userToken")->first('admin')->admin; $user = Auth::user()->name; $item = $create->input('item'); // $item = $create->validate(['item' => 'required']) ; // $rules=[ // 'item' => 'required|max:255', // ]; // $messages = [ // 'item.required' => 'item can not null.' , // 'item.max' => 'item can not over 255 characters' // ]; // $validator = Validator::make($create->all(), $rules, $messages); // if ($validator->fails()) { // // dd($validator); // return redirect('todolist') // ->withErrors($validator) // ->withInput(); // } T1::create(['item' => "$item", 'status' => '未完成', 'update_user' => 'admin', 'update_user' => $user]); return redirect('todolist'); } public function complete(Request $complete) { // dd('Hello'); // $userToken = $complete->cookie('userToken'); // $user = Admin::where('remember_token', "$userToken")->first('admin')->admin; // dd($user->admin); $user = Auth::user()->name; $id = $complete->input('id'); $data = T1::find($id); $status = $data->status; if ($status == '未完成') { $data->update(['status' => '已完成', 'update_user' => $user]); } else { $data->update(['status' => '未完成', 'update_user' => $user]); } return redirect('todolist'); // $value = $complete->cookie('userToken'); // return $value; } }
php
15
0.512108
109
33.411111
90
starcoderdata
<?php namespace PleskX\Api\Struct; use SimpleXMLElement; use PleskX\Api\Struct; abstract class User extends Struct { /** * The date when the account was created. * * @var string */ public $creationDate; /** * The company name. * * @var string */ public $company; /** * The personal name. * * @var string */ public $personalName; /** * The login name (username). * * @var string */ public $login; /** * The current status. * * Possible values: * - 0 (active) * - 4 (under backup/restore) * - 16 (disabled_by admin) * - 256 (expired) * * @var int */ public $status; /** * The phone number. * * @var string */ public $phone; /** * The fax number. * * @var string */ public $fax; /** * The email address. * * @var string */ public $email; /** * The postal address. * * @var string */ public $address; /** * The city. * * @var string */ public $city; /** * The state. * * @var string */ public $state; /** * The postal code. * * @var string */ public $postalCode; /** * The 2-character country code. * * @var string */ public $country; /** * The locale. * * @var string */ public $locale; /** * The global user ID. * * @var string */ public $guid; /** * The customer GUID in the Panel components (for example, Business Manager). * * @var string */ public $externalId; /** * The customer description (only available when authenticating as admin). * * @var string */ public $description; /** * The password in the format of $passwordType. * * @var string */ public $password; /** * The type of the customer account password. * * Possible values: * - crypt * - plain * * @var string */ public $passwordType; /** * GeneralInfo constructor. * * @param \SimpleXMLElement $apiResponse */ abstract public function __construct(SimpleXMLElement $apiResponse); }
php
8
0.477349
81
13.993711
159
starcoderdata
def assert_kpis_event(self, device_id, event_present=True): def validate_output(data): kpis_data = simplejson.loads(data) if not kpis_data or \ 'ts' not in kpis_data or \ 'prefixes' not in kpis_data: return False # Check only new kpis if kpis_data['ts'] > self.consume_kafka_message_starting_at: for key, value in kpis_data['prefixes'].items(): if device_id in key: return True return False cmd = command_defs['kafka_kpis'].format(self.kafka_endpoint) self.run_command_and_wait_until(cmd, validate_output, 60, 'kpis', expected_predicate_result=event_present)
python
12
0.5116
80
38.047619
21
inline
package com.showka.service.persistence.u06; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.showka.domain.u07.Seikyu; import com.showka.entity.SUrikakeSeikyuDone; import com.showka.entity.SUrikakeSeikyuNotYet; import com.showka.repository.i.SUrikakeSeikyuDoneRepository; import com.showka.repository.i.SUrikakeSeikyuNotYetRepository; import com.showka.service.persistence.u06.i.UrikakeSeikyuStatusPersistence; import com.showka.service.query.u07.i.SeikyuQuery; @Service public class UrikakeSeikyuStatusPersistenceImpl implements UrikakeSeikyuStatusPersistence { @Autowired private SUrikakeSeikyuNotYetRepository seikyuNotYetRepo; @Autowired private SUrikakeSeikyuDoneRepository seikyuDoneRepo; @Autowired private SeikyuQuery seikyuQuery; @Override public void toNotYet(String urikakeId) { // 未請求状態とする Optional _e = seikyuNotYetRepo.findById(urikakeId); SUrikakeSeikyuNotYet e = _e.orElse(new SUrikakeSeikyuNotYet()); e.setUrikakeId(urikakeId); if (!_e.isPresent()) { // ID = 売掛ID e.setRecordId(urikakeId); } seikyuNotYetRepo.save(e); } @Override public void toDone(String urikakeId, String seikyuId) { // 未請求状態解除 this.deleteNotYetIfExists(urikakeId); // 請求済状態とする Optional _e = seikyuDoneRepo.findById(urikakeId); SUrikakeSeikyuDone e = _e.orElse(new SUrikakeSeikyuDone()); e.setUrikakeId(urikakeId); e.setSeikyuId(seikyuId); if (!_e.isPresent()) { // ID = 売掛ID e.setRecordId(urikakeId); } seikyuDoneRepo.save(e); } @Override public void revert(String urikakeId) { // レコード存在チェック // 既存の場合は何もせず処理終了。 boolean exists = seikyuDoneRepo.existsById(urikakeId); if (exists) { return; } // 最新請求を取得。 // 未請求の場合、未請求状態とする。 Optional _newestSeikyu = seikyuQuery.getNewest(urikakeId); if (!_newestSeikyu.isPresent()) { this.toNotYet(urikakeId); return; } // 最新請求 Seikyu seikyu = _newestSeikyu.get(); // save this.toDone(urikakeId, seikyu.getRecordId()); } @Override public void toSettled(String urikakeId) { this.deleteNotYetIfExists(urikakeId); this.deleteDoneIfExists(urikakeId); } @Override public void delete(String urikakeId) { this.deleteNotYetIfExists(urikakeId); this.deleteDoneIfExists(urikakeId); } /** * 未請求状態テーブルのレコードを削除(存在すれば) * * @param urikakeId * 売掛ID */ void deleteNotYetIfExists(String urikakeId) { boolean exists = seikyuNotYetRepo.existsById(urikakeId); if (exists) { seikyuNotYetRepo.deleteById(urikakeId); } } /** * 請求済状態テーブルのレコードを削除(存在すれば) * * @param urikakeId * 売掛ID */ void deleteDoneIfExists(String urikakeId) { boolean exists = seikyuDoneRepo.existsById(urikakeId); if (exists) { seikyuDoneRepo.deleteById(urikakeId); } } }
java
9
0.750672
98
24.655172
116
starcoderdata
using System.Collections.Generic; using DllService.app.Model; namespace DllService.Model { public class TypeLoadEntity:AbstractArg { public string DllName { get; set; } public string FullClassName{get;set;} public string MethodName { get; set; } public LoadType LoadType { get; set; } public List ConstructorArgs { get; set; } = new List public List MethodArgs { get; set; } = new List } }
c#
9
0.681574
89
30.111111
18
starcoderdata
void ReadCharsetsFormat0() { //Table 17: Format 0 //Type Name Description //Card8 format =0 //SID glyph[nGlyphs-1] Glyph name array //Each element of the glyph array represents the name of the //corresponding glyph. This format should be used when the SIDs //are in a fairly random order. The number of glyphs (nGlyphs) is //the value of the count field in the //CharStrings INDEX. (There is //one less element in the glyph name array than nGlyphs because //the .notdef glyph name is omitted.) Glyph[] cff1Glyphs = _currentCff1Font._glyphs; int nGlyphs = cff1Glyphs.Length; for (int i = 1; i < nGlyphs; ++i) { ushort sid = _reader.ReadUInt16(); if (sid <= Cff1FontSet.N_STD_STRINGS) { //use standard name //TODO: review here cff1Glyphs[i]._cff1GlyphData.Name = Cff1FontSet.s_StdStrings[sid]; } else { cff1Glyphs[i]._cff1GlyphData.Name = _uniqueStringTable[sid - Cff1FontSet.N_STD_STRINGS - 1]; } } }
c#
16
0.494407
112
39.666667
33
inline
package com.craxiom.networksurvey; import com.craxiom.messaging.BluetoothRecord; import com.craxiom.messaging.BluetoothRecordData; import com.craxiom.messaging.bluetooth.SupportedTechnologies; import com.craxiom.messaging.bluetooth.Technology; import com.craxiom.networksurvey.fragments.BluetoothFragment; import com.craxiom.networksurvey.model.SortedSet; import com.craxiom.networksurvey.util.IOUtils; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Field; import java.time.ZonedDateTime; /** * Test for the custom {@link com.craxiom.networksurvey.model.SortedSet} class. * * @since 1.0.0 */ public class SortedSetTest { private static final double FLOAT_TOLERANCE = 0.0001; @Test public void validateRemovalOfOldMatchingItem() { // Two records with the same source addresses final String matchingSourceAddress = "E1:A1:19:A9:68:B0"; final BluetoothRecord record1 = getFakeBluetoothRecord(matchingSourceAddress, -71f); final BluetoothRecord matchingRecord = getFakeBluetoothRecord(matchingSourceAddress, -81f); // Records with different source addresses final BluetoothRecord record2 = getFakeBluetoothRecord("E1:A1:19:A9:68:B2", -72f); final BluetoothRecord record3 = getFakeBluetoothRecord("E1:A1:19:A9:68:B3", -73f); final BluetoothRecord record4 = getFakeBluetoothRecord("E1:A1:19:A9:68:B4", -74f); SortedSet bluetoothRecordSortedSet = null; try { final BluetoothFragment bluetoothFragment = new BluetoothFragment(); Field bluetoothRecordSortedSetField = BluetoothFragment.class.getDeclaredField("bluetoothRecordSortedSet"); bluetoothRecordSortedSetField.setAccessible(true); bluetoothRecordSortedSet = (SortedSet) bluetoothRecordSortedSetField.get(bluetoothFragment); } catch (NoSuchFieldException | IllegalAccessException e) { Assert.fail("Could not get the bluetoothRecordSortedSet field from the BluetoothFragment class"); } bluetoothRecordSortedSet.add(record1); Assert.assertEquals(1, bluetoothRecordSortedSet.size()); bluetoothRecordSortedSet.add(record2); Assert.assertEquals(2, bluetoothRecordSortedSet.size()); // The old record should be removed and the new one present Assert.assertEquals(-71f, ((BluetoothRecord) bluetoothRecordSortedSet.get(0)).getData().getSignalStrength().getValue(), FLOAT_TOLERANCE); bluetoothRecordSortedSet.add(matchingRecord); Assert.assertEquals(2, bluetoothRecordSortedSet.size()); // Use index 1 because record2 will be at the top since its RSSI value (-72) is now stronger than the matching record's -81 Assert.assertEquals(-81f, ((BluetoothRecord) bluetoothRecordSortedSet.get(1)).getData().getSignalStrength().getValue(), FLOAT_TOLERANCE); bluetoothRecordSortedSet.add(record3); Assert.assertEquals(3, bluetoothRecordSortedSet.size()); bluetoothRecordSortedSet.add(record4); Assert.assertEquals(4, bluetoothRecordSortedSet.size()); bluetoothRecordSortedSet.add(record1); Assert.assertEquals(4, bluetoothRecordSortedSet.size()); Assert.assertEquals(-71f, ((BluetoothRecord) bluetoothRecordSortedSet.get(0)).getData().getSignalStrength().getValue(), FLOAT_TOLERANCE); bluetoothRecordSortedSet.add(record4); Assert.assertEquals(4, bluetoothRecordSortedSet.size()); } /** * Create a fake BluetoothRecord that can be used for testing. * * Note that the time used for the record is the current time. * * @param sourceAddress The source address, which is important because it is used to determine if two records are the same. * @param signalStrength The signal strength which can be used to know if the new record replaces the old one. * @return The new Bluetooth record. */ private BluetoothRecord getFakeBluetoothRecord(String sourceAddress, float signalStrength) { final BluetoothRecord.Builder recordBuilder = BluetoothRecord.newBuilder(); recordBuilder.setVersion("0.4.0"); recordBuilder.setMessageType("BluetoothRecord"); final BluetoothRecordData.Builder dataBuilder = BluetoothRecordData.newBuilder(); dataBuilder.setDeviceSerialNumber("ee4d453e4c6f73fa"); dataBuilder.setDeviceName("BT Pixel"); dataBuilder.setDeviceTime(IOUtils.getRfc3339String(ZonedDateTime.now())); dataBuilder.setLatitude(51.470334); dataBuilder.setLongitude(-0.486594); dataBuilder.setAltitude(184.08124f); dataBuilder.setMissionId("NS ee4d453e4c6f73fa 20210114-124535"); dataBuilder.setRecordNumber(1); dataBuilder.setSourceAddress(sourceAddress); dataBuilder.setDestinationAddress("56:14:62:0D:98:01"); dataBuilder.setSignalStrength(FloatValue.newBuilder().setValue(signalStrength).build()); dataBuilder.setTxPower(FloatValue.newBuilder().setValue(8f).build()); dataBuilder.setTechnology(Technology.LE); dataBuilder.setSupportedTechnologies(SupportedTechnologies.DUAL); dataBuilder.setOtaDeviceName("846B2162E22433AFE9"); dataBuilder.setChannel(Int32Value.newBuilder().setValue(6).build()); recordBuilder.setData(dataBuilder); return recordBuilder.build(); } }
java
13
0.734979
145
46.389831
118
starcoderdata
#include<bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<(n);i++) #define pb push_back #define all(v) (v).begin(),(v).end() #define fi first #define se second typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;} template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;} string solve(int x,int y,int z){ if(x==0){ string s=solve(y,z,0); rep(i,s.size()){ if(s[i]=='a')s[i]='b'; else if(s[i]=='b')s[i]='c'; } return s; } if(y==0&&z){ string s=solve(x,z,0); rep(i,s.size()){ if(s[i]=='b')s[i]='c'; } return s; } if(y==0)return string(x,'a'); if(z==0){ if(x<=y){ string s=solve(x,y%x,0); string t; rep(i,s.size()){ if(s[i]=='a'){ t+="a"; t+=string(y/x,'b'); } else{ t+="b"; } } return t; } string s=solve(x-y,y,0); string t; rep(i,s.size()){ if(s[i]=='a'){ t+="a"; } else{ t+="ab"; } } return t; } if(x<=z){ string s=solve(x,y,z%x); string t; rep(i,s.size()){ if(s[i]=='a'){ t+="a"; t+=string(z/x,'c'); } else if(s[i]=='b'){ t+="b"; } else{ t+="c"; } } return t; } int q=y%(x-z); int p=x-z-q; int r=z; string s=solve(p,q,r); string t; rep(i,s.size()){ if(s[i]=='a'){ t+="a"; t+=string(y/(x-z),'b'); } else if(s[i]=='b'){ t+="a"; t+=string(y/(x-z)+1,'b'); } else{ t+="ac"; } } return t; } signed main(){ int X,Y,Z; cin>>X>>Y>>Z; cout<<solve(X,Y,Z)<<endl; return 0; }
c++
16
0.356981
71
18.936937
111
codenet
using System; using System.Collections.Generic; using System.Threading.Channels; namespace Lanymy.Common.Instruments { public class WorkTaskTriggerQueue : BaseWorkTaskTriggerQueue where TDataModel : IWorkTaskQueueDataModel { internal WorkTaskTriggerQueue(Channel channel, Action workTriggerAction, ushort actionTriggerCount, TimeSpan actionTriggerTimeSpan, int taskSleepMilliseconds = 3000, int channelCapacityCount = 0, BoundedChannelFullMode channelFullMode = BoundedChannelFullMode.Wait) : base(channel, workTriggerAction, actionTriggerCount, actionTriggerTimeSpan, taskSleepMilliseconds, channelCapacityCount, channelFullMode) { } public WorkTaskTriggerQueue(Action workTriggerAction, ushort actionTriggerCount, TimeSpan actionTriggerTimeSpan, int taskSleepMilliseconds = 3000, int channelCapacityCount = 0, BoundedChannelFullMode channelFullMode = BoundedChannelFullMode.Wait) : this(null, workTriggerAction, actionTriggerCount, actionTriggerTimeSpan, taskSleepMilliseconds, channelCapacityCount, channelFullMode) { } } }
c#
12
0.780811
303
33.542857
35
starcoderdata
package tn.esprit.spring.entity; import java.io.Serializable; import javax.persistence.Embeddable; @Embeddable public class DonationPK implements Serializable{ private long id_event ; private long id_user ; private long id_donation ; public long getId_event() { return id_event; } public void setId_event(long id_event) { this.id_event = id_event; } public long getId_user() { return id_user; } public void setId_user(long id_user) { this.id_user = id_user; } public long getId_donation() { return id_donation; } public void setId_donation(long id_donation) { this.id_donation = id_donation; } }
java
8
0.702028
48
14.634146
41
starcoderdata
UnqualifiedType* Variant::GetOrNull() const { // Variant is not storing a value of type T? if (!Is<UnqualifiedType>()) return nullptr; // Get stored value UnqualifiedType* value = reinterpret_cast<UnqualifiedType*>(GetData()); return value; }
c++
10
0.708171
73
24.8
10
inline
import { FETCH_BANNERS_REQUEST, FETCH_BANNERS_SUCCESS, FETCH_BANNERS_FAILURE, } from "./bannerActionTypes"; import { BANNERS_URL } from "../../constants"; export const fetchBannersRequest = () => { return { type: FETCH_BANNERS_REQUEST, }; }; export const fetchBannersSuccess = (banners) => { return { type: FETCH_BANNERS_SUCCESS, payload: banners, }; }; export const fetchBannersFailure = (error) => { return { type: FETCH_BANNERS_FAILURE, payload: error, }; }; export const fetchBanners = () => { return (dispatch) => { dispatch(fetchBannersRequest()); fetch(BANNERS_URL) .then((res_) => res_.json()) .then((data) => { dispatch(fetchBannersSuccess(data)); }) .catch((err) => { dispatch(fetchBannersFailure(err)); }); }; };
javascript
13
0.617613
49
20.04878
41
starcoderdata
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.winde.comicsweb.domain; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.*; import java.io.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.*; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import org.imgscalr.Scalr; /** * * @author Winde */ public abstract class ProcessFile implements Iterator { public static List rarExtensions = new ArrayList() { { add("cbr"); add("rar"); } }; public static List zipExtensions = new ArrayList() { { add("cbz"); add("zip"); } }; public static List imgExtensions = new ArrayList() { { add("jpg"); add("png"); add("gif"); } }; public static List bookExtensions = new ArrayList() { { add("pdf"); } }; public static String getNameWithoutExtension(String filename) { if (!filename.contains(".")) { return null; } return filename.substring(0, filename.lastIndexOf(".")); } public static String getExtension(String filename) { if (!filename.contains(".")) { return null; } return filename.substring(filename.lastIndexOf(".") + 1); } private static BufferedImage deepCopy(BufferedImage bi) { ColorModel cm = bi.getColorModel(); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); WritableRaster raster = bi.copyData(null); return new BufferedImage(cm, raster, isAlphaPremultiplied, null); } public static BufferedImage imageFromBytes(byte[] bytes) { if (bytes != null) { InputStream in = new ByteArrayInputStream(bytes); ImageInputStream iis; try { iis = ImageIO.createImageInputStream(in); } catch (IOException ex) { return null; } try { BufferedImage bufferedImage = ImageIO.read(iis); return bufferedImage; } catch (IOException ex) { Logger.getLogger(ProcessFileRar.class.getName()).log(Level.SEVERE, null, ex); return null; } } else { return null; } } public static BufferedImage imageFromBytesAlternate(byte[] bytes) { int[] RGB_MASKS = {0xFF0000, 0xFF00, 0xFF}; ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]); Image image = Toolkit.getDefaultToolkit().createImage(bytes); PixelGrabber pg = new PixelGrabber(image, 0, 0, -1, -1, true); try { pg.grabPixels(); } catch (InterruptedException ex) { Logger.getLogger(ProcessFile.class.getName()).log(Level.SEVERE, null, ex); } int width = pg.getWidth(), height = pg.getHeight(); DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight()); BufferedImage bi; try { WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null); bi = new BufferedImage(RGB_OPAQUE, raster, false, null); } catch (IllegalArgumentException e) { return null; } return bi; } public static byte[] bytesFromImage(BufferedImage bufferedImage) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageOutputStream ios; try { ios = ImageIO.createImageOutputStream(out); } catch (IOException ex) { return null; } try { Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float quality = (float) 0.9; iwp.setCompressionQuality(quality); writer.setOutput(ios); if (bufferedImage != null) { writer.write(bufferedImage); } else { return null; } //ImageIO.write(bufferedImage, "jpg", out); writer.dispose(); } catch (IOException ex) { return null; } byte[] salida = out.toByteArray(); try { out.close(); } catch (IOException ex) { Logger.getLogger(ProcessFile.class.getName()).log(Level.SEVERE, null, ex); } return salida; } public static ProcessFile createProcesFile(File fichero) { if (fichero == null) { return null; } String filename = fichero.getName(); String extension = ProcessFile.getExtension(filename); if (extension != null) { extension = extension.toLowerCase(); } ProcessFile procesador = null; if (bookExtensions.contains(extension)) { procesador = ProcessFilePdfIce.createProcessFile(fichero); if (procesador == null) { System.out.println(fichero.getName() + " Pdf unsupported by PDFIce"); return ProcessFilePdfBox.createProcessFilePdfBox(fichero); } else { return procesador; } } procesador = ProcessFileZip.createProcesFile(fichero); if (procesador != null) { return procesador; } procesador = ProcessFileRar.createProcesFile(fichero); if (procesador != null) { return procesador; } return null; } public abstract String getNextExtension(); @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } public abstract BufferedImage getImageAt(int index); public BufferedImage getThumbAt(int index, int dimension) { BufferedImage image = this.getImageAt(index); if (image != null) { return Scalr.resize(image, dimension); } else { return null; } } public abstract String getImg64At(int index); public abstract byte[] getImgBytesAt(int index); public abstract String getExtensionAt(int index); public abstract int getCount(); public abstract String getFileName(); public abstract void close(); @Override public int hashCode() { return this.getFileName().hashCode(); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (o instanceof ProcessFile) { ProcessFile temp = (ProcessFile) o; return temp.getFileName().equals(this.getFileName()); } else { return false; } } @Override protected void finalize() throws Throwable { super.finalize(); this.close(); } }
java
16
0.558839
109
27.960474
253
starcoderdata
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ namespace newarp { //! This class implements the eigen solver for real symmetric matrices. template<typename eT, int SelectionRule, typename OpType> class SymEigsSolver { protected: const OpType& op; // object to conduct matrix operation, e.g. matrix-vector product const uword nev; // number of eigenvalues requested Col<eT> ritz_val; // ritz values // Sort the first nev Ritz pairs in decreasing magnitude order // This is used to return the final results virtual void sort_ritzpair(); private: const uword dim_n; // dimension of matrix A const uword ncv; // number of ritz values uword nmatop; // number of matrix operations called uword niter; // number of restarting iterations Mat<eT> fac_V; // V matrix in the Arnoldi factorisation Mat<eT> fac_H; // H matrix in the Arnoldi factorisation Col<eT> fac_f; // residual in the Arnoldi factorisation Mat<eT> ritz_vec; // ritz vectors Col<eT> ritz_est; // last row of ritz_vec std::vector<bool> ritz_conv; // indicator of the convergence of ritz values const eT eps; // the machine precision // e.g. ~= 1e-16 for double type const eT approx0; // a number that is approximately zero // approx0 = eps^(2/3) // used to test the orthogonality of vectors, // and in convergence test, tol*approx0 is // the absolute tolerance // Arnoldi factorisation starting from step-k inline void factorise_from(uword from_k, uword to_m, const Col<eT>& fk); // Implicitly restarted Arnoldi factorisation inline void restart(uword k); // Calculate the number of converged Ritz values inline uword num_converged(eT tol); // Return the adjusted nev for restarting inline uword nev_adjusted(uword nconv); // Retrieve and sort ritz values and ritz vectors inline void retrieve_ritzpair(); public: //! Constructor to create a solver object. inline SymEigsSolver(const OpType& op_, uword nev_, uword ncv_); //! Providing the initial residual vector for the algorithm. inline void init(eT* init_resid); //! Providing a random initial residual vector. inline void init(); //! Conducting the major computation procedure. inline uword compute(uword maxit = 1000, eT tol = 1e-10); //! Returning the number of iterations used in the computation. inline uword num_iterations() { return niter; } //! Returning the number of matrix operations used in the computation. inline uword num_operations() { return nmatop; } //! Returning the converged eigenvalues. inline Col<eT> eigenvalues(); //! Returning the eigenvectors associated with the converged eigenvalues. inline Mat<eT> eigenvectors(uword nvec); //! Returning all converged eigenvectors. inline Mat<eT> eigenvectors() { return eigenvectors(nev); } }; } // namespace newarp
c++
13
0.65285
96
36.843137
102
research_code
# A - Libra # https://atcoder.jp/contests/abc083/tasks/abc083_a A, B, C, D = map(int, input().split()) ab = A + B cd = C + D result = 'Balanced' if ab > cd: result = 'Left' elif ab < cd: result = 'Right' print(result)
python
9
0.582609
51
14.333333
15
codenet
import React from 'react'; export default function LinkText( props ) { if (!props.children) { return null; } return( <a href={props.url} target={props.target} rel={props.rel} className={props.className} > { props.children } ) } LinkText.defaultProps = { url: '#', rel:'nofollow', target: '_self', className: '' };
javascript
11
0.585366
119
20.705882
17
starcoderdata
static void tst_ext_gcd() { std::cout << "\nExtended GCD\n"; polynomial::numeral_manager nm; polynomial::manager m(nm); polynomial_ref x(m); x = m.mk_polynomial(m.mk_var()); // create univariate polynomial using multivariate polynomial package polynomial_ref a(m); polynomial_ref b(m); a = (x^6) + 5*(x^5) + 9*(x^4) + 5*(x^2) + 5*x; b = (x^8) + (x^6) + 10*(x^4) + 10*(x^3) + 8*(x^2) + 2*x + 8; // Computing GCD of p an q in Z_3[x] std::cout << "GCD in Z_13[x]\n"; upolynomial::zp_manager um(nm); um.set_zp(13); mpzzp_manager & z13 = um.m(); upolynomial::zp_manager::scoped_numeral_vector A(z13), B(z13), U(z13), V(z13), D(z13); um.to_numeral_vector(a, A); um.to_numeral_vector(b, B); um.ext_gcd(A.size(), A.c_ptr(), B.size(), B.c_ptr(), U, V, D); std::cout << "A: "; um.display(std::cout, A); std::cout << "\n"; std::cout << "B: "; um.display(std::cout, B); std::cout << "\n"; std::cout << "U: "; um.display(std::cout, U); std::cout << "\n"; std::cout << "V: "; um.display(std::cout, V); std::cout << "\n"; std::cout << "D: "; um.display(std::cout, D); std::cout << "\n"; }
c++
13
0.535897
90
42.37037
27
inline
package me.jessyan.mvparms.graduation.mvp.ui.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import org.litepal.crud.DataSupport; import org.simple.eventbus.EventBus; import java.util.List; import butterknife.BindView; import common.AppComponent; import common.WEFragment; import me.jessyan.mvparms.graduation.R; import me.jessyan.mvparms.graduation.mvp.model.entity.Answer; /** * 作者: 张少林 on 2017/4/18 0018. * 邮箱: */ public class WriteAnserFragment extends WEFragment { @BindView(R.id.nav_left_text) TextView mNavLeftText; @BindView(R.id.center_title) TextView mCenterTitle; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.edt_title) EditText mEdtTitle; @BindView(R.id.bottom_view) LinearLayout mBottomView; @BindView(R.id.nav_right_text_button) TextView mNavRightTextButton; public static final String ARG_TITLE = "arg_title"; public String title = null; public static WriteAnserFragment newInstance(String title) { Bundle bundle = new Bundle(); bundle.putString(ARG_TITLE, title); WriteAnserFragment writeAnserFragment = new WriteAnserFragment(); writeAnserFragment.setArguments(bundle); return writeAnserFragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle arguments = getArguments(); title = arguments.getString(ARG_TITLE); } @Override protected void setupFragmentComponent(AppComponent appComponent) { } @Override protected View initView() { return LayoutInflater.from(_mActivity).inflate(R.layout.frg_write_answer_view, null); } @Override protected void initData() { showSoftInput(mEdtTitle); mNavLeftText.setVisibility(View.VISIBLE); mNavLeftText.setText("撰写回答"); mCenterTitle.setVisibility(View.GONE); mNavRightTextButton.setVisibility(View.VISIBLE); mNavRightTextButton.setText("发送"); mNavRightTextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Answer answer = new Answer(); String data = mEdtTitle.getText().toString(); answer.setAnswer(data); answer.setTitle(title); List answerList = DataSupport .where("title = ?", title) .find(Answer.class); if (answerList.isEmpty()) { answer.saveThrows(); } if (answer.isSaved()) { EventBus.getDefault().post(new me.jessyan.mvparms.graduation.app.EventBus.RefreshData("刷新数据")); pop(); } } }); } @Override protected void onEnterAnimationEnd(Bundle savedInstanceState) { } }
java
24
0.655727
115
29.471154
104
starcoderdata
package io.lineage; /** * Lowest building block */ public abstract class Gene { /** * Value represented by this gene */ protected T allele; /** * Clone current gene */ @Override protected abstract Gene clone() throws CloneNotSupportedException; /** * Called when gene needs to mutate self */ public abstract void mutate(); /** * @param allele the value to set */ public void setAllele(final T allele) { this.allele = allele; } public T getAllele() { return allele; } @Override public String toString() { return "G :" + allele; } }
java
8
0.574194
79
16.222222
45
starcoderdata
func InsertIntoBlockchain(transaction *model.DbTransaction, block *Block) error { // for local tests blockID := block.Header.BlockID if block.Header.BlockID == 1 { if *conf.StartBlockID != 0 { blockID = *conf.StartBlockID } } // record into the block chain bl := &model.Block{} err := bl.DeleteById(transaction, blockID) if err != nil { log.WithFields(log.Fields{"type": consts.DBError, "error": err}).Error("deleting block by id") return err } rollbackTx := &model.RollbackTx{} blockRollbackTxs, err := rollbackTx.GetBlockRollbackTransactions(transaction, blockID) if err != nil { log.WithFields(log.Fields{"type": consts.DBError, "error": err}).Error("getting block rollback txs") return err } buffer := bytes.Buffer{} for _, rollbackTx := range blockRollbackTxs { if rollbackTxBytes, err := json.Marshal(rollbackTx); err != nil { log.WithFields(log.Fields{"type": consts.JSONMarshallError, "error": err}).Error("marshalling rollback_tx to json") return err } else { buffer.Write(rollbackTxBytes) } } rollbackTxsHash, err := crypto.Hash(buffer.Bytes()) if err != nil { log.WithFields(log.Fields{"type": consts.CryptoError, "error": err}).Error("hashing block rollback_txs") return err } b := &model.Block{ ID: blockID, Hash: block.Header.Hash, Data: block.BinData, EcosystemID: block.Header.EcosystemID, KeyID: block.Header.KeyID, NodePosition: block.Header.NodePosition, Time: block.Header.Time, RollbacksHash: rollbackTxsHash, Tx: int32(len(block.Parsers)), } err = b.Create(transaction) if err != nil { log.WithFields(log.Fields{"type": consts.DBError, "error": err}).Error("creating block") return err } err = autoupdate.TryUpdate(uint64(blockID)) if err != nil { log.WithFields(log.Fields{"type": consts.AutoupdateError, "error": err, "blockID": blockID}).Fatal("update for blockID") return err } return nil }
go
17
0.682766
122
31.262295
61
inline
<?php /** * (c) Meritoo.pl, http://www.meritoo.pl * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Meritoo\Test\FlashBundle\Twig; use Meritoo\CommonBundle\Test\Twig\Base\BaseTwigExtensionTestCase; use Meritoo\FlashBundle\Twig\ConfigurationExtension; /** * Test case for the Twig extension that provides functions and filters related to configuration of this bundle * * @author Meritoo * @copyright Meritoo */ class ConfigurationExtensionTest extends BaseTwigExtensionTestCase { /** * @covers \Meritoo\FlashBundle\Twig\ConfigurationExtension::getFunctions */ public function testGetFunctions(): void { $functions = static::$container ->get($this->getExtensionNamespace()) ->getFunctions(); static::assertCount(5, $functions); } public function testContainerCssClassesUsingTestEnvironment(): void { $this->verifyRenderedTemplate( 'container_css_classes', '{{ meritoo_flash_container_css_classes() }}', 'all-flash-messages' ); } public function testContainerCssClassesUsingDefaults(): void { static::bootKernel([ 'environment' => 'defaults', ]); $this->verifyRenderedTemplate( 'container_css_classes', '{{ meritoo_flash_container_css_classes() }}', 'alerts' ); } public function testOneFlashMessageCssClassesUsingTestEnvironment(): void { $this->verifyRenderedTemplate( 'one_flash_message_css_classes', '{{ meritoo_flash_one_flash_message_css_classes(\'positive\') }}', 'message positive-message-type single-row' ); } public function testOneFlashMessageCssClassesUsingDefaults(): void { static::bootKernel([ 'environment' => 'defaults', ]); $this->verifyRenderedTemplate( 'one_flash_message_css_classes', '{{ meritoo_flash_one_flash_message_css_classes(\'success\') }}', 'alert alert-success' ); } public function testGetPositiveFlashMessageTypeUsingTestEnvironment(): void { $this->verifyRenderedTemplate( 'positive_flash_message_type', '{{ meritoo_flash_positive_flash_message_type() }}', 'positive' ); } public function testGetPositiveFlashMessageTypeUsingDefaults(): void { static::bootKernel([ 'environment' => 'defaults', ]); $this->verifyRenderedTemplate( 'positive_flash_message_type', '{{ meritoo_flash_positive_flash_message_type() }}', 'success' ); } public function testGetNegativeFlashMessageTypeUsingTestEnvironment(): void { $this->verifyRenderedTemplate( 'negative_flash_message_type', '{{ meritoo_flash_negative_flash_message_type() }}', 'negative' ); } public function testGetNegativeFlashMessageTypeUsingDefaults(): void { static::bootKernel([ 'environment' => 'defaults', ]); $this->verifyRenderedTemplate( 'negative_flash_message_type', '{{ meritoo_flash_negative_flash_message_type() }}', 'danger' ); } public function testGetNeutralFlashMessageTypeUsingTestEnvironment(): void { $this->verifyRenderedTemplate( 'neutral_flash_message_type', '{{ meritoo_flash_neutral_flash_message_type() }}', 'information' ); } public function testGetNeutralFlashMessageTypeUsingDefaults(): void { static::bootKernel([ 'environment' => 'defaults', ]); $this->verifyRenderedTemplate( 'neutral_flash_message_type', '{{ meritoo_flash_neutral_flash_message_type() }}', 'info' ); } /** * {@inheritdoc} */ protected function getExtensionNamespace(): string { return ConfigurationExtension::class; } }
php
13
0.601446
111
26.844156
154
starcoderdata
double calculateDirection(const lanelet::BasicPoint3d& p1, const lanelet::BasicPoint3d& p2) { const auto dy = p2.y() - p1.y(); const auto dx = p2.x() - p1.x(); const auto direction = atan2(dx, dy); // cw from north return direction; }
c++
8
0.668033
91
29.625
8
inline
""" Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.) EXAMPLE Input: " ", 13 Output: "Mr%20John%20Smith" """ # additional question: will we replace two spaces with %20%20 or just with %20? # additional question 2: will we put %20 at the spaces at the 0th index? def urlify(string, str_length): # O(n) time, O(n) space space = "%20" urlified = [] for i in range(str_length): if string[i] == " ": urlified.append(space) else: urlified.append(string[i]) return "".join(urlified) def urlify_inplace(string, str_length): # Assuming we have an array of chars, this is an inplace algo space = "%20" urlified = list(string) for i in range(str_length): if urlified[i] == " ": urlified[i] = space j = str_length while True: try: urlified[j] = "" j += 1 except IndexError: break return "".join(urlified) def test_solutions(): print(urlify(" ", 13)) print(urlify_inplace(" ", 13)) assert urlify(" ", 13) == "Mr%20John%20Smith" assert urlify_inplace(" ", 13) == "Mr%20John%20Smith" if __name__ == '__main__': test_solutions()
python
12
0.591667
100
28
52
starcoderdata
bool CreateSchema(sql::Connection* db) { // If you create a transaction but don't Commit() it is automatically // rolled back by its destructor when it falls out of scope. sql::Transaction transaction(db); if (!transaction.Begin()) return false; if (!db->DoesTableExist(kOfflinePagesTable.table_name)) { if (!CreateTable(db, kOfflinePagesTable)) return false; } if (!db->DoesColumnExist(kOfflinePagesTable.table_name, "expiration_time")) { if (!RefreshColumns(db)) return false; } // TODO(bburns): Add indices here. return transaction.Commit(); }
c++
10
0.693086
79
28.7
20
inline
<?php session_start(); if ( ! isset($_SESSION['username']) ) { die('Not logged in'); } ?> <!DOCTYPE html> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity=" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity=" crossorigin="anonymous"> <div class="container"> <?php if ( isset($_SESSION["success"]) ) { echo('<p style="color:green">'.$_SESSION["success"]." unset($_SESSION["success"]); } ?> <?php if ( isset($_SESSION['username']) ) { echo " "; echo htmlentities($_SESSION['username']); echo " } ?> Autos for <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbcacbaa99faab2b6bcb7f1babbaa">[email&#160;protected] <a href="add.php">Add New (case matters) | <a href="logout.php">Logout <a href="add.php">Add New (case matters) <script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js">
php
9
0.636634
159
26.408163
49
starcoderdata
<?php namespace App\Repositories\Brand; use App\Models\Brand; use App\Repositories\CacheTrait; class BrandRepositoryCache implements BrandInterface { use CacheTrait; protected $model; public function __construct(Brand $model) { $this->model = $model; } public function model() { return $this->model; } public function query() { return $this->model->query(); } public function all() { return $this->setCache()->remember('brands_cache', $this->timeToLive(), function () { return $this->model->all(); }); } public function activeItems() { return $this->setCache()->remember('brands_cache_active', $this->timeToLive(), function () { return $this->model->active(); }); } public function getBrand($slug, $with = null) { $slugg = json_encode($slug); if (isset($with) && is_array($with)) { return $this->setCache()->remember("brands_cache_slug_{$slugg}", $this->timeToLive(), function () use ($slug, $with) { return $this->model->whereSlug($slug)->whereActive(true) ->with($with) ->firstOrFail(); }); } return $this->setCache()->remember("brands_cache_slug_{$slugg}", $this->timeToLive(), function () use ($slug) { return $this->model->whereSlug($slug)->whereActive(true) ->firstOrFail(); }); } }
php
21
0.563975
130
24.967742
62
starcoderdata
using System; using System.Diagnostics; using JetBrains.Annotations; namespace Albumprinter.CorrelationTracking.Correlation.Core { [Serializable] public sealed class CorrelationScope { internal static Guid AutoProcessId => Guid.NewGuid(); internal CorrelationScope(Guid correlationId, string requestId) { CorrelationId = correlationId; RequestId = requestId; } [CanBeNull] public static CorrelationScope Current { get { var currentActivity = Activity.Current; if (currentActivity == null) return null; var correlationIdX = currentActivity.GetTagItem(CorrelationKeys.CorrelationId); var requestIdX = currentActivity.GetTagItem(CorrelationKeys.RequestId); if (correlationIdX == null || !Guid.TryParse(correlationIdX, out var correlationIdGuid)) return null; return new CorrelationScope(correlationIdGuid, requestIdX); } internal set { var currentActivity = Activity.Current; if (currentActivity == null) return; if (value == null) return; currentActivity.AddTag(CorrelationKeys.CorrelationId, value.CorrelationId.ToString()); currentActivity.AddTag(CorrelationKeys.RequestId, value.RequestId); } } /// /// Gets the process identifier. The process is created once during the application lifecycle. /// /// /// The process identifier. /// public Guid ProcessId => AutoProcessId; /// /// Gets the correlation identifier. An explicit correlation identifier for the business transaction. /// /// /// The correlation identifier. /// public Guid CorrelationId { get; } /// /// Gets the request identifier. An explicit correlation identifier for the request. /// /// /// The request identifier. /// public String RequestId { get; } } }
c#
17
0.571606
113
34.651515
66
starcoderdata
using System; namespace PushServe.Entity { public class ClientInfo { public string uid { get; set; } public string connid { get; set; } public DateTime timespan { get; set; } } }
c#
8
0.59447
46
18.727273
11
starcoderdata
private final Future<?> loadAndStartPlayingTrack (final PlayItem item) { if (item == null) throw new IllegalArgumentException("PlayItem can not be null."); if (!item.hasTrack()) throw new IllegalArgumentException("Item must have a track."); if (!item.getTrack().isPlayable()) throw new IllegalArgumentException("Item is not playable: '" + item.getTrack().getFilepath() + "'."); try { if (StringHelper.notBlank(item.getTrack().getFilepath())) { final File file = new File(item.getTrack().getFilepath()); if (!file.exists()) throw new FileNotFoundException(file.getAbsolutePath()); } else if (StringHelper.blank(item.getTrack().getRemoteLocation())) { throw new FileNotFoundException("Track has no filepath or remote location: " + item.getTrack()); } markLoadingState(true); } catch (final Exception e) { // NOSONAR reporting exceptions. rollbackToTopOfQueue(item); this.listeners.onException(e); } return this.loadEs.submit(new Runnable() { @Override public void run () { try { markLoadingState(true); try { AbstractPlayer.this.listeners.currentItemChanged(item); File altFile = null; final TranscodeProfile tProfile = getTranscode().profileForItem(item.getList(), item.getTrack()); if (tProfile != null) { AbstractPlayer.this.transcoder.transcodeToFile(tProfile); altFile = tProfile.getCacheFileEvenIfItDoesNotExist(); // This should exist because the transcode just ran. } loadAndPlay(item, altFile); } finally { markLoadingState(false); } } catch (final Exception e) { // NOSONAR reporting exceptions. rollbackToTopOfQueue(item); AbstractPlayer.this.listeners.onException(e); } } }); }
java
20
0.685974
138
34.959184
49
inline
package migrations import ( "strings" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" testsv1 "github.com/kubeshop/testkube-operator/apis/tests/v1" testsv2 "github.com/kubeshop/testkube-operator/apis/tests/v2" testsuite "github.com/kubeshop/testkube-operator/apis/testsuite/v1" scriptsclientv2 "github.com/kubeshop/testkube-operator/client/scripts/v2" testsclientv1 "github.com/kubeshop/testkube-operator/client/tests" testsclientv2 "github.com/kubeshop/testkube-operator/client/tests/v2" testsuitesclientv1 "github.com/kubeshop/testkube-operator/client/testsuites/v1" "github.com/kubeshop/testkube/pkg/migrator" ) func NewVersion_0_9_2( scriptsClient *scriptsclientv2.ScriptsClient, testsClientV1 *testsclientv1.TestsClient, testsClientV2 *testsclientv2.TestsClient, testsuitesClient *testsuitesclientv1.TestSuitesClient, ) *Version_0_9_2 { return &Version_0_9_2{ scriptsClient: scriptsClient, testsClientV1: testsClientV1, testsClientV2: testsClientV2, testsuitesClient: testsuitesClient, } } type Version_0_9_2 struct { scriptsClient *scriptsclientv2.ScriptsClient testsClientV1 *testsclientv1.TestsClient testsClientV2 *testsclientv2.TestsClient testsuitesClient *testsuitesclientv1.TestSuitesClient } func (m *Version_0_9_2) Version() string { return "0.9.2" } func (m *Version_0_9_2) Migrate() error { scripts, err := m.scriptsClient.List(nil) if err != nil { return err } for _, script := range scripts.Items { if _, err = m.testsClientV2.Get(script.Name); err != nil && !errors.IsNotFound(err) { return err } if err == nil { continue } test := &testsv2.Test{ ObjectMeta: metav1.ObjectMeta{ Name: script.Name, Namespace: script.Namespace, }, Spec: testsv2.TestSpec{ Type_: script.Spec.Type_, Name: script.Spec.Name, Params: script.Spec.Params, }, } if script.Spec.Content != nil { test.Spec.Content = &testsv2.TestContent{ Type_: script.Spec.Content.Type_, Data: script.Spec.Content.Data, Uri: script.Spec.Content.Uri, } if script.Spec.Content.Repository != nil { test.Spec.Content.Repository = &testsv2.Repository{ Type_: script.Spec.Content.Repository.Type_, Uri: script.Spec.Content.Repository.Uri, Branch: script.Spec.Content.Repository.Branch, Path: script.Spec.Content.Repository.Path, } } } if _, err = m.testsClientV2.Create(test); err != nil { return err } if err = m.scriptsClient.Delete(script.Name); err != nil { return err } } tests, err := m.testsClientV1.List(nil) if err != nil { return err } OUTER: for _, test := range tests.Items { if _, err = m.testsuitesClient.Get(test.Name); err != nil && !errors.IsNotFound(err) { return err } if err == nil { continue } for _, managedField := range test.GetManagedFields() { if !strings.HasSuffix(managedField.APIVersion, "/v1") { continue OUTER } } testsuite := &testsuite.TestSuite{ ObjectMeta: metav1.ObjectMeta{ Name: test.Name, Namespace: test.Namespace, }, Spec: testsuite.TestSuiteSpec{ Repeats: test.Spec.Repeats, Description: test.Spec.Description, }, } for _, step := range test.Spec.Before { testsuite.Spec.Before = append(testsuite.Spec.Before, copyTestStepTest2Testsuite(step)) } for _, step := range test.Spec.Steps { testsuite.Spec.Steps = append(testsuite.Spec.Steps, copyTestStepTest2Testsuite(step)) } for _, step := range test.Spec.After { testsuite.Spec.After = append(testsuite.Spec.After, copyTestStepTest2Testsuite(step)) } if _, err = m.testsuitesClient.Create(testsuite); err != nil { return err } if err = m.testsClientV1.Delete(test.Name); err != nil { return err } } return nil } func (m *Version_0_9_2) Info() string { return "Moving scripts v2 resources to tests v2 ones and tests v1 resources to testsuites v1 ones" } func (m *Version_0_9_2) Type() migrator.MigrationType { return migrator.MigrationTypeServer } func copyTestStepTest2Testsuite(step testsv1.TestStepSpec) testsuite.TestSuiteStepSpec { result := testsuite.TestSuiteStepSpec{ Type: step.Type, } if step.Execute != nil { result.Execute = &testsuite.TestSuiteStepExecute{ Namespace: step.Execute.Namespace, Name: step.Execute.Name, StopOnFailure: step.Execute.StopOnFailure, } } if step.Delay != nil { result.Delay = &testsuite.TestSuiteStepDelay{ Duration: step.Delay.Duration, } } return result }
go
20
0.701904
99
24.52514
179
starcoderdata
def item_action(self, index=QModelIndex(), prev=QModelIndex()): """ typical action is to show image """ if not self.initialized: return if self.image_to_show_left is not None: self.pixmap = self.channelmodel.\ get_image(index.row(), self.image_to_show_left) if self.pixmap is not None: self.labelImage.setPixmap(self.pixmap) if self.image_to_show_right is not None: self.pixmapRight = self.channelmodel.\ get_image(index.row(), self.image_to_show_right) if self.pixmapRight is not None: self.labelImageRight.setPixmap(self.pixmapRight) self.set_sizes() # set the status status = self.channelmodel.get_status(index.row()) self.labelCurrentCh.setText(status)
python
11
0.584971
64
33.64
25
inline
let search = document.getElementById("search-bar"); let dropdown = document.getElementById("drop-down"); let email = document.getElementById("session-email").innerHTML; let user = {}; search.onchange = handleSearch; setup(); let courses = []; function callFunc (postparams, completion) { let xhttp = new XMLHttpRequest(); let formData = new FormData(); for (each in postparams) formData.append (each, postparams[each]); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { completion (this.responseText); } } xhttp.open("POST", "/data/datafunc.php") xhttp.send(formData); } function setup() { let params = { funcName: "getAllCourses" }; function handler(responseText) { let json = JSON.parse(responseText); courses = json; } callFunc(params, handler); let params2 = { funcName: "getUserByEmail", email: email, }; function handler2(responseText) { let json = JSON.parse(responseText); if (json) user = json; setCourses(); } callFunc(params2, handler2); } function handleSearch() { let stack = []; let searchstring = search.value.trim().toLowerCase(); let searcharr = searchstring.split(" "); for (let i = 0; i < courses.length; i++) { courses[i]["matchval"] = 0; } for (let i = 0; i < courses.length; i++) { let course = courses[i]; for (let k = 0; k < searcharr.length; k++) { if (course["code"].includes(searcharr[k].toLowerCase())) courses[i]["matchval"]++; if (course["title"].includes(searcharr[k].toLowerCase())) courses[i]["matchval"]++; if (course["lectureNumber"].includes(searcharr[k].toLowerCase())) courses[i]["matchval"]++; if (course["labNumber"].includes(searcharr[k].toLowerCase())) courses[i]["matchval"]++; } } courses.sort(function (a, b) { return b["matchval"] - a["matchval"]; }); for (let i = 0; i < courses.length; i++) { if (courses[i]["matchval"] != 0) { let newhtml = ` <div class="drop-course-item"> <div class="add-course"><img src="/includes/images/add.png" alt="add icon" class="add-img"/> <div class="course-code">${courses[i]["code"]} <div class="course-name">${courses[i]["title"]} <div class="lecture">lecture: ${courses[i]["lectureNumber"]} <div class="section">section: ${courses[i]["labNumber"]} `; stack.push(newhtml); } } dropdown.innerHTML = stack.join(""); let addbuttons = document.getElementsByClassName("add-course"); for (let i = 0; i < addbuttons.length; i++) { addbuttons[i].addEventListener("click", function(e) { addCourse(i); }); } } function addCourse(idx) { let userid = user["id"]; let usercourses = user["courses"]; for (let i = 0; i < usercourses.length; i++) { if (usercourses[i]["id"] == courses[idx]["id"]) { alert ("already added"); return; } } let params = { funcName: "addCourseToUser", user_id: userid, course_id: courses[idx]["id"] } function handler (responseText) { location.reload(); } callFunc(params, handler); } ///courses let nocourse = document.getElementById("no-course"); let coursecontainer = document.getElementById("courses-container"); function setCourses() { let courses = user["courses"]; if (courses.length == 0) nocourse.className = "no-course active"; else nocourse.className = "no-course"; let stack = []; for (let i = 0; i < courses.length; i++) { let course = courses[i]; let newhtml = ` <a href="/prof/course/course.php?id=${course["id"]}" style="text-decoration: none; color: black;"> <div class="badcontainer" style="position:relative; width: 100%;"> <div class="underline"> <span class="course-code">${course["code"]} <span class="course-name" style="margin-left: 10px;">${course["title"]} <span class="lecture" style="margin-left: 10px;"><span style="font-family:'montserratbold'">lecture: <span class="section" style="margin-left: 10px;"><span style="font-family:'montserratbold'">section: <div class="remove"><img alt="remove img" class="remove-img" src="/includes/images/remove.png"/> ` stack.push(newhtml); } coursecontainer.innerHTML = stack.join(""); let removebuttons = document.getElementsByClassName("remove"); for (let i = 0; i < removebuttons.length; i++) { removebuttons[i].addEventListener("click", function(e) { removeCourse(i, courses); }); } } function removeCourse(idx, courses) { let id = courses[idx]["id"]; let user_id = user["id"]; let param = { funcName: "removeCourseFromUser", course_id:id, user_id:user_id }; function handler(response) { location.reload(); } callFunc(param, handler); }
javascript
25
0.567645
157
30.191011
178
starcoderdata
#!/usr/bin/env python3 """ This script removes volumes created by cinder csi that are * older than 3 hours * not attached to any node """ import openstack import logging import sys from datetime import datetime, timedelta def main(): logging.basicConfig(level=logging.INFO, stream=sys.stdout) log = logging.getLogger(__name__) log.info("cleaning up orphaned volumes") con = openstack.connect() volumes = con.block_storage.volumes(details=True, status="available") for v in filter(filter_volumes, volumes): log.info("deleting volume %s", v.id) try: con.block_storage.delete_volume(v, ignore_missing=True) except: log.exception("unable to delete volume %s... skipping", v.id) pass def filter_volumes(vol): """ filter_volumes takes care to only clean up volumes created by cinder csi """ try: if not vol.name.startswith("pvc-"): return False if vol.attachments: return False created = datetime.fromisoformat(vol.created_at) age = datetime.now() - created if age < timedelta(hours=3): return False cluster_name = vol.metadata.get("cinder.csi.openstack.org/cluster", "") if not cluster_name.startswith("kubernetes"): return False except: return False return True if __name__ == "__main__": main()
python
12
0.638594
83
27.45283
53
starcoderdata
<?php use yii\helpers\Html; use kartik\grid\GridView; use app\models\Common; /* @var $this yii\web\View */ /* @var $searchModel app\models\TblBillingSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Billing Management'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="panel panel-info"> <div class="panel-heading" ><i class="fa fa-list"> Html::encode(' Available Billings') ?> <?= $this->render('_search', ['model' => $searchModel]); ?> <div class="panel-body"> <?= (Yii::$app->user->can('create-billing'))?Html::a('Generate Bill', ['create'], ['class' => 'btn btn-primary']):'' ?> <?= (Yii::$app->user->can('Cancel Bill Access'))?"<input type='button' class='btn btn-danger' value='Cancell Bills' id='cancell'>":""?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'pager' => [ 'firstPageLabel' => 'First', 'lastPageLabel' => 'Last' ], 'id' => 'grid', 'columns' => [ ['class' => 'yii\grid\SerialColumn'], ['class' => 'yii\grid\CheckboxColumn'], //'id', 'payer_name', 'bill_amount', // 'bill_exp_date', //'bill_gen_date', // [ // 'attribute'=>'bill_gen_date', // 'filter'=>false // ], 'bill_description', //'bill_gen_by', //'bill_appr_by', //'payer_cell_num', //'payer_email:email', 'bill_currency', // 'payment_type_id', [ 'attribute'=>'payment_type_id', 'format'=>'text', 'value'=>function($data){ return \app\models\PaymentType::find()->where('id=:id',[':id'=>$data->payment_type_id])->one()->acc_description; } ] , //'company_id', 'bill_id', 'control_number', // 'bill_pay_opt', //'use_on_pay', //'bill_eqv_amount', 'bill_item_ref', // 'is_posted', [ 'attribute'=>'is_posted', 'filter'=>\yii\helpers\ArrayHelper::map(array(['id'=>'1','name'=>'Drafted'],['id'=>'2','name'=>'Posted']),'id','name'), 'format'=>'text', 'value'=>function($data){ return Common::isPosted($data->is_posted); } ], // 'is_cancelled', [ 'attribute'=>'is_cancelled', 'filter'=>\yii\helpers\ArrayHelper::map(array(['id'=>'1','name'=>'Not Cancelled'],['id'=>'2','name'=>'Cancelled']),'id','name'), 'format'=>'text', 'value'=>function($data){ return Common::isCancelled($data->is_cancelled); } ], [ 'class' => 'yii\grid\ActionColumn', 'template'=>\app\models\MenuPanel::getActions(Yii::$app->controller->id), 'buttons' => [ 'delete' => function ($url, $model) { if($model->is_posted==2){ return false; }else{ return Html::a(' <i class="fa fa-trash text-red"> ['delete', 'id' => $model->id], [ 'data' => [ 'confirm' => 'Are you sure you want to delete this bill item?', 'method' => 'post', ], ]); } }, 'update' => function ($url, $model) { if($model->is_posted==2){ return false; }else{ return Html::a(' <i class="fa fa-pen"> ['update', 'id' => $model->id]); } }, ], ], ], ]); ?> <!-- Modal form--> <div class="modal fade" id="myModal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog "> <div class="modal-content"> <div class="modal-header text-center"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times; class="sr-only">Close <h4 class="modal-title" id="myModalLabel"> <div class="modal-body" id="modal-bodyku"> <div class="modal-footer" id="modal-footerq"> <!-- end of modal ------------------------------> <?php $script = <<< JS $(document).on('click','#cancell',function(e) { e.preventDefault(); var content = ''; var title = '<b class="text-center">UDOM BILLING SYSTEM var footer = '<button type="button" class="btn btn-default" data-dismiss="modal">Close var keys = $('#grid').yiiGridView('getSelectedRows'); // returns an array of pkeys, and #grid is your grid element id if(keys.length>0){ var reason = prompt("Please enter reason for cancell bill item(s)"); if ((reason != null)&&reason.length>10 ) { $.ajax({ type: "GET", url : '/billing/cancellbills.aspx', timeout: 30000, data : {keyslist:keys,reason:encodeURI(reason)}, success : function(data) { var v=JSON.parse(data); if(v['code']==200){ setModalBox(title,v['message'],footer); $('#myModal').modal('show'); }else{ setModalBox(title,v['message'],footer); $('#myModal').modal('show'); // document.getElementById('response').innerHTML='<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times; } }, error: function(data){ alert(data); // document.getElementById('response').innerHTML="<p style='color:red;font-size:16px;font-weight:bold;font-family:arial'>Failed to fetch your details. Please try again later } }); }else{ alert("No action can be taken without specify the reason for cancellation"); } }else{ alert('No data selected'); } }); function setModalBox(title,content,footer) { document.getElementById('modal-bodyku').innerHTML=content; document.getElementById('myModalLabel').innerHTML=title; document.getElementById('modal-footerq').innerHTML=footer; $('#myModal').attr('class', 'modal fade bs-example-modal-lg') .attr('aria-labelledby','myLargeModalLabel'); $('.modal-dialog').attr('class','modal-dialog modal-lg'); } JS; $this->registerJs($script); ?>
php
27
0.463764
223
35.800995
201
starcoderdata
public static void main(String[] args) { Scanner scan = new Scanner(System.in); int entradaUsuario = -1; do { String[] opciones = { "Tabla del 3", "Tabla del 4", "Tabla del 5" }; /** * Mostrando el menu de opciones. */ System.out.println("TABLAS DE MULTIPLICAR"); System.out.println("*********************************"); for(int i = 0; i < opciones.length; i++) { System.out.println((i + 1) + ".- " + opciones[i]); } // Opcion de salir System.out.println("0.- Salir"); // Leemos la entrada del usuario try { System.out.print("\nIntroduce opcion: "); entradaUsuario = Integer.parseInt(scan.nextLine()); } catch (Exception ex) { System.out.println("*** Operacion no valida. ***"); } // Si la entrada del usuario es 0 nos salimos del bucle y // el programa termina if(entradaUsuario == 0) { break; } System.out.println(""); switch(entradaUsuario) { case 1: System.out.println("Tabla del 3"); for(int i = 1; i <= 10; i++) { System.out.printf("%d * %d = %d\n", i, 3, (i * 3)); } break; case 2: System.out.println("Tabla del 4"); for(int i = 1; i <= 10; i++) { System.out.printf("%d * %d = %d\n", i, 4, (i * 4)); } break; case 3: System.out.println("Tabla del 5"); for(int i = 1; i <= 10; i++) { System.out.printf("%d * %d = %d\n", i, 5, (i * 5)); } break; default: System.out.println("Opcion no valida."); break; } System.out.println(""); }while(true); }
java
15
0.35347
80
33.850746
67
inline
def resolve(): N,k = map(int,input().split()) K = k-1 H = list(int(input()) for _ in range(N)) H.sort() minh = 10**10 for i in range(K,N): minh = min(minh,abs(H[i-K]-H[i])) print(minh) resolve()
python
14
0.502165
44
22.1
10
codenet
import CS from 'ember-chan'; import Ember from 'ember'; import MockSocket from 'mock-socket'; import { task } from 'ember-concurrency'; const { guid, RSVP, run, A } = Ember; const { Websocket } = MockSocket; export default CS.Adapter.extend({ socket: task(function*() { const socket = new Websocket('ws://asdf:6666'); const connectPromise = new RSVP.Promise(function(resolve) { socket.onopen(() => { resolve(socket); }) }); return yield connectPromise; }).drop(), connect: task(function* (channel, roomName) { const socket = yield this.get('socket').perform(); const id = guid(channel); socket.send('join', {id, roomName}); const joinPromise = new RSVP.Promise(function(resolve) { socket.onmessage(function(msg) { if (id === msg.id && roomName == msg.roomName) { resolve(); } }) }) yield joinPromise; return this; }).drop(), mergeOrigin() {} });
javascript
28
0.607032
63
23.2
40
starcoderdata
package com.cjoop.ad.rest; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; /** * 行政区划数据接口 * @author 陈均 * */ public interface ADInfoRepository extends JpaRepository<ADInfo, String>{ /** * 根据父级行政区划获取子级行政区划数据集合 * @param id 父级ID * @return 子级数据集合 */ List findByPidOrderById(String id); }
java
7
0.721264
72
15.571429
21
starcoderdata
/*================= *\ | ID : aman__guta__ | | LANG: C++ | \*==================*/ #include <bits/stdc++.h> using namespace std; #define ll long long int #define ld long double #define pb push_back #define mk make_pair #define fs first #define sc second #define mod 1000000007 #define sp <<" "<< #define JOKER ios_base::sync_with_stdio (false) ; cin.tie(0) ; cout.tie(0) ; int spf[10000001]; long long int fac[200005]; void sieve(int n) { spf[1]=1; for(int i=2;i<=n;i++) spf[i]=i; for(int i=4;i<=n;i+=2) spf[i]=2; for(int i=3;i*i<=n;i++) { if(spf[i]==i) { for(int j=i*i;j<=n;j+=i) { if(spf[j]==j) spf[j]=i; } } } } long long int power(long long int x, long long int y, long long int p) { long long int res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res*x) % p; y = y>>1; x = (x*x) % p; } return res; } long long int modInverse(long long int n, long long int p) { return power(n, p-2, p); } long long int nCrModPFermat(long long int n, long long int r, long long int p) { if (r==0) return 1; return (fac[n]* modInverse(fac[r], p) % p * modInverse(fac[n-r], p) % p) % p; } int lps(string s) { int n=s.size(); int lps[n]; lps[0]=0; int i=1; int j=0; while(i<n) { if(s[i]==s[j]) { j++; lps[i]=j; i++; } else { if(j) { j=lps[j-1]; } else { lps[i]=0; i++; } } } return min(n/2,lps[n-1]); } main() { JOKER int n,x,y; cin>>n>>x>>y; int a[n]={}; for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { int ans=1e9; ans=min({abs(i-j),abs(i-x)+1+abs(y-j),abs(i-y)+1+abs(j-x)}); a[ans]++; } } for(int i=1; i<n; i++) { cout<<a[i]/2<<endl; } cerr<<"Time elapsed : "<<clock()*1000.0/CLOCKS_PER_SEC<<"ms"<<'\n'; return 0; }
c++
17
0.408656
79
18.774775
111
codenet
import React, {Component} from 'react'; import '../newCss.css'; import News from './Layout/News'; import axios from 'axios'; import Header from './Header'; class Test extends Component { sendPost = event => { const headers = { 'Content-Type': 'application/json', } const data = { "comment": "Test react", "total_score": 4, "food_rate": 4, "security_rate": 4, "location_rate": 4, "facility_rate": 4, "internet_rate": 4 } let HOST = 'http://127.0.0.1:8000' axios.get(`${HOST}/university/get-university-rates/1/`, data, {headers:headers}).then( res => { console.log(res); } ) } render() { return( <div className="Home"> <div className="Test"> <button onClick={this.sendPost}>send post ); } } export default Test;
javascript
14
0.467422
94
23.651163
43
starcoderdata
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef Window_DEFINED #define Window_DEFINED #include "SkTypes.h" #include "SkRect.h" class SkCanvas; namespace sk_app { class WindowContext; class Window { public: static Window* CreateNativeWindow(void* platformData); virtual ~Window() {}; virtual void setTitle(const char*) = 0; virtual void show() = 0; virtual void inval() = 0; virtual bool scaleContentToFit() const { return false; } virtual bool supportsContentRect() const { return false; } virtual SkRect getContentRect() { return SkRect::MakeEmpty(); } enum BackEndType { kNativeGL_BackendType, kVulkan_BackendType }; virtual bool attach(BackEndType attachType, int msaaSampleCount) = 0; void detach(); // input handling enum Key { kNONE_Key, //corresponds to android's UNKNOWN kLeftSoftKey_Key, kRightSoftKey_Key, kHome_Key, //!< the home key - added to match android kBack_Key, //!< (CLR) kSend_Key, //!< the green (talk) key kEnd_Key, //!< the red key k0_Key, k1_Key, k2_Key, k3_Key, k4_Key, k5_Key, k6_Key, k7_Key, k8_Key, k9_Key, kStar_Key, //!< the * key kHash_Key, //!< the # key kUp_Key, kDown_Key, kLeft_Key, kRight_Key, kOK_Key, //!< the center key kVolUp_Key, //!< volume up - match android kVolDown_Key, //!< volume down - same kPower_Key, //!< power button - same kCamera_Key, //!< camera - same kLast_Key = kCamera_Key }; static const int kKeyCount = kLast_Key + 1; enum ModifierKeys { kShift_ModifierKey = 1 << 0, kControl_ModifierKey = 1 << 1, kOption_ModifierKey = 1 << 2, // same as ALT kCommand_ModifierKey = 1 << 3, kFirstPress_ModifierKey = 1 << 4, }; enum InputState { kDown_InputState, kUp_InputState, kMove_InputState // only valid for mouse }; // return value of 'true' means 'I have handled this event' typedef bool(*OnCharFunc)(SkUnichar c, uint32_t modifiers, void* userData); typedef bool(*OnKeyFunc)(Key key, InputState state, uint32_t modifiers, void* userData); typedef bool(*OnMouseFunc)(int x, int y, InputState state, uint32_t modifiers, void* userData); typedef void(*OnPaintFunc)(SkCanvas*, void* userData); void registerCharFunc(OnCharFunc func, void* userData) { fCharFunc = func; fCharUserData = userData; } void registerKeyFunc(OnKeyFunc func, void* userData) { fKeyFunc = func; fKeyUserData = userData; } void registerMouseFunc(OnMouseFunc func, void* userData) { fMouseFunc = func; fMouseUserData = userData; } void registerPaintFunc(OnPaintFunc func, void* userData) { fPaintFunc = func; fPaintUserData = userData; } bool onChar(SkUnichar c, uint32_t modifiers); bool onKey(Key key, InputState state, uint32_t modifiers); bool onMouse(int x, int y, InputState state, uint32_t modifiers); void onPaint(); void onResize(uint32_t width, uint32_t height); uint32_t width() { return fWidth; } uint32_t height() { return fHeight; } protected: Window(); uint32_t fWidth; uint32_t fHeight; OnCharFunc fCharFunc; void* fCharUserData; OnKeyFunc fKeyFunc; void* fKeyUserData; OnMouseFunc fMouseFunc; void* fMouseUserData; OnPaintFunc fPaintFunc; void* fPaintUserData; WindowContext* fWindowContext; }; } // namespace sk_app #endif
c
12
0.603138
99
24.578947
152
starcoderdata
public void findPatterns() { if (parameters == null || gi == null || datasetTree == null) { return; } initialize(); datasetTree.buildTree(parameters.crossStrand); GeneralizedSuffixTree datasetSuffixTree = datasetTree.getSuffixTree(); datasetSuffixTree.computeCount(); totalCharsInData = datasetSuffixTree.getRoot().getCountMultipleInstancesPerGenome(); InstanceNode dataTreeRoot = datasetSuffixTree.getRoot(); //the instance of an empty string is the root of the data tree Instance emptyInstance = new Instance(dataTreeRoot); countNodesInDataTree++; patternTreeRoot.addInstance(emptyInstance); if (patternTreeRoot.getType() == TreeType.VIRTUAL) { spellPatternsVirtually(patternTreeRoot, dataTreeRoot, -1, null, new Gene[0], 0); } else { spellPatterns(patternTreeRoot, new Gene[0], 0); } removeRedundantPatterns(); }
java
10
0.640873
92
36.37037
27
inline
[Fact] //[Variation(Desc = "v10 - set1 added to set2 with set1 containing an invalid schema")] public void v10() { XmlSchemaSet schemaSet1 = new XmlSchemaSet(); XmlSchemaSet schemaSet2 = new XmlSchemaSet(); XmlSchema schema1 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdAuthor, FileMode.Open, FileAccess.Read)), null); XmlSchema schema2 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdNoNs, FileMode.Open, FileAccess.Read)), null); schemaSet1.Add(schema1); schemaSet1.Add(schema2); // added two schemas //schemaSet1.Compile (); XmlSchemaElement elem = new XmlSchemaElement(); schema1.Items.Add(elem); // make the first schema dirty //the following throws an exception try { schemaSet2.Add(schemaSet1); // shound not reach here } catch (XmlSchemaException) { Assert.Equal(schemaSet2.Count, 0); // no schema should be added Assert.Equal(schemaSet1.Count, 2); // no schema should be added Assert.Equal(schemaSet2.IsCompiled, false); // no schema should be added Assert.Equal(schemaSet1.IsCompiled, false); // no schema should be added return; } Assert.Equal(schemaSet2.Count, 0); // no schema should be added Assert.True(false); }
c#
18
0.583333
140
42.571429
35
inline
with open('in', 'r') as f: lines = [i.strip() for i in f] rules_lines, lines = lines[:lines.index('')], lines[lines.index('') + 1:] my_ticket_lines, nearby_tickets_lines = lines[:lines.index('')], lines[lines.index('') + 2:] all_valid_numbers = set() rules = {} rule_names = [] for rule_line in rules_lines: rule_name, rules_str = rule_line.split(':') rule_names.append(rule_name) valid_numbers = set() for rule in rules_str.split('or'): r = rule.strip().split('-') a, b = int(r[0].strip()), int(r[1].strip()) for i in range(a, b + 1): valid_numbers.add(i) all_valid_numbers.add(i) rules[rule_name] = valid_numbers tickets = [] for ticket_line in nearby_tickets_lines: tickets.append(list(map(int, ticket_line.split(',')))) my_ticket = list(map(int, my_ticket_lines[1].split(','))) tickets.append(my_ticket) possible_positions = [set(rule_names) for _ in range(len(my_ticket))] for ticket in tickets: for rule_i in range(len(rule_names)): for num_i in range(len(rule_names)): rule_name = rule_names[rule_i] current_number = ticket[num_i] if current_number not in all_valid_numbers: continue if current_number not in rules[rule_name]: if rule_name in possible_positions[num_i]: possible_positions[num_i].remove(rule_name) while sum([len(i) for i in possible_positions]) != len(rule_names): for i in range(len(possible_positions)): if len(possible_positions[i]) == 1: for j in range(len(possible_positions)): if i == j: continue # get element without removal rule_name = None for el in possible_positions[i]: rule_name = el break if rule_name in possible_positions[j]: possible_positions[j].remove(rule_name) result = 1 for i in range(len(possible_positions)): rule_name = possible_positions[i].pop() if not rule_name.startswith('departure'): continue result *= my_ticket[i] print(result)
python
15
0.574182
96
30.871429
70
starcoderdata
public void syncLikes( String uploadLikedUrl, boolean liked) throws MalformedURLException { ////////////////////////////////////////////////////////////////////////////// // [DESTINATION] UPLOADING Likes!! ////////////////////////////////////////////////////////////////////////////// JamNetworkParam likesParamHeader = new JamNetworkParam(); likesParamHeader.add("Content-Type", "application/json"); JSONObject likesParamBody = new JSONObject(); likesParamBody.put("Liked", liked); final InputStream likedInputStream = new ByteArrayInputStream(likesParamBody.toString().getBytes()); JamNetworkManager.getInstance().PatchRequest(uploadLikedUrl, likesParamHeader, likedInputStream); }
java
10
0.561039
108
54.071429
14
inline
/** * Openbiz App Backend Role file * * APPBUILDER_ALLOW_OVERRIDE = YES // if you have manual modified this file please change APPBUILDER_ALLOW_OVERRIDE value to NO * @type {exports|object} */ 'use strict'; module.exports = {{ROLE_DATA}};
javascript
6
0.709016
128
29.625
8
starcoderdata
// +build !e2 package main import ( "fmt" "log" "net" "github.com/CodesShareA/sctp" "github.com/pion/logging" ) func main() { conn, err := net.Dial("udp", "127.0.0.1:5678") if err != nil { log.Panic(err) } defer func() { if closeErr := conn.Close(); closeErr != nil { panic(err) } }() fmt.Println("dialed udp ponger") config := sctp.Config{ NetConn: conn, LoggerFactory: logging.NewDefaultLoggerFactory(), } a, err := sctp.Client(config) if err != nil { log.Panic(err) } defer func() { if closeErr := a.Close(); closeErr != nil { panic(err) } }() fmt.Println("created a client") stream, err := a.OpenStream(0, sctp.PayloadTypeORanE2CP) if err != nil { log.Panic(err) } defer func() { if closeErr := stream.Close(); closeErr != nil { panic(err) } }() fmt.Println("opened a stream") // set unordered = true and 10ms treshold for dropping packets stream.SetReliabilityParams(true, sctp.ReliabilityTypeTimed, 10) go func() { var pingSeqNum int for { pingMsg := fmt.Sprintf("ping %d", pingSeqNum) _, err = stream.Write([]byte(pingMsg)) if err != nil { log.Panic(err) } fmt.Println("sent:", pingMsg) pingSeqNum++ } }() for { buff := make([]byte, 1024) _, err = stream.Read(buff) if err != nil { log.Panic(err) } pongMsg := string(buff) fmt.Println("received:", pongMsg) } }
go
15
0.611671
65
17.025974
77
starcoderdata
@Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; // cast g to Graphics2D // draw 2D ellipse filled with a blue-yellow gradient g2d.setPaint(new GradientPaint(5, 30, Color.BLUE, 35, 100, Color.YELLOW, true)); g2d.fill(new Ellipse2D.Double(5, 30, 65, 100)); // draw 2D rectangle in red g2d.setPaint(Color.RED); g2d.setStroke(new BasicStroke(10.0f)); g2d.draw(new Rectangle2D.Double(80, 30, 65, 100)); // draw 2D rounded rectangle with a buffered background BufferedImage buffImage = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); // obtain Graphics2D from buffImage and draw on it Graphics2D gg = buffImage.createGraphics(); gg.setColor(Color.YELLOW); gg.fillRect(0, 0, 10, 10); gg.setColor(Color.BLACK); gg.drawRect(1, 1, 6, 6); gg.setColor(Color.BLUE); gg.fillRect(1, 1, 3, 3); gg.setColor(Color.RED); gg.fillRect(4, 4, 3, 3); // paint buffImage onto the JFrame g2d.setPaint(new TexturePaint(buffImage, new Rectangle(10, 10))); g2d.fill( new RoundRectangle2D.Double(155, 30, 75, 100, 50, 50)); // draw 2D pie-shaped arc in white g2d.setPaint(Color.WHITE); g2d.setStroke(new BasicStroke(6.0f)); g2d.draw( new Arc2D.Double(240, 30, 75, 100, 0, 270, Arc2D.PIE)); // draw 2D lines in green and yellow g2d.setPaint(Color.GREEN); g2d.draw(new Line2D.Double(395, 30, 320, 150)); // draw 2D line using stroke float[] dashes = {10}; // specify dash pattern g2d.setPaint(Color.YELLOW); g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, dashes, 0)); g2d.draw(new Line2D.Double(320, 30, 395, 150)); }
java
10
0.591485
65
34.574074
54
inline
def _extract_values_from_hepdata_dependent_variable(var: Mapping[str, Any]) -> T_Extraction_Function: """Extract values from a HEPdata dependent variable. As the simplest useful HEPdata extraction function possible, it retrieves y values, symmetric statical errors. Symmetric systematic errors are stored in the metadata. Args: var: HEPdata dependent variable. Returns: y values, errors squared, metadata containing the systematic errors. """ values = var["values"] hist_values = [val["value"] for val in values] # For now, only support symmetric errors. hist_stat_errors = [] hist_sys_errors = [] for val in values: for error in val["errors"]: if error["label"] == "stat": hist_stat_errors.append(error["symerror"]) elif "sys" in error["label"]: hist_sys_errors.append(error["symerror"]) # Validate the collected values. if len(hist_stat_errors) == 0: raise ValueError( f"Could not retrieve statistical errors for dependent var {var}.\n" f" hist_stat_errors: {hist_stat_errors}" ) if len(hist_values) != len(hist_stat_errors): raise ValueError( f"Could not retrieve the same number of values and statistical errors for dependent var {var}.\n" f" hist_values: {hist_values}\n" f" hist_stat_errors: {hist_stat_errors}" ) if len(hist_sys_errors) != 0 and len(hist_sys_errors) != len(hist_stat_errors): raise ValueError( f"Could not extract the same number of statistical and systematic errors for dependent var {var}.\n" f" hist_stat_errors: {hist_stat_errors}\n" f" hist_sys_errors: {hist_sys_errors}" ) # Create the histogram metadata: Dict[str, Any] = {"sys_error": np.array(hist_sys_errors)} return hist_values, hist_stat_errors, metadata
python
15
0.631851
120
41.065217
46
inline
<?php // 本类由系统自动生成,仅供测试用途 namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function index(){ $this->assign('title','杭州电子科技大学'); $this->assign('index_active','active'); $news = D('News'); $news_list = $news->getToptenNewsList(); foreach ($news_list as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $notice = $news->getTopNotice(); $studys = D('Study'); $study_list = $studys->getAllStudyList(); $users = D('UserInfo'); $users_list = $users->getAllUsersList(); $link = D('Links'); $links = $link->getAllLinksList(); $this->assign('news_list', $news_list); $this->assign('study_list', $study_list); $this->assign('notice', $notice); $this->assign('users_list', $users_list); $this->assign('links', $links); $this->display(); } /** * 实验室介绍 */ public function info(){ $this->assign('title','实验室介绍'); $this->assign('info_active','active'); $news = D('News'); $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $this->assign('hot_news', $hot_news); $user_info = D('UserInfo'); $hot_students = $user_info->getHotStudentList(); $this->assign('hot_students', $hot_students); $labinfo = D('Labinfo'); $info = $labinfo->getInfo(); $this->assign('lab_info',$info[0]['info']); $this->display(); } /** * 科研团队 */ public function member(){ $this->assign('title','科研团队'); $member = D('UserInfo'); $teachers_list = $member->getAllTeachersList(); $students_list = $member->getAllUsersList(); $news = D('News'); $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $user_info = D('UserInfo'); $hot_students = $user_info->getHotStudentList(); $this->assign('hot_students', $hot_students); $this->assign('hot_news', $hot_news); $this->assign('member_active','active'); $this->assign('teachers_list',$teachers_list); $this->assign('students_list',$students_list); $this->display(); } /** * 新闻中心 */ public function news(){ $this->assign('title','新闻中心'); $news = D('News'); $news_list = $news->getAllNewsList(); foreach ($news_list as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $user_info = D('UserInfo'); $hot_students = $user_info->getHotStudentList(); $this->assign('hot_students', $hot_students); $this->assign('news_list', $news_list); $this->assign('hot_news', $hot_news); $this->assign('news_active','active'); $this->display(); } /** * 论文 */ public function paper(){ $this->assign('title','发表论文'); $news = D('News'); $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $result = D('Result'); $count = $result->where('type = 0')->count();// 查询满足要求的总记录数 $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25) $show = $Page->show();// 分页显示输出 // 进行分页数据查询 注意limit方法的参数要使用Page类的属性 $list = $result->order('id')->where('type = 0')->limit($Page->firstRow.','.$Page->listRows)->select(); $this->assign('result_list',$list);// 赋值数据集 $this->assign('page',$show);// 赋值分页输出 $this->assign('hot_news', $hot_news); $this->assign('paper_active','active'); $this->display(); } /** * 科研项目 */ public function projects(){ $this->assign('title','科研项目'); $projects = D('projects'); $news = D('News'); $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $user_info = D('UserInfo'); $hot_students = $user_info->getHotStudentList(); $count = $projects->count();// 查询满足要求的总记录数 $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25) $show = $Page->show();// 分页显示输出 // 进行分页数据查询 注意limit方法的参数要使用Page类的属性 $list = $projects->order('id')->limit($Page->firstRow.','.$Page->listRows)->select(); $this->assign('projects_list',$list);// 赋值数据集 $this->assign('page',$show);// 赋值分页输出 $this->assign('hot_students', $hot_students); $this->assign('hot_news', $hot_news); $this->assign('projects_active','active'); $this->display(); } /** * 成果展示 */ public function result(){ $this->assign('title','成果展示'); $result = D('Result'); $this->assign('result_active','active'); $count = $result->where('type = 1')->count();// 查询满足要求的总记录数 $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25) $show = $Page->show();// 分页显示输出 // 进行分页数据查询 注意limit方法的参数要使用Page类的属性 $list = $result->order('id')->where('type = 1')->limit($Page->firstRow.','.$Page->listRows)->select(); $this->assign('result_list',$list);// 赋值数据集 $this->assign('page',$show);// 赋值分页输出 $news = D('News'); $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $user_info = D('UserInfo'); $hot_students = $user_info->getHotStudentList(); $this->assign('hot_students', $hot_students); $this->assign('hot_news', $hot_news); $this->display(); } /** * 常用链接 */ public function link(){ $this->assign('title','常用链接'); $link = D('Links'); $news = D('News'); $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $user_info = D('UserInfo'); $hot_students = $user_info->getHotStudentList(); $this->assign('hot_students', $hot_students); $this->assign('hot_news', $hot_news); $links = $link->getAllLinksList(); $this->assign('links', $links); $this->assign('link_active','active'); $this->display(); } /** * 通知公告 */ public function notice(){ $this->assign('title','通知公告'); $this->assign('notice_active','active'); $news = D('News'); $count = $news->where('type = 1')->count();// 查询满足要求的总记录数 $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25) $show = $Page->show();// 分页显示输出 // 进行分页数据查询 注意limit方法的参数要使用Page类的属性 $list = $news->order('nid')->where('type = 1')->limit($Page->firstRow.','.$Page->listRows)->select(); $this->assign('result_list',$list);// 赋值数据集 $this->assign('page',$show);// 赋值分页输出 foreach ($list as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $hot_news = $news->getHotNewsList(); foreach ($hot_news as &$value) { $value['time'] = date('Y-m-d' , $value['time']); } $user_info = D('UserInfo'); $hot_students = $user_info->getHotStudentList(); $this->assign('hot_students', $hot_students); $this->assign('notice_list', $list); $this->assign('hot_news', $hot_news); $this->display(); } }
php
15
0.50683
110
33.102564
234
starcoderdata
@Override public void onTouch(ControlTouchEvent event) { super.onTouch(event); int action = event.getAction(); if (action == Control.TapActions.DOUBLE_TAP){ // send question to the server on a double tap if (bitmap == null) return; // did not take a picture ByteArrayOutputStream bao = new ByteArrayOutputStream(); //Constants.getCameraData.compress(Bitmap.CompressFormat.JPEG, 100, bao); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao); byte [] ba = bao.toByteArray(); String fileName = saveFilePrefix + String.format("%04d", saveFileIndex) + ".jpg"; MainActivity.object.runUploading(bitmap, fileName); } }
java
12
0.626846
93
40.444444
18
inline
package com.power.xuexi.entity; import java.math.BigDecimal; import java.util.Date; public class XxTotalList { private String uname; // 学习人姓名 private String xxzt; // 学习主题 private String content; // 学习内容 private Date fbsj; // 学习发布时间 private Date wcsj; // 学习完成时间 private BigDecimal fz;// 学习对应的分值 public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getXxzt() { return xxzt; } public void setXxzt(String xxzt) { this.xxzt = xxzt; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getFbsj() { return fbsj; } public void setFbsj(Date fbsj) { this.fbsj = fbsj; } public Date getWcsj() { return wcsj; } public void setWcsj(Date wcsj) { this.wcsj = wcsj; } public BigDecimal getFz() { return fz; } public void setFz(BigDecimal fz) { this.fz = fz; } }
java
8
0.647295
41
17.96
50
starcoderdata
int starneig_eigvec_gen_generalised_eigenvalues( int m, double *s, size_t lds, double *t, size_t ldt, int *select, double *alphar, double *alphai, double *beta) { // Pointers to mini-blocks double *sjj; double *tjj; // Variables needed by DLAG2 double scale1; double scale2; double wr1; double wr2; double wi; // Column index int j=0; // Initialize number of selected eigenvalues/vectors int k=0; // Loop over columns of S, T while (j<m) { if (j<m-1) { // Check for 2-by-2 block if (_s(j+1,j)!=0) { // Current block is 2-by-2 if ((select[j]==1) || (select[j+1]==1)) { // Find eigenvalues with DLAG2 sjj=&_s(j,j); tjj=&_t(j,j); starneig_eigvec_gen_dlag2(sjj, lds, tjj, ldt, smin, &scale1, &scale2, &wr1, &wr2, &wi); // Copy values into output arrays alphar[k+0]=wr1; alphai[k+0]= wi; beta[k+0]=scale1; alphar[k+1]=wr2; alphai[k+1]=-wi; beta[k+1]=scale2; // Increase eigenvalue count: +2 k=k+2; } // Always advance to the next mini-block: +2 j=j+2; } else { // Current block is 1-by-1 if (select[j]==1) { // Copy values into output arrays alphar[k]=_s(j,j); alphai[k]=0; beta[k]=_t(j,j); // Increase eigenvalue count: +1 k++; } // Always advance to the next mini-block: +1 j++; } } else { // Last column: j=m-1 // Current block is 1-by-1 if (select[j]==1) { // Copy values into output arrays alphar[k]=_s(j,j); alphai[k]=0; beta[k]=_t(j,j); // Increase eigenvalue count : +1 k++; } // Always advance to the next mini-block +1 j++; } } // Return the number of selected eigenvalues return k; }
c
16
0.538717
69
25.602941
68
inline
/** * @file unit_test_fnd_tuple_forward_as_tuple.cpp * * @brief forward_as_tuple のテスト * * @author myoukaku */ #include #include #include #include #include #include "constexpr_test.hpp" namespace bksge_tuple_test { namespace forward_as_tuple_test { #define VERIFY(...) if (!(__VA_ARGS__)) { return false; } inline BKSGE_CXX14_CONSTEXPR bool test() { using std::get; { auto t = bksge::forward_as_tuple(); static_assert(bksge::is_same<decltype(t), bksge::tuple ""); } { auto t = bksge::forward_as_tuple(0.5f); static_assert(bksge::is_same<decltype(t), bksge::tuple ""); VERIFY(get == 0.5f); } { auto t = bksge::forward_as_tuple(1, 'a', 2.5); static_assert(bksge::is_same<decltype(t), bksge::tuple<int&&, char&&, double&&>>::value, ""); VERIFY(get 'a', 2.5)) == 1); VERIFY(get 'a', 2.5)) == 'a'); VERIFY(get 'a', 2.5)) == 2.5); } { int a = 3; const float b = 4.5f; auto t = bksge::forward_as_tuple(a, 5, b); static_assert(bksge::is_same<decltype(t), bksge::tuple<int&, int&&, const float&>>::value, ""); VERIFY(get == a); VERIFY(get == b); } return true; } #undef VERIFY GTEST_TEST(TupleTest, ForwardAsTupleTest) { BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(test()); } } // namespace forward_as_tuple_test } // namespace bksge_tuple_test
c++
19
0.615339
97
24.296875
64
starcoderdata
func TestRead(t *testing.T) { type args struct { reader io.Reader } tests := []struct { name string args args want Fasta wantErr bool }{ { name: "Simple FASTA", args: args{reader: strings.NewReader(`>BLABLA Something ACDEFGH >BLA2 EEEY > WE ARE CPM `)}, want: Fasta{ []Prot{ {id: "BLABLA", desc: "Something", seq: "ACDEFGH"}, {id: "BLA2", desc: "", seq: "EEEY"}, {id: "DUMMY_ID_3", desc: "", seq: "WEARECPM"}, }, }, wantErr: false, }, { name: "No newline end FASTA", args: args{reader: strings.NewReader(`>TEST2 No newline at end AHAH`)}, want: Fasta{ []Prot{ {id: "TEST2", desc: "No newline at end", seq: "AHAH"}, }, }, wantErr: false, }, { name: "Additional spacing FASTA", args: args{reader: strings.NewReader(`>TEST3 After some spaces and tab HAHA `)}, want: Fasta{ []Prot{ {id: "TEST3", desc: "After some spaces and tab", seq: "HAHA"}, }, }, wantErr: false, }, { name: "Additional spacing FASTA2", args: args{reader: strings.NewReader(`>TEST4 Spaces in/around seq HADIHI NAH `)}, want: Fasta{ []Prot{ {id: "TEST4", desc: "Spaces in/around seq", seq: "HADIHINAH"}, }, }, wantErr: false, }, { name: "PEFF header", args: args{reader: strings.NewReader(` # This ain't no PEFF file! >TEST5 Blabla HAHAHA `)}, want: Fasta{ []Prot{ {id: "TEST5", desc: "Blabla", seq: "HAHAHA"}, }, }, wantErr: false, }, // FIXME: Add test that generates error } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := Read(tt.args.reader) if (err != nil) != tt.wantErr { t.Errorf("Read() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("Read() = %v, want %v", got, tt.want) } }) } }
go
21
0.558164
76
18.329897
97
inline
<?php namespace app\models; use Yii; /** * This is the model class for table "{{%p_count}}". * * @property int $id * @property int $p_id 产品id * @property int $user_id 用户id * @property int $user_type 用户类型 * @property int $time 查看时间 * @property int $channel_id 来源渠道 * @property int $front 前端类型 0=pc 1=wap 2=ios 3=android * @property string $ip ip地址 * @property string $city_id 城市id * @property string $info_id 通过资讯详情页跳转过来的id * @property string $product_source * @property string $guide_id 新手指南ID 从指南详情条跳转过来啊 * @property string $card_id * @property string $subject_id 专题ID 从专题条跳转过来 * @property int $app_id */ class PCount extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%p_count}}'; } /** * @return \yii\db\Connection the database connection used by this AR class. */ public static function getDb() { return Yii::$app->get('db3'); } /** * @inheritdoc */ public function rules() { return [ [['p_id', 'user_id', 'user_type', 'time', 'channel_id', 'front', 'ip', 'city_id', 'info_id', 'product_source', 'app_id'], 'required'], [['p_id', 'user_id', 'time', 'channel_id', 'city_id', 'info_id', 'product_source', 'guide_id', 'card_id', 'subject_id'], 'integer'], [['user_type', 'front'], 'string', 'max' => 1], [['ip'], 'string', 'max' => 15], [['app_id'], 'string', 'max' => 3], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'p_id' => 'P ID', 'user_id' => 'User ID', 'user_type' => 'User Type', 'time' => 'Time', 'channel_id' => 'Channel ID', 'front' => 'Front', 'ip' => 'Ip', 'city_id' => 'City ID', 'info_id' => 'Info ID', 'product_source' => 'Product Source', 'guide_id' => 'Guide ID', 'card_id' => 'Card ID', 'subject_id' => 'Subject ID', 'app_id' => 'App ID', ]; } }
php
13
0.503865
146
25.817073
82
starcoderdata
import reducer from '../../src/reducers/networkRequestReducer'; import * as types from '../../src/actions/types'; describe('Test suite for network request state', () => { it('should return the initial state', () => { expect(reducer(false, {})).toEqual(false); }); it('should check if an ajax request was made', () => { expect(reducer(false, { type: types.IS_LOADING, isLoading: true })).toEqual(true); }); });
javascript
21
0.617117
63
28.6
15
starcoderdata
#ifndef FLECS_COMPONENTS_PHYSICS_H #define FLECS_COMPONENTS_PHYSICS_H #include #ifdef __cplusplus //extern "C" { #endif ECS_STRUCT(EcsVelocity2, { float x; float y; }); ECS_STRUCT(EcsVelocity3, { float x; float y; float z; }); ECS_STRUCT(EcsAngularSpeed, { float value; }); ECS_STRUCT(EcsAngularVelocity, { float x; float y; float z; }); ECS_STRUCT(EcsBounciness, { float value; }); ECS_STRUCT(EcsFriction, { float value; }); typedef struct FlecsComponentsPhysics { ECS_DECLARE_ENTITY(EcsCollider); ECS_DECLARE_ENTITY(EcsRigidBody); ECS_DECLARE_COMPONENT(EcsVelocity2); ECS_DECLARE_COMPONENT(EcsVelocity3); ECS_DECLARE_COMPONENT(EcsAngularSpeed); ECS_DECLARE_COMPONENT(EcsAngularVelocity); ECS_DECLARE_COMPONENT(EcsBounciness); ECS_DECLARE_COMPONENT(EcsFriction); } FlecsComponentsPhysics; #ifdef __cplusplus extern "C" { #endif void FlecsComponentsPhysicsImport( ecs_world_t *world); #ifdef __cplusplus } #endif #define FlecsComponentsPhysicsImportHandles(handles)\ ECS_IMPORT_ENTITY(handles, EcsCollider);\ ECS_IMPORT_ENTITY(handles, EcsRigidBody);\ ECS_IMPORT_COMPONENT(handles, EcsVelocity2);\ ECS_IMPORT_COMPONENT(handles, EcsVelocity3);\ ECS_IMPORT_COMPONENT(handles, EcsAngularSpeed);\ ECS_IMPORT_COMPONENT(handles, EcsAngularVelocity);\ ECS_IMPORT_COMPONENT(handles, EcsBounciness);\ ECS_IMPORT_COMPONENT(handles, EcsFriction); #ifdef __cplusplus //} #endif #ifdef __cplusplus namespace flecs { namespace components { class physics : FlecsComponentsPhysics { public: using Velocity2 = EcsVelocity2; using Velocity3 = EcsVelocity3; using AngularSpeed = EcsAngularSpeed; using AngularVelocity = EcsAngularVelocity; using Bounciness = EcsBounciness; using Friction = EcsFriction; physics(flecs::world& ecs) { FlecsComponentsPhysicsImport(ecs.c_ptr()); ecs.module ecs.pod_component ecs.pod_component ecs.pod_component ecs.pod_component ecs.pod_component ecs.pod_component } }; } } #endif #endif
c
19
0.713522
90
23.018349
109
starcoderdata
<?php namespace App\Http\Controllers\Uptek; use Illuminate\Http\Request; use App\Model\Uptek\AccumulatePoint as ThisModel; use Yajra\DataTables\DataTables; use Validator; use \stdClass; use Response; use App\Http\Controllers\Controller; use \Carbon\Carbon; use Illuminate\Validation\Rule; use DB; class AccumulatePointController extends Controller { protected $view = 'uptek.accumulate_points'; protected $route = 'AccumulatePoint'; public function edit() { $object = ThisModel::where('id',1)->first(); return view($this->view.'.edit', compact('object')); } public function update(Request $request) { $validate = Validator::make( $request->all(), [ 'value_to_point_rate' => 'required|integer', 'point_to_money_rate' => 'required|integer', ] ); $json = new stdClass(); if ($validate->fails()) { $json->success = false; $json->errors = $validate->errors(); $json->message = "Thao tác thất bại!"; return Response::json($json); } DB::beginTransaction(); try { $object = ThisModel::where('id',1)->first(); $object->value_to_point_rate = $request->value_to_point_rate; $object->point_to_money_rate = $request->point_to_money_rate; $request->allow_pay === 'true' ? $allow_pay = 1 : $allow_pay = 0; $request->accumulate_pay_point === 'true' ? $accumulate_pay_point = 1 : $accumulate_pay_point = 0; $object->allow_pay = $allow_pay; $object->accumulate_pay_point = $accumulate_pay_point; $object->save(); DB::commit(); $json->success = true; $json->message = "Thao tác thành công!"; return Response::json($json); } catch (Exception $e) { DB::rollBack(); throw new Exception($e->getMessage()); } } }
php
15
0.647059
101
25.362319
69
starcoderdata
@Test @SuppressWarnings("unchecked") public void testCreate() { FormOptions fo = new FormOptions().setShowQuickSearchField(true).setShowRemoveButton(true); MultiDomainEditLayout layout = new MultiDomainEditLayout(fo, Lists.newArrayList(Country.class, Region.class)); layout.addEntityModelOverride(Region.class, "CustomRegion"); layout.build(); // check that first domain class is selected by default assertEquals(2, layout.getDomainClasses().size()); assertEquals(Country.class, layout.getSelectedDomain()); assertTrue(layout.isDeleteAllowed(Country.class)); layout.selectDomain(Region.class); BaseSplitLayout<?, ?> splitLayout = layout.getSplitLayout(); assertNotNull(splitLayout); splitLayout.build(); // adding is possible assertNotNull(splitLayout.getAddButton()); assertTrue(splitLayout.getAddButton().isVisible()); // test reload splitLayout.reload(); }
java
10
0.681145
118
36.555556
27
inline
#include <bits/stdc++.h> using namespace std; #define loop for(int i = 0;i < prime.size();i++) vector<int> prime,q; bool D(int n){ loop{ if(n%prime[i] == 0)return 0; } return 1; } int main() { int ip = 6,n; while(ip <= 300000){ if(D(ip))prime.push_back(ip); ip += 2; if(D(ip))prime.push_back(ip); ip += 5; } while(cin >> n){ if(n == 1)break; else q.push_back(n); } for(int n = 0;n < q.size();n++){ bool flag = 1; cout << q[n] << ":"; loop{ if(q[n]%prime[i] == 0){ flag = 0; cout << " " << prime[i]; } } if(flag)cout << " " << q[n]; cout << endl; } return 0; }
c++
15
0.461538
48
16.918919
37
codenet
using System; namespace EverisHire.HireManagement.Application.Features.Categories.Commands { public class CreateCategoryDto { public Guid CategoryId { get; set; } public string Name { get; set; } } }
c#
8
0.688596
76
21.9
10
starcoderdata
using System; using System.Text; namespace TS_SE_Tool.Utils { class HexString { public string ConvertStringToHex(string strASCII, string separator = null) { StringBuilder sbHex = new StringBuilder(); foreach (char chr in strASCII) { sbHex.Append(String.Format("{0:X2}", Convert.ToInt32(chr))); sbHex.Append(separator ?? string.Empty); } return sbHex.ToString(); } public string ConvertHexToString(string HexValue, string separator = null) { HexValue = string.IsNullOrEmpty(separator) ? HexValue : HexValue.Replace(string.Empty, separator); StringBuilder sbStrValue = new StringBuilder(); while (HexValue.Length > 0) { sbStrValue.Append(Convert.ToChar(Convert.ToUInt32(HexValue.Substring(0, 2), 16)).ToString()); HexValue = HexValue.Substring(2); } return sbStrValue.ToString(); } } }
c#
24
0.575264
110
32.645161
31
starcoderdata
/* * This header is generated by classdump-dyld 1.0 * on Saturday, August 24, 2019 at 9:43:23 PM Mountain Standard Time * Operating System: Version 12.4 (Build 16M568) * Image Source: /System/Library/PrivateFrameworks/TextInput.framework/TextInput * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by */ @protocol TIKeyboardInputManager @required -(void)generateAutocorrectionsWithKeyboardState:(id)arg1 candidateRange:(NSRange)arg2 completionHandler:(/*^block*/id)arg3; -(void)generateRefinementsForCandidate:(id)arg1 keyboardState:(id)arg2 completionHandler:(/*^block*/id)arg3; -(void)adjustPhraseBoundaryInForwardDirection:(BOOL)arg1 keyboardState:(id)arg2 completionHandler:(/*^block*/id)arg3; -(void)syncToKeyboardState:(id)arg1 completionHandler:(/*^block*/id)arg2; -(void)textAccepted:(id)arg1; -(void)handleKeyboardInput:(id)arg1 keyboardState:(id)arg2 completionHandler:(/*^block*/id)arg3; -(void)generateCandidatesWithKeyboardState:(id)arg1 candidateRange:(NSRange)arg2 completionHandler:(/*^block*/id)arg3; -(void)generateAutocorrectionsWithKeyboardState:(id)arg1 candidateRange:(NSRange)arg2 requestToken:(id)arg3 completionHandler:(/*^block*/id)arg4; -(void)handleAcceptedCandidate:(id)arg1 keyboardState:(id)arg2 completionHandler:(/*^block*/id)arg3; -(void)generateReplacementsForString:(id)arg1 keyLayout:(id)arg2 continuation:(/*^block*/id)arg3; -(void)skipHitTestForTouchEvent:(id)arg1 keyboardState:(id)arg2; -(void)performHitTestForTouchEvent:(id)arg1 keyboardState:(id)arg2 continuation:(/*^block*/id)arg3; -(void)adjustPhraseBoundaryInForwardDirection:(BOOL)arg1 granularity:(int)arg2 keyboardState:(id)arg3 completionHandler:(/*^block*/id)arg4; -(void)lastAcceptedCandidateCorrected; -(void)setOriginalInput:(id)arg1; -(void)candidateRejected:(id)arg1; -(void)generateAutocorrectionsWithKeyboardState:(id)arg1 completionHandler:(/*^block*/id)arg2; -(void)writeTypologyLogWithCompletionHandler:(/*^block*/id)arg1; @end
c
5
0.799292
145
60.8125
32
starcoderdata
import requests from bs4 import BeautifulSoup class AktieScraper: def __init__(self, url): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") all_tables = soup.find_all("div", class_="box table-quotes") self.kurs_matrix = [] self.init(all_tables=all_tables) def init(self, all_tables): for table in all_tables: if "Daten im Zeitverlauf" in str(table): thead = table.find_all("th") keys = [] for i in range(len(thead)): keys.append(str(thead[i]).strip("<th class=\"\">").strip(" tbody = table.find_all("td") data = {} for i in range(len(tbody)): if i % len(thead) == 0: data = {} data[keys[i % len(thead)]] = str(tbody[i]).strip(" ".") if i % len(thead) == len(thead) - 1: self.kurs_matrix.append(data) def min_last_5(self): for entry in self.kurs_matrix: if entry["Datum"] == "5 Jahre": return entry["Tief"] def max_last_5(self): for entry in self.kurs_matrix: if entry["Datum"] == "5 Jahre": return entry["Hoc"] def max_today(self): for entry in self.kurs_matrix: if entry["Datum"] == "Heute": return entry["Hoc"] def min_today(self): for entry in self.kurs_matrix: if entry["Datum"] == "Heute": return entry["Tief"] def schluss_kurs(self): for entry in self.kurs_matrix: if entry["Datum"] == "Heute": return entry["Schlusskurs"]
python
23
0.493261
109
32.142857
56
starcoderdata
// // yas_audio_types.h // #pragma once #include #include #include #include #include #include namespace yas::audio { enum class pcm_format : uint32_t { other = 0, float32, float64, int16, fixed824, }; enum class render_type : uint32_t { normal = 0, input, notify, unknown, }; enum class direction { output = 0, input = 1, }; enum class continuation { abort, keep, }; using bus_result_t = std::optional using abl_uptr = std::unique_ptr<AudioBufferList, std::function<void(AudioBufferList *)>>; using abl_data_uptr = std::unique_ptr using channel_map_t = std::vector } // namespace yas::audio namespace yas { uint32_t to_uint32(audio::direction const &); std::string to_string(audio::pcm_format const &); std::type_info const &to_sample_type(audio::pcm_format const &); uint32_t to_bit_depth(audio::pcm_format const &); std::string to_string(audio::direction const &); std::string to_string(AudioUnitScope const scope); std::string to_string(audio::render_type const &); std::string to_string(OSStatus const err); } // namespace yas std::ostream &operator<<(std::ostream &, yas::audio::pcm_format const &); std::ostream &operator<<(std::ostream &, yas::audio::direction const &); std::ostream &operator<<(std::ostream &, yas::audio::render_type const &);
c
10
0.685087
90
23.622951
61
starcoderdata
<?php namespace App\Controller; use App\Requests\StatisticRedirectRequest; use App\Services\ShortUrlService; use App\Services\StatisticRedirectService; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class StatisticRedirectController extends AbstractController { /** * @param StatisticRedirectRequest $request * @param StatisticRedirectService $statisticService * * @return array */ public function index(StatisticRedirectRequest $request, StatisticRedirectService $statisticService) { $page = $request->getPage(); $limit = $request->getLimit(); $schema = $request->getScheme(); $host = $request->getHost(); $statistic = $statisticService->getStatisticAll($page, $limit); $result = array_map(function ($items) use ($schema, $host) { $items['short_url'] = ShortUrlService::makeShortUrl($schema, $host, $items['code']); unset($items['code']); return $items; }, $statistic); return [ 'items' => $result, ]; } /** * @param int $id * @param StatisticRedirectRequest $request * @param StatisticRedirectService $statisticService * * @throws \Doctrine\ORM\NonUniqueResultException * @return array|null */ public function getById(int $id, StatisticRedirectRequest $request, StatisticRedirectService $statisticService) { $schema = $request->getScheme(); $host = $request->getHost(); $statistic = $statisticService->getStatisticById($id); if ($statistic) { $statistic['short_url'] = ShortUrlService::makeShortUrl($schema, $host, $statistic['code']); } return $statistic; } }
php
19
0.62744
115
28.409836
61
starcoderdata
package jnr.posix; import jnr.ffi.*; import jnr.ffi.byref.NumberByReference; public abstract class SpawnAttribute { public static final int RESETIDS = 0x0001; /* [SPN] R[UG]ID not E[UG]ID */ public static final int SETPGROUP = 0x0002; /* [SPN] set non-parent PGID */ public static final int SETSIGDEF = 0x0004; /* [SPN] reset sigset default */ public static final int SETSIGMASK = 0x0008; /* [SPN] set signal mask */ abstract boolean set(POSIX posix, Pointer nativeFileActions); public static SpawnAttribute pgroup(long pgroup) { return new PGroup(pgroup); } public static SpawnAttribute flags(short flags) { return new SetFlags(flags); } public static SpawnAttribute sigdef(long sigdef) { throw new RuntimeException("sigdefault not yet supported"); // return new Sigdef(sigdef); } public static SpawnAttribute sigmask(long sigmask) { throw new RuntimeException("sigmask not yet supported"); // return new Sigmask(sigmask); } private static final class PGroup extends SpawnAttribute { final long pgroup; public PGroup(long pgroup) { this.pgroup = pgroup; } final boolean set(POSIX posix, Pointer nativeSpawnAttr) { return ((UnixLibC) posix.libc()).posix_spawnattr_setpgroup(nativeSpawnAttr, pgroup) == 0; } public String toString() { return "SpawnAttribute::PGroup(pgroup = " + pgroup + ")"; } } private static final class SetFlags extends SpawnAttribute { final short flags; public SetFlags(short flags) { this.flags = flags; } final boolean set(POSIX posix, Pointer nativeSpawnAttr) { return ((UnixLibC) posix.libc()).posix_spawnattr_setflags(nativeSpawnAttr, flags) == 0; } public String toString() { return "SpawnAttribute::SetFlags(flags = " + Integer.toHexString(flags) + ")"; } } private static final class Sigmask extends SpawnAttribute { final long sigmask; public Sigmask(long sigmask) { this.sigmask = sigmask; } final boolean set(POSIX posix, Pointer nativeSpawnAttr) { throw new RuntimeException("sigmask not yet supported"); // return ((UnixLibC) posix.libc()).posix_spawnattr_setsigmask(nativeSpawnAttr, mask) == 0; } public String toString() { return "SpawnAttribute::Sigmask(mask = " + Long.toHexString(sigmask) + ")"; } } private static final class Sigdef extends SpawnAttribute { final long sigdef; public Sigdef(long sigdef) { this.sigdef = sigdef; } final boolean set(POSIX posix, Pointer nativeSpawnAttr) { throw new RuntimeException("sigdefault not yet supported"); // return ((UnixLibC) posix.libc()).posix_spawnattr_setsigdefault(nativeSpawnAttr, sigdef) == 0; } public String toString() { return "SpawnAttribute::Sigdef(def = " + Long.toHexString(sigdef) + ")"; } } }
java
14
0.628094
107
31.32
100
starcoderdata
package gamejam.spy.gameObjects.levels; import java.awt.Color; import gamejam.spy.SpyGame; import gamejam.spy.Vector; import gamejam.spy.controllers.SoundPlayer; import gamejam.spy.gameObjects.Level; import gamejam.spy.gameObjects.entities.Camera; import gamejam.spy.gameObjects.entities.Hat; import gamejam.spy.gameObjects.entities.Player; import gamejam.spy.gameObjects.tiles.DeathTile; import gamejam.spy.gameObjects.tiles.LevelExit; import gamejam.spy.gameObjects.tiles.SlimeDispenser; import gamejam.spy.gameObjects.tiles.Tile; public class Level3 extends Level { public Level3() { super(); this.backgroundImage = "SCENE3"; SoundPlayer.playSound("SPY2_SEWER.wav"); //Universal Death line for(int i = 0; i < 32; i++) { addTile(new DeathTile().setTextureKey("slime"), new Vector(i, 24)); } // Walls for(int i = 0; i < 24; i++) { this.addTile(new Tile().setTextureKey("box"), new Vector(-1, i)); this.addTile(new Tile().setTextureKey("box"), new Vector(31, i)); } // Random floating platforms addTile(new Tile().setTextureKey("box"), new Vector(0, 3)); addTile(new Tile().setTextureKey("box"), new Vector(1, 3)); addTile(new Tile().setTextureKey("box"), new Vector(2, 3)); addTile(new Tile().setTextureKey("box"), new Vector(4, 5)); addTile(new Tile().setTextureKey("box"), new Vector(8, 0)); addTile(new Tile().setTextureKey("box"), new Vector(9, 2)); addTile(new Tile().setTextureKey("box"), new Vector(10, 2)); addTile(new Tile().setTextureKey("box"), new Vector(11, 3)); addTile(new Tile().setTextureKey("box"), new Vector(12, 2)); //Slime dispensers addTile(new SlimeDispenser().setChance(0.06f).setTextureKey("box"), new Vector(9, 3)); addTile(new SlimeDispenser().setChance(0.06f).setTextureKey("box"), new Vector(2, 3)); addTile(new Tile().setTextureKey("box"), new Vector(12, 5)); addTile(new Tile().setTextureKey("box"), new Vector(13, 5)); addTile(new Tile().setTextureKey("box"), new Vector(6, 9)); addTile(new Tile().setTextureKey("box"), new Vector(11, 11)); addTile(new Tile().setTextureKey("box"), new Vector(14, 8)); addTile(new Tile().setTextureKey("box"), new Vector(15, 6)); addTile(new Tile().setTextureKey("box"), new Vector(17, 7)); addTile(new Tile().setTextureKey("box"), new Vector(18, 7)); addTile(new Tile().setTextureKey("box"), new Vector(19, 7)); addTile(new Tile().setTextureKey("box"), new Vector(20, 7)); addTile(new Tile().setTextureKey("box"), new Vector(21, 7)); addTile(new Tile().setTextureKey("box"), new Vector(22, 6)); addTile(new Tile().setTextureKey("box"), new Vector(23, 5)); addTile(new Tile().setTextureKey("box"), new Vector(23, 2)); addTile(new Tile().setTextureKey("box"), new Vector(23, 1)); addTile(new Tile().setTextureKey("box"), new Vector(24, 0)); // Tiles to hat addTile(new Tile().setTextureKey("box"), new Vector(10, 13)); addTile(new Tile().setTextureKey("box"), new Vector(7, 15)); addTile(new Tile().setTextureKey("box"), new Vector(5, 16)); addTile(new Tile().setTextureKey("box"), new Vector(4, 16)); addTile(new Tile().setTextureKey("box"), new Vector(1, 16)); // Tiles to end addTile(new Tile().setTextureKey("box"), new Vector(23, 5)); addTile(new Tile().setTextureKey("box"), new Vector(24, 5)); addTile(new Tile().setTextureKey("box"), new Vector(25, 5)); addTile(new Tile().setTextureKey("box"), new Vector(27, 23)); addTile(new Tile().setTextureKey("box"), new Vector(27, 24)); addTile(new Tile().setTextureKey("box"), new Vector(29, 23)); addTile(new Tile().setTextureKey("box"), new Vector(29, 24)); addTile(new LevelExit(), new Vector(28, 24)); //Entities addEntity(new Player()); Hat h = new Hat(); h.setPosition(1*32, 15*32); h.setHatID(Player.Hat.SCUBA); h.setTextureKey("scuba"); addEntity(h); Camera c = new Camera(); c.setPosition((int) (20 * 32), 2 * 32); c.colour = Color.GREEN; c.dist = 170; c.width = 25; addEntity(c); } @Override public void restartLevel() { System.out.println("restarting"); SpyGame.loadedLevel = new Level3(); SpyGame.deaths++; } @Override public void nextLevel() { SpyGame.loadedLevel = new Level4(); } }
java
13
0.650536
88
31.96124
129
starcoderdata
private void DrawMainMenu(Graphics gc, int cameraX, int cameraY) { // after drawing the map, move the compositing mode to sourc over, for the item to be drawn with transparency gc.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; // compute the camera position in game world coordinates int cameraXWorld = cameraX * WALL_SPRITE_WIDTH; int cameraYWorld = cameraY * WALL_SPRITE_HEIGHT; // compute the menuX position float playMenuX = (27f - cameraXWorld) * mPixelSize; float otherMenuX = (40f - cameraXWorld) * mPixelSize; Font mainMenuTextFont = new Font(FontFamily.GenericMonospace, 8f * mPixelSize, FontStyle.Bold); // draw the menus gc.DrawString("> Play", mainMenuTextFont, mMainMenuTextBrush, playMenuX, (30 - cameraYWorld) * mPixelSize); gc.DrawString("Sound On", mainMenuTextFont, mMainMenuTextBrush, otherMenuX, (41 - cameraYWorld) * mPixelSize); gc.DrawString("Controls", mainMenuTextFont, mMainMenuTextBrush, otherMenuX, (52 - cameraYWorld) * mPixelSize); }
c#
12
0.737846
113
56.388889
18
inline
// // ResourceController.h // Journler // // Created by on 10/26/06. // Copyright 2006 Sprouted, All rights reserved. // /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Basically, you can use the code in your free, commercial, private and public projects // as long as you include the above notice and attribute the code to Philip Dow / Sprouted // If you use this code in an app send me a note. I'd love to know how the code is used. // Please also note that this copyright does not supersede any other copyrights applicable to // open source code used herein. While explicit credit has been given in the Journler about box, // it may be lacking in some instances in the source code. I will remedy this in future commits, // and if you notice any please point them out. #import #import #import #import #import "JournlerResource.h" typedef enum { kSortResourcesByKind = 0, kSortResourcesByTitle = 1, kSortResourcesByRank = 2 } ResourceSortCommand; typedef enum { kResourceNodeHidden = 0, // not available kResourceNodeCollapsed = 1, // visble but closed kResourceNodeExpanded = 2 // visble and expanded } ResourceCategoryNodeState; @class ResourceTableView; @class ResourceNode; @class JournlerEntry; @class JournlerResource; @interface ResourceController : NSArrayController { id delegate; NSSet *intersectSet; IBOutlet ResourceTableView *resourceTable; NSArray *folders; NSArray *resources; NSArray *resourceNodes; NSArray *selectedResources; NSArray *arrangedResources; ResourceNode *foldersNode, *internalNode; ResourceNode *contactsNode, *correspondenceNode, *urlsNode, *documentsNode, *pdfsNode, *archivesNode, *imagesNode, *avNode; NSMutableDictionary *stateDictionary; NSUInteger _dragOperation; BOOL showingSearchResults; BOOL usesSmallResourceIcons; NSInteger onTheFlyTag; BOOL dragProducedEntry; NSImage *defaultDisclosure; NSImage *defaultAltDisclosure; NSImage *smallDiscloure; NSImage *smallAltDisclosure; } - (id) delegate; - (void) setDelegate:(id)anObject; - (BOOL) showingSearchResults; - (void) setShowingSearchResults:(BOOL)searching; - (NSArray*) selectedResources; - (void) setSelectedResources:(NSArray*)anArray; - (NSArray*) arrangedResources; - (void) setArrangedResources:(NSArray*)anArray; - (NSSet*) intersectSet; - (void) setIntersectSet:(NSSet*)newSet; - (NSArray*) resources; - (void) setResources:(NSArray*)anArray; - (NSArray*) folders; - (void) setFolders:(NSArray*)anArray; - (NSArray*) resourceNodes; - (void) setResourceNodes:(NSArray*)anArray; - (NSDictionary*) stateDictionary; - (BOOL) restoreStateFromDictionary:(NSDictionary*)aDictionary; - (void) prepareResourceNodes; - (IBAction) tableDoubleClick:(id)sender; - (IBAction) showEntryForSelectedResource:(id)sender; - (IBAction) setSelectionAsDefaultForEntry:(id)sender; - (IBAction) renameResource:(id)sender; - (IBAction) editResourceLabel:(id)sender; - (IBAction) editResourcePropety:(id)sender; - (IBAction) revealResource:(id)sender; - (IBAction) launchResource:(id)sender; - (IBAction) emailResourceSelection:(id)sender; - (IBAction) openResourceInNewTab:(id)sender; - (IBAction) openResourceInNewWindow:(id)sender; - (IBAction) openResourceInNewFloatingWindow:(id)sender; - (void) openAResourceWithFinder:(JournlerResource*)aResource; - (void) openAResourceInNewTab:(JournlerResource*)aResource; - (void) openAResourceInNewWindow:(JournlerResource*)aResource; - (IBAction) setProperty:(id)sender; - (IBAction) setDisplayOption:(id)sender; - (IBAction) deleteSelectedResources:(id)sender; - (void) sortBy:(NSInteger)sortTag; - (IBAction) sortByCommand:(id)sender; - (IBAction) exposeAllResources:(id)sender; - (BOOL) selectResource:(JournlerResource*)aResource byExtendingSelection:(BOOL)extend; - (IBAction) rescanResourceIcon:(id)sender; - (IBAction) rescanResourceUTI:(id)sender; - (BOOL) _addMailMessage:(NSDictionary*)objectDictionary; - (BOOL) _addMailMessage:(id toEntry:(JournlerEntry*)anEntry; - (BOOL) _addPerson:(ABPerson*)aPerson toEntry:(JournlerEntry*)anEntry; - (BOOL) _addURL:(NSURL*)aURL title:(NSString*)title toEntry:(JournlerEntry*)anEntry; - (BOOL) _addJournlerObjectWithURI:(NSURL*)aURL toEntry:(JournlerEntry*)anEntry; - (BOOL) _addAttributedString:(NSAttributedString*)anAttributedString toEntry:(JournlerEntry*)anEntry; - (BOOL) _addString:(NSString*)aString toEntry:(JournlerEntry*)anEntry; - (BOOL) _addWebArchiveFromURL:(NSURL*)aURL title:(NSString*)title toEntry:(JournlerEntry*)anEntry; - (BOOL) _addImageData:(NSData*)imageData dataType:(NSString*)type title:(NSString*)title toEntry:(JournlerEntry*)anEntry; - (BOOL) _addFile:(NSString*)filename title:(NSString*)title resourceCommand:(NewResourceCommand)command toEntry:(JournlerEntry*)anEntry; - (NSString*) _mdTitleFoFileAtPath:(NSString*)fullpath; - (NSString*) _linkedTextForAudioFile:(NSString*)fullpath; - (NSUInteger) _commandForCurrentCommand:(NSUInteger)dragOperation fileType:(NSString*)type directory:(BOOL)dir package:(BOOL)package; - (void) _entryDidChangeResourceContent:(NSNotification*)aNotification; - (ResourceNode*) _nodeForResource:(JournlerResource*)aResource; @end @interface NSObject (ResourceControllerDelegate) - (BOOL) resourceController:(ResourceController*)aController newDefaultEntry:(NSNotification*)aNotification; - (void) resourceController:(ResourceController*)aController willChangeSelection:(NSArray*)currentSelection; @end
c
26
0.783887
137
36.042105
190
starcoderdata
public ProbeMapManager.ProbeOutput UpdateProbeCubemap(GLContext control, GLTextureCube probeMap, OpenTK.Vector3 position) { var lmap = Resources.LightMapFiles.FirstOrDefault().Value; var collectRes = Resources.CollectFiles.FirstOrDefault().Value; //Find the area to get the current light map var areaObj = collectRes.GetArea(position.X, position.Y, position.Z); var lightMapName = areaObj.GetLightmapName(); if (!lmap.Lightmaps.ContainsKey(lightMapName)) UpdateLightmap(control, lightMapName); return ProbeMapManager.Generate(control, lmap.Lightmaps[lightMapName], probeMap.ID, position); }
c#
12
0.682652
121
49.714286
14
inline
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcBloggy.Web.Infrastructure.MetaWeblogItems { //https://bitbucket.org/FunnelWeb/dev/src/264a7c2272cc/src/FunnelWeb.Web/Application/MetaWeblog/MetaWeblogRouteHandler.cs public class MetaWeblogRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return DependencyResolver.Current.GetService } } }
c#
12
0.753356
125
29.526316
19
starcoderdata
<?php namespace Youkok\Web\Views; use Monolog\Logger; use Slim\Http\Message; use Slim\Http\Stream; use Slim\Http\Response; use Slim\Http\Request; use Psr\Container\ContainerInterface; use Youkok\Biz\Exceptions\ElementNotFoundException; use Youkok\Biz\Exceptions\TemplateFileNotFoundException; use Youkok\Biz\Exceptions\YoukokException; use Youkok\Biz\Services\Auth\AuthService; use Youkok\Biz\Services\Download\DownloadFileInfoService; use Youkok\Biz\Services\Download\UpdateDownloadsService; use Youkok\Biz\Services\Models\ElementService; class Download extends BaseView { private DownloadFileInfoService $downloadService; private UpdateDownloadsService $updateDownloadsProcessor; private ElementService $elementService; private AuthService $authService; private Logger $logger; public function __construct(ContainerInterface $container) { $this->downloadService = $container->get(DownloadFileInfoService::class); $this->updateDownloadsProcessor = $container->get(UpdateDownloadsService::class); $this->elementService = $container->get(ElementService::class); $this->authService = $container->get(AuthService::class); $this->logger = $container->get(Logger::class); } /** * @param Request $request * @param Response $response * @param array $args * @return Message|Response * @throws TemplateFileNotFoundException */ public function view(Request $request, Response $response, array $args) { $flags = [ ElementService::FLAG_FETCH_PARENTS, ElementService::FLAG_ENSURE_ALL_PARENTS_ARE_DIRECTORIES_CURRENT_IS_FILE ]; // If we are not currently logged in as admin, also make sure that the file is visible if (!$this->authService->isAdmin($request)) { $flags[] = ElementService::FLAG_ENSURE_VISIBLE; } try { $element = $this->elementService->getElementFromUri( $args['uri'], ['id', 'checksum', 'directory', 'name'], $flags ); if (!$this->downloadService->fileExists($element)) { $this->logger->error('Tried to download file which does not exist. Id: ' . $element->id); throw new ElementNotFoundException(); } if (!$this->authService->isAdmin($request)) { $this->updateDownloadsProcessor->run($element); } $fileInfo = $this->downloadService->getFileInfo($element); $fileSize = $this->downloadService->getFileSize($element); $filePath = $this->downloadService->getFilePath($element); return $response ->withHeader('Content-Description', 'File Transfer') ->withHeader('Content-Type', $fileInfo) ->withHeader('Content-Disposition', 'inline; filename="' . $element->name . '"') ->withHeader('Expires', '0') ->withHeader('Cache-Control', 'must-revalidate') ->withHeader('Pragm', 'public') ->withHeader('Content-Length', $fileSize) ->withBody(new Stream(fopen($filePath, 'r'))); } catch (YoukokException $ex) { // TODO: Handle file errors, not found errors etc better here $this->logger->error($ex); return $this->render404($response); } } }
php
20
0.62936
105
36.802198
91
starcoderdata
<?php /** * DronePHP (http://www.dronephp.com) * * @link http://github.com/Pleets/DronePHP * @copyright Copyright (c) 2016-2018 Pleets. (http://www.pleets.org) * @license http://www.dronephp.com/license * @author */ namespace Drone\Loader; /** * AbstractModule class * * This class is an autoloader */ class ClassMap { /** * The class path * * @var string */ public static $path; /** * Creates an autoloader for module classes * * @param string $name * @param string $path * * @return null */ public static function autoload($name) { $nm = explode('\\', $name); $module = array_shift($nm); $path = is_null(self::$path) ? '' : self::$path . DIRECTORY_SEPARATOR; $class = $path . implode(DIRECTORY_SEPARATOR, $nm) . ".php"; if (file_exists($class)) { include $class; } } }
php
13
0.542977
78
18.875
48
starcoderdata