code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
package org.exercise.ssss.controller; import java.util.List; import org.exercise.ssss.dao.StudentRepository; import org.exercise.ssss.model.ClassEntity; import org.exercise.ssss.model.StudentEntity; import org.exercise.ssss.service.StudentService; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/students") public class StudentController extends SsssController<StudentEntity, Long, StudentRepository, StudentService> { @RequestMapping(value = "/{id}/classes", method = RequestMethod.GET) public ResponseEntity getClasses(@PathVariable Long id) { return ResponseEntity.ok(getService().get(id).getClasses()); } @Override public boolean validateAdd(StudentEntity entity) { if (entity.getId() != null) { return false; } return validateEmptyFields(entity); } @Override public boolean validateUpdate(StudentEntity entity) { return validateEmptyFields(entity); } @Override public boolean validateDelete(Long id) { return super.validateDelete(id) && validateEmptyCollection(id); } private boolean validateEmptyFields(StudentEntity entity) { if (entity.getStudentId() == null || StringUtils.isEmpty(entity.getStudentId())) { return false; } if (entity.getLastName() == null || StringUtils.isEmpty(entity.getLastName())) { return false; } if (entity.getFirstName() == null || StringUtils.isEmpty(entity.getFirstName())) { return false; } return true; } private boolean validateEmptyCollection(Long id) { StudentEntity entity = getService().get(id); if (entity != null) { if (entity.getClasses().size() == 0) { return true; } } return false; } }
java
11
0.686763
111
31.925373
67
starcoderdata
def __init__(self, worker_ids): """ Constructor. """ if hasattr(worker_ids, '__iter__'): self.worker_ids = worker_ids else: self.worker_ids = list(range(worker_ids)) self.num_workers = len(self.worker_ids) # These will be set in reset self.experiment_designer = None self.latest_results = None # Reset self.reset()
python
12
0.61326
47
29.25
12
inline
func (p *PegnetMiner) Mine(ctx context.Context) { mineLog := log.WithFields(log.Fields{"miner": p.ID}) var _ = mineLog select { // Wait for the first command to start // We start 'paused'. Any command will knock us out of this init phase case c := <-p.commands: p.HandleCommand(c) case <-ctx.Done(): return // Cancelled } for { select { case <-ctx.Done(): return // Mining cancelled case c := <-p.commands: p.HandleCommand(c) default: } if p.paused { // Waiting on a resume command p.waitForResume(ctx) continue } p.MiningState.NextNonce() p.MiningState.stats.TotalHashes++ diff := opr.ComputeDifficulty(p.MiningState.oprhash, p.MiningState.Nonce) if diff > p.MiningState.minimumDifficulty && p.MiningState.rankings.AddNonce(p.MiningState.Nonce, diff) { p.MiningState.stats.NewDifficulty(diff) //mineLog.WithFields(log.Fields{ // "oprhash": fmt.Sprintf("%x", p.MiningState.oprhash), // "Nonce": fmt.Sprintf("%x", p.MiningState.Nonce), // "diff": diff, //}).Debugf("new Nonce") } } }
go
12
0.663217
107
24.333333
42
inline
package ee.desertgun.jttracker.controller; import ee.desertgun.jttracker.domain.Mail; import ee.desertgun.jttracker.domain.User; import ee.desertgun.jttracker.dto.PasswordTokenDTO; import ee.desertgun.jttracker.dto.UserDTO; import ee.desertgun.jttracker.dto.UserProfileDTO; import ee.desertgun.jttracker.service.EmailService; import ee.desertgun.jttracker.service.PasswordTokenValidationService; import ee.desertgun.jttracker.service.UserService; import ee.desertgun.jttracker.service.ValidationResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.mail.MessagingException; import javax.validation.Valid; import java.net.InetAddress; import java.util.HashMap; import java.util.Map; import java.util.UUID; @RestController @CrossOrigin public class UserAccountController { private final PasswordEncoder passwordEncoder; private final UserService userService; private final EmailService emailService; private final PasswordTokenValidationService passwordTokenValidationService; @Value("${server.port}") private String port; //TODO: Only for testing!!! private static final String FRONTEND_PORT = "3000"; public UserAccountController(PasswordEncoder passwordEncoder, UserService userService, EmailService emailService, PasswordTokenValidationService passwordTokenValidationService) { this.passwordEncoder = passwordEncoder; this.userService = userService; this.emailService = emailService; this.passwordTokenValidationService = passwordTokenValidationService; } @PostMapping("/user/password/reset") public ValidationResponse resetPassword(@RequestBody @Valid UserDTO userDTO, BindingResult bindingResult) throws MessagingException { ValidationResponse response = new ValidationResponse(); if (userService.userExists(userDTO.getUsername()) && !bindingResult.hasErrors()) { response.setValidated(true); String token = UUID.randomUUID().toString(); userService.createPasswordResetTokenForUser(userDTO, token); String url = constructResetTokenLink(token, userDTO); response.setSuccessMessage(url); Mail passwordResetMail = new Mail(); passwordResetMail.setMailTo(userDTO.getUsername()); passwordResetMail.setSubject("Password-Reset"); Map<String, Object> propPasswordReset = new HashMap<>(); propPasswordReset.put("passwordResetLink", url); passwordResetMail.setProps(propPasswordReset); emailService.sendComplexMail(passwordResetMail, "password_reset"); } else if (bindingResult.hasErrors()) { String error = bindingResult.getFieldErrors().toString(); response.setValidated(false); response.setErrorMessage(error); } else { String error = "Following E-Mail-Adress does not exist! Please re-enter!"; response.setValidated(false); response.setErrorMessage(error); } return response; } @PostMapping("/user/password/reset/validate") public ValidationResponse checkToken(@RequestBody @Valid PasswordTokenDTO passwordTokenDTO) { ValidationResponse response = new ValidationResponse(); String result = passwordTokenValidationService.validatePasswordResetToken(passwordTokenDTO.getUsername(), passwordTokenDTO.getPasswordResetToken()); if (result == null) { response.setValidated(true); response.setSuccessMessage("Validation successfull"); } else if (result.equals("invalidToken") || result.equals("expired")) { response.setValidated(false); response.setErrorMessage("Token is invalid"); } return response; } @PostMapping("/user/password/reset/change") public ValidationResponse resetPassword(@RequestBody @Valid UserProfileDTO userProfileDTO) throws MessagingException { ValidationResponse response = new ValidationResponse(); User user = userService.getUserByUsername(userProfileDTO.getUsername()); userService.updateUserPassword(user, passwordEncoder.encode(userProfileDTO.getNewPassword())); response.setValidated(true); response.setSuccessMessage("Password changed"); Mail passwordUpdateResetMail = new Mail(); passwordUpdateResetMail.setMailTo(user.getUsername()); passwordUpdateResetMail.setSubject("Password-Reset completed"); Map<String, Object> propUpdateReset = new HashMap<>(); propUpdateReset.put("userName", passwordUpdateResetMail.getMailTo()); propUpdateReset.put("displayName", user.getAccountName()); passwordUpdateResetMail.setProps(propUpdateReset); emailService.sendComplexMail(passwordUpdateResetMail, "password_changed"); return response; } @PostMapping("/user/password/update") public ValidationResponse changeUserPasswordIfOldIsValid(@RequestBody @Valid UserDTO userDTO, Authentication authentication) throws MessagingException { ValidationResponse response = new ValidationResponse(); User user = userService.getUserByUsername(authentication.getName()); String userPassword = user.getPassword(); if (passwordEncoder.matches(userDTO.getOldPassword(), userPassword)) { userService.updateUserPassword(user, passwordEncoder.encode(userDTO.getNewPassword())); response.setValidated(true); response.setSuccessMessage("Password changed"); Mail passwordUpdateMail = new Mail(); passwordUpdateMail.setMailTo(user.getUsername()); passwordUpdateMail.setSubject("Password-Update"); Map<String, Object> propPasswordUpdate = new HashMap<>(); propPasswordUpdate.put("userName", passwordUpdateMail.getMailTo()); propPasswordUpdate.put("displayName", user.getAccountName()); passwordUpdateMail.setProps(propPasswordUpdate); emailService.sendComplexMail(passwordUpdateMail, "password_changed"); } else { response.setValidated(false); response.setErrorMessage("Your old-password doesn't match! Please try again"); } return response; } @PutMapping("/user/update") public ValidationResponse updateUserProfile(@RequestBody @Valid UserProfileDTO userProfileDTO) throws MessagingException { ValidationResponse response = new ValidationResponse(); User user = userService.getUserByUsername(userProfileDTO.getUsername()); userService.updateUserProfile(user, userProfileDTO); response.setValidated(true); Mail profileUpdateMail = new Mail(); profileUpdateMail.setMailTo(userProfileDTO.getUsername()); profileUpdateMail.setSubject("Profile-Update"); Map<String, Object> propProfileUpdate = new HashMap<>(); propProfileUpdate.put("userName", profileUpdateMail.getMailTo()); propProfileUpdate.put("displayName", userProfileDTO.getAccountName()); profileUpdateMail.setProps(propProfileUpdate); emailService.sendComplexMail(profileUpdateMail, "profile_updated"); return response; } //TODO: Remember to change to real port when finished and the real server protocol ! private String constructResetTokenLink(String token, @Valid UserDTO userResetDTO) { return "http://" + InetAddress.getLoopbackAddress().getHostName() + ":" + FRONTEND_PORT + "/reset?username=" + userResetDTO.getUsername() + "&token=" + token; } @GetMapping("/user") public User loadUser(Authentication authentication) { return userService.getUserByUsername(authentication.getName()); } }
java
16
0.71568
166
43.712707
181
starcoderdata
internal static void SetParagraphProperty(TextPointer start, TextPointer end, DependencyProperty property, object value, PropertyValueAction propertyValueAction) { Invariant.Assert(start != null, "null check: start"); Invariant.Assert(end != null, "null check: end"); Invariant.Assert(start.CompareTo(end) <= 0, "expecting: start <= end"); Invariant.Assert(property != null, "null check: property"); // Exclude last opening tag to avoid affecting a paragraph following the selection end = (TextPointer)TextRangeEdit.GetAdjustedRangeEnd(start, end); // Expand start pointer to the beginning of the first paragraph/blockuicontainer Block startParagraphOrBlockUIContainer = start.ParagraphOrBlockUIContainer; if (startParagraphOrBlockUIContainer != null) { start = startParagraphOrBlockUIContainer.ContentStart; } // Applying FlowDirection requires splitting all containing lists on the range boundaries // because the property is applied to whole List element (to affect bullet appearence) if (property == Block.FlowDirectionProperty) { // Split any boundary lists if needed. // We want to maintain the invariant that all lists and paragraphs within a list, have the same FlowDirection value. // If paragraph FlowDirection command requests a different value of FlowDirection on parts of a list, // we split the list to maintain this invariant. if (!TextRangeEditLists.SplitListsForFlowDirectionChange(start, end, value)) { // If lists at start and end cannot be split successfully, we cannot apply FlowDirection property to the paragraph content. return; } // And expand range start to the beginning of the containing list ListItem listItem = start.GetListAncestor(); if (listItem != null && listItem.List != null) { start = listItem.List.ElementStart; } } // Walk all paragraphs in the affected segment. For FlowDirection property, also walk lists. SetParagraphPropertyWorker(start, end, property, value, propertyValueAction); }
c#
12
0.630908
161
56.952381
42
inline
using System.Collections.Generic; namespace LocalAdmin.V2 { public class CommandService { private readonly List commands = new List public void RegisterCommand(CommandBase command) { commands.Add(command); } public void UnregisterCommand(CommandBase command) { if (commands.Contains(command)) commands.Remove(command); else throw new KeyNotFoundException(); } public CommandBase GetCommandByName(string name) { foreach (var command in commands) if (command.Name == name.ToUpper()) return command; return null; } } }
c#
12
0.561039
78
23.870968
31
starcoderdata
void bl31_arch_next_el_setup(void) { unsigned long id_aa64pfr0 = read_id_aa64pfr0_el1(); unsigned long current_sctlr, next_sctlr; unsigned long el_status; unsigned long scr = read_scr(); /* Use the same endianness than the current BL */ current_sctlr = read_sctlr(); next_sctlr = (current_sctlr & SCTLR_EE_BIT); /* Find out which EL we are going to */ el_status = (id_aa64pfr0 >> ID_AA64PFR0_EL2_SHIFT) & ID_AA64PFR0_ELX_MASK; /* Check what if EL2 is supported */ if (el_status && (scr & SCR_HCE_BIT)) { /* Set SCTLR EL2 */ next_sctlr |= SCTLR_EL2_RES1; write_sctlr_el2(next_sctlr); } else { /* Set SCTLR Non-Secure EL1 */ next_sctlr |= SCTLR_EL1_RES1; write_sctlr_el1(next_sctlr); } }
c
9
0.665734
75
26.538462
26
inline
void Ledger::historySuccess(QNetworkReply* reply) { // here we send a historyResult with some extra stuff in it // Namely, the styled text we'd like to show. The issue is the // QML cannot do that easily since it doesn't know what the wallet // public key(s) are. Let's keep it that way QByteArray response = reply->readAll(); QJsonObject data = QJsonDocument::fromJson(response).object(); qInfo(commerce) << "history" << "response" << QJsonDocument(data).toJson(QJsonDocument::Compact); // we will need the array of public keys from the wallet auto wallet = DependencyManager::get<Wallet>(); auto keys = wallet->listPublicKeys(); // now we need to loop through the transactions and add fancy text... auto historyArray = data.find("data").value().toObject().find("history").value().toArray(); QJsonArray newHistoryArray; // TODO: do this with 0 copies if possible for (auto it = historyArray.begin(); it != historyArray.end(); it++) { // We have 2 text fields to synthesize, the one on the left is a listing // of the HFC in/out of your wallet. The one on the right contains an explaination // of the transaction. That could be just the memo (if it is a regular purchase), or // more text (plus the optional memo) if an hfc transfer auto valueObject = (*it).toObject(); valueObject["hfc_text"] = hfcString(valueObject["sent_money"], valueObject["received_money"]); valueObject["transaction_text"] = transactionString(valueObject); newHistoryArray.push_back(valueObject); } // now copy the rest of the json -- this is inefficient // TODO: try to do this without making copies QJsonObject newData; newData["status"] = "success"; QJsonObject newDataData; newDataData["history"] = newHistoryArray; newData["data"] = newDataData; newData["current_page"] = data["current_page"].toInt(); emit historyResult(newData); }
c++
18
0.678607
102
51.184211
38
inline
<?php /** * Metaetiquetas del tema || Meta tags * * @package ekiline */ /** * Meta descripcion **/ function ekiline_meta_description() { // La descripcion general, default: is_home(). $desc_head = get_bloginfo( 'description' ); // Si es pagina o post. if ( is_singular() ) { global $post; if ( $post->post_content ) { $cont_trim = wp_trim_words( strip_shortcodes( $post->post_content ), 24, '...' ); if ( $cont_trim ) { $desc_head = $cont_trim; } } } // Si es archivo o categoria. if ( is_archive() ) { if ( category_description() ) { $desc_head = wp_strip_all_tags( category_description() ); } else { $cat = get_the_category(); if ( $cat ) { $cat_count = $cat[0]->count; /* translators: %1$s is replaced with post count and %2$s is asigned to title */ $desc_head = sprintf( __( 'There are %1$s entries related to %2$s', 'ekiline' ), $cat_count, wp_strip_all_tags( get_the_archive_title() ) ); } } } return $desc_head; } /** * Meta descripcion, incorporar. **/ function ekiline_print_meta_description() { echo '<meta name="description" content="' . esc_attr( ekiline_meta_description() ) . '" />' . "\n"; } add_action( 'wp_head', 'ekiline_print_meta_description', 0, 0 ); /** * Incluir todas // ensure all tags are included in queries * * @param string $wp_query setup. */ function ekiline_tags_support_query( $wp_query ) { if ( $wp_query->get( 'tag' ) ) { $wp_query->set( 'post_type', 'any' ); } } add_action( 'pre_get_posts', 'ekiline_tags_support_query' ); /** * Funcion: Obtener Keywords segun el tipo de contenido. **/ function ekiline_meta_keywords() { $keywords = ''; if ( is_single() || is_page() ) { global $post; $tags = get_the_tags( $post->ID ); if ( $tags && ! is_wp_error( $tags ) ) { $keywords = ekiline_collect_tags( $tags ); } } elseif ( is_tag() ) { $keywords = single_tag_title( '', false ); } elseif ( is_archive() ) { $keywords = single_cat_title( '', false ); } elseif ( is_home() || is_front_page() ) { $tags = get_tags(); $tags = array_slice( $tags, 0, 10 ); if ( $tags && ! is_wp_error( $tags ) ) { $keywords = ekiline_collect_tags( $tags ); } } if ( $keywords ) { return $keywords; } } /** * Funcion para obtener etiquetas y ocupar como keywords * * @param array $tags obtener etiquetas de posts. */ function ekiline_collect_tags( $tags ) { $kwds = array(); foreach ( $tags as $kwd ) { $kwds[] = $kwd->name; } return join( ',', $kwds ); } /** * Meta Keywords, incorporar. **/ function ekiline_print_meta_keywords() { if ( ekiline_meta_keywords() ) { echo '<meta name="keywords" content="' . esc_attr( ekiline_meta_keywords() ) . '" />' . "\n"; } } add_action( 'wp_head', 'ekiline_print_meta_keywords', 0, 0 ); /** * Meta Image url, extender para usar URL redes sociales. * meta image url, extend this to use URL in socialmedia. */ function ekiline_meta_image() { $img_url = wp_get_attachment_url( get_theme_mod( 'ekiline_logo_max' ) ); if ( get_header_image() ) { $img_url = get_header_image(); } if ( is_singular() && ! is_front_page() || is_home() || is_front_page() ) { global $post; $img_url = ( has_post_thumbnail() ) ? get_the_post_thumbnail_url( $post->ID, 'medium_large' ) : $img_url; } return $img_url; } /** * Obtener de un menu la direccion url de una meta. * Get url from nav * * @link https://developer.wordpress.org/reference/functions/get_term_by/ * @link https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/ * * @param string $find_string direccion o dominio a verificar. */ function ekiline_find_in_nav( $find_string ) { $array_menu = wp_get_nav_menu_items( 'social' ); $item = $find_string; if ( $array_menu ) { foreach ( $array_menu as $m ) { $url = $m->url; if ( ! empty( $find_string ) && strpos( $url, $find_string ) !== false ) { $item = $url; } } } return $item; } /** * Obtener el username de una url de twitter * * @param string $url dominio a extraer. */ function ekiline_twitter_username( $url ) { if ( 'twitter.com' === $url ) { $url = str_replace( ' ', '', get_bloginfo( 'name' ) ); } preg_match( '/[^\/]+$/', $url, $matches ); $last_word = $matches[0]; if ( strpos( $last_word, '@' ) !== false ) { return $last_word; } else { return '@' . $last_word; } } /** * Meta social, itemprop, twitter y facebook. * * @link https://developer.wordpress.org/reference/hooks/wp_title/; */ function ekiline_meta_social() { global $wp; $meta_social = ''; $find_url = ekiline_find_in_nav( 'twitter.com' ); $meta_title = wp_get_document_title(); $meta_desc = ekiline_meta_description(); $meta_imgs = ekiline_meta_image(); $ttr_link = ekiline_twitter_username( $find_url ); $meta_type = 'website'; $current_url = home_url( add_query_arg( array(), $wp->request ) ); $meta_locale = get_locale(); // Google, Browsers. $meta_social .= '<meta itemprop="name" content="' . $meta_title . '">' . "\n"; $meta_social .= '<meta itemprop="description" content="' . $meta_desc . '">' . "\n"; $meta_social .= '<meta itemprop="image" content="' . $meta_imgs . '">' . "\n"; // Twitter. $meta_social .= '<meta name="twitter:card" content="summary">' . "\n"; $meta_social .= '<meta name="twitter:site" content="' . $ttr_link . '">' . "\n"; $meta_social .= '<meta name="twitter:title" content="' . $meta_title . '">' . "\n"; $meta_social .= '<meta name="twitter:description" content="' . $meta_desc . '">' . "\n"; $meta_social .= '<meta name="twitter:creator" content="' . $ttr_link . '">' . "\n"; $meta_social .= '<meta name="twitter:image" content="' . $meta_imgs . '">' . "\n"; // Facebook, OG. $meta_social .= '<meta property="og:title" content="' . $meta_title . '"/>' . "\n"; $meta_social .= '<meta property="og:type" content="' . $meta_type . '"/>' . "\n"; $meta_social .= '<meta property="og:url" content="' . $current_url . '"/>' . "\n"; $meta_social .= '<meta property="og:image" content="' . $meta_imgs . '"/>' . "\n"; $meta_social .= '<meta property="og:description" content="' . $meta_desc . '"/>' . "\n"; $meta_social .= '<meta property="og:site_name" content="' . get_bloginfo( 'name' ) . '"/>' . "\n"; $meta_social .= '<meta property="og:locale" content="' . $meta_locale . '"/>' . "\n"; $allowed_html = array( 'meta' => array( 'itemprop' => array(), 'content' => array(), 'name' => array(), 'property' => array(), ), ); echo wp_kses( $meta_social, $allowed_html ); } add_action( 'wp_head', 'ekiline_meta_social', 1 );
php
20
0.587323
144
26.759494
237
starcoderdata
/* * SPDX-License-Identifier: MIT * SPDX-FileCopyrightText: Copyright (c) 2021 (mytechtoybox.com) */ #ifndef WEBSERVER_DESCRIPTORS_H_ #define WEBSERVER_DESCRIPTORS_H_ #include #include "tusb.h" enum { STRID_LANGID = 0, STRID_MANUFACTURER, STRID_PRODUCT, STRID_SERIAL, STRID_INTERFACE, STRID_MAC }; static const uint8_t webserver_string_language[] = { 0x09, 0x04 }; static const uint8_t webserver_string_manufacturer[] = "TinyUSB"; static const uint8_t webserver_string_product[] = "USB Webserver"; static const uint8_t webserver_string_version[] = "1.0"; static const uint8_t *webserver_string_descriptors[] = { webserver_string_language, webserver_string_manufacturer, webserver_string_product, webserver_string_version }; static const tusb_desc_device_t webserver_device_descriptor = { .bLength = sizeof(tusb_desc_device_t), .bDescriptorType = TUSB_DESC_DEVICE, .bcdUSB = 0x0200, // Use Interface Association Descriptor (IAD) device class .bDeviceClass = TUSB_CLASS_MISC, .bDeviceSubClass = MISC_SUBCLASS_COMMON, .bDeviceProtocol = MISC_PROTOCOL_IAD, .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, .idVendor = 0xCAFE, .idProduct = 0x4001, .bcdDevice = 0x0101, .iManufacturer = 0x01, .iProduct = 0x02, .iSerialNumber = 0x03, .bNumConfigurations = 0x02 // multiple configurations }; #define MAIN_CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_RNDIS_DESC_LEN) #define ALT_CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_ECM_DESC_LEN) #define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_HID_INOUT_DESC_LEN) #define EPNUM_HID 0x01 #define EPNUM_NET_NOTIF 0x81 #define EPNUM_NET_OUT 0x02 #define EPNUM_NET_IN 0x82 static uint8_t const rndis_configuration[] = { // Config number (index+1), interface count, string index, total length, attribute, power in mA TUD_CONFIG_DESCRIPTOR(1, 2, 0, MAIN_CONFIG_TOTAL_LEN, 0, 100), // Interface number, string index, EP notification address and size, EP data address (out, in) and size. TUD_RNDIS_DESCRIPTOR(0, STRID_INTERFACE, EPNUM_NET_NOTIF, 8, EPNUM_NET_OUT, EPNUM_NET_IN, CFG_TUD_NET_ENDPOINT_SIZE), }; static uint8_t const ecm_configuration[] = { // Config number (index+1), interface count, string index, total length, attribute, power in mA TUD_CONFIG_DESCRIPTOR(2, 2, 0, ALT_CONFIG_TOTAL_LEN, 0, 100), // Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size. TUD_CDC_ECM_DESCRIPTOR(0, STRID_INTERFACE, STRID_MAC, EPNUM_NET_NOTIF, 64, EPNUM_NET_OUT, EPNUM_NET_IN, CFG_TUD_NET_ENDPOINT_SIZE, CFG_TUD_NET_MTU), }; // Configuration array: RNDIS and CDC-ECM // - Windows only works with RNDIS // - MacOS only works with CDC-ECM // - Linux will work on both // Note index is Num-1x static uint8_t const * const net_configuration_arr[] = { rndis_configuration, ecm_configuration, }; #endif
c
8
0.705294
162
30.612245
98
starcoderdata
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (mediaPlayer.isPlaying()) { stop(); } // path = intent.getStringExtra("url"); path = mp3Url; Log.d(TAG, "onStartCommand: " + path); // int msg = intent.getIntExtra("MSG", 0); // if(msg == AppConstant.PlayerMsg.PLAY_MSG) { play(0); // } else if(msg == AppConstant.PlayerMsg.PAUSE_MSG) { // pause(); // } else if(msg == AppConstant.PlayerMsg.STOP_MSG) { // stop(); // } return super.onStartCommand(intent, flags, startId); }
java
8
0.533123
70
34.277778
18
inline
/* * Copyright 2011-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vertx.java.core.sockjs.impl; import org.vertx.java.core.Handler; import org.vertx.java.core.buffer.Buffer; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.http.RouteMatcher; import org.vertx.java.core.impl.VertxInternal; import org.vertx.java.core.json.JsonObject; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; import org.vertx.java.core.sockjs.SockJSSocket; import java.util.Map; /** * @author <a href="http://tfox.org"> */ class XhrTransport extends BaseTransport { private static final Logger log = LoggerFactory.getLogger(XhrTransport.class); private static final Buffer H_BLOCK; static { byte[] bytes = new byte[2048 + 1]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte)'h'; } bytes[bytes.length - 1] = (byte)'\n'; H_BLOCK = new Buffer(bytes); } XhrTransport(VertxInternal vertx,RouteMatcher rm, String basePath, final Map<String, Session> sessions, final JsonObject config, final Handler sockHandler) { super(vertx, sessions, config); String xhrBase = basePath + COMMON_PATH_ELEMENT_RE; String xhrRE = xhrBase + "xhr"; String xhrStreamRE = xhrBase + "xhr_streaming"; Handler xhrOptionsHandler = createCORSOptionsHandler(config, "OPTIONS, POST"); rm.optionsWithRegEx(xhrRE, xhrOptionsHandler); rm.optionsWithRegEx(xhrStreamRE, xhrOptionsHandler); registerHandler(rm, sockHandler, xhrRE, false, config); registerHandler(rm, sockHandler, xhrStreamRE, true, config); String xhrSendRE = basePath + COMMON_PATH_ELEMENT_RE + "xhr_send"; rm.optionsWithRegEx(xhrSendRE, xhrOptionsHandler); rm.postWithRegEx(xhrSendRE, new Handler { public void handle(final HttpServerRequest req) { if (log.isTraceEnabled()) log.trace("XHR send, post, " + req.uri); String sessionID = req.params().get("param0"); final Session session = sessions.get(sessionID); if (session != null) { handleSend(req, session); } else { req.response.statusCode = 404; setJSESSIONID(config, req); req.response.end(); } } }); } private void registerHandler(RouteMatcher rm, final Handler sockHandler, String re, final boolean streaming, final JsonObject config) { rm.postWithRegEx(re, new Handler { public void handle(final HttpServerRequest req) { if (log.isTraceEnabled()) log.trace("XHR, post, " + req.uri); String sessionID = req.params().get("param0"); Session session = getSession(config.getLong("session_timeout"), config.getLong("heartbeat_period"), sessionID, sockHandler); session.register(streaming? new XhrStreamingListener(config.getInteger("max_bytes_streaming"), req, session) : new XhrPollingListener(req, session)); } }); } private void handleSend(final HttpServerRequest req, final Session session) { req.bodyHandler(new Handler { public void handle(Buffer buff) { String msgs = buff.toString(); if (msgs.equals("")) { req.response.statusCode = 500; req.response.end("Payload expected."); return; } if (!session.handleMessages(msgs)) { sendInvalidJSON(req.response); } else { req.response.headers().put("Content-Type", "text/plain; charset=UTF-8"); setJSESSIONID(config, req); setCORS(req); req.response.statusCode = 204; req.response.end(); } if (log.isTraceEnabled()) log.trace("XHR send processed ok"); } }); } private abstract class BaseXhrListener extends BaseListener { final HttpServerRequest req; final Session session; boolean headersWritten; BaseXhrListener(HttpServerRequest req, Session session) { this.req = req; this.session = session; } public void sendFrame(String body) { if (log.isTraceEnabled()) log.trace("XHR sending frame"); if (!headersWritten) { req.response.headers().put("Content-Type", "application/javascript; charset=UTF-8"); setJSESSIONID(config, req); setCORS(req); req.response.setChunked(true); headersWritten = true; } } public void close() { } } private class XhrPollingListener extends BaseXhrListener { XhrPollingListener(HttpServerRequest req, final Session session) { super(req, session); addCloseHandler(req.response, session); } boolean closed; public void sendFrame(String body) { super.sendFrame(body); req.response.write(body + "\n"); close(); } public void close() { if (log.isTraceEnabled()) log.trace("XHR poll closing listener"); if (!closed) { try { session.resetListener(); req.response.end(); req.response.close(); closed = true; } catch (IllegalStateException e) { // Underlying connection might already be closed - that's fine } } } } private class XhrStreamingListener extends BaseXhrListener { int bytesSent; int maxBytesStreaming; boolean closed; XhrStreamingListener(int maxBytesStreaming, HttpServerRequest req, final Session session) { super(req, session); this.maxBytesStreaming = maxBytesStreaming; addCloseHandler(req.response, session); } public void sendFrame(String body) { boolean hr = headersWritten; super.sendFrame(body); if (!hr) { req.response.write(H_BLOCK); } String sbody = body + "\n"; Buffer buff = new Buffer(sbody); req.response.write(buff); bytesSent += buff.length(); if (bytesSent >= maxBytesStreaming) { close(); } } public void close() { if (log.isTraceEnabled()) log.trace("XHR stream closing listener"); if (!closed) { session.resetListener(); try { req.response.end(); req.response.close(); closed = true; } catch (IllegalStateException e) { // Underlying connection might alreadu be closed - that's fine } } } } }
java
21
0.649814
157
30.258929
224
starcoderdata
const options = [{ option: '-v, --verbose', doc: 'verbose mode' }, { option: '--lib', doc: 'generate a library instead of an application' }, { option: '--ui-framework [framework]', doc: 'create application with built-in ui framework. "material" or "bootstrap" (defaults to: none)' }, { option: '--make-it-progressive', doc: 'add the default configuration for a Progressive Web App (defaults to: false)' }, { option: '--skip-install', doc: 'skip installing packages (defaults to: false)' }, { option: '--skip-git', doc: 'skip initializing a git repository (defaults to: false)' }, { option: '--commit-message-conventions', doc: 'add commit-msg hook to force use of the Google message conventions (defaults to: false)' }]; module.exports.name = 'new'; module.exports.options = options;
javascript
6
0.672705
101
30.846154
26
starcoderdata
def app_lookup(url): # input validation if not isinstance(url, str): abort(400) # find out which API key to use api_key = request.headers.get('x-gsb-api-key', gsb_api_key) if not api_key: app.logger.error('no API key to use') abort(401) # look up URL matches = _lookup(url, api_key) if matches: return jsonify(url=url, matches=[{'threat': x.threat_type, 'platform': x.platform_type, 'threat_entry': x.threat_entry_type} for x in matches]) else: resp = jsonify(url=url, matches=[]) resp.status_code = 404 return resp
python
13
0.56682
97
31.6
20
inline
import akka.actor.ActorSystem; import com.typesafe.config.ConfigFactory; public class WorkerEnvironment { public static void main(String[] args) { // Creating environment ActorSystem.create("WorkerEnvironment", ConfigFactory.load()); } }
java
10
0.719697
70
25.4
10
starcoderdata
namespace AutoParts.Infrastructure.Exceptions { using System; using Models; public class ApiException : Exception { public Error[] Errors { get; set; } public ApiException(string message) : base(message) { } public ApiException(string message, Exception innerException) : base(message, innerException) { } public ApiException(params Error[] errors) { Errors = errors; } } }
c#
10
0.583333
101
19.5
24
starcoderdata
bool Is_Number (const std::string& str) // integer or floating point { const char *nptr = str.c_str(), *last_character = nptr + strlen (nptr); char *endptr; strtod (nptr, &endptr); return endptr == last_character; }
c++
8
0.680365
72
30.428571
7
inline
/* C++ 17 working draft 8.5.5.4 If the second operand of / or % is zero the behavior is undefined */ #include #include #include int main() { int32_t a = 1; std::cout << a / 0 << std::endl; return EXIT_SUCCESS; }
c++
7
0.63745
65
15.733333
15
starcoderdata
#include #include #include "datatypes/color.h" #include "filetypes/tpl.h" #include "filetypes/png.h" #include "test_tpl.h" using types::Color; Color** make_color_block(uint w, uint h) { Color** data = new Color*[h]; for (uint i = 0; i < h; ++i) { data[i] = new Color[w]; } return data; } void fill_color(Color** data, uchar* block, uint w, uint h, Color(func)(const uchar*, uchar)) { for (uint i = 0; i < h; ++i) { for (uint j = 0; j < w; ++j) { data[i][j] = func(block, i * h + j); } } } void TestBlockParsers::test_parse_i4() { uchar block[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0xFE, 0xDC, 0x45, 0x67, 0xBA, 0x98, 0x89, 0xAB, 0x76, 0x54, 0xCD, 0xEF, 0x32, 0x10}; Color** data = make_color_block(8, 8); fill_color(data, block, 8, 8, types::parse_i4); types::PNG png = types::PNG(types::Image(8, 8, data)); png.save("./test_i4.png"); std::ifstream good("./resources/test_i4.png"); std::ifstream output("./test_i4.png"); testing::assert_files_equal(output, good); } void TestBlockParsers::test_parse_i8() { throw testing::skip_test(); } void TestBlockParsers::test_parse_rgb565() { uchar block[] = { 0xF8, 0x00, 0x07, 0xE0, 0x00, 0x1F, 0x00, 0x00, 0xF8, 0x00, 0x07, 0xE0, 0x00, 0x1F, 0x00, 0x00, 0xFF, 0xE0, 0x07, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF }; Color** data = make_color_block(4, 4); fill_color(data, block, 4, 4, types::parse_rgb565); types::PNG png = types::PNG(types::Image(4, 4, data)); png.save("./test_rgb565.png"); std::ifstream good("./resources/test_rgb565.png"); std::ifstream output("./test_rgb565.png"); testing::assert_files_equal(output, good); } void TestBlockParsers::test_parse_rgb5A3() { throw testing::skip_test(); } void TestBlockParsers::test_parse_cmpr() { uchar block[] = { 0xF8, 0x00, 0x07, 0xE0, 0x0A, 0x0A, 0xF5, 0xF5, 0x07, 0xE0, 0x00, 0x1F, 0x0A, 0x0A, 0xF5, 0xF5, 0xF8, 0x00, 0x00, 0x1F, 0x5F, 0x5F, 0xA0, 0xA0, 0x00, 0x00, 0xFF, 0xFF, 0x0A, 0x0A, 0x5F, 0x5F, }; Color** data = make_color_block(8, 8); fill_color(data, block, 8, 8, types::parse_cmpr); types::PNG png = types::PNG(types::Image(8, 8, data)); png.save("./test_cmpr.png"); std::ifstream good("./resources/test_cmpr.png"); std::ifstream output("./test_cmpr.png"); testing::assert_files_equal(output, good); } void TestBlockParsers::run() { TEST_METHOD(test_parse_i4) TEST_METHOD(test_parse_i8) TEST_METHOD(test_parse_rgb565) TEST_METHOD(test_parse_rgb5A3) TEST_METHOD(test_parse_cmpr) } void run_tpl_tests() { TEST(TestBlockParsers()) }
c++
13
0.56133
95
27.953271
107
starcoderdata
package de.hhu.stups.plues.ui.components.detailview; import com.google.inject.Inject; import de.hhu.stups.plues.data.entities.AbstractUnit; import de.hhu.stups.plues.data.entities.Module; import de.hhu.stups.plues.data.entities.ModuleAbstractUnitSemester; import de.hhu.stups.plues.data.entities.ModuleAbstractUnitType; import de.hhu.stups.plues.data.entities.Unit; import de.hhu.stups.plues.routes.Router; import de.hhu.stups.plues.ui.layout.Inflater; import javafx.beans.binding.Bindings; import javafx.beans.binding.ListBinding; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.VBox; import java.net.URL; import java.util.ResourceBundle; import java.util.stream.Collectors; public class AbstractUnitDetailView extends VBox implements Initializable, DetailView { private final ObjectProperty abstractUnitProperty; private final Router router; @FXML @SuppressWarnings("unused") private Label key; @FXML @SuppressWarnings("unused") private Label title; @FXML @SuppressWarnings("unused") private TableView tableViewUnits; @FXML @SuppressWarnings("unused") private TableView tableViewModules; @FXML @SuppressWarnings("unused") private TableColumn<Module, String> tableColumnUnitsKey; @FXML @SuppressWarnings("unused") private TableColumn<Module, String> tableColumnUnitsTitle; @FXML @SuppressWarnings("unused") private TableColumn<Module, String> tableColumnModulesPordnr; @FXML @SuppressWarnings("unused") private TableColumn<Module, String> tableColumnModulesTitle; @FXML @SuppressWarnings("unused") private TableColumn<Module, String> tableColumnModulesSemesters; @FXML @SuppressWarnings("unused") private TableColumn<Module, String> tableColumnModulesType; /** * Default constructor. * * @param inflater Inflater to handle fxml and lang */ @Inject public AbstractUnitDetailView(final Inflater inflater, final Router router) { abstractUnitProperty = new SimpleObjectProperty<>(); this.router = router; inflater.inflate("components/detailview/AbstractUnitDetailView", this, this, "detailView", "Column"); } /** * Set property for this detail view. * * @param abstractUnit Unit for property containing displayed data */ public void setAbstractUnit(final AbstractUnit abstractUnit) { abstractUnitProperty.set(abstractUnit); } public String getTitle() { return title.getText(); } @Override public void initialize(final URL location, final ResourceBundle resources) { initializeLabels(); tableViewUnits.itemsProperty().bind(new UnitListBinding(abstractUnitProperty)); tableViewModules.itemsProperty().bind(new ModuleListBinding(abstractUnitProperty)); initializeTableColumnModuleSemesters(); initializeTableColumnModulesTypes(); initializeEventHandlers(); } private void initializeTableColumnModulesTypes() { tableColumnModulesType.setCellValueFactory(param -> { final AbstractUnit abstractUnit = this.abstractUnitProperty.get(); final ObservableList modules = this.tableViewModules.getItems(); return new ReadOnlyStringWrapper(param.getValue().getModuleAbstractUnitTypes().stream() .filter(moduleAbstractUnitSemester -> abstractUnit.equals(moduleAbstractUnitSemester.getAbstractUnit())) .filter(moduleAbstractUnitSemester -> modules.contains(moduleAbstractUnitSemester.getModule())) .map(ModuleAbstractUnitType::getType) .distinct() .map(String::valueOf) .collect(Collectors.joining(", "))); }); tableColumnModulesType.setCellFactory(param -> DetailViewHelper.createTableCell()); } private void initializeTableColumnModuleSemesters() { tableColumnModulesSemesters.setCellValueFactory(param -> { final AbstractUnit abstractUnit = this.abstractUnitProperty.get(); final ObservableList modules = this.tableViewModules.getItems(); final String semesters = param.getValue().getModuleAbstractUnitSemesters().stream() .filter(moduleAbstractUnitSemester -> abstractUnit.equals(moduleAbstractUnitSemester.getAbstractUnit())) .filter(moduleAbstractUnitSemester -> modules.contains(moduleAbstractUnitSemester.getModule())) .map(ModuleAbstractUnitSemester::getSemester) .sorted() .map(String::valueOf) .collect(Collectors.joining(",")); return new ReadOnlyStringWrapper(semesters); }); tableColumnModulesSemesters.setCellFactory(param -> DetailViewHelper.createTableCell()); } private void initializeEventHandlers() { tableViewUnits.setOnMouseClicked(DetailViewHelper.getUnitMouseHandler( tableViewUnits, router)); tableViewModules.setOnMouseClicked(DetailViewHelper.getModuleMouseHandler( tableViewModules, router)); } private void initializeLabels() { key.textProperty().bind(Bindings.when(abstractUnitProperty.isNotNull()) .then(Bindings.selectString(abstractUnitProperty, "key")) .otherwise("")); title.textProperty().bind(Bindings.when(abstractUnitProperty.isNotNull()) .then(Bindings.selectString(abstractUnitProperty, "title")) .otherwise("")); } private static class UnitListBinding extends ListBinding { private final ObjectProperty property; private UnitListBinding(final ObjectProperty abstractUnitProperty) { this.property = abstractUnitProperty; bind(property); } @Override protected ObservableList computeValue() { final AbstractUnit abstractUnit = property.get(); if (abstractUnit == null) { return FXCollections.emptyObservableList(); } return FXCollections.observableArrayList(abstractUnit.getUnits()); } } private static class ModuleListBinding extends ListBinding { private final ObjectProperty property; private ModuleListBinding(final ObjectProperty abstractUnitProperty) { this.property = abstractUnitProperty; bind(property); } @Override protected ObservableList computeValue() { final AbstractUnit abstractUnit = property.get(); if (abstractUnit == null) { return FXCollections.emptyObservableList(); } return FXCollections.observableArrayList(abstractUnit.getModules()); } } }
java
25
0.744953
94
33.772727
198
starcoderdata
import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { authLogin } from 'containers/Auth/actions' import ThemeProvider from 'components/ThemeProvider' import routes from './routes' class App extends Component { componentWillMount () { const { auth } = this.props if (auth.token != null) { this.props.userAuthLogin(auth.authToken) } } render () { return ( {routes()} ) } } App.propTypes = { auth: PropTypes.object.isRequired, userAuthLogin: PropTypes.func.isRequired } const mapStateToProps = ({ auth }) => ({ auth }) const mapDispatchToProps = (dispatch) => ({ userAuthLogin: (token) => dispatch(authLogin(token)) }) export default connect(mapStateToProps, mapDispatchToProps)(App)
javascript
12
0.662132
64
21.05
40
starcoderdata
#ifndef CFG_h #define CFG_h #include #include namespace Cfg { const char wifiSsid[] = "SSID"; const char wifiPassword[] = "password"; const char mqttNodeId[] = "GW_NODE_ID1"; const IPAddress mqttHost(192, 168, 0, 1); const uint16_t mqttPort = 1883; const char mqttUser[] = "admin"; const char mqttPassword[] = " const char otaPassword[] = "OTA_Password"; const char radioEncriptionKey[] = "sampleEncryptKey"; const uint8_t idMaxGroupA = 10; const uint8_t idMaxGroupB = 20; } #endif
c
8
0.630068
57
22.666667
24
starcoderdata
package action import ( "bosh-softlayer-cpi/softlayer/disk_service" ) type DeleteDisk struct { diskService disk.Service } func NewDeleteDisk( diskService disk.Service, ) DeleteDisk { return DeleteDisk{ diskService: diskService, } } func (dd DeleteDisk) Run(diskCID DiskCID) (interface{}, error) { return nil, dd.diskService.Delete(diskCID.Int()) }
go
9
0.756627
64
17.863636
22
starcoderdata
import click import json import pandas as pd from typing import Dict, Any from kfp import dsl from hypermodel.platform.abstract.services import PlatformServicesBase from datetime import datetime # This is the default `click` entrypoint for kicking off the command line class HmlPackage: """ A HyperModel package is a collection of all the assets / artifacts created by a Pipeline run. During Pipeline Execution, this is saved to the DataLake, but which may also be stored in SourceControl so that we can use git revisions for managing what the current version of a Model is. """ def __init__( self: "HmlPackage", name: str, services: PlatformServicesBase = None, op: "HmlContainerOp" = None, pipeline: "HmlPipeline" = None, ): """ Initialize a new Hml App with the given name, platform ("local" or "GCP") and a dictionary of configuration values Args: name (str): The name of the package (usually the pipeline name) op (HmlContainerOp): The ContainerOp we are executing in services (PlatformServicesBase): A reference to our platform services for interacting with external services (data warehouse / data lake) """ self.name = name if op is not None: self.op = op self.pipeline = op.pipeline if pipeline is not None: self.pipeline = pipeline self.services = services self.config = self.services.config def artifact_path(self: "HmlPackage", artifact_name: str): """ Get the path to where we are saving artifacts in the DataLake """ workflow_id = self.op.workflow_id() return f"{workflow_id}/artifacts/{artifact_name}" def package_path(self: "HmlPackage"): """ Get the path to the Package in the DataLake """ workflow_id = self.op.workflow_id() return f"{workflow_id}/hml-package.json" def add_artifact_json(self: "HmlPackage", name: str, obj: Any): # Lets save the artifact as JSON to the data lake artifact_path = self.artifact_path(name) object_json = json.dumps(obj) self.services.lake.upload_string(self.config.lake_bucket, artifact_path, object_json) # Then lets update our reference artifact (via the link) self.link_artifact(name, artifact_path) return artifact_path def add_artifact_file(self: "HmlPackage", name: str, file_path: Any): # Lets save the artifact as JSON to the data lake artifact_path = self.artifact_path(name) self.services.lake.upload(self.config.lake_bucket, artifact_path, file_path) # Then lets update our reference artifact (via the link) self.link_artifact(name, artifact_path) return artifact_path def add_artifact_dataframe(self: "HmlPackage", name: str, dataframe: pd.DataFrame): # Lets save the artifact as JSON to the data lake artifact_path = self.artifact_path(name) self.services.lake.upload_dataframe(self.config.lake_bucket, artifact_path, dataframe) # Then lets update our reference artifact (via the link) self.link_artifact(name, artifact_path) return artifact_path def link_artifact(self: "HmlPackage", name: str, storage_path: str): # We don't store any state as a part of this object, all operations # are designed to minimize the chance of mid-air collisions package = self.get() package["artifacts"][name] = storage_path package["updated"] = str(datetime.now()) self.save(package) def save(self: "HmlPackage", package): path = self.package_path() json_string = json.dumps(package) self.services.lake.upload_string(self.config.lake_bucket, path, json_string) def get(self: "HmlPackage"): """ Go to the DataLake and get the PackageData for this pipeline run """ path = self.package_path() json_string = self.services.lake.download_string(self.config.lake_bucket, path) if json_string is None: return { "name": self.name, "updated": str(datetime.now()), "created": str(datetime.now()), "artifacts": dict(), "updates": list(), } package = json.loads(json_string) if not "artifacts" in package: raise (BaseException("No `artifacts` property was found in JSON")) if not "name" in package: raise (BaseException("No `name` property was found in JSON")) return package
python
14
0.630564
94
35.573643
129
starcoderdata
package com.vk.api.sdk.objects.friends.responses; import com.google.gson.annotations.SerializedName; import java.util.List; import java.util.Objects; /** * GetOnlineMobileResponse object */ public class GetOnlineMobileResponse { @SerializedName("online") private List online; @SerializedName("online_mobile") private List onlineMobile; public List getOnline() { return online; } public List getOnlineMobile() { return onlineMobile; } @Override public int hashCode() { return Objects.hash(online, onlineMobile); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetOnlineMobileResponse getOnlineMobileResponse = (GetOnlineMobileResponse) o; return Objects.equals(online, getOnlineMobileResponse.online) && Objects.equals(onlineMobile, getOnlineMobileResponse.onlineMobile); } @Override public String toString() { final StringBuilder sb = new StringBuilder("GetOnlineMobileResponse{"); sb.append("online=").append(online); sb.append(", onlineMobile=").append(onlineMobile); sb.append('}'); return sb.toString(); } }
java
11
0.664151
86
26.040816
49
starcoderdata
/* * On a Linux MIPS test target 'x' assigned to a buffer coerced into 255 * instead of 0. */ /*=== 0 0 ===*/ try { var buf = new ArrayBuffer(1); // Buffer object new Uint8Array(buf)[0] = 'x'; print(new Uint8Array(buf)[0]); buf = Duktape.dec('hex', '12'); // plain buffer buf[0] = 'x'; print(buf[0]); } catch (e) { print(e.stack || e); }
javascript
9
0.538462
73
16.952381
21
starcoderdata
import torch from torch.distributions import Categorical, normal # ref: https://github.com/p-christ/Deep-Reinforcement-Learning-Algorithms-with-PyTorch/blob/6297608b8524774c847ad5cad87e14b80abf69ce/utilities/Utility_Functions.py#L22 def create_actor_distribution(action_type, actor_output, action_size): """Creates a distribution that the actor can then use to randomly draw actions""" if action_type == "discrete": assert actor_output.size()[1] == action_size, "Actor output the wrong size" action_distribution = Categorical(actor_output) # this creates a distribution to sample from elif action_type == "continuous": assert actor_output.size()[1] == action_size * 2, "Actor output the wrong size" means = actor_output[:, :action_size].squeeze(0) stds = actor_output[:, action_size:].squeeze(0) # if len(means.shape) == 2: # means = means.squeeze(-1) # if len(stds.shape) == 2: # stds = stds.squeeze(-1) # if len(stds.shape) > 1 or len(means.shape) > 1: # raise ValueError("Wrong mean and std shapes - {} -- {}".format(stds.shape, means.shape)) action_distribution = normal.Normal(means.squeeze(0), torch.abs(stds).clamp(-0.01, 0.01)) else: raise NotImplementedError() return action_distribution
python
14
0.667913
167
52.48
25
starcoderdata
void mapperMBC2ROM(uint16 address, uint8 value) { switch(address & 0x6000) { case 0x0000: // RAM enable if(!(address & 0x0100)) { gbDataMBC2.mapperRAMEnable = (value & 0x0f) == 0x0a; } break; case 0x2000: // ROM bank select if(address & 0x0100) { value &= 0x0f; if(value == 0) value = 1; if(gbDataMBC2.mapperROMBank != value) { gbDataMBC2.mapperROMBank = value; SetROMMap(value << 14); } } break; } }
c++
14
0.575
58
20.863636
22
inline
/* * Copyright (c) 2016-2019 * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System.Collections.Generic; namespace Piranha.Models { public class PostArchive : PostArchive { } public class PostArchive where T : PostBase { /// /// Gets/sets the optionally requested year. /// public int? Year { get; set; } /// /// Gets/sets the optionally requested month. /// public int? Month { get; set; } /// /// Gets/sets the current page. /// public int CurrentPage { get; set; } /// /// Gets/sets the total number of pages available. /// public int TotalPages { get; set; } /// /// Gets/sets the total number of posts available. /// public int TotalPosts { get; set; } /// /// Gets/sets the optionally selected category. /// public Taxonomy Category { get; set; } /// /// Gets/sets the optionally selected tag. /// public Taxonomy Tag { get; set; } /// /// Gets/sets the available posts. /// public IList Posts { get; set; } = new List } }
c#
9
0.549613
64
25.305085
59
starcoderdata
public final void unregisterNativeAd() { Object obj = ((Object) (zzvj)); // 0 0:aload_0 // 1 1:getfield #76 <Field zzqf zzvj> // 2 4:astore_1 if(obj != null) //* 3 5:aload_1 //* 4 6:ifnull 25 try { ((zzqf) (obj)).unregisterNativeAd(); // 5 9:aload_1 // 6 10:invokeinterface #143 <Method void zzqf.unregisterNativeAd()> } //* 7 15:goto 25 catch(RemoteException remoteexception) //* 8 18:astore_1 { zzane.zzb("Unable to call unregisterNativeAd on delegate", ((Throwable) (remoteexception))); // 9 19:ldc1 #145 <String "Unable to call unregisterNativeAd on delegate"> // 10 21:aload_1 // 11 22:invokestatic #106 <Method void zzane.zzb(String, Throwable)> } remoteexception = ((RemoteException) (zzvl)); // 12 25:aload_0 // 13 26:getfield #58 <Field WeakReference zzvl> // 14 29:astore_1 if(remoteexception != null) //* 15 30:aload_1 //* 16 31:ifnull 45 remoteexception = ((RemoteException) ((View)((WeakReference) (remoteexception)).get())); // 17 34:aload_1 // 18 35:invokevirtual #86 <Method Object WeakReference.get()> // 19 38:checkcast #88 <Class View> // 20 41:astore_1 else //* 21 42:goto 47 remoteexception = null; // 22 45:aconst_null // 23 46:astore_1 if(remoteexception != null) //* 24 47:aload_1 //* 25 48:ifnull 59 zzvk.remove(((Object) (remoteexception))); // 26 51:getstatic #21 <Field WeakHashMap zzvk> // 27 54:aload_1 // 28 55:invokevirtual #148 <Method Object WeakHashMap.remove(Object)> // 29 58:pop // 30 59:return }
java
14
0.52537
96
36.117647
51
inline
@Transactional public void examplePersist(){ //region EXAMPLE 6 log.info("-------------------------------"); log.info("EXAMPLE - 6 -------------------"); log.info("-------------------------------"); //JPAInsertClause just introduced and it's buggy // new JPAInsertClause(entityManager, qEmployee) // .set(qEmployee.firstName, "Mike") // .set(qEmployee.lastName, "Osberg") // .set(qEmployee.salary, 25000) // .execute(); // // Employee addedEmployee = new JPAQuery<>(entityManager).select(qEmployee) // .from(qEmployee) // .where(qEmployee.lastName.eq("Osberg")) // .fetchOne(); // printData(singletonList(addedEmployee)); //endregion }
java
7
0.500632
82
35
22
inline
import java.util.Scanner; public class Switch { public static void main(String[] args) { int cheeze = 2; int taco = 5; int soda = 4; int salsa = 20; int mayo = 17; int butter = 900; int count = 0; int choice = 0; int sum = 0; int error = 0; Scanner input = new Scanner(System.in); while (choice !=7) { System.out.println("select a option"); System.out.println("1) cheeze cost 2 bucks"); System.out.println("2) taco cost 5 bucks"); System.out.println("3) soda cost 4 bucks"); System.out.println("4) salsa cost 20 bucks"); System.out.println("5) mayo cost 17 bucks"); System.out.println("6) butter cost 900 bucks"); System.out.println("7) exit menu"); System.out.println("8) invalid choose again or go home"); choice = input.nextInt(); switch(choice){ case 1: sum += cheeze; break; case 2: sum += salsa; break; case 3: sum += taco; break; case 4: sum +=soda; break; case 5: sum += mayo; break; case 6: sum += butter; break; case 7: System.out.printf("ur total is " + sum + " bucks"); break; } } } }
java
16
0.530211
59
14.158537
82
starcoderdata
<?php declare(strict_types=1); namespace Symplify\PackageBuilder\Tests\Parameter; use Symplify\PackageBuilder\Parameter\ParameterProvider; use Symplify\PackageBuilder\Testing\AbstractKernelTestCase; use Symplify\PackageBuilder\Tests\HttpKernel\PackageBuilderTestKernel; final class ParameterProviderTest extends AbstractKernelTestCase { public function test(): void { $this->bootKernelWithConfigs( PackageBuilderTestKernel::class, [__DIR__ . '/ParameterProviderSource/config.yml'] ); $parameterProvider = self::$container->get(ParameterProvider::class); $parameters = $parameterProvider->provide(); $this->assertArrayHasKey('key', $parameters); $this->assertArrayHasKey('camelCase', $parameters); $this->assertArrayHasKey('pascal_case', $parameters); $this->assertSame('value', $parameters['key']); $this->assertSame('Lion', $parameters['camelCase']); $this->assertSame('Celsius', $parameters['pascal_case']); $this->assertSame('value', $parameterProvider->provideParameter('key')); $parameterProvider->changeParameter('key', 'anotherKey'); $this->assertSame('anotherKey', $parameterProvider->provideParameter('key')); } public function testIncludingYaml(): void { $this->bootKernelWithConfigs( PackageBuilderTestKernel::class, [__DIR__ . '/ParameterProviderSource/Yaml/including-config.php'] ); $parameterProvider = self::$container->get(ParameterProvider::class); $parameters = $parameterProvider->provide(); $this->assertArrayHasKey('one', $parameters); $this->assertArrayHasKey('two', $parameters); $this->assertSame(1, $parameters['one']); $this->assertSame(2, $parameters['two']); $this->assertArrayHasKey('kernel.project_dir', $parameterProvider->provide()); } }
php
13
0.668724
86
33.714286
56
starcoderdata
package com.onpositive.text.analisys.tests; import java.util.ArrayList; import java.util.List; import com.onpositive.semantic.wordnet.composite.CompositeWordnet; import com.onpositive.text.analisys.tools.data.TokenSerializer; import com.onpositive.text.analysis.BasicCleaner; import com.onpositive.text.analysis.IToken; import com.onpositive.text.analysis.syntax.SentenceToken; import com.onpositive.text.analysis.syntax.SyntaxParser; public class JSONSerializerTest extends ParserTest { private TokenSerializer serializer; public JSONSerializerTest() { super(); CompositeWordnet wn=new CompositeWordnet(); wn.addUrl("/numerics.xml"); wn.addUrl("/dimensions.xml"); wn.addUrl("/modificator-adverb.xml"); wn.addUrl("/prepositions.xml"); wn.addUrl("/conjunctions.xml"); wn.addUrl("/modalLikeVerbs.xml"); wn.addUrl("/participles.xml"); wn.prepare(); SyntaxParser syntaxParser = new SyntaxParser(wn); this.composition = syntaxParser; this.serializer = new TokenSerializer(); } @Override protected List process(String str){ List processed = composition.parse(str); ArrayList list = new ArrayList for(IToken t : processed){ if(t instanceof SentenceToken){ list.addAll(new BasicCleaner().clean(t.getChildren())); } else{ list.add(t); } } System.out.println(serializer.serialize()); return list; } public void test001() { String str = "Я не знаю"; List processed = process(str); assertTrue(processed != null); } public void test003() { String str = "Странно будет без очков смотреть на его рукоплескания."; List processed = process(str); assertTrue(processed != null); } }
java
16
0.731508
72
27.163934
61
starcoderdata
var forma = require("forma"); var router = forma.router(); var get = router.get; var post = router.post; var put = router.put; var del = router.delete; module.exports = router;
javascript
3
0.72428
62
19.333333
12
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Course; use App\Lesson; class LessonController extends Controller { public function index() { $data['course']= Course::get()->all(); return view('lesson',$data); } public function subjek(Request $request) { // $id=$request->get('id'); $id=$request->id; // dd($id); $data['lesson']= Lesson::where('id_subjek', '=', $id)->get(); $data['id_course']=$request->id; // dd($data); return view('subjek',$data); } }
php
12
0.571659
69
21.178571
28
starcoderdata
<?php use Illuminate\Database\Seeder; class UserTypesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // DB::table('user_types')->insert([ [ 'title' => 'Groom', 'slug' => 'groom' ], [ 'title' => 'Bride', 'slug' => 'bride' ], [ 'title' => 'Attendee', 'slug' => 'attendee' ], [ 'title' => 'Groomsmen', 'slug' => 'groomsmen' ], [ 'title' => 'Bridesmaid', 'slug' => 'bridesmaid' ], [ 'title' => 'Family Groom', 'slug' => 'family-groom' ], [ 'title' => 'Family Bride', 'slug' => 'family-bride' ], [ 'title' => 'Flower Girl', 'slug' => 'flower-girl' ], [ 'title' => 'Officiant', 'slug' => 'officiant' ], [ 'title' => 'DJ', 'slug' => 'dj' ], [ 'title' => 'Photographer', 'slug' => 'photographer' ], [ 'title' => 'Videographer', 'slug' => 'videographer' ], [ 'title' => 'Ring Bearer', 'slug' => 'ring-bearer' ] ]); } }
php
14
0.290634
42
22.642857
70
starcoderdata
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BackToMainMenuEvent : EventBaseT { }
c#
5
0.838095
66
22.333333
9
starcoderdata
#ifndef _LIST_H_ #define _LIST_H_ #include #include "pool.h" typedef struct _list_item list_item; typedef struct _list_item * list_item_t; struct _list_item { void *value; list_item_t next; }; typedef struct { list_item_t head; list_item_t tail; int count; int size; pool_t pool; pthread_mutex_t lock; pthread_cond_t cond; } list; typedef list * list_t; list_t list_new(int size); void list_resize(list_t l, int new_size); void list_destroy(list_t l); void list_init(list_t l); void * list_prepend(list_t l, void *value); void * list_append(list_t l, void *value); void list_concat(list_t left, list_t right); void list_concat_with_transform(list_t left, list_t right, void *(*transform)(list_item_t)); void * list_get(list_t l, int pos); void * list_remove_by_value(list_t l, void *value); void * list_remove_by_pos(list_t l, int pos); int list_contains(list_t l, void *value); int list_count(list_t l); int list_full(list_t l); void list_set_user_data(list_t l, void *data); void * list_get_user_data(list_t l); #define list_for_each_item(item, l) \ for (item = (l)->head; item != NULL; item = item->next) #define list_for_each(item, v, l) \ for (item = (l)->head, v = item ? item->value : NULL; \ item != NULL; \ item = item->next, v = item ? item->value : NULL) #endif
c
10
0.616391
69
24.928571
56
starcoderdata
exports = module.exports; exports.CreateTask = function() { var sql = "INSERT INTO `tasks` (text, notes, priority, created, completed, estimate, actual) VALUES ( ?, ?, ?, ?, ?, ?, ?)" return sql; } // LOL update is tough, actually exports.UpdateTask = function(task) { if(!task.idtasks) { // no ID, no Update return ""; } var fields = 0; var sql = "UPDATE `tasks` SET "; if(task.text) { sql += "text = ?"; } sql += " WHERE idtasks = ?"; } exports.CompleteTask = function(task) { if(!task.idtasks) { // no ID no completion return ""; } var sql = "UPDATE `tasks` SET completed = ? WHERE `task`.`idtasks` = ?"; return sql; } exports.DeleteTask = function(task) { if(!task.idtasks) { // no ID no deletion } var sql = "DELETE FROM `tasks` WHERE idtasks = ?"; return sql; } exports.FindTask = function(task) { var sql = "SELECT FROM `tasks`" if(!task.idtasks) { // no ID, not sure how to find it // TODO: Search function } else { var sql = "SELECT FROM `tasks` WHERE idtasks = ?"; return sql; } return sql; }
javascript
11
0.548223
127
22.196078
51
starcoderdata
public final synchronized String getCurrentDirectory() { if (this.currentDirectory == null) { // Default to the home directory of the user if (this.user != null) { this.currentDirectory = FileUtils.normalize(this.user.getHomePath().toString()); } else { this.currentDirectory = System.getProperty("user.dir"); } } return this.currentDirectory; }
java
14
0.576159
96
40.272727
11
inline
"""Current file format for the various text only notebook extensions""" import os FILE_FORMAT_VERSION = { # R markdown format '.Rmd': '1.0', # Version 1.0 on 2018-08-22 - jupytext v0.5.2 : Initial version # Markdown format '.md': '1.0', # Version 1.0 on 2018-08-31 - jupytext v0.6.0 : Initial version # Python and Julia scripts '.py': '1.2', '.jl': '1.2', # Version 1.2 on 2018-09-05 - jupytext v0.6.3 : Metadata bracket can be # omitted when empty, if previous line is empty #57 # Version 1.1 on 2018-08-25 - jupytext v0.6.0 : Cells separated with one # blank line #38 # Version 1.0 on 2018-08-22 - jupytext v0.5.2 : Initial version # Python scripts '.R': '1.0', # Version 1.0 on 2018-08-22 - jupytext v0.5.2 : Initial version } MIN_FILE_FORMAT_VERSION = {'.Rmd': '1.0', '.md': '1.0', '.py': '1.1', '.jl': '1.1', '.R': '1.0'} FILE_FORMAT_VERSION_ORG = FILE_FORMAT_VERSION def file_format_version(ext): """Return file format version for given ext""" return FILE_FORMAT_VERSION.get(ext) def min_file_format_version(ext): """Return minimum file format version for given ext""" return MIN_FILE_FORMAT_VERSION.get(ext) def check_file_version(notebook, source_path, outputs_path): """Raise if file version in source file would override outputs""" _, ext = os.path.splitext(source_path) current = file_format_version(ext) version = notebook.metadata.get('jupytext_format_version') if version: del notebook.metadata['jupytext_format_version'] # Missing version, still generated by jupytext? if notebook.metadata and not version: version = current # Same version? OK if version == current: return # Version larger than minimum readable version if version <= current and version >= min_file_format_version(ext): return # Not merging? OK if source_path == outputs_path: return raise ValueError("File {} has jupytext_format_version={}, but " "current version for that extension is {}.\n" "It would not be safe to override the source of {} " "with that file.\n" "Please remove one or the other file." .format(os.path.basename(source_path), version, current, os.path.basename(outputs_path)))
python
11
0.601781
76
31.946667
75
starcoderdata
# -*- coding: utf-8 -*- """ jsix.py - Wor2Vec model trained from Juliet and Six other open source project :Author: Verf :Email: :License: MIT """ import pathlib from torchplp.processor.embedder import Word2Vec from torchplp.utils.utils import download_file url = 'https://nas.dothings.top:5002/NIPCDL/Jsix/jsix_{}.w2v' def jsix(root='/tmp', length=100, delete=True, proxy=None): """word2vec model trained by juliet and other six open source project""" root = pathlib.Path(root).expanduser() file = root / f'jsix_{length}.w2v' download_file(url.format(length), root, proxy) wm = Word2Vec() wm.load(str(file)) if delete: file.unlink() return wm
python
9
0.690411
77
26.037037
27
starcoderdata
def makeGuess(triangles, indexes, viewable, stars): vtriangles, vindexes = findTriangles(viewable) #print("Starting to guess, calculated vtriangles:") #print(vtriangles) potentials, matches = findPotentials(triangles, indexes, vtriangles, vindexes, stars) # Find the indexes of stars that would best fill the slots pairs, costA = hungarian(potentials, matches) pairs.sort(key=lambda x:costA[x]) indexes = list(map(lambda x: potentials[x[1]], pairs)) return indexes
python
12
0.707602
89
33.266667
15
inline
<?php // Alert the user about their environment for all those "help!" requests passthru('git --version; type git'); $runAgain = false; chdir(__DIR__); if(empty($argv[1])) { /* * When a unit is no longer needed we need to clear it from the system. * Rather than doing something complex, lets just remove all existing * units and checkout only the ones we need. Makes the compile stage much * easier. * * @todo this wastes bandwidth re-downloading projects over and over */ foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator('Units', FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ) as $path) { $path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname()); } } // Starting with us, loop over all existing gists foreach (array_merge(array('../'), glob("Units/*")) as $directory) { chdir(__DIR__ . '/' . $directory); is_dir('.git') AND passthru('git pull origin master'); /** * The Units.md file is a mix of readme + composer.json. We allow notes and * comments in addition to gist ID's. We autodetect gists that start with * "https://" (vs "http://") and add them as dependencies of this unit. If * you want to talk about a gist that is not required by your unit then please * use "http://". * * Samples: * https://gist.github.com/[integer](.git) * https://gist.github.com/[user]/[integer] * https://gist.github.com/[hash](.git) * https://gist.github.com/[user]/[hash] * * Format to: * https://gist.github.com/([hash]|[integer]).git */ if(is_file('readme.md')) { if(preg_match_all('~https://gist.github.com/(?:\w+/)?(\w+)~', file_get_contents('readme.md'), $matches)) { foreach($matches[1] as $id) { chdir(__DIR__ . '/Units'); if( ! is_dir($id)) { passthru("git clone https://gist.github.com/$id.git"); $runAgain = true; } } } } } if($runAgain) { passthru("php ".__FILE__ . ' 1'); } else { passthru("php " . __DIR__ . '/compile.php'); }
php
17
0.636319
108
29.507463
67
starcoderdata
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { updateReportName, fetchReport } from 'base/redux/actions/Actions'; import { Link } from 'react-router-dom'; import classNames from 'classnames/bind'; import styles from './_header-report.scss'; import ContentEditable from 'base/components/inputs/ContentEditable' import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import { faCopy, faTrashAlt, faFilePdf, faPrint, faAngleRight, faEllipsisH } from '@fortawesome/fontawesome-free-solid'; let cx = classNames.bind(styles); class HeaderReport extends Component { constructor(props) { super(props); this.state = { reportName: this.props.reportName, controlsExpanded: false, }; this.editReportData = this.editReportData.bind(this); } editReportData = (evt) => { this.setState({ reportName: evt.target.value, }); } expandControls = () => { this.setState({ controlsExpanded: !this.state.controlsExpanded, }); } componentWillReceiveProps(nextProps) { if (this.props !== nextProps) { this.setState({ reportName: nextProps.reportName, }) } } componentDidMount() { this.props.fetchReport(this.props.reportId) } render() { return ( <section className={styles['header-content-report']}> <div className={cx({ 'main-content': true, 'container': true})}> <div className={styles['content-top']}> <Link to='/figures/reports' className={styles['back-link']} > Back to reports list <ContentEditable className={styles['report-title']} html={this.state.reportName} dataLabel={'reportTitle'} onChange={this.editReportData} onBlur={() => this.props.updateReportName(this.state.reportName)} /> <div className={styles['content-bottom']}> <span className={styles['title-underline']}> <div className={styles['controls-container']}> <button key="save-button" className={styles['button-main']}>Save report {this.state.controlsExpanded && [ <span key="separator-1" className={styles['controls-separator']}> <button key="duplicate-button" className={styles['button-secondary']}> <FontAwesomeIcon icon={faCopy} className={styles['button-icon']} /> <button key="trash-button" className={styles['button-secondary']}> <FontAwesomeIcon icon={faTrashAlt} className={styles['button-icon']} /> <button key="pdf-button" className={styles['button-secondary']}> <FontAwesomeIcon icon={faFilePdf} className={styles['button-icon']} /> <button key="print-button" className={styles['button-secondary']}> <FontAwesomeIcon icon={faPrint} className={styles['button-icon']} /> <span key="separator-2" className={styles['controls-separator']}> ]} <button onClick={() => this.expandControls()} key="expand-button" className={cx({ 'button-secondary': true, 'button-more': true})}> {this.stateControlsExpanded ? ( <FontAwesomeIcon icon={faAngleRight} className={styles['button-icon']} /> ) : ( <FontAwesomeIcon icon={faEllipsisH} className={styles['button-icon']} /> )} ); } } HeaderReport.defaultProps = { } const mapStateToProps = (state, ownProps) => ({ reportName: state.report.reportName, }) const mapDispatchToProps = dispatch => ({ updateReportName: newName => dispatch(updateReportName(newName)), fetchReport: reportId => dispatch(fetchReport(reportId)), }) export default connect( mapStateToProps, mapDispatchToProps )(HeaderReport)
javascript
18
0.599577
145
34.14876
121
starcoderdata
import Firebase from '../../config/firebase'; // import { installActionNames } from '..'; const db = Firebase.getFirestore(); const storageRef = Firebase.getStorageRef(); export const service = { async addCustomer(values) { let docRef = await db.collection('customers').add({ ...values, }); let customer = {}; let doc = await docRef.get(); let docId = doc.id; customer = { docId, ...doc.data() }; return customer; }, async getCustomers() { let customers = []; let querySnapshot = await db.collection('customers').get(); querySnapshot.forEach(doc => { let docId = doc.id; let customerData = doc.data(); let customer = { docId, ...customerData }; customers.push(customer); }); return customers; }, async getCustomerJobs(jobPaths) { let promises = []; //Create a promise for each job Path jobPaths.forEach(path => { path = path.slice(path.indexOf('/') + 1); promises.push( db .collection('jobs') .doc(path) .get() ); }); //Resolve all the promises let docSnaps = await Promise.all(promises); //map each resolved promise to the jobs table let jobs = docSnaps.map(docSnap => { let docId = docSnap.id; return { docId, ...docSnap.data() }; }); return jobs; }, async updateCustomer(docId, values) { await db .collection('customers') .doc(docId) .update({ ...values }); let updatedCustomer = await db .collection('customers') .doc(docId) .get(); return { docId, ...updatedCustomer.data() }; }, async getCurrentCustomer(customerId) { console.log('Service: ', customerId); let customer = await db .collection('customers') .doc(customerId) .get(); try { //If an image exists pass it on with the customer Data let customer_img_url = await storageRef .child(`customer_imgs/${customerId}`) .getDownloadURL(); customer = { docId: customer.id, img: customer_img_url, ...customer.data(), }; return customer; } catch (err) { //if no image exists, then just passs the data customer = { docId: customer.id, ...customer.data() }; return customer; } }, async getCustomerImage(customerId) { let customer_img_url = await storageRef .child(`customer_imgs/${customerId}`) .getDownloadURL(); return customer_img_url; }, };
javascript
22
0.503404
67
25.954128
109
starcoderdata
package com.march.uikit.mvp.P; import com.march.uikit.lifecycle.StateLifeCycle; import com.march.uikit.mvp.V.MvpView; /** * CreateAt : 2017/12/7 * Describe : * * @author chendong */ interface IPresenter<V extends MvpView> extends StateLifeCycle { /** * presenter 被创建,绑定到 View,此时 View 的状态无法确定 * @param view view */ void onAttachView(V view); /** * view 执行了 onViewCreated */ void onViewReady(); /** * 从 view 中解除绑定 */ void onDetachView(); /** * 获取绑定到的 view * @return view */ V getView(); }
java
7
0.605519
64
15.648649
37
starcoderdata
import React from 'react'; import { PropTypes as PT } from 'prop-types'; import { Container } from './styled'; const Button = props => { return <Container {...props}>{props.label} }; Button.propTypes = { label: PT.string.isRequired, onClick: PT.func.isRequired, }; export default Button;
javascript
10
0.683871
57
21.142857
14
starcoderdata
def test_too_few_values(self): class Foo(Command): bar = Option(nargs=2) with Context(['--bar', 'a'], Foo) as ctx: foo = Foo() # This is NOT the recommended way of initializing a Command with self.assertRaises(BadArgument): CommandParser.parse_args() with self.assertRaisesRegex(BadArgument, r'expected nargs=.* values but found \d+'): foo.bar
python
11
0.575964
96
43.2
10
inline
using UnityEngine; public class TimeManager : MonoBehaviour { #region Singleton public static TimeManager Instance { get { if (m_Instance != null) return m_Instance; m_Instance = FindObjectOfType if (m_Instance == null) { GameObject obj = new GameObject("TimeManager"); m_Instance = obj.AddComponent } return m_Instance; } } private static TimeManager m_Instance; #endregion private float m_Amount; private float m_Duration; private float m_Timer; private bool m_GraduallyIncreaseTimeBackToNormal; private float m_OriginalFixedDeltaTime; private void Awake() { m_OriginalFixedDeltaTime = Time.fixedDeltaTime; } private void Update() { if (m_Timer > 0) { m_Timer -= Time.unscaledDeltaTime; if (m_GraduallyIncreaseTimeBackToNormal) { GraduallyIncreaseTimeToNormal(); } if (m_Timer <= 0) { ChangeTimeBackToNormal(); } } } public void ChangeTimeBackToNormal() { Time.timeScale = 1; Time.fixedDeltaTime = m_OriginalFixedDeltaTime; } private void GraduallyIncreaseTimeToNormal() { Time.timeScale += (1 - m_Amount) / (m_Duration / Time.unscaledDeltaTime); } /// /// Slowdown time of entire system /// /// <param name="amount">0 to 1 /// <param name="duration"> public void SlowdownTime(float amount, float duration, bool graduallyIncreaseTimeBackToNormal = true) { //Change time back to normal first ChangeTimeBackToNormal(); //Variables m_GraduallyIncreaseTimeBackToNormal = graduallyIncreaseTimeBackToNormal; m_Timer = duration; m_Amount = Mathf.Clamp(amount, 0, 1); m_Duration = duration; //Slowdown Time.timeScale = amount; Time.fixedDeltaTime = Time.timeScale * m_OriginalFixedDeltaTime; } }
c#
17
0.575909
105
20.568627
102
starcoderdata
def __action_api (host,action, data_dict): # Make the HTTP request for data set generation. response='' rvalue = 0 action_url = "http://{host}/api/3/action/{action}".format(host=host,action=action) # make json data in conformity with URL standards data_string = urllib.quote(json.dumps(data_dict)) ##print('\t|-- Action %s\n\t|-- Calling %s\n\t|-- Object %s ' % (action,action_url,data_dict)) try: request = urllib2.Request(action_url) response = urllib2.urlopen(request,data_string) except urllib2.HTTPError as e: print '\t\tError code %s : The server %s couldn\'t fulfill the action %s.' % (e.code,host,action) if ( e.code == 403 ): print '\t\tAccess forbidden, maybe the API key is not valid?' exit(e.code) elif ( e.code == 409 and action == 'package_create'): print '\t\tMaybe the dataset already exists or you have a parameter error?' action('package_update',data_dict) return {"success" : False} elif ( e.code == 409): print '\t\tMaybe you have a parameter error?' return {"success" : False} elif ( e.code == 500): print '\t\tInternal server error' exit(e.code) except urllib2.URLError as e: exit('%s' % e.reason) ##except urllib2.BadStatusLine as e: ## exit('%s' % e.reason) except Exception, e: exit('%s' % e.reason) else : out = json.loads(response.read()) assert response.code >= 200 return out
python
13
0.574388
104
40.947368
38
inline
#ifndef PLUS_H_INCLUDED #define PLUS_H_INCLUDED export template<typename T> T plus(const T& lhs, const T& rhs); #endif // #ifndef PLUS_H_INCLUDED
c
7
0.724832
35
17.625
8
starcoderdata
import React, {Component} from 'react'; import {BrowserRouter, Route, Redirect, Switch} from 'react-router-dom'; import {Grid, Row} from 'react-bootstrap'; import './App.css'; import CustomNavbar from '../components/custom-navbar/custom-navbar'; import LoginPage from '../pages/Login/login'; import HomePage from "../pages/Home/Home"; import AuctionPage from "../pages/Auction/auction"; import ProfilePage from "../pages/Profile/Profile"; export default class App extends Component { render() { return ( <div className="App"> <PrimaryLayout /> ); } } const PrimaryLayout = () => ( <div className="primary-layout"> {/*<Row xs={12} md={8} lg={6}>*/} <Route path="/" exact component={HomePage}/> <Route path="/auction" component={AuctionPage}/> <PrivateRoute path="/profile" component={ProfilePage}/> <Route path="/login" component={LoginPage}/> <Redirect to="/404"/> {/* ) const auth = { isAuthenticated: false, } // https://reacttraining.com/react-router/web/example/auth-workflow const PrivateRoute = ({component: Component, ...rest}) => ( <Route {...rest} render={props => ( auth.isAuthenticated ? ( <Component {...props}/> ) : ( <Redirect to={{ pathname: '/login', state: {from: props.location} }}/> ) )}/> )
javascript
17
0.507353
79
29.709677
62
starcoderdata
func TestGoPackagesOODOnSource(t *testing.T) { controller := gomock.NewController(t) defer controller.Finish() cli := io.NewMockDockerCli(controller) helper := io.NewMockHelper(controller) etcd := io.NewMockEtcdClient(controller) c := setupForDontBuildBletch(controller, helper, cli, etcd) //this is called to figure out how to mount the source... we don't care how many //times this happens helper.EXPECT().DirectoryRelative("src").Return("/home/gredo/project/bounty/src").AnyTimes() //we want to suggest that the nashville container was built recently when first //asked... we will be asked a second time, but it gets discarded so we just //do the same thing both times now := time.Now() insp := io.NewMockInspectedImage(controller) insp.EXPECT().CreatedTime().Return(now).Times(2) cli.EXPECT().InspectImage("test:nashville").Return(insp, nil).Times(2) // // this is the test of how the go source OOD really works // // test for code build needed, then build it runConfigBase := io.RunConfig{ Image: "blah/bletch", Volumes: map[string]string{ "/vagrant/src": "/han", }, } probe := runConfigBase probe.Attach = false build := runConfigBase build.Attach = true buffer := new(bytes.Buffer) buffer.WriteString("stuff") cli.EXPECT().CmdRun(gomock.Any(), "go", "install", "-n", "p1...").Return(new(bytes.Buffer), "", nil) cli.EXPECT().CmdRun(gomock.Any(), "go", "test", "p1...").Return(nil, "cont1", nil) //test for code build needed, then build it cli.EXPECT().CmdRun(gomock.Any(), "go", "install", "-n", "p2/p3").Return(buffer, "", nil) cli.EXPECT().CmdRun(gomock.Any(), "go", "test", "p2/p3").Return(nil, "cont2", nil) // //Fake the results of the two "probes" with -n, we want to return true (meaning that //there is no output, thus to code is up to date) on the first one. we return false //on the second one and it needs to be the second one because the system won't //bother asking about the second one if the first one already means we are OOD // //first := cli.EXPECT().EmptyOutput(true).Return(true) //cli.EXPECT().EmptyOutput(true).Return(false).After(first) //after we build successfully, we use "ps -q -l" to check to see the id of //the container that we built in. //expectContainerPSAndCommit(cli) cli.EXPECT().CmdCommit("cont1", nil).Return("someid", nil) cli.EXPECT().CmdCommit("cont2", nil).Return("someotherid", nil) cli.EXPECT().CmdTag("someotherid", true, &io.TagInfo{"test", "nashville"}) //hit it! c.Build("test:nashville") }
go
14
0.698728
101
36.014706
68
inline
<?php /** * sjaakp/yii2-comus * ---------- * Comment module for Yii2 framework * Version 1.0.0 * Copyright (c) 2019 * Amsterdam * MIT License * https://github.com/sjaakp/yii2-comus * https://sjaakpriester.nl */ namespace sjaakp\comus\models; use Yii; use yii\db\ActiveRecord; use yii\behaviors\BlameableBehavior; use yii\helpers\Html; use yii\helpers\HtmlPurifier; use sjaakp\novelty\NoveltyBehavior; use yii\db\Expression; /** * Class Comment * @package sjaakp\comus * * @property int $id * @property string $subject * @property int $parent * @property int $status * @property string $body * @property int $created_by * @property int $updated_by * @property string $created_at * @property string $updated_at */ class Comment extends ActiveRecord { const PENDING = 0; const ACCEPTED = 1; const REJECTED = 2; const STATUSES = [ self::PENDING => 'pending', self::ACCEPTED => 'accepted', self::REJECTED => 'rejected' ]; /** * @var array */ public $purifierConfig = [ 'HTML.Allowed' => 'p,a[href]', 'AutoFormat.AutoParagraph' => true ]; /** * {@inheritdoc} */ public static function tableName() { return '{{%comment}}'; } /** * {@inheritdoc} */ public function behaviors() { return [ [ 'class' => NoveltyBehavior::class, 'value' => new Expression('NOW()'), ], BlameableBehavior::class, ]; } /** * @inheritDoc */ public function beforeDelete() { if (!parent::beforeDelete()) { return false; } $children = self::find()->where([ 'parent' => $this->id ])->all(); foreach($children as $child) { try { $child->delete(); } catch (\Throwable $e) { return false; } } return true; } /** * @return string */ public function getClasses() { $r = [ 'comus-' . self::STATUSES[$this->status] ]; $novelty = $this->novelty; // null|'new'|'updated' if (! empty($novelty)) $r[] = 'comus-' . $novelty; if (Yii::$app->user->id == $this->created_by) $r[] = 'comus-own'; if (Yii::$app->authManager->checkAccess($this->created_by, 'manageComments')) $r[] = 'comus-moderator'; return implode(' ', $r); } /** * @return string */ public function getSanitizedBody() { $body = Html::tag('div', $this->body, [ 'class' => 'comus-body' ]); if ($this->status == self::REJECTED) { $r = Html::tag('div', Yii::t('comus', 'This comment has been rejected.'), [ 'class' => 'comus-message' ]); if (Yii::$app->user->can('manageComments')) $r .= $body; return $r; } return $body; } /** * @param $format * @return string 'standard' | 'relative' | any value yii\i18n\formatter::datetimeFormat can take * @throws \yii\base\InvalidConfigException */ public function getFormattedTime($format) { $formatter = Yii::$app->formatter; if ($format == 'standard') { return $formatter->asRelativeTime($this->created_at) . Html::tag('span', $formatter->asDatetime($this->created_at, 'short'), [ 'class' => 'comus-short' ]); } return $format == 'relative' ? $formatter->asRelativeTime($this->created_at) : $formatter->asDatetime($this->created_at, $format); } /** * @return array */ public function getHref() { return [ $this->subject, '#' => "cmt-{$this->id}" ]; } /** * @return \yii\db\ActiveQuery */ public function getCreatedBy() { return $this->hasOne(Yii::$app->user->identityClass, ['id' => 'created_by']); } /** * @return \yii\db\ActiveQuery */ public function getUpdatedBy() { return $this->hasOne(Yii::$app->user->identityClass, ['id' => 'updated_by']); } /** * {@inheritdoc} */ public function rules() { return [ // @link https://stackoverflow.com/questions/30124559/yii2-how-to-validate-xss-cross-site-scripting-in-form-model-input/30124560 [['body'], 'filter', 'filter' => function($in) { return HtmlPurifier::process($in, $this->purifierConfig); }], // [['body'], 'required', 'message' => Yii::t('comus', 'Comment cannot be blank')], // replaced by HTML required [['created_at', 'updated_at', 'created_by', 'updated_by', 'subject', 'parent', 'status'], 'safe'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => Yii::t('comus', 'ID'), 'subject' => Yii::t('comus', 'Subject'), 'body' => Yii::t('comus', 'Body'), 'created_by' => Yii::t('comus', 'Created By'), 'updated_by' => Yii::t('comus', 'Updated By'), 'created_at' => Yii::t('comus', 'Created At'), 'updated_at' => Yii::t('comus', 'Updated At'), 'createdBy.name' => Yii::t('comus', 'Created By'), 'updatedBy.name' => Yii::t('comus', 'Updated By'), ]; } }
php
18
0.523595
167
26.137755
196
starcoderdata
package net.arvin.wanandroid.uis.activities; import android.os.Bundle; import android.view.View; import net.arvin.baselib.base.BaseActivity; import net.arvin.baselib.widgets.TitleBar; import net.arvin.wanandroid.R; import net.arvin.wanandroid.uis.fragments.ArticleListFragment; /** * Created by arvinljw on 2018/11/30 14:57 * Function: * Desc: */ public class CollectionArticleActivity extends BaseActivity { @Override protected int getContentView() { return R.layout.activity_collection_article; } @Override protected void init(Bundle savedInstanceState) { TitleBar titleBar = findViewById(R.id.title_bar); titleBar.getCenterTextView().setText("我的收藏"); titleBar.getLeftImageView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); getSupportFragmentManager().beginTransaction().add(R.id.layout_articles, new ArticleListFragment(-1, ArticleListFragment.API_COLLECTION_LIST)).commit(); } }
java
15
0.692168
95
30.371429
35
starcoderdata
/* * Copyright 1&1 Internet AG, https://github.com/1and1/ * * 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 net.oneandone.troilus.java7; import java.math.BigDecimal; import java.math.BigInteger; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.Date; import java.util.UUID; import net.oneandone.troilus.ColumnName; import net.oneandone.troilus.Result; import com.datastax.driver.core.TupleValue; import com.datastax.driver.core.UDTValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; /** * record result */ public interface Record extends Result { /** * @param name the column name * @return the write time of this column or empty if no write time was requested */ Long getWritetime(String name); /** * @param name the column name * @return the ttl of this column or empty if no ttl was requested or NULL */ Integer getTtl(String name); /** * @param name the column name * @return whether the value for column name in this row is NULL */ boolean isNull(String name); /** * @param name the column name * @return the value of column name as a long. If the value is NULL, 0L is returned. */ long getLong(String name); /** * @param name the column name * @return the value of column name as a string or null */ String getString(String name); /** * @param name the column name * @return the value of column name as a boolean. If the value is NULL, false is returned. */ boolean getBool(String name); /** * @param name the column name * @return the value of column name as a ByteBuffer or null */ ByteBuffer getBytes(String name); /** * @param name the column name * @return the value of column name as a ByteBuffer or null. This method always return the bytes composing the value, even if the column is not of type BLOB */ ByteBuffer getBytesUnsafe(String name); /** * @param name the column name * @return value of column name as a float. If the value is NULL, 0.0f is returned. */ float getFloat(String name); /** * @param name the column name * @return value of column name as a date. If the value is NULL, null is returned. */ Date getDate(String name); /** * @param name the column name * @return value of column name as time. If the value is NULL, 0 is returned. */ long getTime(String name); /** * @param name the column name * @return the value of column name as a decimal. If the value is NULL, null is returned */ BigDecimal getDecimal(String name); /** * @param name the column name * @return value of column name as an integer. If the value is NULL, 0 is returned */ int getInt(String name); /** * @param name the column name * @return value of column name as an InetAddress. If the value is NULL, null is returned. */ InetAddress getInet(String name); /** * @param name the column name * @return the value of column name as a variable length integer. If the value is NULL, null is returned. */ BigInteger getVarint(String name); /** * @param name the column name * @return the value of column name as a UUID. If the value is NULL, null is returned. */ UUID getUUID(String name); /** * @param name the name to retrieve. * @return the value of {@code name} as a tuple value. If the value is NULL, null will be returned. */ TupleValue getTupleValue(String name); /** * @param name the column name * @return the value for column name as a UDT value. If the value is NULL, then null will be returned. */ UDTValue getUDTValue(String name); /** * @param name the column name * @param enumType the enum type * @param the enum type class * @return the value for column name as an enum value or null */ <T extends Enum T getEnum(String name, Class enumType); /** * @param name the column name * @param the name type * @return the value for column name as an value type according the name definition or null */ T getValue(ColumnName name); /** * @param name the column name * @param type the class for value to retrieve. * @param the result type * @return the value of column name or null */ T getValue(String name, Class type); /** * @param name the column name * @param elementsClass the class for the elements of the set to retrieve * @param the set member type * @return the value of column name as a set of an empty Set */ ImmutableSet getSet(String name, Class elementsClass); /** * @param name the column name * @param elementsClass the class for the elements of the list to retrieve * @param the list member type * @return the value of column name as a list or an empty List */ ImmutableList getList(String name, Class elementsClass); /** * @param name the column name * @param keysClass the class for the key element * @param valuesClass the class for the value element * @param the member key type * @param the member key value * @return the value of column name as a map or an empty Map */ <K, V> ImmutableMap<K, V> getMap(String name, Class keysClass, Class valuesClass); }
java
9
0.631802
160
30.418719
203
starcoderdata
/** @ngInject */ function ToolbarController(auth, $state, $rootScope) { const $ctrl = this; this.login = function () { auth.logout(); auth.authenticate('CVUT').then(response => { auth.setToken(response.data); $state.reload(); }); }; this.logout = function () { auth.logout(); $state.reload(); }; this.theme = function () { $rootScope.theme = "default"; }; this.$onInit = function () { auth.oauth().then(val => { $ctrl.oauth = val; }); auth.isAuthenticated().then(val => { $ctrl.isAuthenticated = val; }); auth.getPayload().then(val => { if (val) { $ctrl.isAdmin = (val.role !== "user"); $ctrl.username = val.username; } else { $ctrl.isAdmin = false; $ctrl.username = ""; } }); }; // this.username = this.isAuthenticated() ? auth.getPayload().username : ""; } export const toolbar = { template: require('./toolbar.html'), controller: ToolbarController };
javascript
19
0.552135
80
21.377778
45
starcoderdata
package fr.AleksGirardey.Listeners; import com.sun.org.apache.xpath.internal.operations.Bool; import fr.AleksGirardey.Objects.Core; import fr.AleksGirardey.Objects.DBObject.DBPlayer; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.text.Text; public class OnPlayerCubo { @Listener public void onPlayerCubo(InteractBlockEvent event) { DBPlayer player = Core.getPlayerHandler().get(event.getCause().first(Player.class).orElseGet(null)); Boolean b; if (player != null && Core.getCuboHandler().playerExists(player)) { player.sendMessage(Text.of("[Cubo Debug] My cubo mode is activated")); b = event instanceof InteractBlockEvent.Primary; Core.getCuboHandler().set( player, event.getTargetBlock().getLocation().get().getBlockPosition(), b); event.setCancelled(true); } } }
java
13
0.684575
111
40.214286
28
starcoderdata
package via import ( "fmt" "strings" "github.com/byuoitav/common/log" "github.com/byuoitav/common/nerr" "github.com/byuoitav/common/structs" "github.com/fatih/color" ) // User status constants const ( Inactive = "0" Active = "1" Waiting = "2" ) // IsConnected checks the status of the VIA connection func IsConnected(address string) bool { defer color.Unset() color.Set(color.FgYellow) connected := false log.L.Infof("Getting connected status of %s", address) var command Command resp, err := SendCommand(command, address) if err == nil && strings.Contains(resp, "Successful") { connected = true } return connected } // Get the Room Code and return the current room code as a string func GetRoomCode(address string) (string, error) { var command Command command.Command = "RCode" command.Param1 = "Get" command.Param2 = "Code" log.L.Infof("Sending command to get current room code to %s", address) // Note: RCode Get command in VIA API doesn't have any error handling so it only returns RCode|Get|Code|XXXX or nothing resp, err := SendCommand(command, address) if err != nil { return "", err } split := strings.Split(resp, "|") if len(split) != 4 { return "", fmt.Errorf("Unknown response %v", resp) } roomcode := strings.TrimSpace(split[3]) return roomcode, nil } //GetPresenterCount . func GetPresenterCount(address string) (int, error) { var command Command command.Command = "PList" command.Param1 = "all" command.Param2 = "1" log.L.Infof("Sending command to get VIA Presentation count to %s", address) // Note: Volume Get command in VIA API doesn't have any error handling so it only returns Vol|Get|XX or nothing // I am still checking for errors just in case something else fails during execution resp, err := SendCommand(command, address) if err != nil { return 0, err } firstsplit := strings.Split(resp, "|") //check to assert that first split is len 4 if len(firstsplit) != 4 { return 0, fmt.Errorf("Unknown response %v", resp) } if strings.Contains(strings.ToLower(firstsplit[3]), "error14") { return 0, nil } //otherwise we go through and split on #, then count the number of secondSplit := strings.Split(firstsplit[3], "$") return len(secondSplit), nil } // GetVolume for a VIA device func GetVolume(address string) (int, error) { defer color.Unset() color.Set(color.FgYellow) var command Command command.Command = "Vol" command.Param1 = "Get" log.L.Infof("Sending command to get VIA Volume to %s", address) // Note: Volume Get command in VIA API doesn't have any error handling so it only returns Vol|Get|XX or nothing // I am still checking for errors just in case something else fails during execution vollevel, _ := SendCommand(command, address) return VolumeParse(vollevel) } // GetHardwareInfo for a VIA device func GetHardwareInfo(address string) (structs.HardwareInfo, *nerr.E) { defer color.Unset() color.Set(color.FgYellow) log.L.Infof("Getting hardware info of %s", address) var toReturn structs.HardwareInfo var command Command // get serial number command.Command = "GetSerialNo" serial, err := SendCommand(command, address) if err != nil { return toReturn, nerr.Translate(err).Addf("failed to get serial number from %s", address) } toReturn.SerialNumber = parseResponse(serial, "|") // get firmware version command.Command = "GetVersion" version, err := SendCommand(command, address) if err != nil { return toReturn, nerr.Translate(err).Addf("failed to get the firmware version of %s", address) } toReturn.FirmwareVersion = parseResponse(version, "|") // get MAC address command.Command = "GetMacAdd" macAddr, err := SendCommand(command, address) if err != nil { return toReturn, nerr.Translate(err).Addf("failed to get the MAC address of %s", address) } // get IP information command.Command = "IpInfo" ipInfo, err := SendCommand(command, address) if err != nil { return toReturn, nerr.Translate(err).Addf("failed to get the IP information from %s", address) } hostname, network := parseIPInfo(ipInfo) toReturn.Hostname = hostname network.MACAddress = parseResponse(macAddr, "|") toReturn.NetworkInfo = network return toReturn, nil } func parseResponse(resp string, delimiter string) string { pieces := strings.Split(resp, delimiter) var msg string if len(pieces) < 2 { msg = pieces[0] } else { msg = pieces[1] } return strings.Trim(msg, "\r\n") } func parseIPInfo(ip string) (hostname string, network structs.NetworkInfo) { ipList := strings.Split(ip, "|") for _, item := range ipList { if strings.Contains(item, "IP") { network.IPAddress = strings.Split(item, ":")[1] } if strings.Contains(item, "GAT") { network.Gateway = strings.Split(item, ":")[1] } if strings.Contains(item, "DNS") { network.DNS = []string{strings.Split(item, ":")[1]} } if strings.Contains(item, "Host") { hostname = strings.Trim(strings.Split(item, ":")[1], "\r\n") } } return hostname, network } // GetActiveSignal determines the active signal of the VIA by getting the user count func GetActiveSignal(address string) (structs.ActiveSignal, *nerr.E) { signal := structs.ActiveSignal{Active: false} count, err := GetPresenterCount(address) if err != nil { return signal, nerr.Translate(err).Add("failed to get the status of users") } if count > 0 { signal.Active = true } return signal, nil } // getStatusOfUsers returns the status of users that are logged in to the VIA func GetStatusOfUsers(address string) (structs.VIAUsers, *nerr.E) { var toReturn structs.VIAUsers toReturn.InactiveUsers = []string{} toReturn.ActiveUsers = []string{} toReturn.UsersWaiting = []string{} defer color.Unset() color.Set(color.FgYellow) var command Command command.Command = "PList" command.Param1 = "all" command.Param2 = "4" log.L.Infof("Sending command to get VIA users info to %s", address) response, err := SendCommand(command, address) if err != nil { return toReturn, nerr.Translate(err).Addf("failed to get user information from %s", address) } fullList := strings.Split(response, "|") userList := strings.Split(fullList[3], "#") for _, user := range userList { if len(user) == 0 { continue } userSplit := strings.Split(user, "_") if len(userSplit) < 2 { continue } nickname := userSplit[0] state := userSplit[1] switch state { case Inactive: toReturn.InactiveUsers = append(toReturn.InactiveUsers, nickname) break case Active: toReturn.ActiveUsers = append(toReturn.ActiveUsers, nickname) break case Waiting: toReturn.UsersWaiting = append(toReturn.UsersWaiting, nickname) break } } return toReturn, nil }
go
16
0.705088
120
23.874539
271
starcoderdata
using System.Collections.Generic; using Trails.Data.DomainModels; using Trails.Models.Beacon; namespace Trails.Test.BeaconServiceTests { public static class BeaconServiceTestData { public static List GetTestBeacons() => new() { new() { Id = "00000000-0000-0000-0000-000000000001", Imei = "000000000000001", Description = "Description for this beacon", SimCardNumber = "+359887123456", KeyHash = " }, new() { Id = "00000000-0000-0000-0000-000000000002", Imei = "000000000000002", Description = "Description for this beacon", SimCardNumber = "+359887123789", KeyHash = " }, new() { Id = "00000000-0000-0000-0000-000000000003", Imei = "000000000000003", Description = "Description for this beacon", SimCardNumber = "+359887123004", KeyHash = " }, new() { Id = "00000000-0000-0000-0000-000000000004", Imei = "000000000000004", Description = "Description for this beacon", SimCardNumber = "+359887123005", KeyHash = " }, new() { Id = "00000000-0000-0000-0000-000000000005", Imei = "000000000000005", Description = "Description for this beacon", SimCardNumber = "+359887123014", KeyHash = " }, new() { Id = "00000000-0000-0000-0000-000000000006", Imei = "000000000000006", Description = "Description for this beacon", SimCardNumber = "+359887123025", KeyHash = " } }; public static BeaconFormModel CorrectBeaconCreateTest() => new() { Imei = "111111111111119", Description = "Description for single beacon", SimCardNumber = "0883123456", Key = "1234567890" }; public static BeaconFormModel IncorrectBeaconCreateTest() => new() { Imei = "000000000000006", Description = "Description for single beacon", SimCardNumber = "0883123476", Key = "1234567890" }; public static List GetTestParticipants() => new() { new Participant { Id = "00000000-0000-0000-0000-000000000002", IsApproved = true, BeaconId = "00000000-0000-0000-0000-000000000006" } }; } }
c#
13
0.432836
69
34.340659
91
starcoderdata
private void OnListPickerModeChanged(ListPickerMode oldValue, ListPickerMode newValue) { if ((ListPickerMode.Expanded == oldValue)) { if (null != _page) { _page.BackKeyPress -= OnPageBackKeyPress; _page = null; } if (null != _frame) { _frame.ManipulationStarted -= OnFrameManipulationStarted; _frame = null; } } if (ListPickerMode.Expanded == newValue) { // Hook up to frame if not already done if (null == _frame) { _frame = Application.Current.RootVisual as PhoneApplicationFrame; if (null != _frame) { _frame.AddHandler(ManipulationStartedEvent, new EventHandler<ManipulationStartedEventArgs>(OnFrameManipulationStarted), true); } } if (null != _frame) { _page = _frame.Content as PhoneApplicationPage; if (null != _page) { _page.BackKeyPress += OnPageBackKeyPress; } } } if (ListPickerMode.Full == oldValue) { ClosePickerPage(); } if (ListPickerMode.Full == newValue) { OpenPickerPage(); } SizeForAppropriateView(ListPickerMode.Full != oldValue); IsHighlighted = (ListPickerMode.Expanded == newValue); }
c#
17
0.423901
150
32.823529
51
inline
import os import cv2 import imutil as im import ocrutil as ocr import solver PATH_TO_RES = r"C:/Users/hench/PycharmProjects/rt-sudoku/res/" DEFAULT_FILENAME = "frame_capture_0.png" def main(): capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) cv2.namedWindow("Image Capture") if not capture.isOpened(): capture.open(0) while True: ret, frame = capture.read() cv2.imshow("Image Capture Window", frame) image = None wkey = cv2.waitKey(1) if wkey & 0xFF == ord('q'): break elif wkey & 0xFF == ord('c'): image = frame cv2.imwrite(os.path.join(PATH_TO_RES, DEFAULT_FILENAME), frame) break capture.release() cv2.destroyAllWindows() if image is not None: preprocessed = im.preprocess(image) transformed = im.find_contours(image, preprocessed) im.partition(transformed) pl_board = ocr.images_to_array(PATH_TO_RES).tolist() solver.solve(pl_board) solver.draw(pl_board) if __name__ == "__main__": main()
python
14
0.600736
75
21.645833
48
starcoderdata
#ifndef VID_H #define VID_H #include "mmalincludes.h" extern "C" { #include "RaspiPreview.h" #include "RaspiCamControl.h" } #include "encoder.h" #include "raw.h" #include "tex.h" #include "resizer.h" #include /* Paramters stereo_mode sensor_mode fps_range shutter_speed MMAL_PARAMETER_CAMERA_CONFIG .max_stills_w = state->width, .max_stills_h = state->height, .stills_yuv422 = 0, .one_shot_stills = 0, //Videomode = 0, Stillmode = 1 .max_preview_video_w = state->width, //videomode = state->width stillmode = state->preview_parameters.previewWindow.width .max_preview_video_h = state->height, //videomode = state->height stillmode = state->preview_parameters.previewWindow.height .num_preview_video_frames = 3 + vcos_max(0, (state->framerate-30)/10), //Videomode = 3 + some, Stillmode = 3 .stills_capture_circular_buffer_height = 0, .fast_preview_resume = 0, .use_stc_timestamp = MMAL_PARAM_TIMESTAMP_MODE_RAW_STC //Videomode = MMAL_PARAM_TIMESTAMP_MODE_RAW_STC, Stillmode = MMAL_PARAM_TIMESTAMP_MODE_RESET_STC port format format->es->video.width = VCOS_ALIGN_UP(state->width, 32); //preview = preview.window.width or state->width, video & still = state->width format->es->video.height = VCOS_ALIGN_UP(state->height, 16); //preview = preview.window.height or state->height, video & still = state->height format->es->video.crop.x = 0; //all = 0 format->es->video.crop.y = 0; //all = 0 format->es->video.crop.width = state->width; //preview = preview.window.width or state->width, video & still = state->width format->es->video.crop.height = state->height; //preview = preview.window.height or state->height, video & still = state->height format->es->video.frame_rate.num = FULL_RES_PREVIEW_FRAME_RATE_NUM; //preview = FULL_RES_PREVIEW_FRAME_RATE_NUM or PREVIEW_FRAME_RATE_NUM, still = STILLS_FRAME_RATE_NUM(0), video = state->framerate(30) format->es->video.frame_rate.den = FULL_RES_PREVIEW_FRAME_RATE_DEN; //preview = FULL_RES_PREVIEW_FRAME_RATE_DEN or PREVIEW_FRAME_RATE_DEN, still = STILLS_FRAME_RATE_DEN(1), video = VIDEO_FRAME_RATE_DEN(1) */ enum PortMode { PREVIEW_SPLITTER, VIDEO_SPLITTER, STILL_SPLITTER, PREVIEW, VIDEO, STILL }; class Vid { private: uint32_t framerate; RASPIPREVIEW_PARAMETERS preview_parameters; /// Preview setup parameters RASPICAM_CAMERA_PARAMETERS camera_parameters; /// Camera setup parameters int splitter_port_num; MMAL_COMPONENT_T* camera_component = NULL; /// Pointer to the camera component MMAL_COMPONENT_T* splitter_component = NULL; /// Pointer to the video splitter component MMAL_CONNECTION_T* preview_connection = NULL; /// Pointer to the connection from camera or splitter to preview MMAL_CONNECTION_T* splitter_connection = NULL; /// Pointer to the connection from camera to splitter MMAL_PORT_T *preview_port = NULL; MMAL_PORT_T *video_port = NULL; MMAL_PORT_T *still_port = NULL; bool bCapturing = false; /// State of capture/pause int cameraNum; /// Camera number int settings; /// Request settings from the camera uint32_t sensor_mode; /// Sensor mode. 0=auto. Check docs/forum for modes selected by other values. EncoderPort * encoder = NULL; RawPort * raw = NULL; TexPort * tex = NULL; ResizePort * resizer = NULL; void default_status(); void setSensorDefaults(); void create_camera_component(); void enable_camera_component(); void create_splitter_component(int port_number); void enable_splitter_component(); void dump_status(); public: uint32_t width; /// Requested width of image uint32_t height; /// requested height of image enum PreviewMode { disabled, fullscreen, windowed }; int mode = 0; int wantPreview = false; Vid(); ~Vid(); bool open(); void close(); EncoderPort* addEncoder(); RawPort* addRaw(); TexPort* addTex(); ResizePort* addResize(); bool enablePreview(PreviewMode mode); bool setImageFX(int effect); bool setResolution(int width, int height); }; #endif
c
8
0.703695
205
40.473684
95
starcoderdata
function saveActiveChannelLogs(){ //Get Channel chat = document.getElementById("chat"); channel = chat.getElementsByClassName("chan active")[0]; channelTitle = channel.dataset.title; // Get Message messages = [].slice.call(channel.getElementsByClassName('msg')); nickname = document.getElementById('nick-value').innerText; var data = "Channel logs: " + channelTitle + " and for user: " + nickname + " | Stored by WebChat on channel"; //Foreach Message messages.forEach( function (e) { var DateStamp; var Message; var Sender; //Get DateStamp DateStamp = e.dataset.time; if(e.classList.contains("message")){ Sender = e.dataset.from Message = e.lastElementChild.lastElementChild.innerHTML.replace(/ ''); } else{ Sender = "Server";//e.getElementsByClassName("from")[0].lastElementChild.innerHTML; Message = e.lastElementChild.innerHTML.replace(/ ''); } //Add data to the blob data += "\n" + DateStamp + " " + Sender + ": " + Message; }); // Create blob var Message = new Blob([data], {type: "text/plain;charset=utf-8"}); // Download blob as file saveAs(Message, channelTitle+".log"); } // Event Listener for the little button on the left panel document.getElementById("download-logs").addEventListener("click", function(){ saveActiveChannelLogs(); });
javascript
17
0.693475
110
25.38
50
starcoderdata
import Vuex from 'vuex' import user from './user' import login from './login' import site from './site' import footer from './footer' import unit from './unit' import header from './header' import addPoints from './addPoints' import token from './token' const createStroe = () => { return new Vuex.Store({ modules: { site, footer, login, user, unit, header, addPoints, token } }) } export default createStroe
javascript
11
0.619958
35
17.115385
26
starcoderdata
import numpy as np from ai.go.go_player import GoPlayer class RandomPlayer(GoPlayer): def play(self, color, history, move_history, current_move, mask): size = history[0].shape[0] policy = np.random.uniform(size=(size, size)) policy = np.minimum(policy, mask) point = np.unravel_index(policy.argmax(), policy.shape) if policy[point] == 0: return size * size return point[0] + point[1] * size
python
11
0.626
69
33.785714
14
starcoderdata
jQuery(document).ready(function() { jQuery('.our-djs-edit').click(function () { var $this = jQuery(this); var id = $this.parent().find('.djsid').val(); //console.log(`selected id ${id}`); $.get('/djs/'+id, function(data, status){ if(data){ name = data.name; designation = data.designation; shortBio = data.shortBio; longBio = data.longBio; photo = data.photo; social = data.social; // console.log(social); jQuery('.modal-title').text(name); jQuery('#djsName').val(name); jQuery('#designation').val(designation); jQuery('#shortBio').val(shortBio); jQuery('#longBio').val(longBio); jQuery('#selectedId').val(id); jQuery('#artist-photo').attr('src',photo); social.forEach((data)=>{ jQuery('#'+data.name).val(data.link); }); if(data.featuredDj){ jQuery('#featured').prop("checked", true); }else{ jQuery('#featured').prop("checked", false); } jQuery('#update-djs').attr('action', './djs/'+id); $('#djsModal').modal('show'); } }); }); jQuery('#saveChanges').click(function (e) { e.preventDefault(); var data = jQuery('#update-djs').serialize(); // var form = document.getElementById('update-djs'); // var formData = new FormData(form); // var fileInput = document.getElementById('file-input'); // var file = fileInput.files[0]; // formData.append('file', file); // console.log(data); var id = jQuery('#selectedId').val(); jQuery.ajax({ url: '/djs/'+id, method: 'put', // data:JSON.stringify(formData) data:data }) .then(function(data) { console.log(data); }); }); });
javascript
30
0.458314
66
32.698413
63
starcoderdata
// ---------------------------------------------------------------------------- // Copyright 2020 ARM Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------- #ifndef DS_CUSTOM_METRICS_H #define DS_CUSTOM_METRICS_H #include #include #include "ds_status.h" /** * @file ds_custom_metrics.h * \brief Device Sentry custom metrics definitions. */ /** * Minimum custom metric ID value. All custom metric IDs must be above this value. */ #define DS_CUSTOM_METRIC_MIN_ID 1000 /** * Maximum custom metric ID value. All custom metric IDs must be below this value. */ #define DS_CUSTOM_METRIC_MAX_ID 0x7FFF /** * Numeric integer type size. */ #define DS_SIZE_OF_INT64 8 /** * Metric ID type is an integer between DS_CUSTOM_METRIC_MIN_ID and DS_CUSTOM_METRIC_MAX_ID. */ typedef uint64_t ds_custom_metric_id_t; /** Type of the custom metric. * Note: We currently support DS_INT64 only. */ typedef enum ds_custom_metrics_value_type_t { DS_INVALID_TYPE = 0, /** Invalid or uninitialized type.*/ DS_STRING, /** Null terminated char array.*/ DS_INT64, /** Numeric integer type.*/ DS_FLOAT, /** Numeric float type.*/ DS_BOOLEAN, /** Boolean type.*/ DS_OPAQUE_BUFFER, /** Byte array.*/ DS_MAX_TYPE /** Must be the last item.*/ } ds_custom_metrics_value_type_t; /** * Custom metric value getter callback function prototype. * The client application must implement this callback function consistent with the following declaration. * Device Sentry calls this function periodically to create and send a custom metric report to Pelion Device Management. * * @param[in] metric_id - Custom metric ID. * @param[in] user_context - Opaque pointer that was passed during callback registration. * @param[out] metric_value_out_addr - Address of the pointer that points to the output buffer. * Note: You are responsible for managing the memory allocation for the output buffer (Device Sentry does not free this buffer). * @param[out] metric_value_type_out - Output type of the metric with an appropriate metric ID. * Note: We currently support DS_INT64 only. * @param[out] metric_value_size_out - The metric_value_out_addr buffer size in bytes. * Note: We currently support DS_INT64 only. * @returns * ::DS_STATUS_SUCCESS If the function returns all output values successfully. * One of the ::ds_status_e errors otherwise. */ typedef ds_status_e (*ds_custom_metric_value_getter_t)( ds_custom_metric_id_t metric_id, void *user_context, uint8_t **metric_value_out_addr, ds_custom_metrics_value_type_t *metric_value_type_out, size_t *metric_value_size_out ); /** * Custom metric value getter callback setting function. * @param cb - Callback that Device Sentry calls periodically to create and send a custom metric report to Pelion Device Management. * @param user_context - Opaque pointer to your context that you need to store in Device Sentry. * Note: The framework passes this pointer back to the ds_custom_metric_value_getter_t function during the invocation. */ void ds_custom_metric_callback_set( ds_custom_metric_value_getter_t cb, void *user_context ); #endif // DS_CUSTOM_METRICS_H
c
8
0.569343
161
44.666667
102
starcoderdata
/* Copyright (c) 2019-2020, * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "keepalive.h" void keepalive_init(keepalive_t *opt) { opt->debug = 0; opt->tcp_keepidle = 15; /* TCP_KEEPIDLE: seconds */ opt->tcp_keepcnt = 9; /* TCP_KEEPCNT: 9 retries */ opt->tcp_keepintvl = 15; /* TCP_KEEPINTVL: 9 * 15 = 135 seconds to disconnect */ opt->tcp_user_timeout = -1; /* TCP_USER_TIMEOUT: seconds: 0 to use system default, -1 to derive from tcp_keepidle, tcp_keepcnt and tcp_keepintvl */ opt->tcp_syncnt = 0; /* TCP_SYNCNT: system default */ opt->tcp_defer_accept = 0; /* TCP_DEFER_ACCEPT: seconds */ } int keepalive(int sockfd, keepalive_t *opt) { int enable = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)) < 0) { if (opt->debug) (void)fprintf(stderr, "libkeepalive:setsockopt(SO_KEEPALIVE, 1): %s\n", strerror(errno)); return -1; } #ifdef TCP_KEEPIDLE if (opt->tcp_keepidle > 0 && setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &opt->tcp_keepidle, sizeof(opt->tcp_keepidle)) < 0) { if (opt->debug) (void)fprintf(stderr, "libkeepalive:setsockopt(TCP_KEEPIDLE, %d): %s\n", opt->tcp_keepidle, strerror(errno)); } #endif #ifdef TCP_KEEPCNT if (opt->tcp_keepcnt > 0 && setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, &opt->tcp_keepcnt, sizeof(opt->tcp_keepcnt)) < 0) { if (opt->debug) (void)fprintf(stderr, "libkeepalive:setsockopt(TCP_KEEPCNT, %d): %s\n", opt->tcp_keepcnt, strerror(errno)); } #endif #ifdef TCP_KEEPINTVL if (opt->tcp_keepintvl > 0 && setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &opt->tcp_keepintvl, sizeof(opt->tcp_keepintvl)) < 0) { if (opt->debug) (void)fprintf(stderr, "libkeepalive:setsockopt(TCP_KEEPINTVL, %d): %s\n", opt->tcp_keepintvl, strerror(errno)); } #endif #ifdef TCP_USER_TIMEOUT if (opt->tcp_user_timeout > 0 && setsockopt(sockfd, IPPROTO_TCP, TCP_USER_TIMEOUT, &opt->tcp_user_timeout, sizeof(opt->tcp_user_timeout)) < 0) { if (opt->debug) (void)fprintf(stderr, "libkeepalive:setsockopt(TCP_USER_TIMEOUT, %d): %s\n", opt->tcp_user_timeout, strerror(errno)); } #endif #ifdef TCP_USER_SYNCNT if (opt->tcp_syncnt > 0 && setsockopt(sockfd, IPPROTO_TCP, TCP_SYNCNT, &opt->tcp_syncnt, sizeof(opt->tcp_syncnt)) < 0) { if (opt->debug) (void)fprintf(stderr, "libkeepalive:setsockopt(TCP_SYNCNT, %d): %s\n", opt->tcp_syncnt, strerror(errno)); } #endif #ifdef TCP_DEFER_ACCEPT if (opt->tcp_defer_accept > 0 && setsockopt(sockfd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &opt->tcp_defer_accept, sizeof(opt->tcp_defer_accept)) < 0) { if (opt->debug) (void)fprintf(stderr, "libkeepalive:setsockopt(TCP_DEFER_ACCEPT, %d): %s\n", opt->tcp_defer_accept, strerror(errno)); } #endif return 0; }
c
13
0.622529
79
34.925234
107
starcoderdata
using Dfc.Providerportal.FindAnApprenticeship.Interfaces.DAS; namespace Dfc.Providerportal.FindAnApprenticeship.Models.DAS { public class DasAddress : IDasAddress { public string Address1 { get; set; } public string Address2 { get; set; } public string County { get; set; } public double? Lat { get; set; } public double? Long { get; set; } public string Postcode { get; set; } public string Town { get; set; } } }
c#
13
0.705449
187
28.565217
23
starcoderdata
import sys from itertools import permutations a = [int(i) for i in sys.stdin] b = [(list(map(int, str(k)))[-1], i) for i, k in enumerate(a)] indexes = [i for i, (x, y)in enumerate(b) if x == 0] d = 0 for i in sorted(indexes)[::-1]: d += a[i] b.pop(i) b.sort() c = b[::-1] for i, k in c[:-1]: if i > 5: d += round(a[k], -1) else: d += (round(a[k], -1) + 10) if c != []: d += a[c[-1][1]] print(d)
python
13
0.509615
62
17.130435
23
codenet
def configuration(parent_package='', top_path=None): """ Configuration of xsapr clutter package. """ config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('xsapr_clutter') return config
python
7
0.623832
60
41.9
10
inline
def argyris_polynomials(xs, ys): """ Calculate (symbolically) the Argyris basis functions for some given triangle. """ var('x,y') constants = [var('c' + str(num)) for num in range(1,22)] monic_basis = [x**m * y**(n-m) for n in range(6) for m in [n-k for k in range(n+1)]] test_polynomial = sum(map(op.mul, constants, monic_basis)) constraints = constraint_system(test_polynomial, xs, ys) constraint_matrix = matrix([get_coefficients(constraint, constants) for constraint in constraints]) constraint_inverse = constraint_matrix.inverse() coefficients = [] for i in range(21): rhs = matrix(SR, 21, 1) rhs[i, 0] = 1 coefficients.append(constraint_inverse*rhs) # form the finite element polynomials by recombining the coefficients with # the monic basis. return [sum(map(op.mul, c, monic_basis))[0] for c in coefficients]
python
12
0.618503
78
34.666667
27
inline
package jsonresult import ( "github.com/incognitochain/incognito-chain/dataaccessobject/statedb" ) type GetLiquidateExchangeRates struct { TokenId string `json:"TokenId"` Liquidation statedb.LiquidationPoolDetail `json:"Liquidation"` }
go
7
0.746753
69
27
11
starcoderdata
@Before public void setup() throws IOException { //not really needed because every case cleans after itself, but better to check if(Files.exists(BASE_PATH)){ Files.walk(BASE_PATH) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } Files.createDirectory(BASE_PATH); }
java
12
0.555283
87
36.090909
11
inline
#pragma once namespace e186 { enum struct AutoMatrix : uint32_t { Nothing = 0x0000, TransformMatrix = 0x0001, ModelMatrix = 0x0002, ViewMatrix = 0x0004, ProjectionMatrix = 0x0008, IsNormalMatrix = 0x0010, IsOptional = 0x0020, IsMandatory = 0x0040, DoTranspose = 0x0080, DoInvert = 0x0100, }; inline AutoMatrix operator| (AutoMatrix a, AutoMatrix b) { typedef std::underlying_type EnumType; return static_cast | static_cast } inline AutoMatrix operator& (AutoMatrix a, AutoMatrix b) { typedef std::underlying_type EnumType; return static_cast & static_cast } }
c
16
0.6875
86
25.233333
30
starcoderdata
import React from 'react' import { TailSpin } from 'react-loader-spinner' import { Box } from './styles' export const Loader = () => ( <TailSpin height='50' width='50' color='orange' /> )
javascript
6
0.630631
54
21.2
10
starcoderdata
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/IRGen/IRGen.h" #include "hermes/BCGen/HBC/Bytecode.h" #include "ESTreeIRGen.h" #include "hermes/Parser/JSParser.h" #include "hermes/Support/SimpleDiagHandler.h" namespace hermes { using namespace hermes::irgen; using llvh::dbgs; bool generateIRFromESTree( ESTree::NodePtr node, Module *M, const DeclarationFileListTy &declFileList, const ScopeChain &scopeChain) { // Generate IR into the module M. ESTreeIRGen Generator(node, declFileList, M, scopeChain); Generator.doIt(); LLVM_DEBUG(dbgs() << "Finished IRGen.\n"); return false; } void generateIRForCJSModule( ESTree::FunctionExpressionNode *node, uint32_t segmentID, uint32_t id, llvh::StringRef filename, Module *M, Function *topLevelFunction, const DeclarationFileListTy &declFileList) { // Generate IR into the module M. ESTreeIRGen generator(node, declFileList, M, {}); return generator.doCJSModule( topLevelFunction, node->getSemInfo(), segmentID, id, filename); } std::pair<Function *, Function *> generateLazyFunctionIR( hbc::BytecodeFunction *bcFunction, Module *M, llvh::SMRange sourceRange) { auto &context = M->getContext(); auto lazyData = bcFunction->getLazyCompilationData(); SimpleDiagHandlerRAII diagHandler{context.getSourceErrorManager()}; AllocationScope alloc(context.getAllocator()); sem::SemContext semCtx{}; hermes::parser::JSParser parser( context, lazyData->bufferId, parser::LazyParse); // Note: we don't know the parent's strictness, which we need to pass, but // we can just use the child's strictness, which is always stricter or equal // to the parent's. parser.setStrictMode(lazyData->strictMode); auto parsed = parser.parseLazyFunction( (ESTree::NodeKind)lazyData->nodeKind, lazyData->paramYield, lazyData->paramAwait, sourceRange.Start); // In case of error, generate a function that just throws a SyntaxError. if (!parsed || !sem::validateFunctionAST( context, semCtx, *parsed, lazyData->strictMode)) { LLVM_DEBUG( llvh::dbgs() << "Lazy AST parsing/validation failed with error: " << diagHandler.getErrorString()); auto *error = ESTreeIRGen::genSyntaxErrorFunction( M, lazyData->originalName, sourceRange, diagHandler.getErrorString()); return {error, error}; } ESTreeIRGen generator{parsed.getValue(), {}, M, {}}; return generator.doLazyFunction(lazyData); } } // namespace hermes
c++
14
0.707894
78
29.208791
91
starcoderdata
#include namespace pqxx { namespace internal { namespace gate { class PQXX_PRIVATE result_creation : callgate<const result> { friend class pqxx::connection_base; friend class pqxx::pipeline; result_creation(reference x) : super(x) {} static result create( internal::pq::PGresult *rhs, int protocol, const std::string &query, int encoding_code) { return result(rhs, protocol, query, encoding_code); } void CheckStatus() const { return home().CheckStatus(); } }; } // namespace pqxx::internal::gate } // namespace pqxx::internal } // namespace pqxx
c++
16
0.710963
59
19.758621
29
starcoderdata
def run(self): while True: # Grabs host from queue host = self.queue.get() # Grabs urls of hosts and then grabs chunk of webpage self.f(host) print("Reading: %s" % host) # Signals to queue job is done self.queue.task_done()
python
10
0.507886
65
27.909091
11
inline
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Reflection.Emit; using CommandAndConquer.CLI.Attributes; using Microsoft.Scripting.Hosting; namespace CommandAndConquer.CLI.Template1.Controllers { [CliController("example", "This is a description of the controller.")] public static class ExampleController { private static object BindConstructor(Type type, Type[] parameters, Type delegateType) { DynamicMethod dm = new DynamicMethod("Constructor", type, parameters, type, true); ILGenerator il = dm.GetILGenerator(); ConstructorInfo ctor = type.GetConstructor(parameters); if (ctor == null && type.IsValueType) { il.DeclareLocal(type); il.Emit(OpCodes.Ldloca_S, 0); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc, 0); il.Emit(OpCodes.Ret); } else { for (int i = 0; i < parameters.Length; i++) il.Emit(OpCodes.Ldarg, i); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Ret); } return dm.CreateDelegate(delegateType); } public struct MyStruct { private int _x; public int x { get { return _x; } set { _x = value; } } public int z; } private static void Log(object o) { Console.Write(o.ToString()); Console.WriteLine(); } [CliCommand("test", "This is an example of how you can setup methods.")] public static void MethodExample(string something, List someMoreThings = null) { ScriptEngine scriptEngine = IronPython.Hosting.Python.CreateEngine(); ScriptScope scriptScope = scriptEngine.CreateScope(); scriptScope.SetVariable("MyStruct", BindConstructor(typeof(MyStruct), new Type[] { }, typeof(Func scriptScope.SetVariable("log", new Action List paths = new List // to load python stdlib - not needed // paths.Add (Application.dataPath + "/StreamingAssets/pystdlib"); scriptEngine.SetSearchPaths(paths); string scriptPath = "d:\\dev\\unity\\pytest\\PythonTest\\Assets\\StreamingAssets\\MyScript.py"; string script = File.ReadAllText(scriptPath); ScriptSource src = scriptEngine.CreateScriptSourceFromString(script); src.Execute(scriptScope); Console.ReadKey(); } } }
c#
17
0.554701
123
30.450549
91
starcoderdata
package com.fdorothy.dinopox; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class MainMenuScreen implements Screen { final DinoGame game; OrthographicCamera camera; public MainMenuScreen(final DinoGame game) { this.game = game; camera = new OrthographicCamera(); camera.setToOrtho(false, game.res.width, game.res.height); } public int print(SpriteBatch batch, String text, int line) { game.res.font.draw(batch, text, 0.0f, game.res.height-18*(line+1)); return line + 1; } @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0.15f, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); game.res.batch.setProjectionMatrix(camera.combined); game.res.batch.begin(); SpriteBatch b = game.res.batch; int offset = 0; offset = print(b, "2017, the dinopocalypse. Thunderlizards emerge from their subterranean slumber", offset); offset = print(b, "with their eyes on world domination. One man holds the key to cast them back", offset); offset = print(b, "to the center of the earth, but he is stranded in a single-room research lab", offset); offset = print(b, "in rural Alabama.", offset); offset = print(b, "", offset); offset = print(b, "Do you have what it takes to defeat General Ankyleesaurus's horde?", offset); offset = print(b, "", offset); offset = print(b, "Rules", offset); offset = print(b, "", offset); offset = print(b, " - You must survive 9 waves of attacks from the thunderlizard horde.", offset); offset = print(b, " - Touch the screen to move the researcher around.", offset); offset = print(b, " - Touch a thunderlizard to shoot at it, some are harder than others to kill", offset); b.draw(game.res.dinos[Resources.LEE], 0, 0); TextureRegion t = game.res.dinos[Resources.PARA]; float w = t.getRegionWidth(); float h = t.getRegionHeight(); float x = game.res.width - t.getRegionWidth() / 2.0f; b.draw(t, (x+w) - w / 2.0f, 0.0f, -w, h); b.end(); if (Gdx.input.isTouched()) { game.setScreen(new GameScreen(game)); dispose(); } } @Override public void dispose () { } @Override public void hide() { } @Override public void resume() { } @Override public void pause() { } @Override public void resize(int w, int h) { } @Override public void show() { } }
java
10
0.670891
112
28.163043
92
starcoderdata
void Print(const bool ForcePrint = false) { // // Let's check if we should print the stats. // const uint64_t TimeSinceLastPrint = SecondsSince(LastPrint_).count(); const bool Refresh = (TimeSinceLastPrint >= ClientStats_t::RefreshRate) || ForcePrint; if (!Refresh) { return; } // // Compute the amount of time since the last time we got new coverage. // const auto &[LastCov, LastCovUnit] = SecondsToHuman(SecondsSince(LastCov_)); // // Compute the amount of time since the server started. // const auto &[Uptime, UptimeUnit] = SecondsToHuman(SecondsSince(Start_)); // // Compute the amount of testcases executed per second. // const auto &[ExecsPerSecond, ExecsPerSecondUnit] = NumberToHuman( double(TestcasesNumber_) / double(SecondsSince(Start_).count())); fmt::print("#{} cov: {} exec/s: {:.1f}{} lastcov: {:.1f}{} crash: {} " "timeout: {} cr3: {} uptime: {:.1f}{}\n", TestcasesNumber_, Coverage_, ExecsPerSecond, ExecsPerSecondUnit, LastCov, LastCovUnit, Crashes_, Timeouts_, Cr3s_, Uptime, UptimeUnit); LastPrint_ = chrono::system_clock::now(); }
c++
14
0.610073
80
29.8
40
inline
#include "../../template.hpp" #include "../collection/graph.hpp" #include "../collection/tree_node.hpp" void Init(vi& parent, vi& rank) { int n = size(parent); for (int i = 0; i < n; ++i) { parent[i] = i; rank[i] = 0; } } int Find(vi& parent, vi& rank, int i) { int at = i; for (; at != parent[at]; at = parent[at]) {} int prev = i; for (i = parent[i]; i != parent[i]; prev = i, i = parent[i]) { parent[prev] = at; rank[prev] = 1; } rank[at] = 1; return at; } bool Union(vi& parent, vi& rank, int i, int j) { int iroot = Find(parent, rank, i); int jroot = Find(parent, rank, j); int irank = rank[iroot]; int jrank = rank[jroot]; if (iroot == jroot) return true; else if (irank < jrank) parent[iroot] = jroot; else if (irank > jrank) parent[jroot] = iroot; else if (irank == jrank) parent[iroot] = jroot, rank[jroot]++; return false; } void DetectCycle(vvi& edges, int V) { vi parent(V), rank(V); Init(parent, rank); for (const auto& edge : edges) { if (Union(parent, rank, edge[0], edge[1])) { cout << "Cycle detected" << endl; return; } } cout << "Cycle has not detected" << endl; } int main() { TimeMeasure _; { vvi edges; edges.push_back({0, 1}); edges.push_back({1, 2}); edges.push_back({0, 2}); DetectCycle(edges, 3); // yes } { vvi edges; edges.push_back({0, 1}); edges.push_back({1, 2}); edges.push_back({2, 3}); edges.push_back({0, 2}); DetectCycle(edges, 4); // yes } { vvi edges; edges.push_back({0, 1}); edges.push_back({1, 2}); edges.push_back({2, 3}); DetectCycle(edges, 4); // no } { vvi edges; edges.push_back({1, 0}); edges.push_back({0, 2}); edges.push_back({2, 1}); edges.push_back({0, 3}); edges.push_back({3, 4}); DetectCycle(edges, 5); // yes } { vvi edges; edges.push_back({0, 1}); edges.push_back({0, 2}); edges.push_back({1, 3}); edges.push_back({2, 4}); edges.push_back({3, 4}); edges.push_back({4, 5}); edges.push_back({5, 6}); edges.push_back({6, 7}); edges.push_back({7, 8}); DetectCycle(edges, 9); // yes } { vvi edges; edges.push_back({9, 1}); edges.push_back({0, 1}); edges.push_back({1, 3}); edges.push_back({3, 4}); edges.push_back({4, 2}); edges.push_back({2, 8}); edges.push_back({2, 7}); edges.push_back({4, 5}); edges.push_back({5, 6}); DetectCycle(edges, 10); // no } }
c++
15
0.482808
66
24.851852
108
starcoderdata
/** * @file Manage the export feature */ /* globals Panel, ObjectId, BinData, DBRef, MinKey, MaxKey, Long, Storage*/ 'use strict' let Export = {} Export.specialTypes = [ObjectId, BinData, Long, Date, RegExp] /** * Start the export process * @param {Array docs * @param {string} title * @param {string} [queryString] - the query as a string to show in the file * @returns {string} - an object url */ Export.export = function (docs, title, queryString) { /** * A map from path name to array of values * @type {Object */ let valuesByPath = Object.create(null), blob /** * Recursive function to extract subdocuments and field values * @param {Object} subdoc * @param {string} path * @param {number} i */ function addSubDoc(subdoc, path, i) { let key, value, subpath for (key in subdoc) { subpath = path ? path + '.' + key : key value = subdoc[key] // These types aren't supported if (Array.isArray(value) || value instanceof DBRef || value instanceof MinKey || value instanceof MaxKey) { continue } if (value && typeof value === 'object' && Export.specialTypes.indexOf(value.constructor) === -1) { addSubDoc(value, subpath, i) } else { // Primitive value if (!(subpath in valuesByPath)) { // New result path valuesByPath[subpath] = [] } valuesByPath[subpath][i] = value } } } docs.forEach((doc, i) => { addSubDoc(doc, '', i) }) blob = new Blob([Export.generateHTML(valuesByPath, docs.length, title, queryString)], { type: 'text/html' }) return window.URL.createObjectURL(blob) } /** * Create a HTML document from a value map * @param {Object valuesByPath * @param {number} length - number of docs * @param {string} title * @param {string} [paragraph] - text to display before the table * @returns {string} */ Export.generateHTML = function (valuesByPath, length, title, paragraph) { let localDate = Boolean(Storage.get('localDate')), html, pathNames, i // HTML head html = '<!DOCTYPE html>\n' + ' + ' + ' + Panel.escape(title) + ' + '<meta charset="UTF-8">\n' + ' + ' pathNames = Object.keys(valuesByPath).sort() // Title html += ' + Panel.escape(title) + ' if (paragraph) { html += ' + Panel.escape(paragraph) + ' } html += ' at ' + new Date().toISOString() + ' // Table header html += '<table border="1">\n' + ' pathNames.forEach(path => { html += ' + Panel.escape(Panel.formatDocPath(path)) + ' }) html += ' // Rows function generateRow(i) { html += ' pathNames.forEach(path => { html += ' + Panel.escape(Export.toString(valuesByPath[path][i], localDate)) + ' }) html += ' } for (i = 0; i < length; i++) { generateRow(i) } // Footer html += ' + ' return html } /** * @param {*} value * @param {boolean} [localDate] - show date in local (browser) time * @returns {string} */ Export.toString = function (value, localDate) { if (value === undefined) { return '' } else if (value instanceof BinData) { return value.$binary } else if (value instanceof Long) { return value.$numberLong } else if (value instanceof Date) { return localDate ? value.toLocaleString() : value.toISOString() } // ObjectId, RegExp and others return String(value) }
javascript
22
0.617942
88
22.422819
149
starcoderdata
@NonNull public GenericDocument getDocument( @NonNull String packageName, @NonNull String databaseName, @NonNull String namespace, @NonNull String id, @NonNull Map<String, List<String>> typePropertyPaths) throws AppSearchException { mReadWriteLock.readLock().lock(); try { throwIfClosedLocked(); String prefix = createPrefix(packageName, databaseName); List<TypePropertyMask.Builder> nonPrefixedPropertyMaskBuilders = TypePropertyPathToProtoConverter .toTypePropertyMaskBuilderList(typePropertyPaths); List<TypePropertyMask> prefixedPropertyMasks = new ArrayList<>(nonPrefixedPropertyMaskBuilders.size()); for (int i = 0; i < nonPrefixedPropertyMaskBuilders.size(); ++i) { String nonPrefixedType = nonPrefixedPropertyMaskBuilders.get(i).getSchemaType(); String prefixedType = nonPrefixedType.equals( GetByDocumentIdRequest.PROJECTION_SCHEMA_TYPE_WILDCARD) ? nonPrefixedType : prefix + nonPrefixedType; prefixedPropertyMasks.add( nonPrefixedPropertyMaskBuilders.get(i).setSchemaType(prefixedType).build()); } GetResultSpecProto getResultSpec = GetResultSpecProto.newBuilder().addAllTypePropertyMasks(prefixedPropertyMasks) .build(); String finalNamespace = createPrefix(packageName, databaseName) + namespace; if (mLogUtil.isPiiTraceEnabled()) { mLogUtil.piiTrace( "getDocument, request", finalNamespace + ", " + id + "," + getResultSpec); } GetResultProto getResultProto = mIcingSearchEngineLocked.get(finalNamespace, id, getResultSpec); mLogUtil.piiTrace("getDocument, response", getResultProto.getStatus(), getResultProto); checkSuccess(getResultProto.getStatus()); // The schema type map cannot be null at this point. It could only be null if no // schema had ever been set for that prefix. Given we have retrieved a document from // the index, we know a schema had to have been set. Map<String, SchemaTypeConfigProto> schemaTypeMap = mSchemaMapLocked.get(prefix); DocumentProto.Builder documentBuilder = getResultProto.getDocument().toBuilder(); removePrefixesFromDocument(documentBuilder); return GenericDocumentToProtoConverter.toGenericDocument(documentBuilder.build(), prefix, schemaTypeMap); } finally { mReadWriteLock.readLock().unlock(); } }
java
15
0.62669
100
56.367347
49
inline
package fr.famivac.gestionnaire.domains.sejours.control; import java.math.BigDecimal; import java.util.Date; /** * * @author paoesco */ public class BilanDTO { private Date dateDebut; private Date dateFin; private Integer totalNombreJourneesVacances; private BigDecimal totalForfait; private BigDecimal totalFraisDossier; private BigDecimal totalFraisVoyage; private BigDecimal totalFraisPensionFamille; public Date getDateDebut() { return dateDebut; } public void setDateDebut(Date dateDebut) { this.dateDebut = dateDebut; } public Date getDateFin() { return dateFin; } public void setDateFin(Date dateFin) { this.dateFin = dateFin; } public Integer getTotalNombreJourneesVacances() { return totalNombreJourneesVacances; } public void setTotalNombreJourneesVacances(Integer totalNombreJourneesVacances) { this.totalNombreJourneesVacances = totalNombreJourneesVacances; } public BigDecimal getTotalForfait() { return totalForfait; } public void setTotalForfait(BigDecimal totalForfait) { this.totalForfait = totalForfait; } public BigDecimal getTotalFraisDossier() { return totalFraisDossier; } public void setTotalFraisDossier(BigDecimal totalFraisDossier) { this.totalFraisDossier = totalFraisDossier; } public BigDecimal getTotalFraisVoyage() { return totalFraisVoyage; } public void setTotalFraisVoyage(BigDecimal totalFraisVoyage) { this.totalFraisVoyage = totalFraisVoyage; } public BigDecimal getTotalFraisSejour() { return getTotalForfait().add(getTotalFraisDossier()).add(getTotalFraisVoyage()); } public BigDecimal getTotalFraisPensionFamille() { return totalFraisPensionFamille; } public void setTotalFraisPensionFamille(BigDecimal totalFraisPensionFamille) { this.totalFraisPensionFamille = totalFraisPensionFamille; } }
java
11
0.723335
123
25.506173
81
starcoderdata
describe("chorus.models.HdfsDataset", function() { beforeEach(function () { this.model = backboneFixtures.workspaceDataset.hdfsDataset({id: null, content: ["first line", "second line"]}); }); describe('dataSource', function () { it("is not null", function () { expect(this.model.dataSource()).toBeA(chorus.models.HdfsDataSource); }); }); describe("#urlTemplate", function() { it("returns the correct create url", function () { expect(this.model.url({ method: 'create' })).toMatchUrl("/hdfs_datasets/"); }); it("returns the correct update url", function () { this.model.set("id", 1234); expect(this.model.url({ method: 'update' })).toMatchUrl("/hdfs_datasets/1234"); }); it("returns the show url when it is anything else", function () { this.model.set("id", 1234); expect(this.model.url({method: "read"})).toMatchUrl('/workspaces/' + this.model.workspace().id + '/datasets/1234'); }); it("returns the correct delete url", function () { this.model.set("id", 1234); expect(this.model.url({ method: 'delete' })).toMatchUrl("/hdfs_datasets/1234"); }); }); it("has the correct showUrl", function () { this.model.set({id: "123", workspace: {id: "789"}}); expect(this.model.showUrl()).toMatchUrl("#/workspaces/789/hadoop_datasets/123"); }); describe("#content", function() { it("returns the contents", function() { expect(this.model.content()).toBe("first line\nsecond line"); }); }); describe("#asWorkspaceDataset", function () { it("returns a HdfsDataset", function () { expect(this.model.asWorkspaceDataset()).toBeA(chorus.models.HdfsDataset); }); }); describe("#isDeletable", function () { it("is deletable", function () { expect(this.model.isDeleteable()).toBeTruthy(); }); }); });
javascript
26
0.567275
128
35.25
56
starcoderdata
#include "dbw_node_core.h" namespace DBWNODE_NS{ DBWNode::DBWNode() : private_nh_("~"), sys_enable_(false), control_gap_(1.0/LOOP_RATE) { ROS_INFO("DBW_node launch...initForROS..."); initForROS(); } DBWNode::~DBWNode() {} void DBWNode::initForROS() { srv_.setCallback(boost::bind(&DBWNode::cbFromDynamicReconfig, this, _1, _2)); private_nh_.param vehicle_mass_, 1736.35); private_nh_.param fuel_capacity_, 13.5); private_nh_.param brake_deadband_, 0.1); private_nh_.param decel_limit_, -5.0); //default: -5.0 private_nh_.param accel_limit_, 1.0); //default: 1.0 private_nh_.param wheel_radius_, 0.2413); private_nh_.param wheel_base_, 2.8498); private_nh_.param steer_ratio_, 14.8); private_nh_.param max_lat_accel_, 3.0); private_nh_.param max_steer_angle_, 8.0); private_nh_.param fuel_level_, -1.0); //set basic parameters for yaw controller. yaw_controller_.setParameters(wheel_base_, steer_ratio_, max_lat_accel_, max_steer_angle_); //steer, throttle, brake publisher steer_pub_ = nh_.advertise 2); throttle_pub_ = nh_.advertise 2); brake_pub_ = nh_.advertise 2); //twist_cmd, dbw_enabled, current_velocity,steering_report subscriber sub_vel_ = nh_.subscribe("/twist_cmd", 2, &DBWNode::cbFromTwistCmd, this); sub_enable_ = nh_.subscribe("/vehicle/dbw_enabled", 1, &DBWNode::cbFromRecvEnable, this); sub_cur_vel_ = nh_.subscribe("/current_velocity", 2, &DBWNode::cbFromCurrentVelocity, this); sub_steer_report_ = nh_.subscribe("/vehicle/steering_report", 2, &DBWNode::cbFromSteeringReport, this); sub_fuel_report_ = nh_.subscribe("/vehicle/fuel_level_report", 2, &DBWNode::cbFromFuelLevelReport, this); //give a general value for MKZ, MKZ gas container is 63. lpf_fuel_.setParams(63.0, 0.02); //in simulation env, fuel_level is 50% assumed, in real env, //fuel_level is filled by callback function. if(fuel_level_ > 0) { //assume 50% Fuel level lpf_fuel_.filt(fuel_level_); //ROS_INFO("DBW_node, lpf_fuel_.get(): %f", lpf_fuel_.get()); //ROS_INFO("DBW_node, lpf_fuel_.getReady(): %d", lpf_fuel_.getReady()); } //lowpass accel, lpf_accel_.setParams(0.5, 0.02); //set speed pid range for tune speed_pid_.setRange(-MAX_THROTTLE_PERCENTAGE, MAX_THROTTLE_PERCENTAGE); accel_pid_.setRange(0, MAX_THROTTLE_PERCENTAGE); } void DBWNode::run() { ros::Rate loop_rate(LOOP_RATE); //50hz while(ros::ok()) { ros::spinOnce(); if(sys_enable_ == true) { //get controller's value, including throttle, steering, brake getPredictedControlValues(); } else /*if enable is false, means manually drive, should reset PID parameter to avoid accumulate error.*/ { speed_pid_.resetError(); accel_pid_.resetError(); } loop_rate.sleep(); } } /* Publish control command */ void DBWNode::publishControlCmd(Controller v_controller) { dbw_mkz_msgs::ThrottleCmd tcmd = dbw_mkz_msgs::ThrottleCmd(); tcmd.enable = true; // throttle is percentage tcmd.pedal_cmd_type = dbw_mkz_msgs::ThrottleCmd::CMD_PERCENT; tcmd.pedal_cmd = v_controller.throttle; this->throttle_pub_.publish(tcmd); dbw_mkz_msgs::SteeringCmd scmd = dbw_mkz_msgs::SteeringCmd(); scmd.enable = true; scmd.steering_wheel_angle_cmd = v_controller.steer; this->steer_pub_.publish(scmd); dbw_mkz_msgs::BrakeCmd bcmd = dbw_mkz_msgs::BrakeCmd(); bcmd.enable = true; //brake is torque (N*m) bcmd.pedal_cmd_type = dbw_mkz_msgs::BrakeCmd::CMD_TORQUE; bcmd.pedal_cmd = v_controller.brake; this->brake_pub_.publish(bcmd); } /* Listen dbw_enable message */ void DBWNode::cbFromRecvEnable(const std_msgs::Bool::ConstPtr& msg) { sys_enable_ = msg->data; } /* Listen twist_cmd message, call back function */ void DBWNode::cbFromTwistCmd(const geometry_msgs::TwistStamped::ConstPtr& msg) { twist_cmd_.header = msg->header; twist_cmd_.twist = msg->twist; } /* Listen cur_velocity message, which is from simulator, call back function */ void DBWNode::cbFromCurrentVelocity(const geometry_msgs::TwistStamped::ConstPtr& msg) { cur_velocity_.header = msg->header; cur_velocity_.twist = msg->twist; } /* Listen SteeringReport message, which is actual value, call back function */ void DBWNode::cbFromSteeringReport(const dbw_mkz_msgs::SteeringReport::ConstPtr& msg) { double raw_accel = LOOP_RATE * (msg->speed - cur_velocity_.twist.linear.x); lpf_accel_.filt(raw_accel); if(fabs(msg->speed - cur_velocity_.twist.linear.x) < (double)1e-2) { cur_velocity_.twist.linear.x = msg->speed; } } /* Listen fuel_level_report message, call back function */ void DBWNode::cbFromFuelLevelReport(const dbw_mkz_msgs::FuelLevelReport::ConstPtr& msg) { lpf_fuel_.filt(msg->fuel_level); } /* Listen Dynamic Reconfig message, which is actual value, call back function */ void DBWNode::cbFromDynamicReconfig(twist_controller::ControllerConfig& config, uint32_t level) { cfg_ = config; ROS_INFO("Reconfigure Request: speed_kp: %f, speed_ki: %f, speed_kd: %f", cfg_.speed_kp, cfg_.speed_ki, cfg_.speed_kd); ROS_INFO("Reconfigure Request: accel_kp: %f, accel_ki: %f, accel_kd: %f", cfg_.accel_kp, cfg_.accel_ki, cfg_.accel_kd); //set speed pid's P/I/D speed_pid_.setGains(cfg_.speed_kp, cfg_.speed_ki, cfg_.speed_kd); //set acceleration pid's P/I/D accel_pid_.setGains(cfg_.accel_kp, cfg_.accel_ki, cfg_.accel_kd); } /* get controller's value, including throttle, steering, brake */ void DBWNode::getPredictedControlValues() { // vehicle mass calculation double vehicle_mass = vehicle_mass_ + lpf_fuel_.get() / 100.0 * fuel_capacity_ * GAS_DENSITY; double vel_cte = twist_cmd_.twist.linear.x - cur_velocity_.twist.linear.x; if(fabs(twist_cmd_.twist.linear.x) < mphToMps(1.0)) { speed_pid_.resetError(); } //speed pid, get adjusted speed_cmd double speed_cmd = speed_pid_.step(vel_cte, control_gap_); if(twist_cmd_.twist.linear.x <= (double)1e-2) { speed_cmd = std::min(speed_cmd, -530 / vehicle_mass / wheel_radius_); } //set throttle signal if(speed_cmd >= 0.0) { vehicle_controller_.throttle = accel_pid_.step(speed_cmd - lpf_accel_.get(), control_gap_); } else { accel_pid_.resetError(); vehicle_controller_.throttle = 0.0; } //set brake signal if (speed_cmd < -brake_deadband_) { //get vehicle brake torque, T = m * a * r vehicle_controller_.brake = -speed_cmd * vehicle_mass * wheel_base_ / 9.8; //ROS_INFO("vehicle_controller_.brake: %f", vehicle_controller_.brake); if(vehicle_controller_.brake > TORQUE_MAX) { vehicle_controller_.brake = TORQUE_MAX; } } else { vehicle_controller_.brake = 0; } //set steering signal, only use kp controller double steering_wheel = yaw_controller_.get_steering(twist_cmd_.twist.linear.x, twist_cmd_.twist.angular.z, cur_velocity_.twist.linear.x); vehicle_controller_.steer = steering_wheel + cfg_.steer_kp * (twist_cmd_.twist.angular.z - cur_velocity_.twist.angular.z); //TODO:: for simulator test to see work or not, remember to remove //vehicle_controller_.throttle = 0.3; //vehicle_controller_.steer = 0.0; //vehicle_controller_.brake = 0; publishControlCmd(vehicle_controller_); vehicle_controller_.reset(); } }
c++
14
0.625661
126
33.581197
234
starcoderdata
// Flux Standard Action utilities for Redux. import { createActions } from 'redux-actions'; export default createActions({ MARK_CANVAS: ({ id }) => ({ id, }), TRANSFORM_CANVAS: ({ width=0, height=0 }) => ({ width, height, }), });
javascript
10
0.593625
49
19.916667
12
starcoderdata
// Copyright 2015-2021 Swim inc. // // 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 swim.runtime.lane; import java.util.Map; import swim.api.Link; import swim.api.data.ValueData; import swim.concurrent.Cont; import swim.concurrent.Conts; import swim.concurrent.Stage; import swim.runtime.LaneRelay; import swim.runtime.LaneView; import swim.runtime.Push; import swim.runtime.WarpBinding; import swim.runtime.warp.WarpLaneModel; import swim.structure.Form; import swim.structure.Value; import swim.warp.CommandMessage; public class ValueLaneModel extends WarpLaneModel ValueLaneUplink> { static final int RESIDENT = 1 << 0; static final int TRANSIENT = 1 << 1; static final int SIGNED = 1 << 2; protected int flags; protected ValueData data; ValueLaneModel(int flags) { this.flags = flags; } public ValueLaneModel() { this(0); } @Override public String laneType() { return "value"; } @Override protected ValueLaneUplink createWarpUplink(WarpBinding link) { return new ValueLaneUplink(this, link, createUplinkAddress(link)); } @Override protected void didOpenLaneView(ValueLaneView view) { view.setLaneBinding(this); } @Override public void onCommand(Push push) { final CommandMessage message = push.message(); final Value value = message.body(); new ValueLaneRelaySet(this, message, push.cont(), value).run(); } public final boolean isResident() { return (this.flags & RESIDENT) != 0; } public ValueLaneModel isResident(boolean isResident) { if (this.data != null) { this.data.isResident(isResident); } if (isResident) { this.flags |= RESIDENT; } else { this.flags &= ~RESIDENT; } final Object views = this.views; if (views instanceof ValueLaneView { ((ValueLaneView views).didSetResident(isResident); } else if (views instanceof LaneView[]) { for (LaneView aViewArray : (LaneView[]) views) { ((ValueLaneView aViewArray).didSetResident(isResident); } } return this; } public final boolean isTransient() { return (this.flags & TRANSIENT) != 0; } public ValueLaneModel isTransient(boolean isTransient) { if (this.data != null) { this.data.isTransient(isTransient); } if (isTransient) { this.flags |= TRANSIENT; } else { this.flags &= ~TRANSIENT; } final Object views = this.views; if (views instanceof ValueLaneView { ((ValueLaneView views).didSetTransient(isTransient); } else if (views instanceof LaneView[]) { final LaneView[] viewArray = (LaneView[]) views; for (int i = 0, n = viewArray.length; i < n; i += 1) { ((ValueLaneView viewArray[i]).didSetTransient(isTransient); } } return this; } public Value get() { return this.data.get(); } @SuppressWarnings("unchecked") public V set(ValueLaneView view, V newObject) { final Form valueForm = view.valueForm; final Value newValue = valueForm.mold(newObject).toValue(); final ValueLaneRelaySet relay = new ValueLaneRelaySet(this, stage(), newValue); relay.valueForm = (Form valueForm; relay.oldObject = newObject; relay.newObject = newObject; relay.run(); if (relay.valueForm != valueForm && valueForm != null) { relay.oldObject = valueForm.cast(relay.oldValue); if (relay.oldObject == null) { relay.oldObject = valueForm.unit(); } } return (V) relay.oldObject; } protected void openStore() { this.data = this.laneContext.store().valueData(laneUri().toString()) .isTransient(isTransient()) .isResident(isResident()); } @Override protected void willLoad() { openStore(); super.willLoad(); } } final class ValueLaneRelaySet extends LaneRelay<ValueLaneModel, ValueLaneView { final Link link; final CommandMessage message; final Cont cont; Form valueForm; Value oldValue; Object oldObject; Value newValue; Object newObject; ValueLaneRelaySet(ValueLaneModel model, CommandMessage message, Cont cont, Value newValue) { super(model, 4); this.link = null; this.message = message; this.cont = cont; this.newValue = newValue; } ValueLaneRelaySet(ValueLaneModel model, Link link, Value newValue) { super(model, 1, 3, null); this.link = link; this.message = null; this.cont = null; this.newValue = newValue; } ValueLaneRelaySet(ValueLaneModel model, Stage stage, Value newValue) { super(model, 1, 3, stage); this.link = null; this.message = null; this.cont = null; this.newValue = newValue; } @Override protected void beginPhase(int phase) { if (phase == 2) { this.oldValue = this.model.data.set(this.newValue); if (this.valueForm != null) { this.oldObject = this.valueForm.cast(this.oldValue); if (this.oldObject == null) { this.oldObject = this.valueForm.unit(); } } } } @SuppressWarnings("unchecked") @Override protected boolean runPhase(ValueLaneView view, int phase, boolean preemptive) { if (phase == 0) { if (preemptive) { view.laneWillCommand(this.message); } return view.dispatchWillCommand(this.message.body(), preemptive); } else if (phase == 1) { final Form valueForm = (Form view.valueForm; if (this.valueForm != valueForm && valueForm != null) { this.valueForm = valueForm; this.oldObject = valueForm.cast(this.newValue); if (this.oldObject == null) { this.oldObject = valueForm.unit(); } } if (preemptive) { this.newObject = ((ValueLaneView view).laneWillSet(this.oldObject); } final Map.Entry<Boolean, Object> result = ((ValueLaneView view).dispatchWillSet(this.link, this.oldObject, preemptive); this.newObject = result.getValue(); if (this.oldObject != this.newObject) { this.newValue = valueForm.mold(this.newObject).toValue(); } return result.getKey(); } else if (phase == 2) { final Form valueForm = (Form view.valueForm; if (this.valueForm != valueForm && valueForm != null) { this.valueForm = valueForm; this.oldObject = valueForm.cast(this.oldValue); if (this.oldObject == null) { this.oldObject = valueForm.unit(); } this.newObject = valueForm.cast(this.newValue); if (this.newObject == null) { this.newObject = valueForm.unit(); } } if (preemptive) { ((ValueLaneView view).laneDidSet(this.newObject, this.oldObject); } return ((ValueLaneView view).dispatchDidSet(this.link, this.newObject, this.oldObject, preemptive); } else if (phase == 3) { if (preemptive) { view.laneDidCommand(this.message); } return view.dispatchDidCommand(this.message.body(), preemptive); } else { throw new AssertionError(); // unreachable } } @Override protected void done() { this.model.cueDown(); if (this.cont != null) { try { this.cont.bind(this.message); } catch (Throwable error) { if (Conts.isNonFatal(error)) { this.cont.trap(error); } else { throw error; } } } } }
java
17
0.649558
134
27.770609
279
starcoderdata
def type_must_match_search_type(cls, search_type): # pylint:disable=no-self-argument # noqa: N805 """Ensure the type is a valid SearchType.""" try: SearchType[search_type] except KeyError: raise ValueError('type must be one of: {}'.format(list(map(lambda st: st.name, SearchType)))) return search_type
python
17
0.628492
105
50.285714
7
inline
@RequestMapping(value = PathRoutes.RoleActionRoutes.NEW_ACTION_POST, method = RequestMethod.POST) public ResponseEntity<?> saveAction(@RequestBody Action action, BindingResult result) throws AuthenticationException { if (result.hasErrors()) { return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); } List<CustomException> validationExceptions = new ArrayList<>(); if (action != null) { if (StringUtils.isBlank("")) { CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, ResponseMessages.ErrorMessages.FEATURE_NAME_UNAVAILABLE, ResponseMessages.UNAVAILABLE, null); validationExceptions.add(exception); } if (StringUtils.isBlank("")) { CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, ResponseMessages.ErrorMessages.FEATURE_CODE_UNAVAILABLE, ResponseMessages.UNAVAILABLE, null); validationExceptions.add(exception); } // if(StringUtils.isBlank(action.getUrl())) { // CustomException exception = new // CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, // ResponseMessages.ErrorMessages.FEATURE_URL_UNAVAILABLE, // ResponseMessages.UNAVAILABLE, null); // validationExceptions.add(exception); // } } else { CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, ResponseMessages.ErrorMessages.FEATURE_DETAILS_UNAVAILABLE, ResponseMessages.UNAVAILABLE, null); validationExceptions.add(exception); } if (!validationExceptions.isEmpty()) { return new ResponseEntity<>(validationExceptions, HttpStatus.BAD_REQUEST); } Action savedAction = roleActionService.saveAction(action); if (savedAction != null) { List<Object> savedActions = new ArrayList<>(); savedActions.add(savedAction); return new ResponseEntity<>(new CustomResponse(HttpStatus.OK.toString(), ResponseMessages.SuccessMessages.ACTION_ADDED, savedActions), HttpStatus.OK); } else { CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, ResponseMessages.ErrorMessages.FEATURE_DETAILS_NOTSAVED, ResponseMessages.INTERNAL_ERROR, null); validationExceptions.add(exception); return new ResponseEntity<>(validationExceptions, HttpStatus.SERVICE_UNAVAILABLE); } }
java
13
0.77127
101
47.75
48
inline
static bool DetectMatch(uint8_t *ref, int reflen, uint8_t *buf, int buflen, std::vector<int> &refstart, std::vector<int> &bufstart, std::vector<int> &len) { if(reflen <= OV_MATCH_MIN) return false; if(buflen <= OV_MATCH_MIN) return false; bool anymatched = false; int bufpos; int refpos; for(bufpos = 0; bufpos<buflen-OV_MATCH_MIN;) { bool matched = false; int matchlen; int refmax = bufpos + OV_MATCH_DIF_MAX; if(refmax >= reflen - OV_MATCH_MIN) refmax = reflen - OV_MATCH_MIN; for(refpos = (bufpos<OV_MATCH_DIF_MAX?0:(bufpos-OV_MATCH_DIF_MAX)); refpos<refmax; refpos++) { if(buf[bufpos] == ref[refpos]) { // first character matched int remain = buflen-bufpos > reflen-refpos ? reflen-refpos : buflen-bufpos; uint8_t *rp = ref + refpos; uint8_t *bp = buf + bufpos; while(*rp == *bp && remain) rp++, bp++, remain--; matchlen = rp - (ref + refpos); if(matchlen >= OV_MATCH_MIN) { // matched refstart.push_back(refpos); bufstart.push_back(bufpos); len.push_back(matchlen); matched = true; break; } } } if(matched) bufpos += matchlen, anymatched = true; else bufpos++; } return anymatched; }
c++
14
0.620149
79
24.25
48
inline
@Test @SuppressWarnings("unchecked") public void testSetDeprecatedComplexPropertiesWithFallbackOnComplex() throws Exception { String deprecatedProperty = "complex2complex"; String fallbackProperty = "complexfallback"; DocumentModel doc = new DocumentModelImpl("/", "doc", "File"); doc.setProperties(DEPRECATED_SCHEMA, Collections.singletonMap("complex2complex", Collections.singletonMap("scalar", "test scalar"))); Map<String, Object> properties = doc.getProperties(DEPRECATED_SCHEMA); assertEquals("test scalar", ((Map<String, Serializable>) properties.get("complex2complex")).get("scalar").toString()); assertEquals("test scalar", ((Map<String, Serializable>) properties.get("complexfallback")).get("scalar").toString()); logCaptureResult.assertHasEvent(); List<String> events = logCaptureResult.getCaughtEventMessages(); // 3 logs: // - a set is done on scalar property // - a set is done on its container // - a get which retrieve the scalar (that's why there's no 4th log on scalar property) assertEquals(3, events.size()); assertEquals(String.format(SET_VALUE_FALLBACK_PARENT_LOG, deprecatedProperty + "/scalar", DEPRECATED_SCHEMA, deprecatedProperty, fallbackProperty + "/scalar"), events.get(0)); assertEquals(String.format(SET_VALUE_FALLBACK_LOG, deprecatedProperty, DEPRECATED_SCHEMA, fallbackProperty), events.get(1)); assertEquals(String.format(GET_VALUE_FALLBACK_LOG, deprecatedProperty, DEPRECATED_SCHEMA, fallbackProperty), events.get(2)); }
java
13
0.670782
116
59.785714
28
inline
import copy import typing import splendor_sim.interfaces.card.i_card as i_card import splendor_sim.interfaces.factories.i_json_buildable_object as i_json_buildable_object import splendor_sim.interfaces.game_state.i_incomplete_game_state as i_incomplete_game_state import splendor_sim.src.factories.json_schemas as json_schemas import splendor_sim.src.factories.json_validator as json_validator import splendor_sim.src.player.player_card_inventory as player_card_inventory class JsonPlayerCardInventory( player_card_inventory.PlayerCardInventory, i_json_buildable_object.IJsonBuildableObject, ): _JSON_VALIDATOR = json_validator.JsonValidator( json_schemas.JSON_PLAYER_CARD_INVENTORY ) def __init__( self, max_reserved_cards: int, reserved_cards: typing.Set[i_card.ICard], cards: typing.Set[i_card.ICard], ): super(JsonPlayerCardInventory, self).__init__( max_reserved_cards, reserved_cards, cards ) @classmethod def build_from_json( cls, json: typing.Dict, incomplete_game_state: i_incomplete_game_state.IIncompleteGameState, ): if not cls._JSON_VALIDATOR.validate_json(json): raise ValueError("Json does not meet schema") card_manager = incomplete_game_state.get_card_manager() reserved_cards: typing.Set[i_card.ICard] = set() for card_name in json["reserved_cards"]: if not card_manager.is_card_in_manager_by_name(card_name): raise ValueError("card name not in manager.") reserved_cards.add(card_manager.get_card_by_name(card_name)) cards: typing.Set[i_card.ICard] = set() for card_name in json["cards"]: if not card_manager.is_card_in_manager_by_name(card_name): raise ValueError("card name not in manager.") cards.add(card_manager.get_card_by_name(card_name)) json_player_card_inventory = cls( json["max_reserved_cards"], reserved_cards, cards ) return json_player_card_inventory @staticmethod def get_json_schema() -> typing.Dict: return copy.deepcopy(json_schemas.JSON_PLAYER_CARD_INVENTORY)
python
14
0.6713
92
34.967742
62
starcoderdata
#!/usr/bin/python3 import RPi.GPIO as GPIO import time import zmq socket_address = "tcp://0.0.0.0:2000" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind(socket_address) GPIO.setmode(GPIO.BCM) TRIG = 27 ECHO = 22 print ("Distance Measurement In Progress") GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) try: while True: GPIO.output(TRIG, False) print ("Waiting For Sensor To Settle") time.sleep(2) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time.time() while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance, 2) print ("Distance:",distance,"cm") socket.send_pyobj(distance) except KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup print ("Closing") GPIO.cleanup()
python
11
0.645946
113
21.2
50
starcoderdata
public void addToQueue(VoiceMessage m) { //add a message to send to the client try { toSend.add(m); } catch (Throwable t) { //mutex error, ignore because the server must be as fast as possible } }
java
8
0.576613
80
34.571429
7
inline