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
bool TCPChannel::_maybe_dropread() { // will possibly notify observer, but not going to set up a // destructor guard here; leave it caller to do // don't care about contents, so can use static static char drop_buf[4096]; /* though shadow's CONFIG_TCP_RMEM_MAX * is 6291456, it always seems to * allow max read of 4k at a time, so * we'll just go with 4k */ auto maybe_theres_more = true; // from socket size_t dropped_this_time = 0; // to be accumulated in the loop, // and notify observer once before // we exit bool had_an_unsuccessful_read = false; int read_error = 0; while (input_drop_.num_remaining() && maybe_theres_more) { // read into drop buf instead of into input_evb_ vlogself(3) << "want to dropread " << input_drop_.num_remaining() << " bytes"; const auto num_to_read = std::min(input_drop_.num_remaining(), sizeof drop_buf); const auto rv = ::read(fd_, drop_buf, num_to_read); vlogself(3) << "got " << rv; if (rv > 0) { num_total_read_bytes_ += rv; dropped_this_time += rv; input_drop_.progress(rv); if (rv < num_to_read) { // there was less data than we wanted, so the socket // doesn't have more for us at this time, so we can // break. // // this fixes a bug where we dont break and try to // read again in the loop and get zero, and we call // _handle_non_successful_socket_io() which notifies // the user of eof, and user destroys himself, and // then we proceed below to the next block with a // positive dropped_this_time and notifies a // now-deleted object maybe_theres_more = false; } } else { had_an_unsuccessful_read = true; read_error = rv; // whetever the reason, there is no more to read this time // around maybe_theres_more = false; } } if (dropped_this_time) { CHECK_NE(fd_, -1); CHECK_NE(state_, ChannelState::CLOSED); const auto remaining = input_drop_.num_remaining(); vlogself(3) << dropped_this_time << " bytes dropped this time around" << " (" << remaining << " remaining)"; if (input_drop_.interested_in_progress()) { vlogself(3) << "notify of any new progress"; input_drop_.observer()->onInputBytesDropped(this, dropped_this_time); if (remaining == 0) { // also have to reset here input_drop_.reset(); } } else if (remaining == 0) { // notify just once, when have dropped all requested amount vlogself(3) << "notify once since we're done"; /* notify first before resetting, to prevent user from * immediately submitting another drop req. not that we * couldn't handle it; just that it might indicate a bug */ input_drop_.observer()->onInputBytesDropped( this, input_drop_.num_requested()); // now reset input_drop_.reset(); } } if (had_an_unsuccessful_read) { _handle_non_successful_socket_io("dropread", read_error, true); } vlogself(3) << "done, returning: " << maybe_theres_more; return maybe_theres_more; }
c++
14
0.517177
81
38.648936
94
inline
import React from 'react'; import { Table, TableHead, TableBody, TableRow, TableCell } from '@material-ui/core'; import MoneyIcon from '@material-ui/icons/AttachMoney'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import Button from '@material-ui/core/Button'; import CircularProgress from '@material-ui/core/CircularProgress'; const circularProgressStyle = { position: 'absolute', top: '50%', left: '50%', marginTop: -12, marginLeft: -12, }; export default class ReportHistoryTable extends React.Component { constructor(props) { super(props); this.state = {events:[], petId:props.petId, loading:true } } formatTimestamp(timestamp){ var date = new Date(parseInt(timestamp)*1000); var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; var year = date.getFullYear(); var month = months[date.getMonth()]; var day = ('0' + date.getDate() ).substr(-2); var hour = date.getHours(); var min = ('0' + date.getMinutes() ).substr(-2); var sec = ('0' + date.getSeconds() ).substr(-2); var time = month + ' ' + day + ' ' + year + ', ' + hour + ':' + min + ':' + sec ; return time; } componentDidMount() { var _this = this; //var shaPetId = this.props.w3w.web3js.utils.sha3(this.state.petId); //var shaPetId = this.props.w3w.web3js.utils.sha3(this.props.w3w.web3js.eth.abi.encodeParameter("string",this.state.petId)); this.props.resolverContract.getPastEvents('LostReportChanged', { filter: {petId:this.state.petId}, fromBlock: 0, toBlock: 'latest' //topics: [null,shaPetId] //topics:[this.state.petId] }, function(e,l){ _this.setState({ events: l, loading:false }) } ) } render() { return( <Dialog open={this.props.open} fullScreen={true} //TransitionComponent={Transition} onClose={this.handleClose} aria-labelledby="alert-dialog-slide-title" aria-describedby="alert-dialog-slide-description" > <DialogTitle id="alert-dialog-slide-title"> {"Report history of Pet ID:"+this.props.chipId+", Name: "+this.props.name} <TableRow > <TableCell >Status <TableCell >Scene Desc <TableCell >Claimer EIN <TableCell > {this.state.events.map( ev => <TableRow key={this.props.petId+'_'+ev.returnValues.date}> )} {this.state.loading && <CircularProgress size={68} style={circularProgressStyle} />} <Button onClick={this.props.handleClose} color="primary"> Close ) } }
javascript
26
0.626317
126
28.016529
121
starcoderdata
package com.jmath; public class ExtendedMath { private ExtendedMath() {} private static final double ROOT_DIFFERENCE = 1e-8; public static boolean equalsExact(double value1, double value2) { return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2); } public static boolean equals(double value1, double value2, double delta) { if (Double.compare(value1, value2) == 0) { return true; } return (Math.abs(value1 - value2) <= delta); } public static double avg(double... numbers) { if (numbers.length == 0) { throw new IllegalArgumentException("empty array"); } double sum = 0.0; for (double number : numbers) { sum += number; } return sum / numbers.length; } public static double constrain(double value, double min, double max) { if (value < min) { return min; } if (value > max) { return max; } return value; } public static boolean constrained(double value, double min, double max){ return value >= min && value <= max; } public static double root(double radicand, int degree){ if(radicand < 0) { throw new IllegalArgumentException("Cannot calculate negative root of negative radicand"); } if(radicand == 0) { return 0; } double x1 = radicand; double x2 = radicand / degree; while (Math.abs(x1 - x2) > ROOT_DIFFERENCE){ x1 = x2; x2 = ((degree - 1.0) * x2 + radicand / Math.pow(x2, degree - 1.0)) / degree; } return x2; } public static double roundToMultiplier(double value, double multiplier){ return multiplier * Math.round(value / multiplier); } public static double roundToMultiplier(double value, double multiplier, boolean up){ double rounded = roundToMultiplier(value, multiplier); if(rounded < value && up) { rounded += multiplier; } else if (rounded > value && !up) { rounded -= multiplier; } return rounded; } }
java
16
0.570199
102
25.60241
83
starcoderdata
package com.trophonius.sql; import com.trophonius.ClientHandler; import com.trophonius.Engines.Engine; import com.trophonius.Main; import com.trophonius.dbo.Field; import com.trophonius.dbo.Row; import com.trophonius.utils.HelperMethods; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.Collectors; /** * Parses an SQL SELECT statement and dispatches it to the table's storage engine for retrieval */ public class Select { private int limit, offset, whereStart=0, whereEnd=0; Logger logger = LoggerFactory.getLogger(Select.class); public Select() { } public Select (String tableName, String sql) { // Split sql into separate words String[] words = sql.split("[ ]"); // make a list to hold field names from sql List fieldList = new ArrayList<>(); List rows = new LinkedList<>(); // Set initial limit value to MAX_VAlUE and change it if LIMIT is in SQL limit = Integer.MAX_VALUE; // set initial offset value to 0 and change it if OFFSET is in SQL offset = 0; //Parse words for (int i = 0; i < words.length; i++) { // Check for LIMIT and set value if (words[i].toLowerCase().equals("limit")) { limit = Integer.valueOf(words[i + 1]); } // Check for offset and set value if (words[i].toLowerCase().equals("offset")) { offset = Integer.valueOf(words[i + 1]); } // check for round() // TODO // / * + - } // end parse words // Check for WHERE start and end if (sql.toLowerCase().contains("where")) { whereStart = sql.toLowerCase().indexOf("where")+6; if (sql.toLowerCase().contains("group")) { whereEnd = sql.toLowerCase().indexOf("group"); } else if (sql.toLowerCase().contains("order")) { whereEnd = sql.toLowerCase().indexOf("order"); } else if (sql.toLowerCase().contains("limit")) { whereEnd = sql.toLowerCase().indexOf("limit"); } else { whereEnd = sql.length(); } } String whereTerms = sql.toLowerCase().substring(whereStart,whereEnd); List filterTerms = new LinkedList<>(); String whereTermes =""; String operand = ""; if (whereTerms.contains("!=") || whereTerms.contains("<>")) { operand = "!="; } else if (whereTerms.contains(">")) { operand = ">"; } else if (whereTerms.contains("<")) { operand = "<"; } else if (whereTerms.contains("=")) { operand = "="; } if(operand!="") { // create a new FilterTerm object with fieldName, operand and value String fieldName = whereTerms.substring(0, whereTerms.indexOf(operand)); fieldName = fieldName.replaceAll(" ",""); String functionName = ""; String functionParameters = ""; // check for functions in where terms if (fieldName.contains("(") & fieldName.contains(")")) { // function is present functionName = fieldName.substring(0,fieldName.indexOf("(")); System.out.println("functionName : "+functionName); switch (functionName) { case "round": // Extract field name and parameter value from where term String fieldName2 = fieldName.substring(fieldName.indexOf("(")+1,fieldName.indexOf(",")); functionParameters = fieldName.substring(fieldName.indexOf(",")+1,fieldName.indexOf(")")); fieldName = fieldName2; // System.out.println("fieldName : "+fieldName); // System.out.println("functionParameters : "+functionParameters); break; } } // end check for functions String value = whereTerms.substring(whereTerms.indexOf(operand)+operand.length()); value = value.trim(); String fieldType = ClientHandler.currentDB.getTables().get(tableName).getTableStructure().get(fieldName).getDataType().getName(); // Create a FilterTerm and add it to List to be sent to Engine for processing FilterTerm filter = new FilterTerm(fieldName,fieldType, operand, value,functionName,functionParameters); filterTerms.add(filter); } // filterTerms.stream().forEach(System.out::println); try { // Read fieldNames and Fields from tableStructure LinkedHashMap<String, Field> tableStructure = ClientHandler.currentDB.getTables().get(tableName).getTableStructure(); // If "select *" then Fetch all fields by putting the whole keySet into the variable fieldList if (words[1].equals("*")) { fieldList.addAll(tableStructure.keySet()); } else if (words[1].equals("count(*)")) { // get and print row count Engine engine = ClientHandler.currentDB.getTables().get(tableName).getEngine(); long rowCount = engine.getRowCount(ClientHandler.currentDB.getDbName(), tableName); HelperMethods.printAsciiTable(rowCount); return; } else { // Or else determine fields to be fetched and put them into the variable fieldList // First substring the fields from sql String fields = sql.toLowerCase() .substring(sql.toLowerCase().indexOf("select") + 6, sql.toLowerCase().indexOf("from")); // Then split the fields string and add Fields into fieldList fieldList.addAll(Arrays.stream(fields.split(",")).map(a -> a.trim()).collect(Collectors.toList())); // Check if all fields from SQL exists in tableStructure of currentTable Boolean found = tableStructure.keySet().containsAll(fieldList); if (found == false) { // Not all field names were found in table structure. Print message and go back to prompt System.out.println("ERROR: One or more field names are not present in table"); System.out.println("Fields in table: " + tableStructure.keySet()); System.out.println("Fields in SQL statement: " + fieldList); return; } } System.out.println("Fields to be fetched: " + fieldList); } catch (Exception e) { System.out.println("Table \""+ tableName +"\" doesn't exist in this database"); return; } // Find table engine try { Engine engine = ClientHandler.currentDB.getTables().get(tableName).getEngine(); try { rows = engine.fetchRows(tableName, fieldList, filterTerms, limit, offset); } catch (Exception e) { System.out.println("Rows could not be retrieved."); logger.error("Rows could not be retrieved from "+ engine.getName()); } if(!rows.isEmpty()) { HelperMethods.printAsciiTable(fieldList, rows); } else { System.out.print("0 rows found"); } } catch (Exception e) { System.out.println("ERROR: Table Storage Engine not found"); System.out.println(e.getMessage()); } } // END SELECT } // END CLASS
java
18
0.568258
141
38.540816
196
starcoderdata
package org.lilliput.chronograph.persistent.epcgraph.test.transformation; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; /** * Copyright (C) 2014-2016 * * This project is part of Oliot open source (http://oliot.org). Oliot EPCIS * v1.2.x is Java Web Service complying with Electronic Product Code Information * Service (EPCIS) v1.2. * * @author Ph.D student * * Korea Advanced Institute of Science and Technology (KAIST) * * Real-time Embedded System Laboratory(RESL) * * */ import java.io.IOException; import java.util.ArrayList; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.oliot.khronos.common.TemporalType; import org.oliot.khronos.common.Tokens.AC; import org.oliot.khronos.common.Tokens.Position; import org.oliot.khronos.persistent.ChronoGraph; import org.oliot.khronos.persistent.VertexEvent; import org.oliot.khronos.persistent.recipe.PersistentBreadthFirstSearch; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; public class TransformationQueryTestInternal { public static String fileBaseLoc = "/home/jack/test/"; // db.edges.createIndex({"_outV" : 1, "_t" : 1, "_inV" : 1}) // db.EventData.createIndex({"inputEPCList.epc":1}) public static String baseURL = "http://localhost:8080/epcgraph"; public int transferCount = 308; public int iterationCount = 100; public void test() throws IOException, InterruptedException { File file = new File(fileBaseLoc + this.getClass().getSimpleName() + "-cache-bfs"); file.createNewFile(); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); String baseEPC = "urn:epc:id:sgtin:0000001.000001."; MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase("test1"); db.getCollection("edges").drop(); db.getCollection("vertices").drop(); db.getCollection("edges").createIndex(new BsonDocument("_outV", new BsonInt32(1)) .append("_label", new BsonInt32(1)).append("_t", new BsonInt32(1)).append("_inV", new BsonInt32(1))); client.close(); ChronoGraph g = new ChronoGraph("test1"); for (int i = 0; i < transferCount; i++) { long cTime = System.currentTimeMillis(); g.addTimestampEdgeProperties(baseEPC + i, baseEPC + (2 * i + 1), "transformTo", cTime, new BsonDocument()); g.addTimestampEdgeProperties(baseEPC + i, baseEPC + (2 * i + 2), "transformTo", cTime, new BsonDocument()); Thread.sleep(2000); double avg = doTransformationQuery(g); System.out.println(i + "\t" + avg); bw.write(i + "\t" + avg + "\n"); bw.flush(); } bw.close(); } public double doTransformationQuery(ChronoGraph g) throws IOException { ArrayList timeList = new ArrayList String source = "urn:epc:id:sgtin:0000001.000001.0"; VertexEvent ve = g.getChronoVertex(source).setTimestamp(0l); for (int i = 0; i < iterationCount; i++) { PersistentBreadthFirstSearch bfs = new PersistentBreadthFirstSearch(); long pre = System.currentTimeMillis(); bfs.compute(g, ve, "transformTo", TemporalType.TIMESTAMP, AC.$gt, null, null, null, null, null, null, Position.first, "ASC"); long aft = System.currentTimeMillis(); long elapsedTime = aft - pre; // System.out.println("Elapsed Time: " + elapsedTime); timeList.add(elapsedTime); } double total = timeList.parallelStream().mapToDouble(t -> { return t.longValue(); }).sum(); return total / iterationCount; } }
java
15
0.708557
120
30.900901
111
starcoderdata
module.exports = { "16174": { "name": " "type": "thi-tran", "slug": "yen-cat", "name_with_type": " "path": "Yên Cát, Như Xuân, Thanh Hóa", "path_with_type": "Thị trấn Yên Cát, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16174", "parent_code": "402" }, "16177": { "name": " "type": "xa", "slug": "bai-tranh", "name_with_type": " "path": "Bãi Trành, Như Xuân, Thanh Hóa", "path_with_type": "Xã Bãi Trành, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16177", "parent_code": "402" }, "16180": { "name": " "type": "xa", "slug": "xuan-hoa", "name_with_type": " "path": "Xuân Hòa, Như Xuân, Thanh Hóa", "path_with_type": "Xã Xuân Hòa, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16180", "parent_code": "402" }, "16183": { "name": " "type": "xa", "slug": "xuan-binh", "name_with_type": " "path": "Xuân Bình, Như Xuân, Thanh Hóa", "path_with_type": "Xã Xuân Bình, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16183", "parent_code": "402" }, "16186": { "name": " "type": "xa", "slug": "hoa-quy", "name_with_type": " "path": "Hóa Quỳ, Như Xuân, Thanh Hóa", "path_with_type": "Xã Hóa Quỳ, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16186", "parent_code": "402" }, "16195": { "name": " "type": "xa", "slug": "cat-van", "name_with_type": " "path": "Cát Vân, Như Xuân, Thanh Hóa", "path_with_type": "Xã Cát Vân, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16195", "parent_code": "402" }, "16198": { "name": " "type": "xa", "slug": "cat-tan", "name_with_type": " "path": "Cát Tân, Như Xuân, Thanh Hóa", "path_with_type": "Xã Cát Tân, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16198", "parent_code": "402" }, "16201": { "name": " "type": "xa", "slug": "tan-binh", "name_with_type": " "path": "Tân Bình, Như Xuân, Thanh Hóa", "path_with_type": "Xã Tân Bình, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16201", "parent_code": "402" }, "16204": { "name": " "type": "xa", "slug": "binh-luong", "name_with_type": " "path": "Bình Lương, Như Xuân, Thanh Hóa", "path_with_type": "Xã Bình Lương, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16204", "parent_code": "402" }, "16207": { "name": " "type": "xa", "slug": "thanh-quan", "name_with_type": " "path": "Thanh Quân, Như Xuân, Thanh Hóa", "path_with_type": "Xã Thanh Quân, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16207", "parent_code": "402" }, "16210": { "name": " "type": "xa", "slug": "thanh-xuan", "name_with_type": " "path": "Thanh Xuân, Như Xuân, Thanh Hóa", "path_with_type": "Xã Thanh Xuân, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16210", "parent_code": "402" }, "16213": { "name": " "type": "xa", "slug": "thanh-hoa", "name_with_type": " "path": "Thanh Hòa, Như Xuân, Thanh Hóa", "path_with_type": "Xã Thanh Hòa, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16213", "parent_code": "402" }, "16216": { "name": " "type": "xa", "slug": "thanh-phong", "name_with_type": " "path": "Thanh Phong, Như Xuân, Thanh Hóa", "path_with_type": "Xã Thanh Phong, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16216", "parent_code": "402" }, "16219": { "name": " "type": "xa", "slug": "thanh-lam", "name_with_type": " "path": "Thanh Lâm, Như Xuân, Thanh Hóa", "path_with_type": "Xã Thanh Lâm, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16219", "parent_code": "402" }, "16222": { "name": " "type": "xa", "slug": "thanh-son", "name_with_type": " "path": "Thanh Sơn, Như Xuân, Thanh Hóa", "path_with_type": "Xã Thanh Sơn, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16222", "parent_code": "402" }, "16225": { "name": " "type": "xa", "slug": "thuong-ninh", "name_with_type": " "path": "Thượng Ninh, Như Xuân, Thanh Hóa", "path_with_type": "Xã Thượng Ninh, Huyện Như Xuân, Tỉnh Thanh Hóa", "code": "16225", "parent_code": "402" } }
javascript
8
0.513016
73
26.337423
163
starcoderdata
/*************************************************************************** * Copyright (C) by * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * SeisComP Public License for more details. * ***************************************************************************/ // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline int ClientDB::size() const { return _clientDB.size(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline ClientDB::iterator ClientDB::begin() { return _clientDB.begin(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline ClientDB::iterator ClientDB::end() { return _clientDB.end(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline ClientInfo::ClientInfo(const ServiceMessage& sm) : _clientName(sm.clientName()) , _privateGroup(sm.privateSenderGroup()) , _clientType(sm.clientType()) , _clientPriority(sm.clientPriority()) , _clientStatus(Communication::ClientStatus::CreateClientStatus(sm.data())) {} // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline ClientInfo::~ClientInfo() {} // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline Seiscomp::Core::TimeSpan ClientInfo::uptime() const { return _timer.elapsed(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline const Communication::ClientStatus* ClientInfo::clientStatus() const { return _clientStatus; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline const std::string& ClientInfo::clientName() const { return _clientName; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline const std::string& ClientInfo::privateGroup() const { return _privateGroup; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline Protocol::ClientType ClientInfo::clientType() const { return _clientType; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inline Protocol::ClientPriority ClientInfo::clientPriority() const { return _clientPriority; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
c++
9
0.294708
78
29.966387
119
starcoderdata
import unittest as ut from gulpy.jobs import MDJob from gulpy.inputs.tests.test_library import ExampleLibrary from gulpy.structure import GulpCrystal, GulpMolecule from gulpy.structure.labels import CatlowLabels, DreidingMoleculeLabels from gulpy.tests.test_files import load_structure, load_molecule, get_jobs_path class TestJob(ut.TestCase): def setUp(self): self.structure = GulpCrystal(load_structure(), CatlowLabels()) self.library = ExampleLibrary() self.job = MDJob(self.structure, self.library) def test_parse(self): results = self.job.parse_results( get_jobs_path("md/md.out"), get_jobs_path("md/md.trg") ) self.assertTrue("frames" in results) class TestMoleculeMDJob(ut.TestCase): def setUp(self): self.structure = GulpMolecule(load_molecule(), DreidingMoleculeLabels()) self.library = ExampleLibrary() self.job = MDJob(self.structure, self.library) def test_parse(self): results = self.job.parse_results( get_jobs_path("md/molecule.out"), get_jobs_path("md/molecule.trg") ) self.assertTrue("frames" in results) if __name__ == "__main__": ut.main()
python
12
0.680834
80
28.690476
42
starcoderdata
import logging import os import string from datetime import datetime from functools import reduce import cf_units import iris import iris.quickplot as qplot import matplotlib.pyplot as plt import numpy as np from esmvalcore.preprocessor._time import regrid_time from iris.analysis.stats import pearsonr from iris.coord_categorisation import add_month_number, add_year from iris.util import unify_time_units from matplotlib.legend import Legend from matplotlib.legend_handler import HandlerBase from matplotlib.text import Text import esmvaltool.diag_scripts.shared from esmvaltool.diag_scripts.shared import group_metadata, names from esmvaltool.diag_scripts.shared._base import ProvenanceLogger logger = logging.getLogger(__name__) class CompareSalinity(object): def __init__(self, config): self.cfg = config def compute(self): data = group_metadata(self.cfg[names.INPUT_DATA].values(), names.SHORT_NAME) for short_name in data: logger.info("Processing variable %s", short_name) variables = group_metadata(data[short_name], names.ALIAS) ref_alias = list(variables.values())[0][0]['reference_dataset'] reference_dataset = variables.pop(ref_alias)[0] reference = iris.load_cube(reference_dataset[names.FILENAME]) reference_ancestor = reference_dataset[names.FILENAME] logger.debug("Info reference dataset:") logger.debug(reference) for alias, dataset_info in variables.items(): logger.info("Plotting dataset %s", alias) dataset_info = dataset_info[0] dataset = iris.load_cube(dataset_info[names.FILENAME]) time_coord = dataset.coord('time') if time_coord.units.calendar == 'proleptic_gregorian': time_coord.units = cf_units.Unit( time_coord.units.name, calendar='gregorian', ) unify_time_units((reference, dataset)) logger.debug("Info dataset %s:", alias) logger.debug(dataset) ancestors = (dataset_info[names.FILENAME], reference_ancestor) for region_slice in dataset.slices_over('shape_id'): region = region_slice.coord('shape_id').points[0] self.create_timeseries_plot(region, region_slice, reference, ref_alias, dataset_info, ancestors) self.create_radar_plot(dataset_info, dataset, reference, ref_alias, ancestors) def create_timeseries_plot(self, region, data, reference, reference_alias, dataset_info, ancestors): alias = dataset_info[names.ALIAS] qplot.plot(data, label=alias) qplot.plot(reference.extract(iris.Constraint(shape_id=region)), label=reference_alias) plt.legend() plt.title(f"{dataset_info[names.LONG_NAME]} ({region})") plt.tight_layout() plt.savefig(f'test_timeseries_{region}.png') plot_path = os.path.join( self.cfg[names.PLOT_DIR], f"{dataset_info[names.SHORT_NAME]}_{region.replace(' ', '')}" f"_{alias}.{self.cfg[names.OUTPUT_FILE_TYPE]}") plt.savefig(plot_path) plt.close() caption = (f"{dataset_info[names.SHORT_NAME]} mean in {region} for " f"{alias} and {reference_alias}") self._create_prov_record(plot_path, caption, ancestors) def create_radar_plot(self, data_info, data, reference, reference_alias, ancestors): interval = self._get_overlap([data, reference]) indices = self._slice_cube(data, interval[0], interval[1]) data = data[indices[0]:indices[1] + 1] indices = self._slice_cube(reference, interval[0], interval[1]) reference = reference[indices[0]:indices[1] + 1] add_month_number(data, 'time') add_year(data, 'time') data.remove_coord('time') add_month_number(reference, 'time') add_year(reference, 'time') reference.remove_coord('time') data_alias = data_info[names.ALIAS] corr = pearsonr(data, reference, ('month_number', 'year')) angles = np.linspace(0, 2 * np.pi, corr.shape[0] + 1) # Initialise the spider plot ax = plt.subplot(111, polar=True) for spine in ax.spines.values(): spine.set_color('grey') # Draw one axe per variable + add labels labels yet letters = [string.ascii_uppercase[i] for i in range(0, corr.shape[0])] plt.xticks(angles[:-1], letters, color='grey', size=8, rotation=angles[:-1]) # Draw ylabels ax.set_rlabel_position(0) plt.yticks([0.25, 0.5, 0.75], ["0.25", "0.5", "0.75"], color="grey", size=7) plt.ylim(0, 1) data = np.append(corr.data, corr.data[0]) more_angles = np.linspace(0, 2 * np.pi, corr.shape[0] * 20 + 1) interp_data = np.interp(more_angles, angles, data) # Plot data ax.plot(more_angles, interp_data, linewidth=1, linestyle='solid') ax.fill(more_angles, interp_data, 'b', alpha=0.1) ax.legend(letters, corr.coord('shape_id').points, loc='upper center', ncol=2, frameon=False, bbox_to_anchor=(0.5, -0.1), borderaxespad=0.) plt.title( f'{data_info[names.SHORT_NAME]} correlation\n' f'{data_alias} vs {reference_alias}', pad=20) plt.tight_layout() plot_path = os.path.join( self.cfg[names.PLOT_DIR], f"{data_info[names.SHORT_NAME]}_comparison_{data_alias}_" f"{reference_alias}.{self.cfg[names.OUTPUT_FILE_TYPE]}") plt.savefig(plot_path) plt.close() caption = (f"Correlation comparison in diferent regions for " f"{data_alias} and {reference_alias}") self._create_prov_record(plot_path, caption, ancestors) def _create_prov_record(self, filepath, caption, ancestors): record = { 'caption': caption, 'domains': [ 'global', ], 'autors': ['vegas-regidor_javier'], 'references': ['acknow_author'], 'ancestors': ancestors } with ProvenanceLogger(self.cfg) as provenance_logger: provenance_logger.log(filepath, record) def _get_time_offset(self, time_unit): """Return a datetime object equivalent to tunit.""" # tunit e.g. 'day since 1950-01-01 00:00:00.0000000 UTC' cfunit = cf_units.Unit(time_unit, calendar=cf_units.CALENDAR_STANDARD) time_offset = cfunit.num2date(0) return time_offset def _align_yearly_axes(self, cube): """ Perform a time-regridding operation to align time axes for yr data. """ years = [cell.point.year for cell in cube.coord('time').cells()] # be extra sure that the first point is not in the previous year if 0 not in np.diff(years): return regrid_time(cube, 'yr') return cube def _datetime_to_int_days(self, cube): """Return list of int(days) converted from cube datetime cells.""" cube = self._align_yearly_axes(cube) time_cells = [cell.point for cell in cube.coord('time').cells()] # extract date info real_dates = [] for date_obj in time_cells: # real_date resets the actual data point day # to the 1st of the month so that there are no # wrong overlap indices real_date = datetime(date_obj.year, date_obj.month, 1, 0, 0, 0) real_dates.append(real_date) # get the number of days starting from the reference unit time_unit = cube.coord('time').units.name time_offset = self._get_time_offset(time_unit) days = [(date_obj - time_offset).days for date_obj in real_dates] return days def _get_overlap(self, cubes): """ Get discrete time overlaps. This method gets the bounds of coord time from the cube and assembles a continuous time axis with smallest unit 1; then it finds the overlaps by doing a 1-dim intersect; takes the floor of first date and ceil of last date. """ all_times = [] for cube in cubes: span = self._datetime_to_int_days(cube) start, stop = span[0], span[-1] all_times.append([start, stop]) bounds = [range(b[0], b[-1] + 1) for b in all_times] time_pts = reduce(np.intersect1d, bounds) if len(time_pts) > 1: time_bounds_list = [time_pts[0], time_pts[-1]] return time_bounds_list def _slice_cube(self, cube, t_1, t_2): """ Efficient slicer. Simple cube data slicer on indices of common time-data elements. """ time_pts = [t for t in cube.coord('time').points] converted_t = self._datetime_to_int_days(cube) idxs = sorted([ time_pts.index(ii) for ii, jj in zip(time_pts, converted_t) if t_1 <= jj <= t_2 ]) return [idxs[0], idxs[-1]] class TextHandler(HandlerBase): def create_artists(self, legend, text, xdescent, ydescent, width, height, fontsize, trans): tx = Text(width / 2., height / 2, text, fontsize=fontsize, ha="center", va="center", fontweight="bold") return [tx] Legend.update_default_handler_map({str: TextHandler()}) def main(): with esmvaltool.diag_scripts.shared.run_diagnostic() as config: CompareSalinity(config).compute() if __name__ == "__main__": main()
python
18
0.569027
78
37.988636
264
starcoderdata
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class VendorController extends CI_Controller { public function __construct() { parent::__construct(); $model = array('ProdukModel','CrudModel'); $helper = array('nominal'); $this->load->model($model); $this->load->helper($helper); } public function index() { $data = array( 'title' => 'Data vendor | Wedding Organizer', 'page_title' => 'Data vendor', 'icon_title' => 'fa-group', 'vendor' => $this->CrudModel->view_data('tb_vendor','vendor_date_created'), ); $this->load->view('backend/templates/header', $data); $this->load->view('backend/vendor/index',$data); $this->load->view('backend/templates/footer'); } public function tambah() { $nama = $this->input->post('nama'); $nope = $this->input->post('nope'); $alamat = $this->input->post('alamat'); $username = $this->input->post('username'); $password = $this->input->post('password'); $data = array( 'vendor_nama' => $nama, 'vendor_nope' => $nope, 'vendor_alamat' => $alamat, 'vendor_username' => $username, 'vendor_password' => ); $simpan = $this->CrudModel->insert('tb_vendor',$data); if ($simpan > 0){ $this->session->set_flashdata('alert', 'success_post'); redirect('admin/vendor'); } else { $this->session->set_flashdata('alert', 'fail_edit'); redirect('admin/vendor'); } } public function hapus($id){ $hapus = $this->CrudModel->delete('vendor_id',$id,'tb_vendor'); if ($hapus > 0){ $this->session->set_flashdata('alert', 'success_delete'); redirect('admin/vendor'); }else{ redirect('admin/vendor'); } } }
php
13
0.602326
78
23.571429
70
starcoderdata
const Discord = require('discord.js'); module.exports = { name: 'lfg-help', description: 'Show the Help Page', async execute(msg, args, lang, myGuildLang, embedError) { if(args[1]) { return msg.channel.send(embedError); } const embed = new Discord.RichEmbed() .attachFiles(['./ICON/logo_lfg.png']) .setAuthor(` Help msg.author.avatarURL) .setDescription( lang("help", myGuildLang) ) .setThumbnail('attachment://logo_lfg.png') return msg.channel.send(embed) } }
javascript
18
0.565724
64
29.631579
19
starcoderdata
/** * Base class for processes * * @namespace GIScene * @class Process * @constructor * @param {Object} config * * @author mcauer https://github.com/mcauer */ GIScene.Process = function(config){ var defaults = { identifier : null, title : null, abstract : null, metadata : null, processVersion : null, description : { inputs:[], outputs:[] } }; this.config = GIScene.Utils.mergeObjects(defaults, config || {}); this.identifier = this.config.identifier; this.title = this.config.title; this.abstract = this.config.abstract; this.metadata = this.config.metadata; this.processVersion = this.config.processVersion; this.description = this.config.description; this.data = { inputs:{}, outputs:{} }; }; GIScene.Process.prototype = { constructor : GIScene.Process, /** * Method to set a specific input parameter * * @method setInput * @param {String} inputIdentifier the inputIdentifier defined in the process description * @param {Mixed} value the value of the input to be set */ setInput : function(inputIdentifier, value) { this.data.inputs[inputIdentifier] = value; }, /** * Method to set several inputs at a time * * @method setInputs * @param {Object} inputParams An object with key:value pairs of input parameters, where key corresponds to the inputIdentifiers defined in the process description */ setInputs : function(inputParams) { for(param in inputParams){ this.setInput(param, inputParams[param]); } }, /** * Method to get a specific output result after process execution * * @method getOutput * @param {Object} outputIdentifier * @return {Mixed} an output value of the process */ getOutput : function(outputIdentifier){ return this.data.outputs[outputIdentifier]; }, /** * Method to get all process outputs after process execution * * @method getOutputs * @return {Object} An object containing all process outputs */ getOutputs : function(){ return this.data.outputs; }, /** * Get a param desription (input or ouput) by its identifier * * @method getParamDescriptionById * @param {String} identifier * @return {Object} parameterDescription */ getParamDescriptionById : function(identifier) { var inputs = this.description.inputs; var outputs = this.description.outputs; var params = inputs.concat(outputs); var parameterDescription = params.filter(function(e,i,a){return e.identifier == identifier;}); parameterDescription = (parameterDescription.length == 0)? undefined : parameterDescription[0]; return parameterDescription; }, //Provide EventDispatcher Functions addEventListener : THREE.EventDispatcher.prototype.addEventListener, hasEventListener : THREE.EventDispatcher.prototype.hasEventListener, removeEventListener : THREE.EventDispatcher.prototype.removeEventListener, dispatchEvent : THREE.EventDispatcher.prototype.dispatchEvent };
javascript
16
0.705726
165
24.041667
120
starcoderdata
// #pragma GCC optimize("Ofast,no-stack-protector")// //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") //#pragma GCC optimize("unroll-loops") //#pragma GCC optimize("fast-math") #include<bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using ull = unsigned long long; #define F first #define S second #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(), v.rend() #define int long long void accell() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); } const int N = 70; vector<int> g[N]; int color[N]; int s[N]; int p[N]; int d[N]; int rs = 0; void dfs(int v, int par = -1) { p[v] = par; for (auto to : g[v]) { if (to != par) { d[to] = d[v] + 1; dfs(to, v); s[v] += s[to]; if (s[to] != 0) rs++; } } } int get_lca(int a, int b) { if (d[a] < d[b]) swap(a, b); while (d[a] > d[b]) a = p[a]; if (a == b) return a; while (a != b) { a = p[a], b = p[b]; } return a; } int lca[N]; signed main() { accell(); #ifdef LOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; cin >> n; for (int i = 0; i + 1 < n; ++i) { int a, b; cin >> a >> b; --a, --b; g[a].push_back(b); g[b].push_back(a); } dfs(0); int m; cin >> m; vector<pair<int, int> > bx(m); for (int i = 0; i < m; ++i) { int a, b; cin >> a >> b; --a, --b; lca[i] = get_lca(a, b); // cout << lca[i] << endl; bx[i] = {a, b}; if (d[a] < d[b]) swap(bx[i].F, bx[i].S); } int res = 0; for (int i = 1; i < (1 << m); ++i) { fill(s, s + N, 0); rs = 0; for (int j = 0; j < m; ++j) { if ((1 << j) & i) { // cout << j << ' ' << lca[j] << ' '; if (bx[j].S == lca[j]) { s[bx[j].S]--; s[bx[j].F]++; } else { s[lca[j]] -= 2; s[bx[j].F]++; s[bx[j].S]++; } } } dfs(0); int x = __builtin_popcount(i); // cout << " " << i << ' ' << x << ' ' << rs << endl; if (x & 1) res += (1LL << (n - 1 - rs)); else res -= (1LL << (n - 1 - rs)); } // cout << res << endl; cout << (1LL << (n - 1)) - res << '\n'; return 0; }
c++
19
0.380806
84
22.053097
113
codenet
public void jsFunction_include(final Scriptable scope, String scriptName) throws Exception { final Context cx = Context.getCurrentContext(); if (scriptName.charAt(0) != '/') { // relative script name -- resolve it against currently executing // script's directory String pathPrefix = currentScriptDirectory; while (scriptName.startsWith("../")) { final int lastSlash = pathPrefix.lastIndexOf('/'); if (lastSlash == -1) { throw new FileNotFoundException("script:" + currentScriptDirectory + '/' + scriptName); } scriptName = scriptName.substring(3); pathPrefix = pathPrefix.substring(0, lastSlash); } scriptName = pathPrefix + '/' + scriptName; } else { // strip off leading slash scriptName = scriptName.substring(1); } final Script script = scriptStorage.getScript(scriptName); if (script == null) { throw new FileNotFoundException("script:" + scriptName); } try { final String oldScriptDirectory = currentScriptDirectory; currentScriptDirectory = getDirectoryForScript(scriptName); try { script.exec(cx, scope); } finally { currentScriptDirectory = oldScriptDirectory; } } finally { } }
java
16
0.546844
107
42.323529
34
inline
const log = require('@hkube/logger').GetLogFromContainer(); const init = async () => { log.throttle.info('In output init'); }; const start = async (options) => { log.debug('In output start'); return options.input; }; const stop = async () => { log.info('In output stop'); }; module.exports = { start, stop, init };
javascript
9
0.595376
59
17.210526
19
starcoderdata
import React from 'react'; import { shallow } from 'enzyme'; import TokenTable from './TokenTable'; it('renders without crashing', () => { const tokenData = [ { symbol: 'EOS', balance: '10.0000', allowed: true }, { symbol: 'ZRX', balance: '1.00000', allowed: false }, { symbol: 'EOS', balance: '5.00000', allowed: false }, { symbol: 'EOS', balance: '8.00000', allowed: true }, ]; const quoteTokens = ['WETH'] const baseTokens = ['ZRX', 'EOS'] shallow(<TokenTable baseTokens={baseTokens} quoteTokens={quoteTokens} tokenData={tokenData} />); });
javascript
12
0.631304
98
32.823529
17
starcoderdata
export default { state: { currentVideo: { actor: '', area: '', des: '', director: '', dl: '', id: '', lang: '', last: '', name: '', note: '', pic: '', state: '', tid: '', type: '', year: '', }, }, mutations: { setCurrentVideo(state, currentVideo) { state.currentVideo = currentVideo; }, }, };
javascript
10
0.41704
42
15.518519
27
starcoderdata
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Carbon\Carbon; class Quote extends Model { use SoftDeletes; public $timestamps=true; //to allow auto updation of created_at & updated_at protected $fillable=['type', 'quote', 'author']; protected $dates=['deleted_at']; public function transform($data) { $quotes=[]; foreach($data as $item) { $modified=new Carbon($item->updated_at); $end=($item->end_date==null) ? null : new Carbon($item->end_date); array_push($quotes, [ 'id'=>$item->id, 'type'=>$item->type, 'quote'=>$item->quote, 'author'=>$item->author, 'lastmodified'=>$modified->toFormattedDateString() ]); } return $batches; } } ?>
php
15
0.556614
80
25.277778
36
starcoderdata
void GripperFirmwareVersion::getYouBotMailboxMsg(YouBotSlaveMailboxMsg& message) const { // Bouml preserved body begin 000BED71 message.stctOutput.commandNumber = FIRMWARE_VERSION; message.stctOutput.moduleAddress = GRIPPER; message.stctOutput.typeNumber = 0; //GripperFirmwareVersion message.stctOutput.motorNumber = 0; message.stctOutput.value = 0; // Bouml preserved body end 000BED71 }
c++
7
0.777778
88
45.111111
9
inline
var http = require ( 'http' ), https = require ( 'https' ), os = require ( 'os' ), util = require ( 'util' ), url = require ( 'url' ); function error ( res, err ) { res.writeHead ( 500, { 'Content-Type': 'text/plain; charset=UTF-8' } ); res.end ( err ? err.stack || "" + err : "Error" ); } function handleHeaders ( httpResponse, responseHeaders, requestToProxy ) { responseHeaders['Pragma'] = 'no-cache'; responseHeaders['Cache-Control'] = 'no-cache, no-store'; responseHeaders['Server'] = 'Proxy for ' + httpResponse.headers['server']; responseHeaders['Expires'] = 'Tue, 2 Jan 1990, 00:00:00 GMT'; } exports.handleHeaders = handleHeaders; // ProxyServer (class) // =========== // Creates a new proxy server. Pass it // // * A configuration, which might be a parsed URL (host, port properties) // * A location converter, which takes ``Location:`` headers and transforms them (may be null) // * A header converter which builds the headers for the response exports.ProxyServer = function ( proxyConfig, convertLocation, headerConverter ) { var requestNumber = 0; if (!proxyConfig.protocol) { proxyConfig.protocol = 'http'; } if (!proxyConfig.port) { proxyConfig.port = proxyConfig.protocol === 'https' ? 443 : 80; } if (!proxyConfig.methods) { proxyConfig.methods = ['get', 'head', 'post', 'put', 'delete', 'options']; } if (!proxyConfig.host) { proxyConfig.host = 'localhost'; } if (!convertLocation) { convertLocation = function ( meth, pth ) { return pth; } } if (!headerConverter) { headerConverter = handleHeaders; } console.log ( "Proxy config: " + util.inspect ( proxyConfig ) ); if (!proxyConfig.paths) { proxyConfig.paths = [/\/.*/]; } // determines if this proxy server will service a request method/url this.accept = function ( meth, u ) { var uu = url.parse ( u ); if (!uu.host || uu.host === proxyConfig.host) { if (!uu.protocol) { uu.protocol = 'http'; } if (/.*?:$/.test ( uu.protocol )) { uu.protocol = /(.*?):$/.exec ( uu.protocol )[1]; } if (uu.protocol !== ( proxyConfig.protocol || 'http' )) { return false; } if (!uu.port) { switch (uu.protocol) { case 'http' : uu.port = 80; break; case 'https' : uu.port = 443; } } if (uu.host === proxyConfig.host && uu.port === proxyConfig.port) { var result = proxyConfig.protocol + '://' + os.hostname () + ":" + proxyConfig.proxyPort + uu.path; return result; } } return false; } // proxies a request. this.req is the request, this.res is the response function proxy () { // Just proxies calls to jobserver, to avoid same-origin security issues var self = this; // Parse the URL and replace host/port/etc var u = url.parse ( self.req.url ); u.host = proxyConfig.host; u.hostname = proxyConfig.host; u.port = proxyConfig.port; u.method = self.req.method; u.headers = self.req.headers; u.href = self.req.url; if (self.req.auth) { u.auth = self.req.auth; } var protocol = !proxyConfig.protocol ? http : proxyConfig.protocol === 'https' ? https : http; var num = requestNumber++; var closed = false; var proxyRequest = protocol.request ( u, function ( res ) { var hdrs = {} headerConverter ( res, hdrs, self.req ); for (var key in res.headers) { if (key.toLowerCase () === 'location') { var val = res.headers[key]; var nue = convertLocation ( self.req.method, val ); if (nue) { hdrs[capitalize ( key )] = nue; } else { hdrs[capitalize ( key )] = val; } } else { // XXX this will fail on duplicate headers if (typeof hdrs[capitalize ( key )] === 'undefined') { hdrs[capitalize ( key )] = res.headers[key]; } } } hdrs['Host'] = os.hostname (); console.log ( num + ': ' + res.statusCode + " " + self.req.method + " " + self.req.url ); self.res.writeHead ( res.statusCode, hdrs ); res.pipe ( self.res ); res.on ( 'end', function () { if (res.trailers) { self.res.addTrailers ( res.trailers ); } self.res.end (); closed = true; } ); proxyRequest.on ( 'close', function () { self.res.end (); closed = true; } ) } ); proxyRequest.on ( 'error', function ( e ) { closed = true; error ( self.res, e ); } ); if (self.req.method.toLowerCase () === 'put' || self.req.method.toLowerCase () === 'post') { var outChunks = 1; self.req.on ( 'data', function ( data ) { proxyRequest.write ( data ); } ); self.req.on ( 'end', function () { proxyRequest.end (); } ); if (proxyRequest.readable) { proxyRequest.resume (); } else { proxyRequest.end (); } } else { proxyRequest.end (); } } this.dispatch = proxy; }; // Re-capitalizes downcased header names, so they're copied into the // response sanely function capitalize ( name ) { var x = /-/g; if (x.test ( name )) { var parts = name.split ( x ); var result = []; for (var i = 0; i < parts.length; i++) { var part = parts[i]; part = part.charAt ( 0 ).toUpperCase () + part.slice ( 1 ); result.push ( part ); } return result.join ( '-' ); } else { return name.charAt ( 0 ).toUpperCase () + name.slice ( 1 ); } } exports.capitalize = capitalize;
javascript
15
0.486611
115
33.946524
187
starcoderdata
static void* threadSorter (void *arg) { Region* region = (Region*) arg; int *x, *y; int *left = region->left; int *right = region->right; int i, swapped; while (1) { x = left; while (x <= right) { y = x; while (y > left && *(y-1) > *y) { swap(y-1, y); y--; } x++; } /* Barrier processing */ pthread_mutex_lock(&barrier.lock); barrier.counter--; if (barrier.counter == 0) { // The last thread reaching the barrier swaps the borders swapped = 0; for (i=1; i<nthreads; i++) { if (*(paddr + (i*len) - 1) > *(paddr + (i*len))) { // Swap borders swap(paddr + (i*len) - 1, paddr + (i*len)); swapped = 1; } } if (swapped) { // Since there was a swap, sort again the region for (i=0; i<nthreads; i++) { sem_post(&barrier.sa); } } else { x = paddr; i = 0; while (x<paddr+n) { fprintf(stdout, "%i : %i\n", i, *x); x++; i++; } exit(0); } } pthread_mutex_unlock(&barrier.lock); sem_wait(&barrier.sa); pthread_mutex_lock(&barrier.lock); barrier.counter++; if (barrier.counter == nthreads) { for (i=0; i<nthreads; i++) { sem_post(&barrier.sb); } } pthread_mutex_unlock(&barrier.lock); sem_wait(&barrier.sb); } return arg; }
c
18
0.493061
60
19.092308
65
inline
private object CreateInstance(Type type) { if (!_cachedDefaultConstructor.ContainsKey(type)) { // Find first constructor without parameters... ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); ConstructorInfo constructor = null; foreach (ConstructorInfo info in constructors) { if(info.GetParameters().Length == 0) { constructor = info; break; } } if (constructor != null) { ConstructorInfoCache constructorInfoCache = new ConstructorInfoCache(constructor, GetParameterInfoCache(constructor.GetParameters())); _cachedDefaultConstructor.Add(type, constructorInfoCache); } else { _cachedDefaultConstructor.Add(type, null); } } if (_cachedDefaultConstructor[type] != null) { return _cachedDefaultConstructor[type].ConstructorInfo.Invoke(null); } return Activator.CreateInstance(type); }
c#
20
0.512323
154
36.222222
36
inline
#include<iostream> #include<algorithm> #include<vector> #include<cstring> using namespace std; const int MAX=100; class edge { public: int src,tar,w; edge(int src=0,int tar=0,int w=0):src(src),tar(tar),w(w){} }; int n; vector<edge> G[MAX]; int cost; vector<edge> GG[MAX];//reverse edge int num[MAX],pre[MAX],mcost[MAX];//number, prev of vertex, edges min cost bool mark[MAX];//vertex used flag vector<int> comp[MAX];//compressed vertex vector<int> nex[MAX];//next of vertex void cycle(int v,int s,int r,bool &found) { if(mark[v]) { int temp[MAX]; for(int i=0;i<n;i++)temp[i]=num[i]; found=true; do { cost+=mcost[v]; v=pre[v]; if(v!=s) { while(!comp[v].empty()) { num[comp[v].back()]=s; comp[s].push_back(comp[v].back()); comp[v].pop_back(); } } }while(v!=s); for(int i=0;i<comp[s].size();i++) { int j=comp[s][i]; if(j!=r) { for(int k=0;k<GG[j].size();k++) { if(num[GG[j][k].src]!=s) { GG[j][k].w-=mcost[temp[j]]; } } } } } mark[v]=true; for(int k=0;k<nex[v].size();k++) { int i=nex[v][k]; if(num[i]!=num[v]&&pre[num[i]]==v) { if(!mark[num[i]]||i==s) { cycle(i,s,r,found); } } } return; } int mincosttree(int r) { for(int i=0;i<n;i++) { for(int j=0;j<G[i].size();j++) { GG[G[i][j].tar].push_back(G[i][j]); } } for(int i=0;i<n;i++) { num[i]=i; comp[i].push_back(i); } cost=0; while(1) { for(int i=0;i<n;i++) { pre[i]=-1; mcost[i]=1<<28; } for(int j=0;j<n;j++) { if(j==r)continue; for(int k=0;k<GG[j].size();k++) { int i=GG[j][k].src; if(num[i]!=num[j]) { if(GG[j][k].w<mcost[num[j]]) { mcost[num[j]]=GG[j][k].w; pre[num[j]]=num[i]; } } } } for(int i=0;i<n;i++) { if(pre[i]>=0) { nex[pre[i]].push_back(i); } } bool stop=true; for(int i=0;i<n;i++)mark[i]=false; for(int i=0;i<n;i++) { if(i==r||mark[i]||comp[i].empty())continue; bool found=false; cycle(i,i,r,found); if(found)stop=false; } if(stop) { for(int i=0;i<n;i++) { if(pre[i]>=0) { cost+=mcost[i]; } } return cost; } } } int main() { int e,r;cin>>n>>e>>r; int s,t,w; for(int i=0;i<e;i++) { cin>>s>>t>>w; G[s].push_back(edge(s,t,w)); } cout<<mincosttree(r)<<endl; return 0; }
c++
20
0.49537
73
13.406061
165
codenet
<html lang="en"> <meta charset="UTF-8"> <meta name="description" content=""> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- The above 4 meta tags *must* come first in the head; any other head content must come *after* these tags --> <!-- Favicon --> <link rel="icon" href="<?php echo base_url().'assets/image/logo_malang.png';?>"> <!-- Core Stylesheet --> <link rel="stylesheet" href="<?php echo base_url().'assets/User/style.css';?>"> <?php $this->load->view('User/Template/navbar')?> <!-- ##### Hero Area Start ##### --> <section class="hero-area"> <div class="hero-post-slides owl-carousel"> <!-- Single Hero Post --> <div class="single-hero-post bg-overlay"> <!-- Post Image --> <div class="slide-img bg-img" style="background-image: url(<?php echo base_url().'assets/User/img/bg-img/1.jpg';?>);"> <div class="container h-100"> <div class="row h-100 align-items-center"> <div class="col-12"> <!-- Post Content --> <div class="hero-slides-content text-center"> Lingkungan Agar tetap Sejuk Lupa yaa :) <!-- <div class="welcome-btn-group"> <a href="#" class="btn alazea-btn mr-30">GET STARTED <a href="#" class="btn alazea-btn active">CONTACT US --> <!-- Single Hero Post --> <div class="single-hero-post bg-overlay"> <!-- Post Image --> <div class="slide-img bg-img" style="background-image: url(<?php echo base_url().'assets/User/img/bg-img/2.jpg';?>);"> <div class="container h-100"> <div class="row h-100 align-items-center"> <div class="col-12"> <!-- Post Content --> <div class="hero-slides-content text-center"> bumi kita! pembuangan sampah <!-- <div class="welcome-btn-group"> <a href="#" class="btn alazea-btn mr-30">GET STARTED <a href="#" class="btn alazea-btn active">CONTACT US --> <!-- ##### Hero Area End ##### --> <!-- ##### Service Area Start ##### --> <section class="our-services-area bg-gray section-padding-100-0"> <div class="container"> <div class="row"> <div class="col-12"> <!-- Section Heading --> <div class="section-heading text-center"> Yang Kita Gunakan Reuse , Recycle <div class="row justify-content-between"> <div class="col-12 col-lg-5"> <div class="alazea-service-area mb-100"> <!-- Single Service Area --> <div class="single-service-area d-flex align-items-center wow fadeInUp" data-wow-delay="100ms"> <!-- Icon --> <div class="service-icon mr-30"> <img src="<?php echo base_url().'assets/User/img/bg-img/reduce_b.png';?>" alt=""> <!-- Content --> <div class="service-content"> berarti kita mengurangi penggunaan bahan-bahan yang bisa merusak lingkungan. <!-- Single Service Area --> <div class="single-service-area d-flex align-items-center wow fadeInUp" data-wow-delay="300ms"> <!-- Icon --> <div class="service-icon mr-30"> <img src="<?php echo base_url().'assets/User/img/bg-img/reuse_b.png';?>" alt=""> <!-- Content --> <div class="service-content"> sendiri berarti pemakaian kembali seperti contohnya memberikan baju-baju bekas anda ke yatim piatu. <!-- Single Service Area --> <div class="single-service-area d-flex align-items-center wow fadeInUp" data-wow-delay="500ms"> <!-- Icon --> <div class="service-icon mr-30"> <img src="<?php echo base_url().'assets/User/img/bg-img/recycle_b.png';?>" alt=""> <!-- Content --> <div class="service-content"> adalah mendaur ulang barang. Paling mudah adalah mendaur ulang sampah organik di rumah anda <div class="col-12 col-lg-6"> <div class="alazea-video-area mb-100"> <img src="<?php echo base_url().'assets/User/img/bg-img/b_3r.jpg';?>" alt="3R"> <!-- ##### Service Area End ##### --> <!-- ##### Team Area Start ##### --> <section class="team-area section-padding-100-0"> <div class="container"> <div class="row"> <div class="col-12"> <!-- Section Heading --> <div class="section-heading text-center"> Bank Sampah Informatika class 2B <div class="row"> <!-- Single Team Member Area --> <div class="col-10 col-sm-16 col-lg-4"> <div class="single-team-member text-center mb-100"> <!-- Team Member Thumb --> <div class="team-member-thumb"> <img src="<?php echo base_url().'assets/image/p_winandri.jpeg';?>" style="width:600px; height:400px;" alt=""> <!-- Social Info --> <div class="team-member-social-info"> <a href="#"><i class="fa fa-facebook" aria-hidden="true"> <a href="#"><i class="fa fa-twitter" aria-hidden="true"> <a href="#"><i class="fa fa-instagram" aria-hidden="true"> <!-- Team Member Info --> <div class="team-member-info mt-30"> <!-- Single Team Member Area --> <div class="col-10 col-sm-16 col-lg-4"> <div class="single-team-member text-center mb-100"> <!-- Team Member Thumb --> <div class="team-member-thumb"> <img src="<?php echo base_url().'assets/image/p_adi.jpg';?>" style="width:600px; height:400px;" alt=""> <!-- Social Info --> <div class="team-member-social-info"> <a href="#"><i class="fa fa-facebook" aria-hidden="true"> <a href="#"><i class="fa fa-twitter" aria-hidden="true"> <a href="#"><i class="fa fa-instagram" aria-hidden="true"> <!-- Team Member Info --> <div class="team-member-info mt-30"> <!-- Single Team Member Area --> <div class="col-10 col-sm-16 col-lg-4"> <div class="single-team-member text-center mb-100"> <!-- Team Member Thumb --> <div class="team-member-thumb"> <img src="<?php echo base_url().'assets/image/p_yoga.jpeg';?>" style="width:600px; height:400px;" alt=""> <!-- Social Info --> <div class="team-member-social-info"> <a href="#"><i class="fa fa-facebook" aria-hidden="true"> <a href="#"><i class="fa fa-twitter" aria-hidden="true"> <a href="#"><i class="fa fa-instagram" aria-hidden="true"> <!-- Team Member Info --> <div class="team-member-info mt-30"> <!-- ##### Team Area End ##### --> <!-- ##### Contact Area Info Start ##### --> <div class="contact-area-info section-padding-0-100"> <div class="container"> <div class="row align-items-center justify-content-between"> <!-- Contact Thumbnail --> <div class="col-12 col-md-20"> <div class="contact--thumbnail-center"> <div class="map-area mb-100"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d31610.312102111984!2d112.6049275578226!3d-7.969054332657968!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x2e7882a9d385ba91%3A0x667db69be1ab50c9!2sBank%20Sampah%20Malang!5e0!3m2!1sen!2sid!4v1586118135626!5m2!1sen!2sid" allowfullscreen="" > <!-- ##### Contact Area Info End ##### --> <?php $this->load->view('User/Template/footer')?> <!-- ##### All Javascript Files ##### --> <!-- jQuery-2.2.4 js --> <script src="<?php echo base_url().'assets/User/js/jquery/jquery-2.2.4.min.js ';?>"> <!-- Popper js --> <script src="<?php echo base_url().'assets/User/js/bootstrap/popper.min.js';?>"> <!-- Bootstrap js --> <script src="<?php echo base_url().'assets/User/js/bootstrap/bootstrap.min.js';?>"> <!-- All Plugins js --> <script src="<?php echo base_url().'assets/User/js/plugins/plugins.js';?>"> <!-- Active js --> <script src="<?php echo base_url().'assets/User/js/active.js';?>">
php
6
0.40213
344
49.907631
249
starcoderdata
#include<bits/stdc++.h> #define rep(i,n)for(int i=0;i<n;i++) using namespace std; int k[101]; char s[101]; int main() { vector<char>v; for (char c = 'a'; c <= 'z'; c++)v.push_back(c); for (char c = 'A'; c <= 'Z'; c++)v.push_back(c); int n; while (scanf("%d", &n), n) { rep(i, n)scanf("%d", &k[i]); scanf("%s", s); int len = strlen(s); rep(i, len) { s[i] = v[(find(v.begin(), v.end(), s[i]) - v.begin() + 52 - k[i%n]) % 52]; } puts(s); } }
c++
20
0.491304
77
20.952381
21
codenet
func processDeletedFiles(cmt *GitCommit, snippets map[string]*Snippet, deletedFilesInThisCommit map[string]bool, seenSnippets map[string]map[string]bool) map[string]*Snippet { log.Debugf("Processing commit: %v, Number of files deleted: %v", cmt.Hash, len(deletedFilesInThisCommit)) // Add all delete records for delFile := range deletedFilesInThisCommit { log.Debugf("Processing commit: %v. Ranging over deletedFilesInThisCommit", cmt.Hash) for seenFile, seenSnps := range seenSnippets { if delFile != seenFile { continue } log.Debugf("Processing commit: %v. File %v was deleted", cmt.Hash, delFile) for seenSnippet, seen := range seenSnps { if !seen { continue } log.Debugf("Processing commit: %v File: %v was deleted. Adding a delete record for Snippet: %v", cmt.Hash, delFile, seenSnippet) if _, ok := snippets[seenSnippet]; !ok { log.Warnf("Processing commit: %v Processing Deletes. Snippet %v was seen, but is not in our snippets collection", cmt.Hash, seenSnippet) continue } seenSnps[seenSnippet] = false // Insert an "empty" snippet version for this nFile := File{ FilePath: delFile, GitCommit: cmt, Size: 0, } snippets[seenSnippet].Versions = append(snippets[seenSnippet].Versions, SnippetVersion{ Name: fmt.Sprintf("%v/%v", seenSnippet, len(snippets[seenSnippet].Versions)), File: &nFile, Lines: make([]string, 0), Content: "", }) snippets[seenSnippet].Primary = SnippetVersion{ Name: snippets[seenSnippet].Versions[len(snippets[seenSnippet].Versions)-1].Name, File: snippets[seenSnippet].Versions[len(snippets[seenSnippet].Versions)-1].File, Lines: make([]string, 0), Content: "", } } } } return snippets }
go
23
0.677778
141
33.634615
52
inline
#include <iostream> #include <string> #include <vector> using std::cin; using std::cout; using std::string; int main(int argc, char* argv[]) { std::vector<string> ws = {"Sunny", "Cloudy", "Rainy"}; std::string w; cin >> w; for (int i = 0; i < 3; ++i) { if (w == ws[i]) { cout << ws[(i + 1) % 3]; return 0; } } return 0; }
c++
14
0.525281
56
16.8
20
codenet
<?php namespace Database\Seeders; use App\Models\User; use Illuminate\Database\Seeder; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; use Spatie\Permission\PermissionRegistrar; class RolesAndPermissionsSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Reset cached roles and permissions app()[PermissionRegistrar::class]->forgetCachedPermissions(); Permission::query()->firstOrCreate(['name' => 'view user']); Permission::query()->firstOrCreate(['name' => 'edit user']); Permission::query()->firstOrCreate(['name' => 'update user']); Permission::query()->firstOrCreate(['name' => 'delete user']); $role = Role::query()->firstOrCreate(['name' => 'user']); $role->givePermissionTo('view user'); $role->givePermissionTo('edit user'); $role->givePermissionTo('update user'); $role->givePermissionTo('delete user'); // create demo users $user = User::factory()->create(); $user->assignRole($role); } }
php
13
0.63302
70
28.225
40
starcoderdata
from flask import Flask from config.config import config from app.core.configure import init def create_app(mode='production'): app = Flask(__name__) app.config.from_object(config[mode]) init(app) return app
python
7
0.71875
40
24
9
starcoderdata
int main(){ cl_int status; /**Step 1: Getting platforms and choose an available one(first).*/ cl_platform_id platform; getPlatform(platform); /**Step 2:Query the platform and choose the first GPU device if has one.*/ cl_device_id *devices = getCl_device_id(platform); /**Step 3: Create context.*/ cl_context context = clCreateContext(NULL,1, devices,NULL,NULL,NULL); /**Step 4: Creating command queue associate with the context.*/ cl_command_queue commandQueue = clCreateCommandQueue(context, devices[0], 0, &status); /**Step 5: Create program object */ const char *filename = "HelloWorld_Kernel.cl"; string sourceStr; status = convertToString(filename, sourceStr); const char *source = sourceStr.c_str(); size_t sourceSize[] = {strlen(source)}; cl_program program = clCreateProgramWithSource(context, 1, &source, sourceSize, NULL); status=clBuildProgram(program, 0, 0, 0, 0, 0); /**Step 7: Initial input,output for the host and create memory objects for the kernel*/ const int NUM = 100000; float* input = new float[NUM]; for(int i = 0;i < NUM;i++) input[i] = float(random()); float* output = new float[NUM]; cl_mem inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, (NUM) * sizeof(float), (void *) input, NULL); cl_mem outputBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY , NUM * sizeof(float), NULL, NULL); /**Step 8: Create kernel object */ cl_kernel kernel = clCreateKernel(program,"helloworld", NULL); auto time0 = time(); /**Step 9: Sets Kernel arguments.*/ status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputBuffer); status = clSetKernelArg(kernel, 1, sizeof(cl_mem), &outputBuffer); /**Step 10: Running the kernel.*/ size_t global_work_size[1] = {NUM}; cl_event enentPoint; status = clEnqueueNDRangeKernel(commandQueue, kernel, 1, NULL, global_work_size, NULL, 0, NULL, &enentPoint); SAMPLE_CHECK_ERRORS(status); clWaitForEvents(1,&enentPoint); ///wait clReleaseEvent(enentPoint); /**Step 11: Read the cout put back to host memory.*/ status = clEnqueueReadBuffer(commandQueue, outputBuffer, CL_TRUE, 0, NUM * sizeof(float), output, 0, NULL, NULL); auto time1 = time(); auto time_use = time_diff(time0, time1); std::cout << " time cost: " << time_use << std::endl; // for (int i = 0; i < NUM; i++) // cout << output[i] << endl; /**Step 12: Clean the resources.*/ status = clReleaseKernel(kernel);//*Release kernel. status = clReleaseProgram(program); //Release the program object. status = clReleaseMemObject(inputBuffer);//Release mem object. status = clReleaseMemObject(outputBuffer); status = clReleaseCommandQueue(commandQueue);//Release Command queue. status = clReleaseContext(context);//Release context. SAMPLE_CHECK_ERRORS(status); if (output != NULL) { free(output); output = NULL; } if (devices != NULL) { free(devices); devices = NULL; } return 0; }
c++
10
0.655584
133
43.271429
70
inline
#include <iostream> #include <vector> const int MAX_N = 100000; std::vector<int> list; bool IsPrime(int n){ for(int i=0; i<list.size(); ++i){ if(n%list[i]==0) return false; } list.push_back(n); return true; } bool IsPrime2(int n){ for(int i=0; i<list.size(); ++i){ if(n==list[i]) return true; } return false; } int main(){ int Q; std::cin >> Q; int l[Q], r[Q]; for(int i=0; i<Q; ++i) std::cin >> l[i] >> r[i]; int x[MAX_N+1]; x[0] = 0; x[1] = 0; for(int i=2; i<=MAX_N; ++i){ if(IsPrime(i) && IsPrime2((i+1)/2)){ x[i] = x[i-1] + 1; }else{ x[i] = x[i-1]; } } for(int i=0; i<Q; ++i){ std::cout << x[r[i]]-x[l[i]-1] << std::endl; } return 0; }
c++
14
0.400685
125
18.931818
44
codenet
package com.sparrow.supports.message; import java.io.File; /** * Created by IntelliJ IDEA. * User: YZC * Date: 12-12-5 * Time: 上午9:57 * To change this template use File | Settings | File Templates. */ public class UserMessage { String site; String siteName; String author; String authorCode; String from; String mailTo; String carbonCopy; String message; String phone; String errMsg; String subject; String title; String timestamp; String detailHref; File files[]; public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getDetailHref() { return detailHref; } public void setDetailHref(String detailHref) { this.detailHref = detailHref; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getAuthorCode() { return authorCode; } public void setAuthorCode(String authorCode) { this.authorCode = authorCode; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getCarbonCopy() { return carbonCopy; } public void setCarbonCopy(String carbonCopy) { this.carbonCopy = carbonCopy; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getMailTo() { return mailTo; } public void setMailTo(String mailTo) { this.mailTo = mailTo; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public File[] getFiles() { return files; } public void setFiles(File[] files) { this.files = files; } }
java
8
0.593023
64
17.469799
149
starcoderdata
var express = require('express'); var app = express(); var mysql = require('mysql'); var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: 'crawl' }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); // let sql = 'select * from lotos'; // let sql = 'insert into lotos (date,focus,full_data) values (10-10-2010,cuchuoi,cuchuoi1)'; }); app.use(express.static('public')); app.set('view engine','ejs'); app.set('views','./views'); app.listen(3000); var request = require('request'); var cheerio = require('cheerio'); function reverse(x) { if (x < 0) return -reverse(-x); // reverse(-123) === -reverse(123) var str = x.toString(); // "123" var strArray = str.split(""); // [ "1", "2", "3" ] var revArray = strArray.reverse(); // [ "3", "2", "1" ] var rev = revArray.join(""); // "321" return rev; } app.get('/test',function(req,res){ //test?month=10&year=2010 console.log(req.query.month,req.query.year); const month = req.query.month; const year = req.query.year; for (let index = 1; index <= 31; index++) { let url = "https://ketqua.net/xo-so-truyen-thong.php?ngay="+index+'-'+month+'-'+year; //https://ketqua.net/xo-so-truyen-thong.php?ngay=17-07-2020 request(url,function(err,resp,body){ if(err){ console.log(err); }else{ $ = cheerio.load(body); var ds = $(body).find('td.phoi-size.chu22'); let arr_focus = []; let arr_full = []; ds.each(function(i,e){ // console.log($(this).text()); let aaa = $(this).text(); aaa = reverse(aaa); const bbb = aaa[1]+aaa[0]; arr_full.push(Number(bbb)); if(i>22){ arr_focus.push(Number(bbb)); } }) const date = year+'-'+month+'-'+index; const focus = JSON.stringify(arr_focus); const full = JSON.stringify(arr_full); let sql = "INSERT INTO `lotos` (`id`, `date`, `focus`, `all_data`) VALUES (NULL, '"+date+"', '"+focus+"', '"+full+"');"; con.query(sql, function (err, result) { if (err) throw err; console.log("Result: " + result); }); console.log(111,focus); console.log(222,full); console.log(333,sql); } }); } });
javascript
28
0.515415
153
30.6375
80
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Luo.Shared.Helper { public static class Request { public static string HOST => "www.luoo.net"; public static string GetAllVol => $"http://{HOST}/tag/?p="; public static string GetTagVol(string tag) { return $"http://{HOST}/tag/{tag}?p="; } public static string HOST_w => "www.luoow.com"; public static string GetAllVol_w => $"https://{HOST_w}/"; public static string RequestParse(int page) { switch (page) { case 1: return "901_1000.html"; case 2: return "801_900.html"; case 3: return "701_800.html"; case 4: return "601_700.html"; case 5: return "501_600.html"; case 6: return "401_500.html"; case 7: return "301_400.html"; case 8: return "201_300.html"; case 9: return "101_200.html"; case 10: return "1_100.html"; case 11: return "r/"; case 12: return "e/"; default: return "r"; } } public static string GetNumVol_w(string num) { return $"https://{HOST_w}/{num}"; } //example: tag="世界音乐" public static string GetTagVol_w(string tag) { return $"https://{HOST_w}/tag/{tag}"; } public static string GetSongListJson(string songSourceNum) { return $"https://{HOST_w}/ajax?m=163music&c2={songSourceNum}"; } // https://www.luoow.com/ajax?m=163music_item&c2= public static string GetSongUrlById(string songId) { return $"https://{HOST_w}/ajax?m=163music_item&c2={songId}"; } #region Washa public static string WashaHOST => "https://www.waasaa.com/category/luoo"; public static string GetWashaVolUrl(string volNum) { var num = int.Parse(volNum); int pageNum = (int)((1010 - num) / 19 + 1); if (pageNum == 1) { return WashaHOST; } else { return WashaHOST + "/page/" + pageNum; } } #endregion //public static string SearchImages => $"http://{HOST}/search/photos?"; //public static string GetRandomImages => $"http://{HOST}/photos/random?"; //public static string GetCategories => $"http://{HOST}/categories?"; //public static string GetFeaturedImages => $"http://{HOST}/collections/featured?"; //public static string GetImageDetail => $"http://{HOST}/photos/"; //public static string GetTodayWallpaper => "https://juniperphoton.net/myersplash/wallpapers"; //public static string GetTodayThumbWallpaper => "https://juniperphoton.net/myersplash/wallpapers/thumbs"; } }
c#
17
0.503343
114
28.909091
110
starcoderdata
<?php /* (c) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Deployer\Executor; use Deployer\Helper\DeployerHelper; use Deployer\Server\Environment; use Deployer\Server\Local; use Deployer\Task\Task; class SeriesExecutorTest extends \PHPUnit_Framework_TestCase { use DeployerHelper; public function testSeriesExecutor() { $this->initialize(); $mock = $this->getMockBuilder('stdClass') ->setMethods(['task', 'once', 'only']) ->getMock(); $mock->expects($this->exactly(2)) ->method('task'); $mock->expects($this->once()) ->method('once'); $mock->expects($this->once()) ->method('only'); $task = new Task('task', function () use ($mock) { $mock->task(); }); $taskOne = new Task('once', function () use ($mock) { $mock->once(); }); $taskOne->once(); $taskOnly = new Task('only', function () use ($mock) { $mock->only(); }); $taskOnly->onlyOn(['one']); $tasks = [$task, $taskOne, $taskOnly]; $environments = [ 'one' => new Environment(), 'two' => new Environment(), ]; $servers = [ 'one' => new Local(), 'two' => new Local(), ]; $executor = new SeriesExecutor(); $executor->run($tasks, $servers, $environments, $this->input, $this->output); } }
php
15
0.524921
85
24.564516
62
starcoderdata
#include <bits/stdc++.h> using namespace std; int main(void){ // Your code here! long long K,A,B;cin>>K>>A>>B; long long ans=1; if(B-A>2){ ans=A; K-=A-1; ans+=(K/2)*(B-A)+K%2; } else{ ans+=K; } cout<<ans<<endl; }
c++
11
0.451264
33
16.3125
16
codenet
public static void finalizeStats(PlayerDataRPG pd) { // multipliers are applied here and nowhere else pd.maxHPMultiplier /= 100; pd.maxHP += (int) Math.ceil((pd.baseMaxHP + pd.maxHP) * pd.maxHPMultiplier); pd.defenseMultiplier /= 100; pd.defense += (int) Math.ceil(pd.defense * pd.defenseMultiplier); pd.speed /= 100; //+50% speed -> 0.5 pd.speed++; //0.5 -> 1.5 pd.speed *= 0.2; //1.5 -> 0.3 [base player speed is 0.2] if (pd.speed > 1.0) pd.speed = 1.0f; pd.getPlayer().setWalkSpeed(pd.speed); pd.critChance /= 100; pd.critDamage /= 100; pd.spellDamage /= 100; pd.spellDamage++; pd.attackDamage /= 100; pd.attackDamage++; pd.lifesteal /= 100; pd.hpRegen /= 100; pd.hpRegen++; pd.attackSpeed /= 100; //can't do 0 base damage if (pd.damageLow < 1) pd.damageLow = 1; if (pd.damageHigh < 1) pd.damageHigh = 1; }
java
12
0.533398
84
35.928571
28
inline
public void gameTick(ButtonInfo leftPressed, ButtonInfo rightPressed, ButtonInfo downPressed, ButtonInfo okPressed, ButtonInfo backPressed) { if (move(this.currentTetromino, 0, 1, 0)) { } else { // Spawn new tetromino and write the old to the permanent grid drawCurrentTetromino(grid); checkLines(); placeNextTetromino(); if (move(this.currentTetromino, 0, 0, 0) == false) { // Lose this.gameStatus = GameStatus.LOST; playAgain(); } } }
java
11
0.672764
115
28.875
16
inline
/* * Copyright 2017 - 2019 KB Kontrakt LLC - All Rights Reserved. * * 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 auth import ( "crypto/sha256" "crypto/x509" "encoding/hex" "github.com/hyperledger/fabric-chaincode-go/pkg/cid" "github.com/hyperledger/fabric-chaincode-go/shim" ) //go:generate mockgen -source=identity_svc.go -package=auth -destination=identity_svc_mocks.go type ( // AttributeValue defines structure for attributes. AttributeValue struct { Value string IsDefined bool } // IdentityService defines identity of the user/client. IdentityService interface { // ID returns id for group of users/clients MspID() (string, error) // CreatorID returns id for concrete user/client CreatorID() (string, error) // Cert returns user/client cert Cert() (*x509.Certificate, error) // CertID returns issue+subj of concrete user/client cert CertID() (string, error) // GetAttribute returns cert attribute GetAttribute(attrName string) (AttributeValue, error) } identityServiceImpl struct { stub shim.ChaincodeStubInterface clientID cid.ClientIdentity creatorID string } ) func (svc *identityServiceImpl) init() error { if svc.clientID != nil { return nil } var err error svc.clientID, err = cid.New(svc.stub) if err != nil { return err } return nil } func (svc *identityServiceImpl) CertID() (string, error) { if err := svc.init(); err != nil { return "", err } return svc.clientID.GetID() } func (svc *identityServiceImpl) Cert() (*x509.Certificate, error) { if err := svc.init(); err != nil { return nil, err } return svc.clientID.GetX509Certificate() } func (svc *identityServiceImpl) CreatorID() (string, error) { if len(svc.creatorID) != 0 { return svc.creatorID, nil } bytes, err := svc.stub.GetCreator() if err != nil { return "", err } array := sha256.Sum256(bytes) svc.creatorID = hex.EncodeToString(array[:]) return svc.creatorID, nil } func (svc *identityServiceImpl) MspID() (string, error) { if err := svc.init(); err != nil { return "", err } return svc.clientID.GetMSPID() } func (svc *identityServiceImpl) GetAttribute(attrName string) (out AttributeValue, err error) { var value string var find bool value, find, err = svc.clientID.GetAttributeValue(attrName) if err != nil { return } out = AttributeValue{value, find} return } // NewIdentityServiceImpl returns default implementation func NewIdentityServiceImpl(stub shim.ChaincodeStubInterface) IdentityService { return &identityServiceImpl{ stub: stub, } }
go
10
0.713731
95
22.044776
134
starcoderdata
namespace crisicheckinweb.ViewModels { public class UnassignClusterCoordinatorViewModel { public int DisasterId { get; set; } public int CoordinatorId { get; set; } public string CoordinatorName { get; set; } public string ClusterName { get; set; } } }
c#
6
0.70202
89
34.272727
11
starcoderdata
package com.jdev.kolya; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentChange; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import com.jdev.kolya.adapters.PostA; import com.jdev.kolya.adapters.SubjectsA; import com.jdev.kolya.lists.PostList; import java.util.ArrayList; public class PostsView extends AppCompatActivity { RecyclerView recyclerView; FirebaseFirestore firestore; ArrayList arrayList; PostA adapter; FirebaseAuth mAuth; Boolean isload = true; DocumentSnapshot lastVisible; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_posts_view); firestore = FirebaseFirestore.getInstance(); mAuth = FirebaseAuth.getInstance(); recyclerView = findViewById(R.id.postlist); arrayList = new ArrayList<>(); adapter = new PostA(arrayList); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(adapter); loaddata(); } public void loaddata() { if (mAuth.getCurrentUser() != null) { Query firstQ = firestore.collection("Posts").document("kesm").collection("mada").orderBy("time", Query.Direction.DESCENDING).limit(10); firstQ.addSnapshotListener(this, new EventListener { @Override public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) { if (documentSnapshots.size() > 0) { if (isload) { lastVisible = documentSnapshots.getDocuments() .get(documentSnapshots.size() - 1); arrayList.clear(); } for (DocumentChange doc : documentSnapshots.getDocumentChanges()) { if (doc.getType() == DocumentChange.Type.ADDED) { String postid = doc.getDocument().getId(); PostList postList = doc.getDocument().toObject(PostList.class).withId(postid); arrayList.add(postList); adapter.notifyDataSetChanged(); } } isload = false; } } }); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); Boolean reachbot = !recyclerView.canScrollVertically(1); if (reachbot) { loadmore(); } } }); } } public void loadmore() { if (mAuth.getCurrentUser() != null) { Query nextQ =firestore.collection("Posts").document("kesm").collection("mada").orderBy("time", Query.Direction.DESCENDING).startAfter(lastVisible).limit(10); nextQ.addSnapshotListener(this, new EventListener { @Override public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) { if (!documentSnapshots.isEmpty()) { lastVisible = documentSnapshots.getDocuments() .get(documentSnapshots.size() - 1); for (DocumentChange doc : documentSnapshots.getDocumentChanges()) { if (doc.getType() == DocumentChange.Type.ADDED) { String postid = doc.getDocument().getId(); PostList postList = doc.getDocument().toObject(PostList.class).withId(postid); arrayList.add(postList); adapter.notifyDataSetChanged(); } } } } }); } } }
java
24
0.565383
173
39.353846
130
starcoderdata
#ifndef AYLA_FLOAT_HPP #define AYLA_FLOAT_HPP #include namespace ayla { using Float = float; using Double = double; /** * @return TRUE if @param a is close enough to zero. */ inline bool isZero(Float a, Float epsilon = std::numeric_limits { return std::abs(a) <= epsilon; } } #endif // AYLA_FLOAT_HPP
c++
14
0.698953
84
17.238095
21
starcoderdata
package main import ( "encoding/binary" "fmt" "github.com/boltdb/bolt" "github.com/ruqqq/carbonchain" "log" ) type DatapackWorker struct { Db *bolt.DB } func (datapackWorker *DatapackWorker) OnReceiveDatapacks(cc *carbonchain.CarbonChain, carbonDb *bolt.DB) { datapacks := make([]carbonchain.Datapack, 0) datapackIds := make(map[int][]byte) // Get all available datapacks err := carbonDb.View(func(tx *bolt.Tx) error { bDatas := tx.Bucket([]byte("datas")) c := bDatas.Cursor() for i, datapackByte := c.First(); i != nil; i, datapackByte = c.Next() { datapack := *carbonchain.NewDatapackFromBytes(datapackByte) datapacks = append(datapacks, datapack) index := make([]byte, len(i)) copy(index, i) datapackIds[len(datapacks)-1] = index } return nil }) if err != nil { panic(err) } // Consume datapacks if len(datapacks) > 0 { err = datapackWorker.ProcessDatapacks(cc, carbonDb, datapacks, datapackIds) if err != nil { panic(err) } //err = carbonDb.Batch(func(tx *bolt.Tx) error { // bDatas := tx.Bucket([]byte("datas")) // err := bDatas.Delete(datapackIds[i]) // return err //}) //if err != nil { // panic(err) //} // Write data to file //_, err = f.WriteString(out) //if err != nil { // log.Fatal(err) //} } } func (datapackWorker *DatapackWorker) ProcessDatapacks(cc *carbonchain.CarbonChain, carbonDb *bolt.DB, datapacks []carbonchain.Datapack, datapackIds map[int][]byte) error { if len(datapacks) > 0 { // Open datas file for writing our datapacks data //var f *os.File //if _, err := os.Stat("ddt.txt"); err != nil { // if os.IsNotExist(err) { // var err error // f, err = os.Create("ddt.txt") // if err != nil { // log.Fatal(err) // } // } else { // f, err = os.OpenFile("ddt.txt", os.O_APPEND, 666) // if err != nil { // log.Fatal(err) // } // } //} // TODO: Remove this later //datapackWorker.Db.Batch(func(tx *bolt.Tx) error { // tx.DeleteBucket([]byte(BUCKET_COMMANDS)) // tx.DeleteBucket([]byte(BUCKET_DATAPACKS)) // tx.CreateBucket([]byte(BUCKET_COMMANDS)) // tx.CreateBucket([]byte(BUCKET_DATAPACKS)) // // return nil //}) fmt.Printf("Datapacks (%d):\n", len(datapacks)) for index, datapack := range datapacks { //log.Printf("[%s] %x\r\n", datapack.OutputAddr, datapack.Data) blockHash, err := cc.GetTransactionBlockHash(datapack.TxIds[0]) if err != nil { log.Println(err) continue } //log.Printf("-> %x\r\n", blockHash) confirmations, err := cc.GetBlockConfirmation(blockHash) if err != nil { log.Println(err) continue } //log.Printf("-> %d confirmations\r\n", confirmations) // Wait for 6 confirmations if confirmations < 6 { fmt.Printf("\tNOT CONFIRMED [%s (c: %d)] %+v\r\n", datapack.OutputAddr, confirmations, datapack) continue } var out string var command CommandInterface switch t := int8(datapack.Data[0]); t { case TYPE_REGISTER_ROOT_KEY: fallthrough case TYPE_DELETE_ROOT_KEY: command = NewRootKeyCommandFromBytes(datapack.Data) case TYPE_REGISTER_KEY: fallthrough case TYPE_DELETE_KEY: command = NewKeyCommandFromBytes(datapack.Data) case TYPE_REGISTER_SIGNATURE: fallthrough case TYPE_DELETE_SIGNATURE: command = NewSignatureCommandFromBytes(datapack.Data) default: log.Printf("Unrecognized command: [%s (c: %d)] %s\r\n", datapack.OutputAddr, confirmations, datapack.Data) // Delete datapack err = carbonDb.Batch(func(tx *bolt.Tx) error { bDatas := tx.Bucket([]byte("datas")) err := bDatas.Delete(datapackIds[index]) return err }) if err != nil { panic(err) return err } continue } out = fmt.Sprintf(" CONFIRMED [%s (c: %d)] %+v\r\n", datapack.OutputAddr, confirmations, command) fmt.Print("\t" + out) validated, err := command.Validate(datapackWorker.Db) if err != nil { log.Printf("Error verification command: %s. [%s (c: %d)] %+v\r\n", err.Error(), datapack.OutputAddr, confirmations, command) // Delete datapack err = carbonDb.Batch(func(tx *bolt.Tx) error { bDatas := tx.Bucket([]byte("datas")) err := bDatas.Delete(datapackIds[index]) return err }) if err != nil { panic(err) return err } continue } if !validated { log.Printf("Command verification failed: [%s (c: %d)] %+v\r\n", datapack.OutputAddr, confirmations, command) // Delete datapack err = carbonDb.Batch(func(tx *bolt.Tx) error { bDatas := tx.Bucket([]byte("datas")) err := bDatas.Delete(datapackIds[index]) return err }) if err != nil { panic(err) return err } continue } err = command.Execute(datapackWorker.Db) if err != nil { log.Printf("Error executing command: %s\n", err.Error()) panic(err) } err = datapackWorker.Db.Batch(func(tx *bolt.Tx) error { bCommands := tx.Bucket([]byte(BUCKET_COMMANDS)) id, _ := bCommands.NextSequence() bId := make([]byte, 8) binary.BigEndian.PutUint64(bId, uint64(id)) err := bCommands.Put(bId, command.Bytes()) if err != nil { return err } bDatapacks := tx.Bucket([]byte(BUCKET_DATAPACKS)) id, _ = bDatapacks.NextSequence() binary.BigEndian.PutUint64(bId, uint64(id)) err = bDatapacks.Put(bId, datapack.Bytes()) if err != nil { return err } return nil }) if err != nil { // TODO: Should I not panic panic(err) return err } err = carbonDb.Batch(func(tx *bolt.Tx) error { bDatas := tx.Bucket([]byte("datas")) err := bDatas.Delete(datapackIds[index]) return err }) if err != nil { panic(err) return err } log.Printf("Command executed: [%s (c: %d)] %+v\r\n", datapack.OutputAddr, confirmations, command) } //f.Close() } return nil }
go
21
0.623638
172
25.214286
224
starcoderdata
package com.srz.moudle; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.srz.moudle.entity.BeautyEntity; import com.srz.moudle.entity.ConfigListEntity; import com.srz.moudle.presenter.HomeContract; import com.srz.moudle.presenter.HomePresenter; import com.srz.net.util.RequestBodyUtil; import java.util.HashMap; import java.util.Map; import okhttp3.RequestBody; public class MainActivity extends AppCompatActivity implements HomeContract.View { private HomeContract.HomePresenters homePresenters; private Map map =new HashMap<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); homePresenters =new HomePresenter(this); map.put("page","1"); map.put("size","10"); map.put("columnId","69"); RequestBody requestBody = RequestBodyUtil.getRequestBody(map); homePresenters.start(requestBody); homePresenters.postHeader(requestBody); // map.clear(); map.put("appId","123456"); homePresenters.getConfigList(map); } @Override public void setResult(BeautyEntity postInfo) { Log.v("Srz","Beauty "+postInfo.getMsg()); } @Override public void setBeautyResult(BeautyEntity postInfo) { Log.v("Srz","BeautyHeder "+postInfo.getMsg()); } @Override public void setConfigList(ConfigListEntity postInfo) { Log.v("Srz","confgList "+postInfo.getMsg()); } @Override public void setError(String error) { Log.v("Srz","Srz >>> "+error); } @Override public void setPresenter(HomeContract.HomePresenters homePresenters) { this.homePresenters=homePresenters; } }
java
9
0.691817
82
22.822785
79
starcoderdata
package com.howtodoinjava.core.datetime; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class DaysBetweenDates { public static void main(final String[] args) { LocalDate date1 = LocalDate.now(); LocalDate date2 = date1.plusDays(99); long diffInDays = ChronoUnit.DAYS.between(date1, date2); System.out.println(diffInDays); diffInDays = date1.until(date2, ChronoUnit.DAYS); System.out.println(diffInDays); LocalDate startDate = LocalDate.now(); LocalDate endDate = startDate.plusMonths(2); long numOfDays = ChronoUnit.DAYS.between(startDate, endDate); List listOfDates = Stream.iterate(startDate, date -> date.plusDays(1)) .limit(numOfDays) .collect(Collectors.toList()); System.out.println(listOfDates); } }
java
12
0.675122
89
29.147059
34
starcoderdata
<?php namespace Room11\HTTP\Body; use Room11\HTTP\Body; use Room11\HTTP\HTTPException; use Room11\HTTP\HeadersSet; class FileBody implements Body { private $fileHandle; private $statusCode; /** @var HeadersSet */ private $headersSet; public function __construct( $path, $downloadFilename, $contentType, $headers = [], $statusCode = 200, $reasonPhrase = null ) { if (!is_string($path)) { throw new HTTPException( sprintf('FileBody path must be a string filesystem path; %s specified', gettype($path)) ); } elseif (!is_readable($path)) { throw new HTTPException( sprintf('FileBody path is not readable: %s', $path) ); } elseif (!is_file($path)) { throw new HTTPException( sprintf('FileBody path is not a file: %s', $path) ); } $this->fileHandle = @fopen($path, 'rb'); if (!$this->fileHandle) { throw new HTTPException( sprintf('FileBody could not open file for reading: %s', $path) ); } $statInfo = fstat($this->fileHandle); if (!array_key_exists('size', $statInfo)) { throw new HTTPException( sprintf('FileBody could not determine file size from fstat: %s', $path) ); } $this->statusCode = $statusCode; $this->reasonPhrase = $reasonPhrase; $this->headersSet = new HeadersSet(); $this->headersSet->addHeader('Content-Length', (string)$statInfo['size']); if ($contentType) { $this->headersSet->addHeader("Content-Type", $contentType); } // TODO - this is not safe, needs to be encode by the appropriate // rfc scheme $this->headersSet->addHeader("Content-Disposition", "inline; filename=".$downloadFilename); foreach ($headers as $name => $value) { $this->headersSet->addHeader($name, $value); } } public function sendData() { if (@fpassthru($this->fileHandle) === false) { throw new HTTPException( sprintf("FileBody could not fpassthru filehandle") ); } } public function getData() { $bytes = stream_get_contents($this->fileHandle); if ($bytes === false) { throw new HTTPException( sprintf("FileBody could not stream_get_contents filehandle") ); } return $bytes; } public function getReasonPhrase() { return $this->reasonPhrase; } public function getHeadersSet() { return $this->headersSet; } /** * @inheritdoc */ public function getStatusCode() { return $this->statusCode; } }
php
19
0.530633
103
25.468468
111
starcoderdata
const fetchLocation = async (lat, lon) => { try { const response = await fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=1c5da32bd6a0d1c4c017b21b49833c7f`); const data = await response.json(); return data; } catch (e) { console.error(e); } }; export default fetchLocation;
javascript
14
0.633523
149
31.090909
11
starcoderdata
import { extname, resolve } from 'path' import { read } from '@dev-xp/fs' import detective from 'detective-es6' import collapse from '@kikd/collapse' import parseSfp from '@entyre/parse-sfp' import { sync as exists } from 'file-exists' const cache = {} export default ({ root, locals = [], structures = {}, manifests = {} }) => // eslint-disable-next-line complexity async function detect(name) { if (!name) return {} const { main, bin } = manifests[name] || {} const { srcDir, files } = structures[name] || {} const sourceFile = main || (bin ? Object.values(bin)[0] : files.includes('index.md') ? 'index.md' : 'index.js') if (!exists(resolve(root, srcDir, sourceFile))) return {} return read(resolve(root, srcDir, sourceFile), 'utf-8') .then( content => extname(sourceFile) === '.md' ? parseSfp({ content }).code : content ) .then(detective) .then(result => Promise.all( result.map(async dependency => { if (!locals.includes(dependency)) return { [dependency]: false } if (dependency in cache) return cache[dependency] return detect(dependency) .then( deps => Object.keys(deps).length === 0 && deps.constructor === Object ? { [dependency]: false } : { [dependency]: deps } ) .then(tree => { cache[dependency] = tree return tree }) }) ).then(results => results.reduce(collapse, {})) ) }
javascript
29
0.417345
74
35.614035
57
starcoderdata
import storage from 'redux-persist/lib/storage'; import { persistReducer } from 'redux-persist'; import { signReducer } from 'scenes/Sign/redux/reducer'; import { compareObject } from 'utils/utility'; export const initialState = { id: null, email: '', username: '', first_name: '', last_name: '', roles: [], phone: '', created_time: '', }; export const userReducer = (state = initialState, { type, payload }) => { if (type === 'RESET_ALL_STATE') { return initialState; } const stateReducer = signReducer(state, { type, payload }); const compare = compareObject(stateReducer, state); if (!compare) { return stateReducer; } return state; }; const persistConfig = { key: 'app:userReducer', storage, whitelist: [ 'id', 'email', 'username', 'first_name', 'last_name', 'roles', 'created_time', 'phone', ], blacklist: [], timeout: null, }; export const reducer = persistReducer(persistConfig, userReducer);
javascript
7
0.640196
73
20.702128
47
starcoderdata
// Copyright 2019 Sound Metrics Corp. All Rights Reserved. namespace SoundMetrics.Aris.BeamWidths { /// /// Holds information about a beam on a specifc ARIS model. /// public struct BeamInfo { /// /// The beam number; /// beams are numbered from right to left in the displayed image. /// public uint BeamNumber; /// /// Degrees off the middle of the field of vision for the /// center of this beam. /// public float Center; /// /// Degrees off the middle of the field of vision for the /// left of this beam. /// public float Left; /// /// Degrees off the middle of the field of vision for the /// rightS of this beam. /// public float Right; } }
c#
8
0.554729
73
26.676471
34
starcoderdata
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using PetStore.Services.Models; namespace PetStore.Services.Interfaces { public interface IBrandService { int Create(string name); BrandModel GetById(int id); void RemoveById(int id); void Remove(BrandModel brand); IEnumerable GetAllBrands(); IEnumerable Search(string name); } }
c#
8
0.699387
52
19.375
24
starcoderdata
void FGImage::Load(FG_Image& destination_image, const std::string locationImage, const FGData_System& system, std::string& message_error, bool& errorEvent) { /* Setup variable check */ bool fileAlready = true; /* Check file already or not */ std::ifstream TempCheckFile; TempCheckFile.open(locationImage, std::ios::binary); if(!TempCheckFile.is_open()) { /* If not defined file set variable into false */ fileAlready = false; /* And Set Error Message and Make error event into true */ errorEvent = true; message_error = "FGame not defined file name: "; message_error += locationImage + " | in function FGImage::Load"; } TempCheckFile.close(); /* If file defined */ if(fileAlready && !errorEvent) { /* Setup data variable for image */ SDL_Surface* tempSurface = IMG_Load(locationImage.c_str()); /* Filling data in variable destination */ destination_image.image = SDL_CreateTextureFromSurface(system.render, tempSurface); destination_image.width = tempSurface->w; destination_image.height = tempSurface->h; /* Free memory surface */ SDL_FreeSurface(tempSurface); } }
c++
11
0.712747
80
31.794118
34
inline
const _ = require('@keyring/util'); class Host { constructor(facet='default') { let plugins = this.constructor.plugins; for (let id of Object.keys(plugins)) { plugins[id].construct(facet, this); } } static use(provider, refresh) { throw new Error('method needs to be added to class'); } static _use(provider, facet, refresh=false) { if(refresh || !this.plugins[provider.id]) { this.plugins[provider.id] = provider; provider.init(facet, this); } } } Host.plugins = {}; module.exports = Host;
javascript
9
0.642857
57
21.615385
26
starcoderdata
<!DOCTYPE html> <html lang="en" class="default-style"> - Order Detail <?php $this->load->view('hfs/html_header') ?> <div class="page-loader"> <div class="bg-primary"> <!-- Layout wrapper --> <div class="layout-wrapper layout-2"> <div class="layout-inner"> <!-- Layout sidenav --> <?php $this->load->view('hfs/sidebar') ?> <!-- / Layout sidenav --> <!-- Layout container --> <div class="layout-container"> <!-- Layout navbar --> <?php $this->load->view('hfs/header') ?> <!-- / Layout navbar --> <!-- Layout content --> <div class="layout-content"> <!-- Content --> <div class="container-fluid flex-grow-1 container-p-y"> <div class="media align-items-center py-3 mb-4" style="margin-top: -20px !important;margin-bottom:-20px !important;"> <img src="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image1'] ?>" alt="" class="d-block ui-w-80 ui-bordered"> <div class="media-body ml-4"> <h4 class="font-weight-bold mb-2"><?= $detail[0]['prod_name'] ?> <div class="row"> <div class="col-md-4"> <div class="card bg-transparent border-primary mb-3 box-shadow-none "> <div class="card-body "> <span class="text-muted">Order Id : <?= $detail[0]['Order_id'] ?> <span class="text-muted">Product Id : <?= $detail[0]['product_id'] ?> <div class="col-md-4"> <div class="card bg-transparent border-primary mb-3 box-shadow-none "> <div class="card-body "> <span class="text-muted">Order Date : <?= $detail[0]['ordered_date'] ?> <span class="text-muted">Shipping Date : <?= $detail[0]['product_delivered_date'] ?> <div class="col-md-4"> <div class="card bg-transparent border-primary mb-3 box-shadow-none "> <div class="card-body "> <span class="text-muted">Buyer GST : <?= $detail[0]['Gst'] ?> <span class="text-muted">Seller GST : <?= $detail[0]['Gst'] ?> <div class="row"> <div class="col-md"> <div class="card bg-transparent border-success mb-3 box-shadow-none"> <div class="card-body"> class="card-title" style="color: #02BC77 ">Product Details <span class="text-muted">Material Name: <?= $detail[0]['product_material'] ?> <span class="text-muted">GSM : <?= $detail[0]['GSM_name'] ?> <span class="text-muted">Style: <?= $detail[0]['style'] ?> <span class="text-muted">Size: $detail[0]['size'] ?> <span class="text-muted">Handle Type: $detail[0]['handle'] ?> <span class="text-muted">Handle Size: $detail[0]['handle_size'] ?> <span class="text-muted">Handle Colour: $detail[0]['handle_color'] ?> <span class="text-muted">Gusset: $detail[0]['gusset_name'] ?> <span class="text-muted">Product Color: $detail[0]['product_material_color'] ?> <span class="text-muted">Lamination: $detail[0]['lamination'] ?> <div class="col-md"> <div class="card bg-transparent border-success mb-3 box-shadow-none"> <div class="card-body"> class="card-title" style="color: #02BC77 ">Buyer Details <span class="text-muted">Name : echo $detail[0]['first_name'] .' '. $detail[0]['last_name'] ?> <span class="text-muted">Mobile No.: $detail[0]['mobile_number'] ?> <span class="text-muted">Email : $detail[0]['email'] ?> <span class="text-muted">Address : echo $detail[0]['address_1'].' '.$detail[0]['address_2'] ?> <span class="text-muted">City: $detail[0]['city'] ?> <span class="text-muted">State: $detail[0]['state'] ?> <span class="text-muted">Zipcode: $detail[0]['zipcode'] ?> <div class="col-md"> <div class="card bg-transparent border-success mb-3 box-shadow-none "> <div class="card-body "> class="card-title" style="color: #02BC77 ">Seller Details <span class="text-muted">Name : $detail[0]['sel_name'] ?> <span class="text-muted">Business Name: $detail[0]['sel_business'] ?> <span class="text-muted">Email: $detail[0]['sel_email'] ?> <span class="text-muted">Address: echo $detail[0]['sel_address1'].' '.$detail[0]['sel_address2'] ?> <span class="text-muted">City : $detail[0]['sel_city'] ?> <span class="text-muted">State: $detail[0]['sel_state'] ?> <span class="text-muted">Zipcode: $detail[0]['sel_zipcode'] ?> <div class="w-100"> <div class="card-body" style="margin-top: -30px !important;margin-bottom: -36px !important;"> <div class="table-responsive bg-lighter border-warning "> <table class="table product-item-discounts-table"> <tr class="table-success"> $detail[0]['quantity'] ?> $detail[0]['product_price'] ?> $detail[0]['discount'] ?> $detail[0]['Gst'] ?> $detail[0]['shipping_charges'] ?> $detail[0]['product_wise_total'] ?> <div class="card-body" style="margin-top: -36px !important;"> <div class="mb-4"> <!-- <span class="badge badge-dot badge-primary"> Primary image --> <!-- Lightbox template --> <div id="product-item-lightbox" class="blueimp-gallery blueimp-gallery-controls"> <div class="slides"> <h3 class="title"> <a class="prev">‹ <a class="next">› <a class="close">× <ol class="indicator"> <div id="product-item-images" class="row"> <div class="col-12 col-sm-6 col-md-4 col-xl-3 mb-4"> <a href="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image1'] ?>" class="d-block border-primary ui-bordered"> <img src="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image1'] ?>" class="img-fluid" alt=""> <div class="col-12 col-sm-6 col-md-4 col-xl-3 mb-4"> <a href="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image2'] ?>" class="d-block ui-bordered"> <img src="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image2'] ?>" class="img-fluid" alt=""> <div class="col-12 col-sm-6 col-md-4 col-xl-3 mb-4"> <a href="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image3'] ?>" class="d-block ui-bordered"> <img src="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image3'] ?>" class="img-fluid" alt=""> <div class="col-12 col-sm-6 col-md-4 col-xl-3 mb-4"> <a href="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image4'] ?>" class="d-block ui-bordered"> <img src="<?php echo base_url() ?>upload/products/<?php echo $detail[0]['prod_image4'] ?>" class="img-fluid" alt=""> <!-- / Content --> <!-- Layout content --> <!-- / Layout container --> <!-- Overlay --> <div class="layout-overlay layout-sidenav-toggle"> <!-- / Layout wrapper --> <?php $this->load->view('hfs/footer') ?>
php
7
0.397212
157
43.35249
261
starcoderdata
// // RSCache.h // libTapLynx // // Created by on 7/12/10. // Copyright 2010 NewsGator Technologies, Inc. All rights reserved. // #import /*Thread-safe *in-memory* cache. Super-easy to use. Treat it like a mutable dictionary. Uses NSCache when it's available. OK if not available -- still runs on OS X 10.5 and iOS 3.x. Removes objects automatically when receives memory warning.*/ @interface RSCache : NSObject { @private BOOL useNSCache; NSMutableDictionary *cacheDictionary; id nativeCache; //NSCache object pthread_mutex_t cacheLock; } + (id)cache; //convenience, not special - (id)objectForKey:(id)key; - (void)setObject:(id)obj forKey:(id)key; - (void)setObjectIfNotNil:(id)obj forKey:(id)key; - (void)removeObjectForKey:(id)key; - (void)removeAllObjects; @property (nonatomic, assign) NSUInteger countLimit; //normally 0 (unlimited). Only works when cache is native NSCache. @end
c
5
0.732724
119
23
41
starcoderdata
(function(root, factory) { if (typeof define === "function" && define.amd) { // use AMD define funtion to support AMD modules if in use define("CXA/Feature/LoyaltyPoints/UnusedCoupons", ["exports"], factory); } else if (typeof exports === "object") { // to support CommonJS factory(exports); } // browser global variable root.UnusedCoupons = factory; }(this, function(element, model) { "use strict"; var component = new Component(element, model); component.Name = "CXA/Feature/LoyaltyPoints/UnusedCoupons"; var AddMockData = function(component) { component.Model.coupons.push(new CouponDetailModel({ Code: "LPXXXXXX01" })); component.Model.coupons.push(new CouponDetailModel({ Code: "LPXXXXXX02" })); component.Model.coupons.push(new CouponDetailModel({ Code: "LPXXXXXX03" })); }; component.InExperienceEditorMode = function() { AddMockData(component); component.Visual.Disable(); }; component.Init = function() { if (CXAApplication.RunningMode === RunningModes.Normal) { AjaxService.Post("/api/cxa/UnusedCoupons/GetUnusedCoupons", {}, function(data, success) { if (success && data && data.Success) { component.Model.updateModel(data); } }); return component; } } } ));
javascript
24
0.533416
88
31.34
50
starcoderdata
@Override @Transactional public void reindex(Project aProject) throws IOException { log.info("Re-indexing project [{}]({}) ", aProject.getName(), aProject.getId()); Index index = getIndexFromMemory(aProject); if (index.getPhysicalIndex().isCreated()) { // Physical index already exists, drop it log.debug("Physical index already exists. Drop it."); index.getPhysicalIndex().dropPhysicalIndex(); } // Create physical index and index all project documents log.debug("Create new physical index."); index.getPhysicalIndex().createPhysicalIndex(); // After reindexing, reset the invalid flag log.trace("Set index invalid flag to false."); index.setInvalid(false); updateIndex(index); }
java
9
0.617577
88
32.72
25
inline
#slicing part 2 Index modile list IBM Digital Nation grocery_list= ["Milk","Eggs","Bread","rice"] my_slicing = grocery_list[:] print(my_slicing) #end of the Program
python
5
0.722892
52
22.857143
7
starcoderdata
def reaction_hash(reactants_smiles, product): """ Create a reaction hash :param reactants_smiles: the SMILES string of the reactants :type reactants_smiles: str :param product: the product molecule :type product: Molecule :return: the hash :rtype: str """ reactant_inchi = Molecule(smiles=reactants_smiles).inchi product_inchi = product.inchi concat_inchi = reactant_inchi + "++" + product_inchi return hashlib.sha224(concat_inchi.encode("utf8")).hexdigest()
python
11
0.690802
66
33.133333
15
inline
'use strict'; angular.module('angularFlaskServices', ['ngResource']) .factory('Post', function($resource) { return $resource('/api/post/:postId', {}, { query: { method: 'GET', params: { postId: '' }, isArray: true } }); }) ; angular.module('angularFlaskServices', ['ngResource']) .factory('GlobalProjectFolderService', function($http) { var getProjects = function() { return $http({method:"GET", url:"/project_folders"}).then(function(response){ return response.data.project_folders; }); }; var selected_project_folder; return { project_folders: function() { return getProjects(); }, selected_project_folder: selected_project_folder, select: function(data) { selected_project_folder = data; } }; }) ; // angular.module('angularFlaskServices', []) // .factory('GlobalProjectFolderService', function() { // project_folders = [] // // $http({ // // method: 'GET', // // url: '/project_folders' // // }).then(function successCallback(response) { // // project_folders = response.data.project_folders; // // return global_project_folder; // // }, function errorCallback(response) { // // console.log(response); // // }); // var global_project_folder = { // selected_folder: null // folders = project_folders; // }; // return global_project_folder; // }) // ;
javascript
18
0.592852
86
23.62069
58
starcoderdata
//ry //sort class Solution { public char findTheDifference(String s, String t) { char[] s_arr = s.toCharArray(); char[] t_arr = t.toCharArray(); Arrays.sort(s_arr); Arrays.sort(t_arr); for(int i = 0; i < s_arr.length; i++) { if(s_arr[i] != t_arr[i]) return t_arr[i]; } return t_arr[t_arr.length - 1]; } }
java
11
0.523923
55
23.588235
17
starcoderdata
package edu.mit.mitmobile2.maps; import java.util.List; import android.content.Context; import android.view.View; import edu.mit.mitmobile2.R; import edu.mit.mitmobile2.SimpleArrayAdapter; import edu.mit.mitmobile2.TwoLineActionRow; import edu.mit.mitmobile2.objs.MapItem; public class MapItemArrayAdapter extends SimpleArrayAdapter { Integer mParentCategoryID; public MapItemArrayAdapter(Context context, List items, Integer parentCategoryID) { super(context, items, R.layout.map_bookmarks_row); mParentCategoryID = parentCategoryID; } @Override public void updateView(MapItem item, View view) { TwoLineActionRow actionRow = (TwoLineActionRow) view; // for subcategories we want the root category // to be call "All categoryName" //actionRow.setTitle((String)item.getItemData().get("displayName")); actionRow.setTitle((String)item.getMapItemName()); } }
java
11
0.781457
93
29.2
30
starcoderdata
def write_highpass(myfft, lowav=0, hiwav=0, writefile=False): fft1 = np.copy(myfft) # Don't want to change the original array. fft1[0:lowav]=fft1[0:lowav]*0.0 if lowav > 0: fft1[-lowav:]=fft1[-lowav:]*0.0 #Remove all frequencies lower than this wave number. #hiwav = int(len(fft1)/2)-hiwav fft1[hiwav:-hiwav] = 0 # Remove all frequencies higher than this wave number. y2 = fftp.ifft(fft1) y2 = np.array([int(round(i)) for i in y2.real]) y2 = np.array(y2,dtype=np.int16) ## https://stackoverflow.com/questions/50431296/wavfile-write-identical-arrays-but-only-one-works if writefile: fs = 44100 wavfile.write('..\\sounds\\Laurel_py.wav',fs,y2) return [y2, abs(fft1[1:int(len(fft1)/2)])]
python
14
0.701854
131
49.142857
14
inline
import tkinter as tk from PIL import ImageTk,Image root=tk.Tk() root.title("EASE") fname=tk.Canvas(bg="black",height=2000,width=800,relief='ridge',highlightthickness=0,bd=0) fname.pack() img1=ImageTk.PhotoImage(file='mech.jpg') imgur1=ImageTk.PhotoImage(file='recon.png') imgur2=ImageTk.PhotoImage(file='ret.png') imgg1= ImageTk.PhotoImage(Image.open("logo.png")) panel = tk.Label(root, image = imgg1,bg="black") panel.pack(side = "top", fill = "both", expand = "no") img=fname.create_image(900,1000,anchor='se',image=img1) fname.pack() #wel=tk.Label(root,bg="black",text="Welcome!",fg="blue",font="comicsans 26 bold ",padx=10,pady=10) #wel.pack(pady=20) msg1="Our software helps in reconstructing 3d models by using CNN's with limited data, as well as retrieving 3d models from online repositories without any hassle.\n"#write whatever you wish to mess1=tk.Message(root,text=msg1) mess1.config(fg="grey",bg="black",font="comicsans 14",justify="center",padx=30,width=600) #change the font as per your choice mess1.pack(pady=10) msg2="Choose the feature that you wish to use.\n" mess2=tk.Message(root,text=msg2) mess2.config(fg="grey",bg="black",font="comicsans 15",justify="center",padx=30,width=600) #change the font as per your choice mess2.pack(pady=10) b1=tk.Button(root,compound="left",image=imgur1,text=" Reconstruction",font='times 22 bold',height=2,width=10,relief='raised',bg='white',fg='DarkOrchid4',bd=3,cursor='hand1') b1.pack(ipadx=125,ipady=20,padx=5, pady=20) b2=tk.Button(root,compound="left",image=imgur2,text=" Retrieval-OD",font='times 24 bold',height=2,width=10,relief='raised',bg='white',fg='DarkOrchid4',bd=3,cursor='hand1') b2.pack(ipadx=125,ipady=20,padx=5, pady=20) def close(): root.destroy() bt=tk.Button(root,text="Exit",font='times 22 bold',height=1,width=15,relief='raised',bg='white',fg='red',bd=3,cursor='hand1',command=close) bt.pack(padx=5, pady=20) fname.pack(side="left") root.configure(background='black') root.mainloop()
python
8
0.733398
193
28.257143
70
starcoderdata
// // ValidAttributesController.h // macSVG // // Created by on 1/1/12. // Copyright © 2016 ArkPhone LLC. All rights reserved. // #import @class EditorUIFrameController; @interface ValidAttributesController : NSObject <NSTableViewDelegate, NSTableViewDataSource> { IBOutlet EditorUIFrameController * editorUIFrameController; IBOutlet NSView * validAttributesFrameView; } @property (weak)IBOutlet NSTableView * validAttributesTableView; @property (strong)NSArray * attributeKeysArray; @property (strong)NSMutableDictionary * attributesDictionary; -(void)setEnabled:(BOOL)enabled; -(void)setValidAttributesForElement:(NSXMLElement *)xmlElement; @end
c
6
0.784423
92
24.678571
28
starcoderdata
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); //----------------------------------DOSEN----------------------------------------- //dashboard dosen Route::get('dashboard-dosen', 'DosenController@dashboard')->name('dashboard-dosen'); //profil dosen Route::get('index-dosen', 'DosenController@index')->name('index-dosen'); //update atau edit profil dosen Route::get('update-dosen2', 'DosenController@editdata')->name('update-dosen2'); Route::match(['get', 'post'], '/updatedatadosen', 'DosenController@updatedata')->name('updatedatadosen'); //hapus mata kuliah Route::get('hapus-matkul/{id}', 'DosenController@destroy')->name('hapus-matkul'); //pilih matkul dan edit hasilnya Route::get('create-dosen/{id}', 'DosenController@create'); Route::match(['get', 'post'], '/pilih-matkul', 'DosenController@pilihmatkul')->name('pilih-matkul'); Route::get('edit-matkul/{id}', 'DosenController@editmatkul')->name('edit-matkul'); Route::match(['get', 'post'], '/updatepilihmatkul/{id}', 'DosenController@editpilihan')->name('updatepilihmatkul'); // --------------SISI MAHASISWA------------ Route::get('/mahasiswa/dashboard', 'MahasiswaController@home'); //pilih KRS Route::get('mahasiswa/lihatkrs', 'MahasiswaController@tambahkrs'); Route::post('mahasiswa/pilihkrs', 'MahasiswaController@proseskrs'); Route::get('mahasiswa/ambilkrs/{id}', 'MahasiswaController@lihatkrs'); // Profil Route::get('mahasiswa/profil', 'MahasiswaController@profil'); Route::get('mahasiswa/editprofil', 'MahasiswaController@edit'); Route::match(['get', 'post'], '/mahasiswa/updateprofil', 'MahasiswaController@update')->name('updatemahasiswa'); //edit dan hapus KRS Route::get('mahasiswa/editkrs/{id}', 'MahasiswaController@editkrs'); Route::match(['get', 'post'], '/mahasiswa/updatekrs/{id}', 'MahasiswaController@editp')->name('updatekrs'); Route::get('mahasiswa/deletekrs/{id}', 'MahasiswaController@hapuskrs'); //--------------------------------------SISI ADMIN----------------------- // Role user Route::get('/dashboard', 'AdminController@home'); Route::get('/role', 'AdminController@tampilrole'); Route::get('/role/create', 'AdminController@create_role'); Route::post('/role/create', 'AdminController@store_role'); Route::get('/role/edit/{id}', 'AdminController@edit_role'); Route::post('/role/update', 'AdminController@update_role'); Route::get('/role/delete/{id}', 'AdminController@delete_role'); // Fitur Mata Kuliah Route::get('/matkul', 'AdminController@tampilmatkul'); Route::get('/matkul/create', 'AdminController@create_matkul'); Route::post('/matkul/create', 'AdminController@store_matkul'); Route::get('/matkul/edit/{kode_matkul}', 'AdminController@edit_matkul'); Route::post('/matkul/update', 'AdminController@update_matkul'); Route::get('/matkul/delete/{kode_matkul}', 'AdminController@delete_matkul'); //Fitur Login Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::get('/logout', 'HomeController@logout');
php
12
0.660169
115
40.914634
82
starcoderdata
package com.godaddy.sonar.ruby.rubocop; import java.io.File; /** * Created by sergio on 3/15/17. */ public class ReportFile { private String path; private File ioFile; public ReportFile(String baseDir, String reportPath) { this.path = baseDir + "/" + reportPath; this.ioFile = new File(path); } public String getPath() { return this.path; } public File getIoFile() { return this.ioFile; } public Boolean isFileExists() { return this.ioFile.exists(); } }
java
10
0.625
58
18.862069
29
starcoderdata
import React, { createElement } from 'preact/compat'; import { setupRerender } from 'preact/test-utils'; import { setupScratch, teardown } from '../../../test/_util/helpers'; describe('PureComponent', () => { /** @type {HTMLDivElement} */ let scratch; /** @type {() => void} */ let rerender; beforeEach(() => { scratch = setupScratch(); rerender = setupRerender(); }); afterEach(() => { teardown(scratch); }); it('should be a class', () => { expect(React) .to.have.property('PureComponent') .that.is.a('function'); }); it('should pass props in constructor', () => { let spy = sinon.spy(); class Foo extends React.PureComponent { constructor(props) { super(props); spy(this.props, props); } } React.render(<Foo foo="bar" />, scratch); let expected = { foo: 'bar' }; expect(spy).to.be.calledWithMatch(expected, expected); }); it('should ignore the __source variable', () => { const pureSpy = sinon.spy(); const appSpy = sinon.spy(); let set; class Pure extends React.PureComponent { render() { pureSpy(); return } } const App = () => { const [, setState] = React.useState(0); appSpy(); set = setState; return <Pure __source={{}} />; }; React.render(<App />, scratch); expect(appSpy).to.be.calledOnce; expect(pureSpy).to.be.calledOnce; set(1); rerender(); expect(appSpy).to.be.calledTwice; expect(pureSpy).to.be.calledOnce; }); it('should only re-render when props or state change', () => { class C extends React.PureComponent { render() { return <div />; } } let spy = sinon.spy(C.prototype, 'render'); let inst = React.render(<C />, scratch); expect(spy).to.have.been.calledOnce; spy.resetHistory(); inst = React.render(<C />, scratch); expect(spy).not.to.have.been.called; let b = { foo: 'bar' }; inst = React.render(<C a="a" b={b} />, scratch); expect(spy).to.have.been.calledOnce; spy.resetHistory(); inst = React.render(<C a="a" b={b} />, scratch); expect(spy).not.to.have.been.called; inst.setState({}); rerender(); expect(spy).not.to.have.been.called; inst.setState({ a: 'a', b }); rerender(); expect(spy).to.have.been.calledOnce; spy.resetHistory(); inst.setState({ a: 'a', b }); rerender(); expect(spy).not.to.have.been.called; }); it('should update when props are removed', () => { let spy = sinon.spy(); class App extends React.PureComponent { render() { spy(); return } } React.render(<App a="foo" />, scratch); React.render(<App />, scratch); expect(spy).to.be.calledTwice; }); it('should have "isPureReactComponent" property', () => { let Pure = new React.PureComponent(); expect(Pure.isReactComponent).to.deep.equal({}); }); });
javascript
22
0.610635
69
21.416
125
starcoderdata
// @flow import { Decimal } from 'decimal.js' import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { translate } from 'react-i18next' import cn from 'classnames' import { getPeriodCaption } from '~/utils/resdex' import { toMaxDigits } from '~/utils/decimal' import { UniformList, UniformListHeader, UniformListRow, UniformListColumn } from '~/components/uniform-list' import { RoundedButton } from '~/components/rounded-form' import { ResDexBuySellActions } from '~/reducers/resdex/buy-sell/reducer' import { ResDexState } from '~/reducers/resdex/resdex.reducer' import styles from './ChoosePair.scss' type Props = { t: any, resDex: ResDexState, actions: object } const na = `—` const quoteSymbols = ['USDT', 'BTC', 'ETH', 'RES'] /** * @class ChoosePair * @extends {Component */ class ChoosePair extends Component { props: Props /** * @memberof ChoosePair */ getGrouppedCurrencies() { const { RESDEX: currenciesMap } = this.props.resDex.accounts.currencies const currencies = Object.values(currenciesMap) const grouppedCurrencies = quoteSymbols.reduce((accumulated, quoteSymbol, index) => ({ ...accumulated, [quoteSymbol]: ( currencies .filter(c => c.symbol !== quoteSymbol && !quoteSymbols.slice(0, index).includes(c.symbol)) .sort((c1, c2) => c1.symbol.localeCompare(c2.symbol)) ) }), {}) return grouppedCurrencies } /** * @memberof ChoosePair */ getListHeaderRenderer(quoteSymbol) { // const { t } = this.props return ( <UniformListColumn width="100%">{quoteSymbol} <UniformListColumn /> ) } /** * @memberof ChoosePair */ getListRowRenderer(quoteSymbol, currency) { const { baseCurrency, quoteCurrency } = this.props.resDex.buySell return ( <UniformListRow className={styles.row} key={currency.symbol} onClick={() => this.props.actions.updatePair(currency.symbol, quoteSymbol)} > <UniformListColumn className={cn(styles.column, { [styles.selected]: baseCurrency === currency.symbol && quoteCurrency === quoteSymbol })} width="100%" > {currency.symbol}/{quoteSymbol} <UniformListColumn className={styles.column} /> ) } getLast() { const { trades } = this.props.resDex.buySell if (trades.length === 0) { return { price: na, isGreen: true, } } let isGreen = true if (trades.length >= 2) { isGreen = Number(trades[0].price) >= Number(trades[1].price) } return { price: toMaxDigits(trades[0].price), isGreen } } getOhlc(field) { const { ohlc } = this.props.resDex.buySell if (ohlc.length === 0) { return na } const value = ohlc[ohlc.length - 1][field] return toMaxDigits(Decimal(value)) } render() { const { t } = this.props const { baseCurrency, quoteCurrency } = this.props.resDex.buySell const grouppedCurrencies = this.getGrouppedCurrencies() const { period } = this.props.resDex.buySell.tradingChart const periodCaption = getPeriodCaption(period) const last = this.getLast() return ( <div className={cn(styles.container, styles.choosePair)}> <div className={styles.info}> <div className={styles.pair}> {baseCurrency}/{quoteCurrency} <div className={cn(styles.last, { [styles.high]: last.isGreen === true, [styles.low]: last.isGreen === false, })}> <div className={styles.caption}> {t(`Last Price`)} {last.price} <div className={styles.high}> <div className={styles.caption}> {t(`{{period}} High`, {period: periodCaption})} {this.getOhlc('high')} <div className={styles.low}> <div className={styles.caption}> {t(`{{period}} Low`, {period: periodCaption})} {this.getOhlc('low')} <div className={styles.volume}> <div className={styles.caption}> {t(`{{period}} Volume`, {period: periodCaption})} {this.getOhlc('volume')} <RoundedButton className={styles.tradingChartButton} onClick={this.props.actions.showTradingChartModal} important small > {t(`Chart`)} <div className={styles.lists}> {quoteSymbols.map(quoteSymbol => ( <UniformList className={styles.list} items={grouppedCurrencies[quoteSymbol]} headerRenderer={() => this.getListHeaderRenderer(quoteSymbol)} rowRenderer={currency => this.getListRowRenderer(quoteSymbol, currency)} emptyMessage={false} scrollable /> ))} ) } } const mapStateToProps = state => ({ resDex: state.resDex, }) const mapDispatchToProps = dispatch => ({ actions: bindActionCreators(ResDexBuySellActions, dispatch) }) export default connect(mapStateToProps, mapDispatchToProps)(translate('resdex')(ChoosePair))
javascript
23
0.588737
100
24.703196
219
starcoderdata
def genome_connect(db_bytes): """Write input genome to local disk and clean after using.""" fp = Path(str(uuid4())) with open('input.gbk', 'wb') as file: for i in db_bytes: fp = bytearray(i) file.write(fp) conn = str(fp) try: yield conn finally: pass
python
11
0.540373
65
25.916667
12
inline
#include #include #include "GatewayESP8266MQTTClient.h" #include "PersistentData.h" #define MAGIC_BYTE (0xCC) #define MAGIC_BYTE_OFFSET (0) #define MAGIC_BYTE_SIZE (1) #define BROKER_IPADDRESS_OFFSET (MAGIC_BYTE_OFFSET + MAGIC_BYTE_SIZE) #define BROKER_IPADDRESS_SIZE (4) #define BROKER_PORT_OFFSET (BROKER_IPADDRESS_OFFSET + BROKER_IPADDRESS_SIZE) #define BROKER_PORT_SIZE (2) #define NW_OFFSET (BROKER_PORT_OFFSET + BROKER_PORT_SIZE) #define NW_SIZE (33) #define NW_PASS_OFFSET (NW_OFFSET + NW_SIZE) #define NW_PASS_SIZE (64) bool IsInitialized() { uint8_t Ebyte = MyLoadState(MAGIC_BYTE_OFFSET); bool bInitOk = true; //check magic byte first if (Ebyte != MAGIC_BYTE) { bInitOk = false; Serial.println("Persistent data check failed on magic byte"); } //check for valid network name if (bInitOk == true) { uint8_t brokerIp[4]; ReadBrokerIPAddress(brokerIp); for (int i=0;i<4;i++) { if (!((brokerIp[i] > 0) && (brokerIp[i] < 255))) { bInitOk = false; Serial.println("Persistent data check failed on broker IP address"); } } } // Check netowrk name if (bInitOk == true) { if (MyLoadState(NW_OFFSET) == 0xFF) { bInitOk = false; Serial.println("Persistent data check failed on network name"); } } if (bInitOk == true) { if (MyLoadState(NW_PASS_OFFSET) == 0xFF) { bInitOk = false; Serial.println("Persistent data check failed on network password"); } } return bInitOk; } void ReadNetworkName(String& networkName) { networkName = ""; char token[2]; int idx=0; do { token[0] = MyLoadState(NW_OFFSET + idx++); token[1] = '\0'; if (token[0] != '\0') { networkName+=token; } } while ((token[0] != '\0') && (idx < NW_SIZE)) ; } void ReadNetworkPass(String& networkPass) { networkPass = ""; char token[2]; int idx=0; do { token[0] = MyLoadState(NW_PASS_OFFSET + idx++); token[1] = '\0'; if (token[0] != '\0') { networkPass+=token; } } while ((token[0] != '\0') && (idx < NW_PASS_SIZE)) ; } void ReadBrokerIPAddress(uint8_t* pIPAddress) { for (int i=0;i<4;i++) { pIPAddress[i] = MyLoadState(BROKER_IPADDRESS_OFFSET+i); } } int ReadBrokerPort() { return (MyLoadState(BROKER_PORT_OFFSET) << 8) + MyLoadState(BROKER_PORT_OFFSET+1); } void InitializeDefaultBrokerIPAddress(uint8_t* pIPAddress) { for (int i=0;i<4;i++) { MySaveState(BROKER_IPADDRESS_OFFSET+i, pIPAddress[i]); } } void WriteMagicByte() { MySaveState(MAGIC_BYTE_OFFSET, MAGIC_BYTE); } void WriteBrokerIP(uint8_t *pIp) { for (int i=0;i<4;i++) { MySaveState(BROKER_IPADDRESS_OFFSET+i, pIp[i]); } } void WriteBrokerPort(int16_t port) { MySaveState(BROKER_PORT_OFFSET, port >> 8); MySaveState(BROKER_PORT_OFFSET + 1, port & 0xFF); } void WriteNetworkName(String NetworkName) { for (int i=0;i < NW_SIZE;i++) { if ((i < NetworkName.length()) && (i < NW_SIZE)) { MySaveState(NW_OFFSET + i, NetworkName[i]); } else { MySaveState(NW_OFFSET + i, 0x00); } } } void WriteNetworkPass(String NetworkPass) { for (int i=0;i < NW_PASS_SIZE;i++) { if ((i < NetworkPass.length()) && (i < NW_PASS_SIZE-1)) { MySaveState(NW_PASS_OFFSET + i, NetworkPass[i]); } else { MySaveState(NW_PASS_OFFSET + i, 0x00); } } } void InvalidateData() { MySaveState(MAGIC_BYTE_OFFSET, 0x00); }
c++
16
0.601425
84
19.261111
180
starcoderdata
import os from twilio.rest import Client account_sid = open('credentials','r').readlines()[0].strip() auth_token = open('credentials','r').readlines()[1].strip() client = Client(account_sid, auth_token) users = { "Andrew":"+17868777177", "Jonathan":"+16462150333", "Minghong": "+19518010312", "Shengyang": "+18056377924", "Janak": "+19292088929" } # for num in team_numbers.values(): # client.messages.create( # to = num, # from_ = "+18162392619 ", # body = "Hello! I am MediBo. Just wanted to say Hi and wanted to check if you are feeling fine today. " # )
python
11
0.674917
107
23.24
25
starcoderdata
def __init__(self, input_size, output_size, device, hidden_dim=128, num_heads=2, dim_feedforward=2048, dim_k=96, dim_v=96, dim_q=96, max_length=43): ''' :param input_size: the size of the input, which equals to the number of words in source language vocabulary :param output_size: the size of the output, which equals to the number of words in target language vocabulary :param hidden_dim: the dimensionality of the output embeddings that go into the final layer :param num_heads: the number of Transformer heads to use :param dim_feedforward: the dimension of the feedforward network model :param dim_k: the dimensionality of the key vectors :param dim_q: the dimensionality of the query vectors :param dim_v: the dimensionality of the value vectors ''' super(TransformerTranslator, self).__init__() assert hidden_dim % num_heads == 0 self.num_heads = num_heads self.word_embedding_dim = hidden_dim self.hidden_dim = hidden_dim self.dim_feedforward = dim_feedforward self.max_length = max_length self.input_size = input_size self.output_size = output_size self.device = device self.dim_k = dim_k self.dim_v = dim_v self.dim_q = dim_q seed_torch(0) ############################################################################## # TODO: # Deliverable 1: Initialize what you need for the embedding lookup. # # You will need to use the max_length parameter above. # # This should take 1-2 lines. # # Initialize the word embeddings before the positional encodings. # # Don’t worry about sine/cosine encodings- use positional encodings. # ############################################################################## self.word_embeddings = torch.nn.Embedding(self.input_size, self.word_embedding_dim).to(self.device) self.positional_encoder = torch.nn.Embedding(self.max_length, self.word_embedding_dim).to(self.device) ############################################################################## # END OF YOUR CODE # ############################################################################## ############################################################################## # Deliverable 2: Initializations for multi-head self-attention. # # You don't need to do anything here. Do not modify this code. # ############################################################################## # Head #1 self.k1 = torch.nn.Linear(self.hidden_dim, self.dim_k) self.v1 = torch.nn.Linear(self.hidden_dim, self.dim_v) self.q1 = torch.nn.Linear(self.hidden_dim, self.dim_q) # Head #2 self.k2 = torch.nn.Linear(self.hidden_dim, self.dim_k) self.v2 = torch.nn.Linear(self.hidden_dim, self.dim_v) self.q2 = torch.nn.Linear(self.hidden_dim, self.dim_q) self.ahp = torch.nn.Linear(self.dim_v * self.num_heads, self.hidden_dim) self.softmax_lay = torch.nn.Softmax(dim=2) ############################################################################## # TODO: # Deliverable 3: Initialize what you need for the feed-forward layer. # # Don't forget the layer normalization. # ############################################################################## self.linear1= torch.nn.Linear(self.hidden_dim,self.dim_feedforward) self.linear2= torch.nn.Linear(self.dim_feedforward,self.hidden_dim) self.norm_lay = torch.nn.LayerNorm(self.hidden_dim) self.relu_lay= torch.nn.ReLU() ############################################################################## # END OF YOUR CODE # ############################################################################## ############################################################################## # TODO: # Deliverable 4: Initialize what you need for the final layer (1-2 lines). # ############################################################################## self.linear3= torch.nn.Linear(self.hidden_dim,self.output_size) ############################################################################## # END OF YOUR CODE # ##############################################################################
python
10
0.428832
148
58.349398
83
inline
from flask import jsonify from pinterest import pinterest_app, client db = client.ejemplo # Select the database collection = db.notas @pinterest_app.route("/example") def example_select_all_queries(): cursor = collection.find() vector = [] for notas in cursor: print(notas) vector.append({ 'nota': notas['nota'], 'materia': notas['materia'] }) return jsonify(vector) @pinterest_app.route("/add") def example_insert_query(): cursor = collection.insert( { 'nota': 100, 'matera': 'cloud' } ) return jsonify("added")
python
13
0.560241
43
20.2
30
starcoderdata
def __init__(self, port=None, ledCount=10, buffered=True): """Creates a BlinkyPendant object and opens the port. Parameters: port Optional, port name as accepted by PySerial library: http://pyserial.sourceforge.net/pyserial_api.html#serial.Serial It is the same port name that is used in Arduino IDE. Ex.: COM5 (Windows), /dev/ttyACM0 (Linux). If no port is specified, the library will attempt to connect to the first port that looks like a BlinkyPendant. """ # If a port was not specified, try to find one and connect automatically if port == None: ports = listports.listPorts() if len(ports) == 0: raise IOError("BlinkyPendant not found!") port = listports.listPorts()[0] self.port = port # Path of the serial port to connect to self.ledCount = ledCount # Number of LEDs on the BlinkyTape self.buffered = buffered # If Frue, buffer output data before sending self.buf = "" # Color data to send self.serial = serial.Serial(port, 115200)
python
11
0.583815
84
43.888889
27
inline
func TestQueries(t *testing.T) { log.Printf("Seeding test items") FillTestItems("test_items", 0, 2500, 20) FillTestItems("test_items", 2500, 2500, 0) FillTestItemsForNot() if err := DB.CloseNamespace("test_items"); err != nil { panic(err) } if err := DB.OpenNamespace("test_items", reindexer.DefaultNamespaceOptions(), TestItem{}); err != nil { panic(err) } CheckTestItemsJsonQueries() CheckAggregateQueries() CheckTestItemsQueries() CheckTestItemsSQLQueries() CheckTestItemsDSLQueries() // Delete test tx := newTestTx(DB, "test_items") for i := 0; i < 4000; i++ { if err := tx.Delete(TestItem{ID: mkID(i)}); err != nil { panic(err) } } // Check insert after delete FillTestItemsTx(0, 500, 0, tx) //Check second update FillTestItemsTx(0, 1000, 5, tx) for i := 0; i < 5000; i++ { tx.Delete(TestItem{ID: mkID(i)}) } // Stress test delete & update & insert for i := 0; i < 5000; i++ { tx.Delete(TestItem{ID: mkID(rand.Int() % 500)}) FillTestItemsTx(rand.Int()%500, 1, 0, tx) tx.Delete(TestItem{ID: mkID(rand.Int() % 500)}) FillTestItemsTx(rand.Int()%500, 1, 10, tx) if (i % 1000) == 0 { tx.Commit(nil) tx = newTestTx(DB, "test_items") } } tx.Commit(nil) FillTestItems("test_items", 3000, 1000, 0) FillTestItems("test_items", 4000, 500, 20) CheckTestItemsQueries() CheckTestItemsSQLQueries() CheckTestItemsDSLQueries() }
go
17
0.659957
104
22.2
60
inline
package cloud.qasino.card.service; import cloud.qasino.card.repository.PlayerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PlayerService { @Autowired private PlayerRepository repository; public int countByGameId(int gameId) { final long count = repository.count(); return (int) count; } }
java
7
0.745136
75
26.722222
18
starcoderdata
package engine.game.eventobserver; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import engine.entities.Entity; import exceptions.ObservableException; /** * Observer superclass for the Observable Design Pattern for detecting and responding to Events. * Subclasses contain Lists of ObservableEntities that will listen to the * corresponding Observer. Class is abstract since you should only be able to * instantiate specific subclasses of EventObserver. Assumes that the argument of attach() * refers to an existing Entity in the game, and that of detach() refers to an Entity * in the "observers" List. Dependencies are Entity and ObservableException. * * Example of use: * observable = new TimerObservable(); * ... * for(Entity entity : levelManager.getCurrentLevel().getEntities()){ * observable.attach(entity); * } * ... * observable.updateObservers(); * ... * for(Entity entity : levelManager.getCurrentLevel().getEntities()){ * observable.detach(entity); * } * * * @author * */ public abstract class EventObservable { private List observers; private transient ResourceBundle resources = ResourceBundle.getBundle("resources/Strings"); public EventObservable() { observers = new ArrayList<>(); } /** * Engine External API. Adds toAttach to the appropriate List(s) of * ObservableEntities that will update upon calling updateObservables(). * Assumes that "toDetach" must be the same * object in memory as originally added to the list. * * @param toAttach the Entity to attach */ public void attach(Entity toAttach) { observers.add(toAttach); } /** * Engine External API. Removes toDetach from all Lists of * ObservableEntities that will update upon calling updateObservables(). * Assumes that observers.contains(toDetach) is true * * @param toDetach the Entity to remove from observers */ public void detach(Entity toDetach) { try { if(observers.contains(toDetach)){ observers.remove(observers.indexOf(toDetach)); } } catch (Exception e) { throw new ObservableException(resources.getString("EntityNotAttached")); } } /** * Engine External API. Assumption is that it is called on every iteration * of the game loop during game play. Takes whatever action is appropriate * on each iteration of the game loop specific to each observable subclass. */ public abstract void updateObservers(); /** * Returns the observers List * @return observers */ public List getObservers() { return observers; } public void setObservers(List observers){ this.observers = observers; } }
java
14
0.735316
96
28.934066
91
starcoderdata
#include #include "../header/constant.h" #include "../header/function.h" //initialise la grille du jeu a 0 void initGrid(int g[6][7]) { for(int i=0 ; i<nbl ; i++) { for(int j=0 ; j<nbc ; j++) { g[i][j] = BLANK; } } } //affiche la grille à l'écran d'apres le cahier des charges void printGrid(int g[6][7]) { for(int i=0 ; i<nbl ; i++) { for(int j=0 ; j<nbc ; j++) { switch(g[i][j]) { case BLANK: putchar('.'); break; case YELLOW: putchar('O'); break; case RED: putchar('X'); break; } putchar(' '); } putchar('\n'); } putchar('\n'); printf("------------- "); putchar('\n'); printf("1 2 3 4 5 6 7 "); putchar('\n'); } //demande a l'utilisateur de choisir un coup int chooseMove(int player) { int move; //Ajouter un message pour le joueur rouge ou jaune printf("\nChoisissez un coup : "); scanf("%d", &move); return move; } //verifie si le coup est valide int isValidMove(int g[6][7], int col) { //Cas coup entre 1 et 7 if( col > 7 || col < 1 ) { printf("\nERREUR : colone invalide\n"); return 0; } //Cas colonne pleine if( g[0][col] != 0 ) { printf("\nERREUR : colone pleine\n"); return 0; } return 1; } //place le jeton dans la grille void putToken(int g[6][7], int col, int player) { printf("putToken non implémentée\n"); } //verifie si il existe un alignement int verifAlign(int g[6][7], int player) { printf("verifAlign non implémentée\n"); return 0; } //revoi 1 si le coup est dans la grille sinon 0 int isInGrid() { printf("isInGrid non implémentée\n"); return 0; } //affiche un message de resultat void printRes(int player) { switch(player) { case 1: printf("\nLe joueur JAUNE a gagner\n"); break; case 0: printf("\nLe joueur ROUGE a gagner\n"); break; default: printf("\nERREUR : numero de joueur invalide\n"); } } //joueur suivant int nextPlayer(int player) { return (player + 1) % 2; } char wantReplay() { char choice; printf("Vous voulez rejouez ? (o/n)"); scanf("%c", &choice); return choice; }
c
14
0.506789
61
17.555556
135
starcoderdata
#ifndef _TOUCH_CALIB_H_ #define _TOUCH_CALIB_H_ #include #include void drawMark(uint16_t x, uint16_t y); void waitTouch(); void waitRelase(); void fail(); void keepHolding(); void initialize(); TSPoint readValues(uint16_t posX, uint16_t posY); void deletePoint(uint8_t strt, uint16_t (&arr)[16], uint8_t num); void insertValue(uint16_t val, uint16_t (&arr)[16]); void printResults(); void optimizeSamples(); void calcCoef(); void calibrate(); void map2Screen(uint16_t &x, uint16_t &y); void setup(); void loop(); #endif
c
10
0.723975
73
22.481481
27
starcoderdata
package com.codeforces.commons.cache.util; import com.codeforces.commons.cache.ByteCache; /** * @author ( * Date: 16.02.11 */ public final class Caches { private Caches() { throw new UnsupportedOperationException(); } public static ByteCache newAsynchronousByteCache(ByteCache cache) { return new AsynchronousByteCache(cache, 0, 0); } public static ByteCache newAsynchronousByteCache( ByteCache cache, long validationTimeoutMillis, long disableOnFailMillis) { return new AsynchronousByteCache(cache, validationTimeoutMillis, disableOnFailMillis); } public static ByteCache newLocalAndRemoteByteCache(ByteCache localCache, ByteCache remoteCache) { return new LocalAndRemoteByteCache(localCache, remoteCache); } public static ByteCache newSilentByteCache(ByteCache cache) { return new SilentByteCache(cache); } public static ByteCache newLocalAndRemoteByteCache( ByteCache localCache, ByteCache remoteCache, boolean localCacheOptional, boolean remoteCacheOptional) { return new LocalAndRemoteByteCache(localCache, remoteCache, localCacheOptional, remoteCacheOptional); } public static ByteCache newLoggingByteCache(ByteCache cache) { return LoggingByteCache.newInstance(cache); } public static ByteCache newSynchronizedByteCache(ByteCache cache) { return new SynchronizedByteCache(cache); } }
java
8
0.741146
115
34.295455
44
starcoderdata
package com.kou.user.service.dao; import com.kou.common.base.BaseDao; import com.kou.user.service.model.Employee; /** * 员工 dao接口 */ public interface EmployeeDao extends BaseDao { }
java
7
0.746193
56
14.230769
13
starcoderdata
package find import "fmt" // Find return the first index that b in a, realized the BM string search algo func Find(a, b string) int { n, m := len(a), len(b) if n == 0 || m == 0 || m > n { return -1 } bc := generateBC(b) suffix, prefix := generateGS(b) var step, gsStep int for i := 0; i < n-m+1; i += step { j := m - 1 //find for ; a[i+j] == b[j]; j-- { if j == 0 { return i } } //bc step step = j - (bc[a[i+j]] - 1) bcStep := step // for log gsStep = 0 //for log //gs step if j < m-1 { j = j + 1 //good suffix's first index gsStep = j - (suffix[j] - 1) if suffix[j] == 0 { for j = j + 1; j < m-1; j++ { if prefix[j] { gsStep = j } } } if gsStep > step { step = gsStep } } if step < 1 { step = 1 } fmt.Printf("bc: %s, step: %d, bcStep: %d, gsStep: %d, a: %s\n", string(a[i+j]), step, bcStep, gsStep, a[0:i+m]) } return -1 } func generateBC(b string) map[byte]int { bc := make(map[byte]int) for i := 0; i < len(b); i++ { bc[b[i]] = i + 1 } return bc } // generateGS generate suffix and prefix map // suffix is a map from the first index of good suffix to the first index of last same string // prefix is a map from the first index of good suffix to a bool that is same with the prefix of string func generateGS(b string) ([]int, []bool) { m := len(b) suffix := make([]int, m) prefix := make([]bool, m) for i := 0; i < m-1; i++ { j := i k := m - 1 for j >= 0 && b[j] == b[k] { suffix[k] = j if j == 0 { prefix[k] = true } j-- k-- } } return suffix, prefix }
go
15
0.522388
114
18.373494
83
starcoderdata
package entidades.usuarios; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import estruturas.RegistroHashExtensivel; public class ParEmailID implements RegistroHashExtensivel { private String email; private int id; private short TAMANHO = 44; public ParEmailID() { this("", -1); } public ParEmailID(String e, int i) { try { this.email = e; this.id = i; if (e.length() + 4 > TAMANHO) throw new Exception("Número de caracteres do email maior que o permitido. Os dados serão cortados."); } catch (Exception ec) { ec.printStackTrace(); } } @Override public int hashCode() { return this.email.hashCode(); } public short size() { return this.TAMANHO; } public String toString() { return this.email + ";" + this.id; } public int getID(){ return this.id; } public String getEmail(){ return this.email; } public byte[] toByteArray() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeUTF(email); dos.writeInt(id); byte[] bs = baos.toByteArray(); byte[] bs2 = new byte[TAMANHO]; for (int i = 0; i < TAMANHO; i++) bs2[i] = ' '; for (int i = 0; i < bs.length && i < TAMANHO; i++) bs2[i] = bs[i]; return bs2; } public void fromByteArray(byte[] ba) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(ba); DataInputStream dis = new DataInputStream(bais); this.email = dis.readUTF(); this.id = dis.readInt(); } }
java
11
0.666112
109
24.771429
70
starcoderdata
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Groupe extends Model { protected $fillable = [ 'name','roles' ]; public function __toString(){ return $this->name; } public function __toHtml(){ return ( $this->id ) ? '<a href="'.route('groupe_edit',$this->id).'" target="_blank">'.$this->name.' : ""; } public function getname(){ return $this->name; } public function getroles(){ return $this->roles; } public function users(){ return $this->hasMany('User','usergroupe','groupe_id'); } public function get__roles(){ return array( 'Groupe' => 'Groups', 'User' => 'Users', 'Module' => 'Modules', 'Session' => 'Sessons', 'Justification' => 'Justification', ); } }
php
16
0.498335
119
20.97561
41
starcoderdata
/* Copyright 2016 Utrecht University http://www.uu.nl/ This software has been created in the context of the EU-funded RAGE project. Realising and Applied Gaming Eco-System (RAGE), Grant agreement No 644187, http://rageproject.eu/ The Behavior Markup Language (BML) is a language whose specifications were developed in the SAIBA framework. More information here : http://www.mindmakers.org/projects/bml-1-0/wiki Created by: Christyowidiasmoro, Utrecht University For more information, contact Dr. Email: Web: http://www.zerrinyumak.com/ https://www.staff.science.uu.nl/~yumak001/UUVHC/index.html */ using System.Xml; namespace BMLRealizer { /// /// Currently, BML offers two types of gesture behaviors. The first provides a set of gestures recalled by name from a gesticon; the second provides simple pointing gestures. /// Coordinated movement with arms and hands, recalled from a gesticon by requesting the corresponding lexeme /// public class BMLGesture : BMLBehavior { /// /// What hand/arm is being used /// public Mode mode; /// /// Refers to an animation or a controller to realize this particular gesture. /// public Lexeme lexeme; /// /// What hand/arm is being used /// public enum Mode { NONE, LEFT_HAND, RIGHT_HAND, BOTH_HANDS } /// /// Refers to an animation or a controller to realize this particular gesture. /// public enum Lexeme { BEAT } /// /// constructor /// public BMLGesture() { } /// /// parsing the xml /// atribute: mode, lexeme /// sync point: start, ready, strokeStart, stroke, strokeEnd, relax, end /// /// <param name="reader"> public override void Parse(XmlReader reader) { base.Parse(reader); mode = TryParseAtribute "mode", Mode.NONE, false); lexeme = TryParseAtribute "lexeme", Lexeme.BEAT, true); TryParseSyncPoint(reader, "start"); TryParseSyncPoint(reader, "ready"); TryParseSyncPoint(reader, "stroke_start"); TryParseSyncPoint(reader, "stroke"); TryParseSyncPoint(reader, "stroke_end"); TryParseSyncPoint(reader, "relax"); TryParseSyncPoint(reader, "end"); } } }
c#
13
0.59695
178
30.306818
88
starcoderdata
package com.etemu.pens.mvp.ui.uploudmissingitemlist; import android.widget.Spinner; import com.etemu.pens.mvp.data.network.model.UploadMissingItem; import com.etemu.pens.mvp.data.network.model.UploadMissingItemResponse; import com.etemu.pens.mvp.ui.base.MvpView; import java.util.List; public interface UploadMissingItemListMvpView extends MvpView { void updateUploadMissingItemList(List uploadMissingItem); void setupCategoryItem(List stringList, Spinner spinner); void setupCategoryList(List stringList); }
java
9
0.824253
88
34.5625
16
starcoderdata
import os, sys, shutil, json import urllib.request as req URLS = 1 << 0 LOCAL_FILES = 1 << 1 LOCAL_DIRS = 1 << 2 ALL = URLS | LOCAL_FILES | LOCAL_DIRS DEFAULT_JSON_URL = "https://bitbucket.org/Josef21296/various-resources/raw/55ac88d9f8d97a4649b67cf70596f8bcd16af066/Templates/templates_source.json" DEFAULT_JSON_NAME = "templates_source.json" class Templates: # Creates the Templates object. Templates origin can be passed as parameter; if both local and hosted are provided, hosted one will be used. def __init__(self, data_path="", data_url="", warn_if_empty=True): # Will priorize online hosted one if data_url != "": self.LoadDataFromUrl(data_url) elif data_path != "": self.LoadLocalData(data_path) else: if warn_if_empty == True: print("WARNING: No template info provided.") self.data = 0 # Loads the templates data from a local json file. def LoadLocalData(self, path): print("Loading templates data from local json: " + path); with open(path) as file_data: self.data = json.load(file_data) # Loads the templates data from a hosted json file. def LoadDataFromUrl(self, url): print("Loading templates data from hosted json: " + url); with req.urlopen(url) as res: self.data = json.loads(res.read()) def IsTemplateDataLoaded(self): return self.data != 0 # Copy a template project. Origin determines from where # (ALL: tries to get all the sources available), # (URLS: only search for files hoested online), # (LOCAL_FILES: only searches for defined local single files), # (LOCAL_DIRS: only searches for defined local dirs and copes all files in there) def CopyTemplate(self, project, destination=os.getcwd(), origin=ALL): if not self.data: print("ERROR: Templates data not loaded!") return if project == "default": try: project = self.data['default'] except KeyError: print("ERROR: Default key not setted.") return if project in self.data: print("Creating project from template: " + project) template = self.data[project] if origin & URLS and 'urls' in template: print("Getting templates from URLS") for file, url in template['urls'].items(): self.CopyFileFromUrl(url, file, destination) if origin & LOCAL_FILES and 'local_files' in template: print("Getting templates from LOCAL_FILES") for file, dir in template['local_files'].items(): self.CopyFileFromLocal(file, dir, destination) if origin & LOCAL_DIRS and 'local_dirs' in template: print("Getting templates from LOCAL_DIRS") for dir in template['local_dirs']: self.CopyFilesFromDir(dir, destination) else: print("ERROR: Project not found... [" + project + "].") # Copy a single file from the url def CopyFileFromUrl(self, url, dst_file, dst_dir): with req.urlopen(url) as response, open(os.path.join(dst_dir, dst_file), 'wb') as out_file: shutil.copyfileobj(response, out_file) # Copy a single src file from local src directory to a dst directory def CopyFileFromLocal(self, src_file, src_dir, dst_dir): if os.path.isfile(os.path.join(src_dir, src_file)): shutil.copy(os.path.join(src_dir, src_file), os.path.join(dst_dir, src_file)) # Copy all files from a src directory into the des directory def CopyFilesFromDir(self, src_dir, dst_dir): for file_name in os.listdir(src_dir): file = os.path.join(src_dir, file_name) if os.path.isfile(file): shutil.copy(file, os.path.join(dst_dir, file_name)) # Displays the help info about the application and list all the templates abailable def Help(self): print(" - Help: This script will create a copy of a template into your current directory. \nArguments:") print("\t-h: Help.") print("\t Will use p5.js as default.") print("--------------------------------------------") for proj, data in self.data.items(): if proj == "default": print("\tDefault: " + str(data)) else: print("\t" + proj + ": ") print("\t \t-Have urls: " + str('urls' in data)) print("\t \t-Have local files: " + str('local_files' in data)) print("\t \t-Have local dirs: " + str('local_dirs' in data)) print("--------------------------------------------")
python
18
0.591414
148
39.12605
119
starcoderdata
using SstRegistrationTestHarness.Core.SstRegistrationService; namespace SstRegistrationTestHarness.Core.Domain { public class ContactSellerInfo { public string FirstName { get; set; } public string LastName { get; set; } public string InitialName { get; set; } public string Phone { get; set; } public string PhoneExtention { get; set; } public string Email { get; set; } public ContactSellerInfo(string firstName, string lastName, string phone, string email) { FirstName = firstName; LastName = lastName; Phone = phone; Email = email; } public ContactType MapContactInformation() { return new ContactType { ContactName = new IndividualNameType { FirstName = FirstName, LastName = LastName, MiddleInitial = InitialName }, ContactPhone = Phone, ContactPhoneExt = PhoneExtention, ContactEmail = Email }; } } }
c#
15
0.542709
95
29.526316
38
starcoderdata
<?php include_once APPPATH . '/third_party/fpdf/fpdf.php'; class PDF extends FPDF{ function Header() { $this->SetDisplayMode(100,'default'); $this->Image(base_url('resource/logo.png'),15,10,20,20); $this->SetFont('Arial','B',16); $this->Cell(190,7,'CELCIUS',0,1,'C'); $this->SetFont('Arial','B',12); $this->Cell(190,7,'Jl. TAPOS No 10 Palingam',0,1,'C'); $this->SetFont('Arial','i',9); $this->Cell(190,7,'Telpon : 089525761176, FAX : 898989, Email : $this->SetLineWidth(1); $this->Line(10,36,195,36); $this->SetLineWidth(0); $this->Line(10,37,195,37); $this->Cell(10,7,'',0,1); $this->Cell(10,7,'',0,1); } function Footer() { $this->SetY(-15); $this->SetFont('Arial','I',8); $this->Cell(0,10,'Halaman '.$this->PageNo().'',0,0,'R'); } } ?>
php
13
0.522075
90
30.275862
29
starcoderdata
<?php include '../../../server/proses/get_tanah.php'; ?> <!-- Script JS Menu--> <div id="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="#">Lakalantas <li class="breadcrumb-item active">Selamat datang <div class="row"> <div class="col-sm-8"> <div class="panel-body"> <div id="map" style="width:100%;height:400px; z-index:60"> function initMap() //google maps { map = new google.maps.Map(document.getElementById('map'), { zoom: 13, center: new google.maps.LatLng(-0.9140897,100.4565161), mapTypeId: google.maps.MapTypeId.ROADMAP, }); } <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA1TwYksj1uQg1V_5yPUZqwqYYtUIvidrY&callback=initMap" async defer> <!-- /.container-fluid --> <!-- Sticky Footer --> <footer class="sticky-footer"> <div class="container my-auto"> <div class="copyright text-center my-auto"> © Your Website 2018 <!-- /.content-wrapper -->
php
4
0.443114
118
25.507937
63
starcoderdata
// Copyright 2016-2020, Pulumi Corporation. // // 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 auto import ( "regexp" "strings" "github.com/pkg/errors" ) type autoError struct { stdout string stderr string code int err error } func newAutoError(err error, stdout, stderr string, code int) autoError { return autoError{ stdout, stderr, code, err, } } func (ae autoError) Error() string { return errors.Wrapf(ae.err, "code: %d\n, stdout: %s\n, stderr: %s\n", ae.code, ae.stdout, ae.stderr).Error() } // IsConcurrentUpdateError returns true if the error was a result of a conflicting update locking the stack. func IsConcurrentUpdateError(e error) bool { ae, ok := e.(autoError) if !ok { return false } return strings.Contains(ae.stderr, "[409] Conflict: Another update is currently in progress.") } // IsSelectStack404Error returns true if the error was a result of selecting a stack that does not exist. func IsSelectStack404Error(e error) bool { ae, ok := e.(autoError) if !ok { return false } regex := regexp.MustCompile(`no stack named.*found`) return regex.MatchString(ae.stderr) } // IsCreateStack409Error returns true if the error was a result of creating a stack that already exists. func IsCreateStack409Error(e error) bool { ae, ok := e.(autoError) if !ok { return false } regex := regexp.MustCompile(`stack.*already exists`) return regex.MatchString(ae.stderr) } // IsCompilationError returns true if the program failed at the build/run step (only Typescript, Go, .NET) func IsCompilationError(e error) bool { as, ok := e.(autoError) if !ok { return false } // dotnet if strings.Contains(as.stdout, "Build FAILED.") { return true } // go // TODO: flimsy for go if strings.Contains(as.stdout, ": syntax error:") { return true } if strings.Contains(as.stdout, ": undefined:") { return true } // typescript if strings.Contains(as.stdout, "Unable to compile TypeScript") { return true } return false } // IsRuntimeError returns true if there was an error in the user program at during execution. func IsRuntimeError(e error) bool { as, ok := e.(autoError) if !ok { return false } if IsCompilationError(e) { return false } // js/ts/dotnet/python if strings.Contains(as.stdout, "failed with an unhandled exception:") { return true } // go if strings.Contains(as.stdout, "panic: runtime error:") { return true } if strings.Contains(as.stdout, "an unhandled error occurred:") { return true } if strings.Contains(as.Error(), "go inline source runtime error") { return true } return false } // IsUnexpectedEngineError returns true if the pulumi core engine encountered an error (most likely a bug). func IsUnexpectedEngineError(e error) bool { // TODO: figure out how to write a test for this as, ok := e.(autoError) if !ok { return false } return strings.Contains(as.stdout, "The Pulumi CLI encountered a fatal error. This is a bug!") }
go
10
0.71367
109
22.849315
146
starcoderdata
public void logSync() { ArrayList<EditLogOutputStream> errorStreams = null; long syncStart = 0; // Fetch the transactionId of this thread. long mytxid = myTransactionId.get().txid; ArrayList<EditLogOutputStream> streams = new ArrayList<EditLogOutputStream>(); boolean sync = false; try { synchronized (this) { try { printStatistics(false); // if somebody is already syncing, then wait while (mytxid > synctxid && isSyncRunning) { try { wait(1000); } catch (InterruptedException ie) { } } // // If this transaction was already flushed, then nothing to do // if (mytxid <= synctxid) { numTransactionsBatchedInSync++; if (metrics != null) // Metrics is non-null only when used inside name node metrics.transactionsBatchedInSync.inc(); return; } // now, this thread will do the sync syncStart = txid; isSyncRunning = true; sync = true; // swap buffers assert editStreams.size() > 0 : "no editlog streams"; for(EditLogOutputStream eStream : editStreams) { try { eStream.setReadyToFlush(); streams.add(eStream); } catch (IOException ie) { LOG.error("Unable to get ready to flush.", ie); // // remember the streams that encountered an error. // if (errorStreams == null) { errorStreams = new ArrayList<EditLogOutputStream>(1); } errorStreams.add(eStream); } } } finally { // Prevent RuntimeException from blocking other log edit write doneWithAutoSyncScheduling(); } } // do the sync long start = now(); for (EditLogOutputStream eStream : streams) { try { eStream.flush(); } catch (IOException ie) { LOG.error("Unable to sync edit log.", ie); // // remember the streams that encountered an error. // if (errorStreams == null) { errorStreams = new ArrayList<EditLogOutputStream>(1); } errorStreams.add(eStream); } } long elapsed = now() - start; processIOError(errorStreams, true); if (metrics != null) // Metrics non-null only when used inside name node metrics.syncs.inc(elapsed); } finally { // Prevent RuntimeException from blocking other log edit sync synchronized (this) { if (sync) { synctxid = syncStart; isSyncRunning = false; } this.notifyAll(); } } }
java
21
0.543651
85
29.472527
91
inline
#pragma once #include #include class Act { protected: int numar; // Construieste un nou act de identificare Act(int nr); /// Calculeaza numarul de cifre ale unui intreg static int numarCifre(int nr); public: virtual ~Act(); virtual void afisare(std::ostream& out) const = 0; /// Citeste tipul de act al candidatului si datele din act static Act* citeste(std::istream& in); friend std::ostream& operator<<(std::ostream& out, const Act& act); }; class CI : public Act { // Seria de buletin std::string serie; public: CI(const std::string& serie, int numar); void afisare(std::ostream& out) const override; }; class Pasaport : public Act { public: Pasaport(int numar); void afisare(std::ostream& out) const override; };
c++
10
0.660517
71
18.829268
41
starcoderdata
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Sepes.Azure.Dto; namespace Sepes.Azure.Service.Interface { public interface IAzureDiskPriceService { Task<Dictionary<string, AzureDiskPriceForRegion>> GetDiskPrices(string region = null, CancellationToken cancellationToken = default); } }
c#
10
0.782486
141
28.583333
12
starcoderdata
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS { using System; /// /// A GroupNamedPropInfo has a dispid. /// public class DispidGroupNamedPropInfo : GroupNamedPropInfo { /// /// The dispid. /// private uint dispid; /// /// Initializes a new instance of the DispidGroupNamedPropInfo class. /// /// <param name="stream">A FastTransferStream public DispidGroupNamedPropInfo(FastTransferStream stream) : base(stream) { } /// /// Gets or sets the dispid. /// public uint Dispid { get { return this.dispid; } set { this.dispid = value; } } /// /// Verify that a stream's current position contains a serialized DispidGroupNamedPropInfo. /// /// <param name="stream">A FastTransferStream /// the stream's current position contains /// a serialized DispidGroupNamedPropInfo, return true, else false public static bool Verify(FastTransferStream stream) { return stream.VerifyUInt32(Guid.Empty.ToByteArray().Length) == 0x00000000; } /// /// Deserialize a DispidGroupNamedPropInfo instance from a FastTransferStream. /// /// <param name="stream">A FastTransferStream /// DispidGroupNamedPropInfo instance public static new LexicalBase DeserializeFrom(FastTransferStream stream) { return new DispidGroupNamedPropInfo(stream); } /// /// Deserialize next object from a FastTransferStream /// /// <param name="stream">A FastTransferStream public override void ConsumeNext(FastTransferStream stream) { base.ConsumeNext(stream); this.dispid = stream.ReadUInt32(); } } }
c#
14
0.586207
111
33.19697
66
starcoderdata
// // infdata.h // #ifdef DECLARE_DATA SHORT g_StaticDistanceTreeTable[STATIC_BLOCK_DISTANCE_TABLE_SIZE]; SHORT g_StaticLiteralTreeTable[STATIC_BLOCK_LITERAL_TABLE_SIZE]; #else extern SHORT g_StaticDistanceTreeTable[STATIC_BLOCK_DISTANCE_TABLE_SIZE]; extern SHORT g_StaticLiteralTreeTable[STATIC_BLOCK_LITERAL_TABLE_SIZE]; #endif
c
5
0.727027
76
28.833333
12
starcoderdata
// // ZQ_ViewController.h // 朝阳项目 // // Created by NIT on 15/5/4. // Copyright (c) 2015年 ZQ. All rights reserved. // #import #import "UIViewController+HUD.h" @interface ZQ_ViewController : UIViewController /** 用于无UINavigationController作为容器的viewController中 */ @property (nonatomic, strong) UIView *contentView; @end
c
4
0.722714
52
18.941176
17
starcoderdata
static void watch_target(struct xenbus_watch *watch, const char **vec, unsigned int len) { unsigned long long new_target; int err; err = xenbus_scanf(XBT_NIL, "memory", "target", "%llu", &new_target); if (err != 1) { /* This is ok (for domain0 at least) - so just return */ return; } /* The given memory/target value is in KiB, so it needs converting to * pages. PAGE_SHIFT converts bytes to pages, hence PAGE_SHIFT - 10. */ balloon_set_new_target(new_target >> (PAGE_SHIFT - 10)); }
c
9
0.664683
70
28.705882
17
inline
using System; using System.Collections.Generic; using System.IO; using System.IO.Packaging; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Markup; using System.Windows.Media.Imaging; namespace YATE { public enum ImageContentType { ImageBmpContentType = 0, ImageGifContentType = 1, ImageJpegContentType = 2, ImageTiffContentType = 3, ImagePngContentType = 4 }; internal class WpfPayload { private const string XamlPayloadDirectory = "/Xaml"; // private const string XamlEntryName = "/Document.xaml"; // private const string XamlContentType = "application/vnd.ms-wpf.xaml+xml"; private const string XamlImageName = "/Image"; // private const string XamlRelationshipFromPackageToEntryPart = "http://schemas.microsoft.com/wpf/2005/10/xaml/entry"; private const string XamlRelationshipFromXamlPartToComponentPart = "http://schemas.microsoft.com/wpf/2005/10/xaml/component"; internal static readonly string[] ImageContentTypeName = { "image/bmp", "image/gif", "image/jpeg", "image/tiff","image/png"}; internal static readonly string[] ImageFileExtension = { ".bmp", ".gif", ".gif", ".tiff",".png"}; Package _package = null; private static BitmapEncoder GetBitmapEncoder(ImageContentType imageContentType) { BitmapEncoder bitmapEncoder; switch (imageContentType) { case ImageContentType.ImageBmpContentType: bitmapEncoder = new BmpBitmapEncoder(); break; case ImageContentType.ImageGifContentType: bitmapEncoder = new GifBitmapEncoder(); break; case ImageContentType.ImageJpegContentType: bitmapEncoder = new JpegBitmapEncoder(); break; case ImageContentType.ImageTiffContentType: bitmapEncoder = new TiffBitmapEncoder(); break; case ImageContentType.ImagePngContentType: bitmapEncoder = new PngBitmapEncoder(); break; default: bitmapEncoder = new PngBitmapEncoder(); break; } return bitmapEncoder; } // Returns a file extension corresponding to a given imageContentType private static string GetImageFileExtension(ImageContentType imageContentType) { return ImageFileExtension[(int)imageContentType]; } private static string GetImageContentName(ImageContentType imageContentType) { return ImageContentTypeName[(int)imageContentType]; } WpfPayload(Package p = null) { this._package = p; } private Package CreatePackage(Stream stream) { _package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite); return _package; } // Generates a image part Uri for the given image index private static string GetImageName(int imageIndex, ImageContentType imageContentType) { string imageFileExtension = GetImageFileExtension(imageContentType); return XamlImageName + (imageIndex + 1) + imageFileExtension; } // Generates a relative URL for using from within xaml Image tag. private static string GetImageReference(string imageName) { return "." + imageName; // imageName is supposed to be created by GetImageName method } private PackagePart CreateWpfEntryPart() { // Define an entry part uri Uri entryPartUri = new Uri(XamlPayloadDirectory + XamlEntryName, UriKind.Relative); // Create the main xaml part PackagePart part = _package.CreatePart(entryPartUri, XamlContentType, CompressionOption.Normal); // Compression is turned off in this mode. //NotCompressed = -1, // Compression is optimized for a resonable compromise between size and performance. //Normal = 0, // Compression is optimized for size. //Maximum = 1, // Compression is optimized for performance. //Fast = 2 , // Compression is optimized for super performance. //SuperFast = 3, // Create the relationship referring to the entry part PackageRelationship entryRelationship = _package.CreateRelationship(entryPartUri, TargetMode.Internal, XamlRelationshipFromPackageToEntryPart); return part; } private void CreateImagePart(PackagePart sourcePart, BitmapSource imageSource, ImageContentType imageContentType, int imageIndex) { // Generate a new unique image part name string imagePartUriString = GetImageName(imageIndex, imageContentType); // Define an image part uri Uri imagePartUri = new Uri(XamlPayloadDirectory + imagePartUriString, UriKind.Relative); // Create a part for the image PackagePart imagePart = _package.CreatePart(imagePartUri, GetImageContentName(imageContentType), CompressionOption.NotCompressed); // Create the relationship referring from the enrty part to the image part PackageRelationship componentRelationship = sourcePart.CreateRelationship(imagePartUri, TargetMode.Internal, XamlRelationshipFromXamlPartToComponentPart); // Encode the image data BitmapEncoder bitmapEncoder = GetBitmapEncoder(imageContentType); bitmapEncoder.Frames.Add(BitmapFrame.Create(imageSource)); // Save encoded image data into the image part in the package Stream imageStream = imagePart.GetStream(); using (imageStream) { bitmapEncoder.Save(imageStream); } } internal PackagePart GetWpfEntryPart() { PackagePart wpfEntryPart = null; // Find a relationship to entry part PackageRelationshipCollection entryPartRelationships = _package.GetRelationshipsByType(XamlRelationshipFromPackageToEntryPart); PackageRelationship entryPartRelationship = null; foreach (PackageRelationship packageRelationship in entryPartRelationships) { entryPartRelationship = packageRelationship; break; } // Get a part referred by this relationship if (entryPartRelationship != null) { // Get entry part uri Uri entryPartUri = entryPartRelationship.TargetUri; // Get the enrty part wpfEntryPart = _package.GetPart(entryPartUri); } return wpfEntryPart; } private static int imageIndex = 0; [System.Security.SecurityCritical] internal static Stream SaveImage(BitmapSource bitmapSource, ImageContentType imageContentType) { MemoryStream stream = new MemoryStream(); // Create the wpf package in the stream WpfPayload wpfPayload = new WpfPayload(); using (wpfPayload.CreatePackage(stream)) { PackagePart xamlEntryPart = wpfPayload.CreateWpfEntryPart(); Stream xamlPartStream = xamlEntryPart.GetStream(); using (xamlPartStream) { // int imageIndex = 0; imageIndex++; string imageReference = GetImageReference(GetImageName(imageIndex, imageContentType)); StreamWriter xamlPartWriter = new StreamWriter(xamlPartStream); using (xamlPartWriter) { string xamlText = "<Span xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" + " " + "Width=\"" + bitmapSource.Width + "\" " + "Height=\"" + bitmapSource.Height + "\" " + "> CacheOption=\"OnLoad\" UriSource=\"" + imageReference + "\"/> xamlPartWriter.Write(xamlText); } wpfPayload.CreateImagePart(xamlEntryPart, bitmapSource, imageContentType, imageIndex); } } return stream; } static int _wpfPayloadCount; // used to disambiguate between all acts of loading from different WPF payloads. internal static object LoadElement(Stream stream) { Package package = Package.Open(stream, FileMode.Open, FileAccess.Read); WpfPayload wpfPayload = new WpfPayload(package); PackagePart xamlEntryPart = wpfPayload.GetWpfEntryPart(); int newWpfPayoutCount = _wpfPayloadCount++; Uri payloadUri = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute); Uri entryPartUri = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part Uri packageUri = PackUriHelper.GetPackageUri(entryPartUri); // extracts package uri from combined package+part uri PackageStore.AddPackage(packageUri, wpfPayload.Package); // Register the package ParserContext parserContext = new ParserContext(); parserContext.BaseUri = entryPartUri; object xamlObject = XamlReader.Load(xamlEntryPart.GetStream(), parserContext); // Remove the temporary uri from the PackageStore PackageStore.RemovePackage(packageUri); return xamlObject; } public Package Package { get { return _package; } } }; }
c#
28
0.607101
166
39.793651
252
starcoderdata