code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
#include #include #include #ifndef True #define True (-1) #endif #ifndef False #define False (0) #endif /* this probably works for Mach-O too, but probably not for PE */ #if (defined(__APPLE__) || defined(__ELF__)) && defined(__GNUC__) && (__GNUC__ >= 3) #define weak __attribute__((weak)) #else #define weak #ifndef __SUNPRO_C /* Sun compilers use #pragma weak in .c files instead */ #define NO_WEAK_SYMBOLS #endif #endif #if defined(NO_WEAK_SYMBOLS) && defined(PIC) #include extern int _font_init_stubs(void); #define OVERRIDE_DATA(sym) \ _font_init_stubs(); \ if (__ptr_##sym && __ptr_##sym != &sym) \ sym = *__ptr_##sym #define OVERRIDE_SYMBOL(sym,...) \ _font_init_stubs(); \ if (__##sym && __##sym != sym) \ return (*__##sym)(__VA_ARGS__) #define OVERRIDE_VA_SYMBOL(sym,f) \ va_list _args; \ _font_init_stubs(); \ va_start(_args, f); \ if (__##sym) \ (*__##sym)(f, _args); \ va_end(_args) int (*__client_auth_generation)(ClientPtr); Bool (*__ClientSignal)(ClientPtr); void (*__DeleteFontClientID)(Font); void (*__VErrorF)(const char *, va_list); FontPtr (*__find_old_font)(FSID); FontResolutionPtr (*__GetClientResolutions)(int *); int (*__GetDefaultPointSize)(void); Font (*__GetNewFontClientID)(void); unsigned long (*__GetTimeInMillis)(void); int (*__init_fs_handlers)(FontPathElementPtr, BlockHandlerProcPtr); int (*__RegisterFPEFunctions)(NameCheckFunc, InitFpeFunc, FreeFpeFunc, ResetFpeFunc, OpenFontFunc, CloseFontFunc, ListFontsFunc, StartLfwiFunc, NextLfwiFunc, WakeupFpeFunc, ClientDiedFunc, LoadGlyphsFunc, StartLaFunc, NextLaFunc, SetPathFunc); void (*__remove_fs_handlers)(FontPathElementPtr, BlockHandlerProcPtr, Bool); void **__ptr_serverClient; int (*__set_font_authorizations)(char **, int *, ClientPtr); int (*__StoreFontClientFont)(FontPtr, Font); Atom (*__MakeAtom)(const char *, unsigned, int); int (*__ValidAtom)(Atom); char *(*__NameForAtom)(Atom); unsigned long *__ptr_serverGeneration; void (*__register_fpe_functions)(void); #else /* NO_WEAK_SYMBOLS && PIC */ #define OVERRIDE_DATA(sym) #define OVERRIDE_SYMBOL(sym,...) #define OVERRIDE_VA_SYMBOL(sym,f) #endif /* This is really just a hack for now... __APPLE__ really should be using * the weak symbols route above, but it's causing an as-yet unresolved issue, * so we're instead building with flat_namespace. */ #ifdef __APPLE__ #undef weak #define weak #endif extern FontPtr find_old_font ( FSID id ); extern int set_font_authorizations ( char **authorizations, int *authlen, ClientPtr client ); extern unsigned long GetTimeInMillis (void); extern void ErrorF(const char *format, ...); /* end of file */
c
8
0.670043
84
30.05618
89
starcoderdata
def test_method_resolution_order(polar, load_policy, query): set_frobbed([]) actor = Actor(name="guest") resource = Widget(id="1") action = "get" assert query(Predicate(name="allow", args=[actor, action, resource])) assert get_frobbed() == ["Widget"] # DooDad is a Widget set_frobbed([]) resource = DooDad(id="2") assert query(Predicate(name="allow", args=[actor, action, resource])) assert get_frobbed() == ["DooDad", "Widget"]
python
10
0.632135
73
35.461538
13
inline
package com.github.alex.zuy.boilerplate.utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; public final class IoUtils { private static final int BUFFER_SIZE = 1024 * 4; private IoUtils() { } @SuppressWarnings("PMD.AssignmentInOperand") public static void copy(InputStream in, OutputStream out) throws IOException { final byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } } @SuppressWarnings("PMD.AssignmentInOperand") public static void copy(Reader in, Writer out) throws IOException { final char[] buffer = new char[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } } public static String readToString(Reader reader) throws IOException { final StringWriter result = new StringWriter(); copy(reader, result); return result.toString(); } }
java
12
0.655172
82
27.292683
41
starcoderdata
#ifndef __STDIO_H__ #define __STDIO_H__ #include "type.h" #ifndef _VALIST #define _VALIST typedef char *va_list; #endif /* _VALIST */ int vsnprintf(char *buf, size_t size, const char *fmt, va_list args); int snprintf(char * buf, size_t size, const char *fmt, ...); int vsprintf(char *buf, const char *fmt, va_list args); int sprintf(char * buf, const char *fmt, ...); int vsscanf(const char * buf, const char * fmt, va_list args); int sscanf(const char * buf, const char * fmt, ...); void putc(unsigned char c); unsigned char getc(void); int printf(const char *fmt, ...); int scanf(const char * fmt, ...); #endif /* __STDIO_H__ */
c
11
0.676349
87
30.434783
23
starcoderdata
def test_searchLimit(self): """ Searching does not return more results than the limit. """ s = Store() def _tx(): for x in xrange(50): SearchEntry.insert( s, SearchClasses.EXACT, u'e', u'i', u'RESULT', u'type{}'.format(x), u'yo') self.assertThat(s.query(SearchEntry).count(), Equals(50)) self.assertThat( list(SearchEntry.search( s, SearchClasses.EXACT, u'e', u'i', u'yo', limit=20)), HasLength(20)) s.transact(_tx)
python
13
0.473684
74
34.823529
17
inline
package org.smartframework.cloud.examples.support.gateway.http.codec; import java.nio.ByteBuffer; import java.util.Collections; import java.util.List; import java.util.Map; import org.reactivestreams.Publisher; import org.smartframework.cloud.examples.support.gateway.constants.ProtostuffConstant; import org.smartframework.cloud.utility.SerializingUtil; import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.MediaType; import org.springframework.http.ReactiveHttpOutputMessage; import org.springframework.http.codec.HttpMessageWriter; import reactor.core.publisher.Mono; public class ProtostuffHttpMessageWriter implements HttpMessageWriter @Override public List getWritableMediaTypes() { return Collections.singletonList(ProtostuffConstant.PROTOBUF_MEDIA_TYPE); } @Override public boolean canWrite(ResolvableType elementType, MediaType mediaType) { return mediaType != null && ProtostuffConstant.PROTOBUF_MEDIA_TYPE.isCompatibleWith(mediaType); } @Override public Mono write(Publisher<? extends Object> inputStream, ResolvableType elementType, MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints) { return Mono.from(inputStream).flatMap(form -> { byte[] data = SerializingUtil.serialize(form); ByteBuffer byteBuffer = ByteBuffer.wrap(data); DataBuffer buffer = message.bufferFactory().wrap(byteBuffer); // wrapping only, no allocation message.getHeaders().setContentLength(byteBuffer.remaining()); return message.writeWith(Mono.just(buffer)); }); } }
java
15
0.811343
114
37.090909
44
starcoderdata
package com.tsmms.skoop.membership.query; import com.tsmms.skoop.membership.Membership; import com.tsmms.skoop.membership.MembershipRepository; import org.springframework.stereotype.Service; import java.util.stream.Stream; import static java.util.Objects.requireNonNull; @Service public class MembershipQueryService { private final MembershipRepository membershipRepository; public MembershipQueryService(MembershipRepository membershipRepository) { this.membershipRepository = requireNonNull(membershipRepository); } public Stream getUserMemberships(String userId) { if (userId == null) { throw new IllegalArgumentException("User ID cannot be null."); } return membershipRepository.findByUserIdOrderByDateDesc(userId); } }
java
9
0.824444
139
31.142857
28
starcoderdata
function Main(input) { var ans = -1; var input = input.split("\n"); input[0] = input[0].split(""); input[1] = input[1].split(""); for(var i=0;i<input[0].length;i++){ if(input[0].join()==input[1].join()){ ans = i break; } input[0].unshift(input[0][input[0].length-1]); input[0].pop(); // console.log(input[0]) } console.log(ans==-1?"No":"Yes"); }Main(require("fs").readFileSync("/dev/stdin","utf8").trim());
javascript
12
0.495984
62
30.125
16
codenet
<?php namespace App\Http\Tools\Captcha; class BspCaptcha{ private $secret_id = ' private $secret_key = ' private $captacha_type ='4'; private $disturb_level ='1'; private $is_htttps =1; private $business_id = '1234'; private $url = 'csec.api.qcloud.com/v2/index.php'; /* *腾迅 bsp 天御验证码 by baoyaoling */ /* Construct query string from array */ private function makeQueryString($args, $isURLEncoded) { return implode( '&', array_map( function ($key, $value) use (&$isURLEncoded) { if (!$isURLEncoded) { return "$key=$value"; } else { return $key . '=' . urlencode($value); } }, array_keys($args), $args ) ); } private function makeURL($method, $action, $region, $secretId, $secretKey, $args) { /* Add common parameters */ $args['Nonce'] = (string)rand(0, 0x7fffffff); $args['Action'] = $action; $args['Region'] = $region; $args['SecretId'] = $secretId; $args['Timestamp'] = (string)time(); /* Sort by key (ASCII order, ascending), then calculate signature using HMAC-SHA1 algorithm */ ksort($args); $args['Signature'] = base64_encode( hash_hmac( 'sha1', $method . $this->url . '?' . $this->makeQueryString($args, false), $secretKey, true ) ); /* Assemble final request URL */ return 'https://' . $this->url . '?' . $this->makeQueryString($args, true); } private function sendJsRequest($url, $method = 'POST') { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (false !== strpos($url, "https")) { // 证书 // curl_setopt($ch,CURLOPT_CAINFO,"ca.crt"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } $resultStr = curl_exec($ch); $result = json_decode($resultStr, true); return $result; } /* Demo section */ function getJsUrl() { $url =$this->makeURL( 'GET', 'CaptchaIframeQuery', 'sz', $this->secret_id, $this->secret_key, array( /* 行为信息参数 */ 'userIp' => $_SERVER['REMOTE_ADDR'], /* 验证码信息参数 */ 'captchaType' =>$this->captacha_type, 'disturbLevel' =>$this->disturb_level, 'isHttps' =>$this->is_htttps, /* 其他信息参数 */ 'businessId' =>$this->business_id ) ); $result = $this->sendJsRequest($url); $jsUrl = $result['url']; return $jsUrl; } function Check($ticket) { $url =$this->makeURL( 'GET', 'CaptchaCheck', 'sz', $this->secret_id, $this->secret_key, array( /* 行为信息参数 */ 'userIp' => $_SERVER['REMOTE_ADDR'], /* 验证码信息参数 */ 'captchaType' => $this->captacha_type, 'ticket' => $ticket, /* 其他信息参数 */ 'businessId' => $this->business_id ) ); $result = $this->sendJsRequest($url); return $result; } /* * 注册保护 */ function register($arr) { $url =$this->makeURL( 'GET', 'RegisterProtection', 'gz', $this->secret_id, $this->secret_key, $arr ); $result = $this->sendJsRequest($url); return $result; } } ?>
php
23
0.462526
101
24.638158
152
starcoderdata
@Override public void init(AvroSchemaEditor editor) { this.editor = editor; final SchemaEditorContentPart contentPart = editor.getContentPart(); registerView(null, contentPart.getSchemaViewer(AvroContext.Kind.MASTER)); registerView(null, new IView() { @Override public void select(Object object, Kind context) { SchemaViewer slaveSchemaViewer = contentPart.getSchemaViewer(AvroContext.Kind.SLAVE); if (slaveSchemaViewer != null) { slaveSchemaViewer.select(object, context); } } @Override public void reveal(Object object, Kind context) { SchemaViewer slaveSchemaViewer = contentPart.getSchemaViewer(AvroContext.Kind.SLAVE); if (slaveSchemaViewer != null) { slaveSchemaViewer.reveal(object, context); } } @Override public void refresh(Object object) { SchemaViewer slaveSchemaViewer = contentPart.getSchemaViewer(AvroContext.Kind.SLAVE); if (slaveSchemaViewer != null) { slaveSchemaViewer.refresh(object); } } @Override public void refresh() { SchemaViewer slaveSchemaViewer = contentPart.getSchemaViewer(AvroContext.Kind.SLAVE); if (slaveSchemaViewer != null) { slaveSchemaViewer.refresh(); } } @Override public String getId() { return SchemaViewer.getId(AvroContext.Kind.SLAVE); } @Override public void notify(Object object) { // } }); final AttributeViewer attributeViewer = contentPart.getAttributeViewer(); registerView(null, new IView() { @Override public void select(Object object, Kind context) { // no selection } @Override public void reveal(Object object, Kind context) { // nothing to reveal } @Override public void refresh(Object object) { attributeViewer.update(); } @Override public void refresh() { attributeViewer.update(); } @Override public void notify(Object object) { // } @Override public String getId() { return "AttributeViewer"; //$NON-NLS-1$ } }); }
java
16
0.674951
89
23.152941
85
inline
def image_crop(input=('ImagePin', 0), img=(REF, ('ImagePin', 0)), rect=('GraphElementPin', 0) ): """Takes an image and mask and applied logic and operation""" if 'rect' in rect.graph.keys(): only_rect=rect.graph['rect'] if only_rect: x, y, w, h=only_rect[0] (ih, iw) = input.image.shape[:2] if (x+w)<=iw and (y+h)<ih: img(input.image[y:(y+h),x:(x+w),:])
python
16
0.440945
69
41.416667
12
inline
<?php namespace Support\View; use Illuminate\View\View; class AppViewComposer { public function compose(View $view): void { $view->with('data', $this->addGlobalData($view->getData())); } protected function addGlobalData(array $baseData): array { $settings = null; // @use-preset-nova-settings if (is_null($settings)) { $settings = config('binalogue'); } return array_merge($baseData, [ // App. 'env' => config('app.env'), 'url' => config('app.url'), // Browser. 'webp_support' => webp_support(), // Config 'settings' => $settings, // Localization. 'locale' => config('app.locale'), 'fallback' => config('app.fallback_locale'), // 'messages' => ExportLocalizations::export()->toFlat(), 'messages' => [], ]); } }
php
15
0.512538
69
22.186047
43
starcoderdata
/* * Generate tables for bit-revese shuffle * * Input: an integer k for tables of size n=2^k * * Basic table: * bitrev[i] = reverse of i for i=0 to n-1 * * Second table: * revpair = all pairs (i, reverse i) where i < reverse i. * nrevpairs = number of pairs in this table */ #include #include #include #include #include /* * Bitreverse of i, interpreted as a k-bit integer */ static uint32_t reverse(uint32_t i, uint32_t k) { uint32_t x, b, j; x = 0; for (j=0; j<k; j++) { b = i & 1; x = (x<<1) | b; i >>= 1; } return x; } /* * Fill in table a with a[i] = reverse(i, k) * - n = 2^k */ static void init_rev_table(uint32_t *a, uint32_t n, uint32_t k) { uint32_t i; assert(n == ((uint32_t)1 << k)); for (i=0; i<n; i++) { a[i] = reverse(i, k); } } /* * Count the number of i such that i < a[i] */ static uint32_t rev_table_npairs(const uint32_t *a, uint32_t n) { uint32_t i, c; c = 0; for (i=0; i<n; i++) { c += (i < a[i]); } return c; } /* * Print table a */ static void print_bitrev_table(FILE *f, const uint32_t *a, uint32_t n) { uint32_t i, k; fprintf(f, "\nconst uint32_t bitrev%"PRIu32"[%"PRIu32"] = {\n", n, n); k = 0; for (i=0; i<n; i++) { if (k == 0) fprintf(f, " "); fprintf(f, " %5"PRIu32",", a[i]); k ++; if (k == 8) { fprintf(f, "\n"); k = 0; } } if (k > 0) fprintf(f, "\n"); fprintf(f, "};\n\n"); } /* * Print the pair tables for a */ static void print_bitrev_pair_table(FILE *f, const uint32_t *a, uint32_t n) { uint32_t s, i, k; s = rev_table_npairs(a, n); fprintf(f, "\n#define BITREV%"PRIu32"_NPAIRS %"PRIu32"\n", n, s); fprintf(f, "\nconst uint32_t bitrev%"PRIu32"_pair[BITREV%"PRIu32"_NPAIRS][2] = {\n", n, n); k = 0; for (i=0; i<n; i++) { if (i < a[i]) { if (k == 0) fprintf(f, " "); fprintf(f, " { %5"PRIu32", %5"PRIu32" },", i, a[i]); k ++; if (k == 4) { fprintf(f, "\n"); k = 0; } } } if (k > 0) fprintf(f, "\n"); fprintf(f, "};\n\n"); } int main(int argc, char *argv[]) { uint32_t n, k; uint32_t *table; long x; if (argc != 2) { fprintf(stderr, "Usage: %s k (to generate tables of size 2^k\n", argv[0]); exit(EXIT_FAILURE); } x = atol(argv[1]); if (x <= 0) { fprintf(stderr, "invalid size: k must be at least 1\n"); exit(EXIT_FAILURE); } if (x > 28) { fprintf(stderr, "size too large: max k = 28\n"); exit(EXIT_FAILURE); } k = (uint32_t)x; n = (uint32_t) 1 << k; table = (uint32_t*) malloc(n * sizeof(uint32_t)); if (table == NULL) { fprintf(stderr, "failed to allocate table (of size %"PRIu32"\n", n); exit(EXIT_FAILURE); } init_rev_table(table, n, k); print_bitrev_table(stdout, table, n); print_bitrev_pair_table(stdout, table, n); free(table); return 0; }
c
13
0.540897
119
19.486486
148
starcoderdata
from __future__ import annotations import logging from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Type import pygame import pygame_gui from pygame_gui.elements import UIButton, UILabel, UIPanel, UITextBox, UITextEntryLine from pygame.rect import Rect from scripts import ui, world from scripts.components import Hourglass from scripts.constants import LINE_BREAK if TYPE_CHECKING: from typing import Union, Optional, Any, Tuple, Dict, List, Callable from pygame_gui import UIManager from pygame_gui.core import UIElement class Screen(ABC): """ The base class for all screens. Provides methods for creating the main screen sections. Adds returning to the antechamber as an initial option. self.options must be overridden to remove this. Otherwise just add more options. """ # default values that dont need rect section_gap = 3 line_height = 38 # Top area header_x = 0 header_y = 0 header_height = 60 post_header_y = header_height + header_y + section_gap # middle area selections section_start_x = 55 button_x = section_start_x button_width = 152 button_height = line_height option_text_x = section_start_x + (button_width - section_gap) # minus to have button touch on both sides info_x = section_start_x # bottom area choice_x = section_start_x choice_width = 200 choice_height = 50 hourglass_width = 300 hourglass_height = choice_height def __init__(self, manager: UIManager, rect: Rect): self.manager: UIManager = manager self.rect: Rect = rect self.elements: Dict[str, UIElement] = {} self.options: Dict[str, Tuple[str, Callable]] = { "anteroom": ("Anteroom - Return", ui.swap_to_antechamber_screen) } self.showing = "" # flag is set in setup # default values that need rect before they can be set self.header_width = rect.width self.option_text_width = rect.width - (self.option_text_x + self.section_start_x) # account for gap on right self.max_section_height = rect.height - (self.post_header_y + self.choice_height + (self.section_gap * 3)) self.half_max_section_height = self.max_section_height / 2 self.choice_y = rect.height - self.choice_height - (self.section_gap * 2) self.hourglass_y = self.choice_y self.info_width = rect.width - (self.info_x + self.section_start_x) # account for gap on right @abstractmethod def handle_event(self, event: pygame.event.Event): """ Process events generated by this element. Must be overridden. """ raise NotImplementedError def kill(self): """ Delete all elements from self.elements and clear self.options. """ elements = self.elements for name, element in elements.items(): element.kill() self.elements = {} self.options = {} ############################ CREATE ############################## def create_info_section(self, x: int, y: int, width: int, height: int, text: str): """ Create an information section on the screen. Called "info". """ info_text = UITextBox(text, Rect((x, y), (width, height)), self.manager, False, 1) self.elements["info"] = info_text def create_option_section(self, button_x: int, text_x: int, y: int, button_width: int, button_height: int, text_width: int, text_height: int): """ Create an options section. Uses self.options. Creates a panel to contains buttons and text box. "options", [option_number] and "text". """ # offsets for alignment offset_y = 0 count = 1 # to hold string from list options_text = "" # create panel to hold it all panel = UIPanel(Rect((button_x, y), (button_width + text_width, text_height)), 0, self.manager, object_id="options") self.elements["panel"] = panel # loop options and extract text and id for _id, (text, _method) in self.options.items(): options_text += text + LINE_BREAK + LINE_BREAK option_button = UIButton(Rect((button_x, y + offset_y), (button_width, button_height)), str(count), self.manager, object_id=_id, parent_element=panel) count += 1 offset_y += button_height self.elements[_id] = option_button # add text to textbox options_text = UITextBox(options_text, Rect((text_x, y), (text_width, text_height)), self.manager, False, 1, parent_element=panel) self.elements["text"] = options_text def create_header(self, text: str): """ Create the header section. Uses default settings. Called "header" """ header = UILabel(Rect((self.header_x, self.header_y), (self.header_width, self.header_height)), text, self.manager) self.elements["header"] = header def create_choice_field(self, allowed_str: bool = True, allowed_num: bool = True): """ Create the choice input field. Uses default settings. Called "choice". """ choice = UITextEntryLine(Rect((self.choice_x, self.choice_y), (self.choice_width, self.choice_height)), self.manager, object_id="choice") # prevent strings based on the arg if allowed_str and allowed_num: pass elif allowed_str and not allowed_num: choice.set_forbidden_characters("numbers") elif not allowed_str and allowed_num: choice.set_allowed_characters("numbers") self.elements["choice"] = choice def create_hourglass_display(self): """ Create the display of how much time is left in the day """ # get the text player_kingdom = world.get_player_kingdom() hourglass = world.get_entitys_component(player_kingdom, Hourglass) text = f"{str(hourglass.minutes_available)} minutes before sunset" # create the label rect = Rect((-self.hourglass_width - self.section_start_x, self.choice_y), (self.hourglass_width, self.hourglass_height)) hourglass_display = UILabel(rect, text, self.manager, object_id="hourglass", anchors={ "left": "right", "right": "right", "top": "top", "bottom": "bottom" }) self.elements["hourglass"] = hourglass_display ############################ CHECKS ############################## def get_object_id(self, event: pygame.event.Event) -> str: """ Strip unnecessary details from the event's ui_object_id and handle keyboard or mouse input to get object id """ # get the id from either click or type object_id = "" if event.user_type == pygame_gui.UI_BUTTON_PRESSED: object_id = event.ui_object_id.replace("options.", "") elif event.user_type == pygame_gui.UI_TEXT_ENTRY_FINISHED: if event.text.isnumeric(): try: object_id = list(self.options)[int(event.text) - 1] # -1 to offset from options starting at 1 except KeyError: logging.warning(f"Key not found in options when getting object id. Dodgy typing? ({event.text})") except IndexError: logging.warning(f"Index outside options when getting object id. Dodgy typing? ({event.text})") return object_id def is_option_implemented(self, object_id: Union[str, int]) -> bool: """ Confirm that the option selected is implemented """ # check for a prefix indicating not implemented try: if object_id: prefix = self.options[object_id][0][:1] if prefix != "*": return True else: logging.warning(f"Selected {object_id}, which is not implemented. Took no action.") except KeyError: logging.warning(f"Key not found in options when getting prefix. Dodgy typing? ({object_id})") return False def call_options_function(self, object_id: str): """ Call the option's function """ self.options[object_id][1]()
python
19
0.581589
118
38.484018
219
starcoderdata
#include "fileinfo.h" #include #include #include #include #include FileInfo::FileInfo(QUrl url, QObject *parent) : QObject(parent), fileUrl(std::move(url)) { connect(&networkManager, &QNetworkAccessManager::finished, this, &FileInfo::onNetworkManagerFinished); timeout.setSingleShot(true); timeout.setInterval(5000); connect(&timeout, &QTimer::timeout, this, &FileInfo::onTimeout); rateTimer.setSingleShot(false); rateTimer.setInterval(1000); connect(&rateTimer, &QTimer::timeout, this, &FileInfo::onRateTimerTimeout); } void FileInfo::onNetworkManagerFinished(QNetworkReply *reply) { if (reply == infoReply) { if (reply->error() == QNetworkReply::NoError) { auto data = reply->readAll(); QJsonDocument doc = QJsonDocument::fromJson(data); QJsonObject obj = doc.object(); QString datetime = obj.value(QStringLiteral("datetime")).toString(); if (!datetime.isEmpty()) { QStringList l1 = datetime.split('T'); filePath = l1.front() + '/' + fileUrl.toString().split('/').back(); emit readyForDownload(this); } else { qDebug() << "error fetching date: " << fileUrl << ": " << data; emit dateFetchError(this); } infoReply->deleteLater(); infoReply = nullptr; } else { qDebug() << "date reply error: " << reply->error(); emit dateFetchError(this); } timeout.stop(); } else if (reply == downloadReply) { if (reply->error() == QNetworkReply::NoError) { QFile file(savePrefix + '/' + filePath); auto data = downloadReply->readAll(); downloadReply->deleteLater(); downloadReply = nullptr; if (!file.open(QFile::WriteOnly)) { qDebug() << "cannot open file " << filePath << ": " << file.errorString(); emit downloadError(this); } else { downloaded = true; file.write(data); file.close(); emit fileDownloaded(this); } } else { downloadReply->deleteLater(); downloadReply = nullptr; qDebug() << "download error: " << reply->errorString(); emit downloadError(this); } timeout.stop(); rateTimer.stop(); } } void FileInfo::onTimeout() { if (infoReply) { if (infoReply->isRunning()) { infoReply->abort(); } } else if (downloadReply) { if (downloadReply->isRunning()) { downloadReply->abort(); } } bytesWritten = 0; bytesWrittenPrevious = 0; } void FileInfo::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) { timeout.start(); double pecrd = static_cast / static_cast int percent = static_cast * pecrd)); bytesWritten = bytesReceived; emit downloadProgress(getFileName(), percent, downloadRate); } void FileInfo::onRateTimerTimeout() { downloadRate = static_cast - bytesWrittenPrevious) / 1000.0; bytesWrittenPrevious = bytesWritten; } QString FileInfo::getFilePath() const { return filePath; } QString FileInfo::getFileDir() const { return filePath.split('/', QString::SkipEmptyParts).front(); } QString FileInfo::getFileName() const { return filePath.split('/', QString::SkipEmptyParts).back(); } void FileInfo::getDate() { // if file is video (*.MOV) auto ext = fileUrl.toString().split('.').back(); if (ext == QLatin1String("MOV")) { filePath = "videos/" + fileUrl.toString().split('/').back(); emit readyForDownload(this); return; } infoReply = networkManager.get(QNetworkRequest(QUrl(fileUrl.toString() + "/info"))); timeout.start(); } void FileInfo::download(const QString &savePrefix) { if (alreadyDownloaded(savePrefix)) { emit fileDownloaded(this); return; } QDir dir(savePrefix + '/' + getFileDir()); if (!dir.exists()) { if (!dir.mkpath(dir.path())) { qDebug() << "cannot create directory: " << dir.path(); } } this->savePrefix = savePrefix; downloadReply = networkManager.get(QNetworkRequest(getFileUrl())); connect(downloadReply, &QNetworkReply::downloadProgress, this, &FileInfo::onDownloadProgress); timeout.start(); rateTimer.start(); } bool FileInfo::operator==(const FileInfo &rhs) const { return (fileUrl == rhs.fileUrl); } bool FileInfo::operator<(const FileInfo &rhs) const { return (fileUrl < rhs.fileUrl); } bool FileInfo::alreadyDownloaded(const QString &savePrefix) { if (downloaded) { return true; } QString dir = getFileDir(); QString file = getFileName(); auto split = file.split('.'); QString filename = split.front(); QString extension = split.back(); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { QString tmp = dir + '/' + (j ? filename.toLower() : filename.toUpper()) + '.' + (i ? extension.toLower() : extension.toUpper()); if (QFile::exists(savePrefix + '/' + tmp)) { downloaded = true; return true; } } } return false; } bool FileInfo::isDownloaded() const { return downloaded; } void FileInfo::abort() { onTimeout(); } QUrl FileInfo::getFileUrl() const { return fileUrl; } void FileInfo::setFileUrl(const QUrl &value) { fileUrl = value; }
c++
18
0.552386
80
24.734177
237
starcoderdata
using LibrarySystemPro.DataAccessLayer; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace LibrarySystemPro.WebClient.Models { public class Book { private bool isRented; public Book() { this.RentedBooks = new HashSet } public int Id { get; set; } public string Name { get; set; } public string ISBN { get; set; } public Nullable PageCount { get; set; } [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public Nullable PublishingDate { get; set; } public int AuthorId { get; set; } public bool IsDeleted { get; set; } public bool IsRented { get; set; } [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public Nullable DateRented { get; set; } [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public Nullable DateToReturn { get; set; } public Author Author { get; set; } public ICollection RentedBooks { get; set; } } }
c#
12
0.642463
90
29.926829
41
starcoderdata
package ie.gmit.sw; import ie.gmit.sw.view.GameView; /** * Takes a gameView object and starts run method using thread which runs a game. * * @author * */ public class Runner { /** * @param args Returns game screen with specified size and title. */ public static void main(String[] args) { GameView gameView = new GameView("GMIT - B.Sc. in Computing (Software Development)", 1280, 640); gameView.start(); } }
java
10
0.695473
98
22.190476
21
starcoderdata
# -*- coding: utf-8 -*- """Generate a default configuration-file section for fn_pagerduty""" from __future__ import print_function def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[pagerduty] api_token= from_email= # bypass https certificate validation (only set to False for testing purposes) verifyFlag=False """ return config_data
python
6
0.704415
78
25.1
20
starcoderdata
/* * I2C.cpp * * Created: 25-Sep-20 15:31:00 * Author: Davod */ #include "Includes.h" #define SCL_FREQ 100000 #define TWBAUD (F_CPU/(2*SCL_FREQ) - 5) #define CareAck false uint8_t currentChar; RingBuffer wordLength; uint8_t currentWord; bool isTransmitting = false; bool addressDone = false; RingBuffer I2Cbuffer_RX; RingBuffer I2Cbuffer_TX; volatile uint8_t test = 0; //Initialize I2C void I2C_Init(){ //Set pins high because weird bug PORTB.OUTSET = PIN0_bm|PIN1_bm; PORTB.DIRCLR = PIN0_bm|PIN1_bm; //TWI0.CTRLA = TWI_SDAHOLD_50NS_gc; //Set SCL TWI0.MBAUD = TWBAUD; //TWI0_MBAUD = TWBAUD; TWI0.MCTRLB = TWI_FLUSH_bm; //Set master interrupt TWI0.MCTRLA = TWI_WIEN_bm|TWI_ENABLE_bm; //TWI0_MCTRLA = TWI_WIEN_bm|TWI_ENABLE_bm; PORTB.DIRSET = PIN0_bm|PIN1_bm; //Force bus-state to idle TWI0.MSTATUS = TWI_BUSSTATE_IDLE_gc; //TWI0_MSTATUS = TWI_BUSSTATE_IDLE_gc|TWI_WIF_bm; //Set slave address TWI0.SADDR = I2CAddress << 1; //TWI0_SADDR = I2CAddress << 1; //Set slave interrupt TWI0.SCTRLA = TWI_APIEN_bm|TWI_DIEN_bm|TWI_ENABLE_bm; //TWI0_SCTRLA = TWI_DIEN_bm|TWI_SMEN_bm|TWI_ENABLE_bm; } //Read from RX buffer uint8_t ReadI2C(){ return I2Cbuffer_RX.Read(); } //Loads next byte into I2C data register void SendI2C(uint8_t ack){ if (ack) { if (currentWord == 0) { EndTransmission(); return; } else { currentWord--; currentChar = I2Cbuffer_TX.Read(); } } addressDone = true; //Put byte in TWI buffer TWI0.MDATA = currentChar; //TWI0_MDATA = currentChar; I2C_Activity(); } //Indicates that a message has been loaded into TX buffer uint8_t WordReady(uint8_t length){ if (wordLength.Count() >= wordLength.length - 1) { return 1; //Failed, full } wordLength.Write(length); return 0; //Success } //Starts I2C transmission if there is none ongoing void StartTransmission(){ if (!isTransmitting) { if ((TWI0.MSTATUS & 0x03) == TWI_BUSSTATE_BUSY_gc) { return; } TWI0.MADDR = I2CAddress << 1; currentWord = wordLength.Read(); addressDone = false; isTransmitting = true; //SendI2C(1); } } //Stops I2C transmission void EndTransmission(){ TWI0.MCTRLB |= TWI_MCMD_STOP_gc; //TWI0_MCTRLB |= TWI_MCMD_STOP_gc; isTransmitting = false; } //Returns amount of data in RX buffer uint8_t RXCountI2C(){ return I2Cbuffer_RX.Count(); } //Returns how many MIDI messages are loaded in buffers uint8_t WordCountI2C(){ return wordLength.Count(); } //Loads I2C byte into buffer uint8_t TXI2C(uint8_t msg){ if (I2Cbuffer_TX.Count() > I2Cbuffer_TX.length) { return 1; } I2Cbuffer_TX.Write(msg); return 0; } //Slave interrupt ISR(TWI0_TWIS_vect){ if ((TWI0.MSTATUS & 0b11) == TWI_BUSSTATE_OWNER_gc) { //Self-triggered volatile uint8_t wat = 4; //TWI hangs without this TWI0.SSTATUS = TWI_DIF_bm|TWI_APIF_bm; //TWI0.SCTRLB = TWI_ACKACT_ACK_gc|TWI_SCMD_NOACT_gc; return; } TWI0.SCTRLB = TWI_ACKACT_ACK_gc|TWI_SCMD_RESPONSE_gc; if (TWI0.SSTATUS & TWI_DIF_bm) { I2Cbuffer_RX.Write(TWI0.SDATA); } } //Master interrupt ISR(TWI0_TWIM_vect){ //I2C_Activity(); uint8_t status = TWI0.MSTATUS; //uint8_t status = TWI0_MSTATUS; if ((status & TWI_ARBLOST_bm)) { //Lost arbitration, resend if (addressDone) { SendI2C(0); } //Clear arblost flag TWI0.MSTATUS |= TWI_ARBLOST_bm; //TWI0_MSTATUS |= TWI_ARBLOST_bm; } else if ((status & TWI_RXACK_bm) || !CareAck) { //ack SendI2C(1); } else { //No ack SendI2C(0); } }
c++
12
0.664288
57
17.638298
188
starcoderdata
<?php namespace Zf1Module\Listener; use Zend\EventManager\AbstractListenerAggregate; use Zend\EventManager\EventManagerInterface; use Zend\Mvc\MvcEvent; use Zend\Mvc\Router\RouteMatch; use Zend\Mvc\Application as Zf2Application; class DispatchListener extends AbstractListenerAggregate { public function attach(EventManagerInterface $events) { $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'onDispatchError'), 1000); } public function onDispatchError(MvcEvent $e) { if ($e->getError() !== Zf2Application::ERROR_ROUTER_NO_MATCH) { return; } $routeMatch = new RouteMatch(array()); $routeMatch->setParam('controller', 'Zf1Module\DispatchController'); $e->setError(null); $e->setRouteMatch($routeMatch); return $routeMatch; } }
php
13
0.687428
116
26.09375
32
starcoderdata
private void SaveAs() { // Save documents Document data as. SaveFileDialog SFD = new SaveFileDialog(); SFD.Filter = "All text files|*.txt"; if (SFD.ShowDialog() == DialogResult.OK) { File.WriteAllText(SFD.FileName, richTextBox1.Text); } }
c#
11
0.497143
66
33.2
10
inline
#ifndef RUNLENGTH_ANALYSIS_BINARYIO_CPP_H #define RUNLENGTH_ANALYSIS_BINARYIO_CPP_H #include "BinaryIO.hpp" void writeStringToBinary(ostream& file, string& s){ /// /// Without worrying about size conversions, write any string to a file using ostream.write /// file.write(reinterpret_cast<const char*>(s.data()), s.size()); } void readStringFromBinary(istream& file, string& s, uint64_t length){ /// /// Without worrying about size conversions, read any value to a file using ostream.write /// s.resize(length); file.read(reinterpret_cast length); } void preadBytes(int fileDescriptor, char* bufferPointer, size_t bytesToRead, off_t& byteIndex){ /// /// Reimplementation of binary readBytes(), but with Linux pread, which is threadsafe /// while (bytesToRead) { const ssize_t byteCount = ::pread(fileDescriptor, bufferPointer, bytesToRead, byteIndex); if (byteCount <= 0) { throw runtime_error("ERROR " + std::to_string(errno) + " while reading: " + string(::strerror(errno))); } bytesToRead -= byteCount; bufferPointer += byteCount; byteIndex += byteCount; } } void preadStringFromBinary(int fileDescriptor, string& s, uint64_t length, off_t& byteIndex){ /// /// Reimplementation of binary readStringFromBinary(), but with Linux pread, which is threadsafe /// s.resize(length); size_t bytesToRead = length; char* bufferPointer = reinterpret_cast preadBytes(fileDescriptor, bufferPointer, bytesToRead, byteIndex); } #endif //RUNLENGTH_ANALYSIS_BINARYIO_CPP_H
c++
16
0.672529
115
27.929825
57
starcoderdata
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/util/cloud/instance_metadata.h" #include #include #include #include #include #include #include "kudu/gutil/macros.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/util/curl_util.h" #include "kudu/util/faststring.h" #include "kudu/util/flag_tags.h" #include "kudu/util/monotime.h" #include "kudu/util/status.h" // The timeout should be high enough to work effectively, but as low as possible // to avoid slowing down detection of running in non-cloud environments. As of // now, the metadata servers of major public cloud providers are robust enough // to send the response in a fraction of a second. DEFINE_uint32(cloud_metadata_server_request_timeout_ms, 1000, "Timeout for HTTP/HTTPS requests to the instance metadata server " "(in milliseconds)"); TAG_FLAG(cloud_metadata_server_request_timeout_ms, advanced); TAG_FLAG(cloud_metadata_server_request_timeout_ms, runtime); // The flags below are very unlikely to be customized since they are a part // of the public API provided by the cloud providers. They are here for // the peace of mind to be able to adapt for the changes in the cloud // environment without the need to recompile the binaries. // See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/\ // ec2-instance-metadata.html#instancedata-data-retrieval // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/\ // ec2-instance-metadata.html#instancedata-data-categories DEFINE_string(cloud_aws_instance_id_url, "http://169.254.169.254/latest/meta-data/instance-id", "The URL to fetch the identifier of an AWS instance"); TAG_FLAG(cloud_aws_instance_id_url, advanced); TAG_FLAG(cloud_aws_instance_id_url, runtime); // See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html // for details. DEFINE_string(cloud_aws_ntp_server, "169.254.169.123", "IP address/FQDN of the internal NTP server to use from within " "an AWS instance"); TAG_FLAG(cloud_aws_ntp_server, advanced); TAG_FLAG(cloud_aws_ntp_server, runtime); // See https://docs.microsoft.com/en-us/azure/virtual-machines/linux/ \ // instance-metadata-service#retrieving-metadata for details. DEFINE_string(cloud_azure_instance_id_url, "http://169.254.169.254/metadata/instance/compute/vmId?" "api-version=2018-10-01&format=text", "The URL to fetch the identifier of an Azure instance"); TAG_FLAG(cloud_azure_instance_id_url, advanced); TAG_FLAG(cloud_azure_instance_id_url, runtime); // See https://cloud.google.com/compute/docs/instances/managing-instances# \ // configure_ntp_for_your_instances for details. DEFINE_string(cloud_gce_ntp_server, "metadata.google.internal", "IP address/FQDN of the internal NTP server to use from within " "a GCE instance"); TAG_FLAG(cloud_gce_ntp_server, advanced); TAG_FLAG(cloud_gce_ntp_server, runtime); // See https://cloud.google.com/compute/docs/storing-retrieving-metadata // for details. DEFINE_string(cloud_gce_instance_id_url, "http://metadata.google.internal/computeMetadata/v1/instance/id", "The URL to fetch the identifier of a GCE instance"); TAG_FLAG(cloud_gce_instance_id_url, advanced); TAG_FLAG(cloud_gce_instance_id_url, runtime); // See https://docs.openstack.org/nova/latest/user/metadata.html#metadata-service // and https://docs.openstack.org/nova/latest/user/metadata.html#metadata-openstack-format // for details. DEFINE_string(cloud_openstack_metadata_url, "http://1172.16.58.354/openstack/latest/meta_data.json", "The URL to fetch metadata of an OpenStack instance via Nova " "metadata service. OpenStack Nova metadata server does not " "provide a separate URL to fetch instance UUID, at least with " "12.0.0 (Liberty) release."); TAG_FLAG(cloud_openstack_metadata_url, advanced); TAG_FLAG(cloud_openstack_metadata_url, runtime); DEFINE_string(cloud_curl_dns_servers_for_testing, "", "Set the list of DNS servers to be used instead of the system default."); TAG_FLAG(cloud_curl_dns_servers_for_testing, hidden); TAG_FLAG(cloud_curl_dns_servers_for_testing, runtime); DEFINE_validator(cloud_metadata_server_request_timeout_ms, [](const char* name, const uint32_t val) { if (val == 0) { LOG(ERROR) << strings::Substitute( "unlimited timeout for metadata requests (value $0 for flag --$1) " "is not allowed", val, name); return false; } return true; }); using std::string; using std::vector; namespace kudu { namespace cloud { const char* TypeToString(CloudType type) { static const char* const kTypeAws = "AWS"; static const char* const kTypeAzure = "Azure"; static const char* const kTypeGce = "GCE"; static const char* const kTypeOpenStack = "OpenStack"; switch (type) { case CloudType::AWS: return kTypeAws; case CloudType::AZURE: return kTypeAzure; case CloudType::GCE: return kTypeGce; case CloudType::OPENSTACK: return kTypeOpenStack; default: LOG(FATAL) << static_cast << ": unknown cloud type"; break; // unreachable } } InstanceMetadata::InstanceMetadata() : is_initialized_(false) { } Status InstanceMetadata::Init() { // As of now, fetching the instance identifier from metadata service is // the criterion for successful initialization of the instance metadata. DCHECK(!is_initialized_); RETURN_NOT_OK(Fetch(instance_id_url(), request_timeout(), request_headers())); is_initialized_ = true; return Status::OK(); } MonoDelta InstanceMetadata::request_timeout() const { return MonoDelta::FromMilliseconds( FLAGS_cloud_metadata_server_request_timeout_ms); } Status InstanceMetadata::Fetch(const string& url, MonoDelta timeout, const vector headers, string* out) { if (timeout.ToMilliseconds() == 0) { return Status::NotSupported( "unlimited timeout is not supported when retrieving instance metadata"); } EasyCurl curl; curl.set_timeout(timeout); curl.set_fail_on_http_error(true); if (PREDICT_FALSE(!FLAGS_cloud_curl_dns_servers_for_testing.empty())) { curl.set_dns_servers(FLAGS_cloud_curl_dns_servers_for_testing); } faststring resp; RETURN_NOT_OK(curl.FetchURL(url, &resp, headers)); if (out) { *out = resp.ToString(); } return Status::OK(); } Status AwsInstanceMetadata::Init() { // Try if the metadata server speaks AWS API. RETURN_NOT_OK(InstanceMetadata::Init()); // If OpenStack instance metadata server is configured to emulate EC2, // one way to tell it apart from a true EC2 instance is to check whether it // speaks OpenStack API: // https://docs.openstack.org/nova/latest/user/metadata.html#metadata-ec2-format OpenStackInstanceMetadata openstack; if (openstack.Init().ok()) { return Status::ServiceUnavailable("found OpenStack instance, not AWS one"); } return Status::OK(); } Status AwsInstanceMetadata::GetNtpServer(string* server) const { DCHECK(server); *server = FLAGS_cloud_aws_ntp_server; return Status::OK(); } const vector AwsInstanceMetadata::request_headers() const { // EC2 doesn't require any specific headers supplied with a generic query // to the metadata server. static const vector kRequestHeaders = {}; return kRequestHeaders; } const string& AwsInstanceMetadata::instance_id_url() const { return FLAGS_cloud_aws_instance_id_url; } Status AzureInstanceMetadata::GetNtpServer(string* /* server */) const { // An Azure instance doesn't have access to dedicated NTP servers: Azure // doesn't provide such a service. return Status::NotSupported("Azure doesn't provide a dedicated NTP server"); } const vector AzureInstanceMetadata::request_headers() const { static const vector kRequestHeaders = { "Metadata:true" }; return kRequestHeaders; } const string& AzureInstanceMetadata::instance_id_url() const { return FLAGS_cloud_azure_instance_id_url; } Status GceInstanceMetadata::GetNtpServer(string* server) const { DCHECK(server); *server = FLAGS_cloud_gce_ntp_server; return Status::OK(); } const vector GceInstanceMetadata::request_headers() const { static const vector kHeaders = { "Metadata-Flavor:Google" }; return kHeaders; } const string& GceInstanceMetadata::instance_id_url() const { return FLAGS_cloud_gce_instance_id_url; } Status OpenStackInstanceMetadata::GetNtpServer(string* /* server */) const { // OpenStack doesn't provide a dedicated NTP server for an instance. return Status::NotSupported("OpenStack doesn't provide a dedicated NTP server"); } const vector OpenStackInstanceMetadata::request_headers() const { // OpenStack Nova doesn't require any specific headers supplied with a // generic query to the metadata server. static const vector kRequestHeaders = {}; return kRequestHeaders; } const string& OpenStackInstanceMetadata::instance_id_url() const { // NOTE: OpenStack Nova metadata server doesn't provide a separate URL to // fetch ID of an instance (at least with 1.12.0 release): // https://docs.openstack.org/nova/latest/user/metadata.html#metadata-openstack-format return FLAGS_cloud_openstack_metadata_url; } } // namespace cloud } // namespace kudu
c++
17
0.714506
90
36.952381
273
starcoderdata
#include "Title.h" #include "GamePad.h" #include "AssetDefine.h" #include "AudioManager.h" #include "UICanvas.h" CTitle::CTitle(const CTitle::InitData & data) : super(data) { if (!CTextureAsset::Load(TextureKey::TitleBack, "TitleBack.png")) { MOF_PRINTLOG("failed to load texture"); } if (!CTextureAsset::Load(TextureKey::TitleName, "title.png")) { MOF_PRINTLOG("failed to load texture"); } m_pTexture = TextureAsset(TextureKey::TitleBack); m_pTitleNameTexture = TextureAsset(TextureKey::TitleName); m_Scroll = 0; CAudioManager::Singleton().Play(SoundStreamBufferKey::title); CUICanvas::Singleton().GetFont().SetSize(50); } CTitle::~CTitle(void) { } void CTitle::Update(void) { m_Scroll += SCROLL_SPEED; if (g_pPad->IsKeyPush(XInputButton::XINPUT_A)) { CAudioManager::Singleton().Play(SoundBufferKey::ok_se); ChangeScene(SceneName::Game); } } void CTitle::Render(void) { if (auto r = m_pTexture.lock()) { int h = r->GetHeight(); float ratio = g_pGraphics->GetTargetWidth() / (float)r->GetWidth(); float w = (g_pGraphics->GetTargetWidth() - r->GetWidth() * ratio) * 0.5f; int sch = g_pGraphics->GetTargetHeight(); for (float y = ((int)m_Scroll % h) - h; y < sch; y += h) { r->RenderScale(w, y, ratio, 1.0f); } } if (auto r = m_pTitleNameTexture.lock()) { r->Render(460, 200); } CFont& font = CUICanvas::Singleton().GetFont(); CRectangle fontRect; font.CalculateStringRect(0, 0, "ボタンでスタート!", fontRect); CCircle buttonCircle(0, 0, 32); float rw = (buttonCircle.r + fontRect.GetWidth()); buttonCircle.Position = Vector2((g_pGraphics->GetTargetWidth() - rw) * 0.5f, g_pGraphics->GetTargetHeight() * 0.6f); Vector2 renderPos(buttonCircle.x, buttonCircle.y); renderPos.x += buttonCircle.r; renderPos.y -= buttonCircle.r * 0.6f; CGraphicsUtilities::RenderFillCircle(buttonCircle, MOF_COLOR_BLACK); buttonCircle.r -= 3; CGraphicsUtilities::RenderFillCircle(buttonCircle, MOF_COLOR_GREEN); font.CalculateStringRect(0, 0, "A", fontRect); font.RenderString(buttonCircle.x - fontRect.GetWidth() * 0.5f, renderPos.y, MOF_COLOR_BLACK, "A"); font.RenderString(renderPos.x, renderPos.y, MOF_COLOR_WHITE, "ボタンでスタート!"); buttonCircle.y += fontRect.GetHeight() + 30; renderPos = Vector2(buttonCircle.x, buttonCircle.y); renderPos.x += buttonCircle.r; renderPos.y -= buttonCircle.r * 0.6f; CGraphicsUtilities::RenderFillCircle(buttonCircle, MOF_COLOR_BLACK); buttonCircle.r -= 3; CGraphicsUtilities::RenderFillCircle(buttonCircle, MOF_COLOR_CWHITE); CGraphicsUtilities::RenderFillTriangle( Vector2(buttonCircle.x + 10, buttonCircle.y - 10), Vector2(buttonCircle.x + 10, buttonCircle.y + 10), Vector2(buttonCircle.x - 10, buttonCircle.y ), MOF_COLOR_BLACK, MOF_COLOR_BLACK, MOF_COLOR_BLACK ); font.RenderString(renderPos.x, renderPos.y, MOF_COLOR_WHITE, "ボタンで終了!"); }
c++
13
0.708577
117
30.215054
93
starcoderdata
package com.our.news.admin.test; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * @author ljs * @time 2018-11-01 */ @Controller @RequestMapping("/excel") public class ExcelController { @Autowired private ExcelImpl excelImpl; @RequestMapping(value="/down_excel") public @ResponseBody String dowm(HttpServletResponse response,String name){ response.setContentType("application/binary;charset=UTF-8"); try{ ServletOutputStream out=response.getOutputStream(); try { //设置文件头:最后一个参数是设置下载文件名(这里我们叫:张三.pdf) response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name+".xls", "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String[] titles; if(name.equals("user")){ titles = new String[]{ "用户id", "用户姓名", "用户密码","用户电话","用户邮箱","创建时间","更新时间","状态"}; excelImpl.exportUser(titles, out); }else{ titles = new String[]{ "新闻id", "新闻标题","作者","新闻内容","创建时间","更新时间","类型"}; excelImpl.exportNews(titles, out); } return "success"; } catch(Exception e){ e.printStackTrace(); return "导出信息失败"; } } @RequestMapping("/user") public String upUser(@RequestParam("file") CommonsMultipartFile file){ try { Workbook workbook = new HSSFWorkbook(file.getInputStream()); excelImpl.upUsers(workbook); } catch (IOException e) { e.printStackTrace(); } return "redirect:/user/list"; } @RequestMapping("/new") public String upNews(@RequestParam("file") CommonsMultipartFile file){ try { Workbook workbook = new HSSFWorkbook(file.getInputStream()); excelImpl.upNews(workbook); } catch (IOException e) { e.printStackTrace(); } return "redirect:/content/news/list"; } }
java
15
0.647948
124
35.077922
77
starcoderdata
from .rouge_prop import RougeProp from .len_prop import LenProp from .rating_prop import RatingProp from .pov_prop import POVProp from .summ_prop import SummProp from .summ_eval_rouge_prop import SummEvalRougeKnob from .summ_len_prop import SummLenProp from .summ_eval_pov_prop import SummEvalPOVProp from .dummy_prop import DummyProp from .summ_rouge_prop import SummRougeProp from .summ_eval_len_prop import SummEvalLenProp
python
4
0.826291
51
37.727273
11
starcoderdata
from google.cloud import texttospeech import os import argparse #parser.add_argument('--cred', help='google application credentials json file', default="/home/pi/google_app_cred.json") os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/home/pi/google_app_cred.json" def list_voices(language_code=None): client = texttospeech.TextToSpeechClient() response = client.list_voices(language_code=language_code) voices = sorted(response.voices, key=lambda voice: voice.name) print(f" Voices: {len(voices)} ".center(60, "-")) for voice in voices: languages = ", ".join(voice.language_codes) name = voice.name gender = texttospeech.SsmlVoiceGender(voice.ssml_gender).name rate = voice.natural_sample_rate_hertz print(f"{languages:<8} | {name:<24} | {gender:<8} | {rate:,} Hz") def text_to_wav(voice_name, text): language_code = "-".join(voice_name.split("-")[:2]) text_input = texttospeech.SynthesisInput(text=text) voice_params = texttospeech.VoiceSelectionParams( language_code=language_code, name=voice_name ) audio_config = texttospeech.AudioConfig( audio_encoding=texttospeech.AudioEncoding.LINEAR16 ) client = texttospeech.TextToSpeechClient() response = client.synthesize_speech( input=text_input, voice=voice_params, audio_config=audio_config ) filename = f"/tmp/tts.wav" with open(filename, "wb") as out: out.write(response.audio_content) print(f'Audio content written to "{filename}"') def speak(message, audioOutputNumber): text_to_wav("en-US-Wavenet-D", message) os.system("ffmpeg -y -i /tmp/tts.wav -ac 2 -ar 48000 /tmp/tts2.wav;aplay /tmp/tts2.wav --device=hw:%d,0" % audioOutputNumber) #list_voices() if __name__ == "__main__": # execute only if run as a script speak("hello I am a robot", 1)
python
12
0.678325
129
33.944444
54
starcoderdata
private static CSharpType MakeCSharpType(GLBaseType glType, string group, string className) => glType.Type switch { // C# primitive types GLPrimitiveType.Void => new CSharpVoid(glType), GLPrimitiveType.Byte => new CSharpPrimitive(glType, "byte"), GLPrimitiveType.Sbyte => new CSharpPrimitive(glType, "sbyte"), GLPrimitiveType.Short => new CSharpPrimitive(glType, "short"), GLPrimitiveType.Ushort => new CSharpPrimitive(glType, "ushort"), GLPrimitiveType.Int => new CSharpPrimitive(glType, "int"), GLPrimitiveType.Uint => new CSharpPrimitive(glType, "uint"), GLPrimitiveType.Long => new CSharpPrimitive(glType, "long"), GLPrimitiveType.Ulong => new CSharpPrimitive(glType, "ulong"), GLPrimitiveType.Half => new CSharpPrimitive(glType, "Half"), // This is System.Half since .NET 5, but does not have yet a keyword (such as float or double) GLPrimitiveType.Float => new CSharpPrimitive(glType, "float"), GLPrimitiveType.Double => new CSharpPrimitive(glType, "double"), // C interop types GLPrimitiveType.Bool8 => new CSharpBool8(glType), GLPrimitiveType.Char8 => new CSharpChar8(glType), // Enum GLPrimitiveType.Enum => new CSharpEnum(glType, group), // Pointers GLPrimitiveType.IntPtr => new CSharpPrimitive(glType, "nint"), GLPrimitiveType.Nint => new CSharpPrimitive(glType, "nint"), GLPrimitiveType.VoidPtr => MakeVoidPtrCSharpType(glType), // FIXME: Output the GLHandleARB again... GLPrimitiveType.GLHandleARB => new CSharpStruct(glType, "GLHandleARB", new CSharpPrimitive(glType, "nint")), GLPrimitiveType.GLSync => new CSharpStruct(glType, "GLSync", new CSharpPrimitive(glType, "nint")), // OpenCL structs GLPrimitiveType.CLContext => new CSharpStruct(glType, "CLContext", new CSharpPrimitive(glType, "nint")), GLPrimitiveType.CLEvent => new CSharpStruct(glType, "CLEvent", new CSharpPrimitive(glType, "nint")), // Function pointer types GLPrimitiveType.GLDebugProc => new CSharpFunctionPointer(glType, "GLDebugProc"), GLPrimitiveType.GLDebugProcARB => new CSharpFunctionPointer(glType, "GLDebugProcARB"), GLPrimitiveType.GLDebugProcKHR => new CSharpFunctionPointer(glType, "GLDebugProcKHR"), GLPrimitiveType.GLDebugProcAMD => new CSharpFunctionPointer(glType, "GLDebugProcAMD"), GLPrimitiveType.GLDebugProcNV => new CSharpFunctionPointer(glType, "GLDebugProcNV"), GLPrimitiveType.GLVulkanProcNV => new CSharpFunctionPointer(glType, "GLVulkanProcNV"), GLPrimitiveType.Invalid => throw new Exception(), _ => throw new NotSupportedException($"Primitive Type {glType.Type} is invalid"), };
c#
13
0.661481
167
61.93617
47
inline
// XibFree - http://www.toptensoftware.com/xibfree/ // // Copyright 2013 Copyright © 2013 Topten Software. All Rights Reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using CoreGraphics; using UIKit; namespace XibFree { internal static class Extensions { /// /// Applies a set of UIEdgeInsets to a RectangleF /// /// adjusted rectangle /// <param name="rect">The rectangle to be adjusted. /// <param name="insets">The edge insets to be applied public static CGRect ApplyInsets(this CGRect rect, UIEdgeInsets insets) { return new CGRect(rect.Left + insets.Left, rect.Top + insets.Top, rect.Width - insets.TotalWidth(), rect.Height- insets.TotalHeight()); } public static nfloat TotalWidth(this UIEdgeInsets insets) { return insets.Left + insets.Right; } public static nfloat TotalHeight(this UIEdgeInsets insets) { return insets.Top + insets.Bottom; } public static CGRect ApplyGravity(this CGRect bounds, CGSize size, Gravity g) { nfloat left; switch (g & Gravity.HorizontalMask) { default: left = bounds.Left; break; case Gravity.Right: left = bounds.Right - size.Width; break; case Gravity.CenterHorizontal: left = (bounds.Left + bounds.Right - size.Width)/2; break; } nfloat top; switch (g & Gravity.VerticalMask) { default: top = bounds.Top; break; case Gravity.Bottom: top = bounds.Bottom - size.Height; break; case Gravity.CenterVertical: top = (bounds.Top + bounds.Bottom - size.Height)/2; break; } return new CGRect(left, top, size.Width, size.Height); } } }
c#
17
0.679204
138
25.904762
84
starcoderdata
var app = new Vue({ el: '#app', data: { selectedExpansions: [], playerTextEntry : "2", randomPlayerFactions: [], expansions: [], factions: [], }, created: function() { this.getExpansions(); this.getFactions(); this.getLatest(); }, computed: { players: function(){ return parseInt(this.playerTextEntry); }, selectedFactions: function(){ let count = 0; this.factions.forEach( element => { if (element.selected){ count++; } }); return count; } }, methods: { selectExpansion: function(expansionName){ axios.put("/api/expansions", {expansion: expansionName }).then(response => { this.getExpansions(); this.getFactions(); }); }, selectFaction: function (factionName) { axios.put("/api/factions", {faction: factionName}).then(response => { this.getExpansions(); this.getFactions(); }); }, randomizeFactions: function() { if (isNaN(this.players) || this.players < 1){ alert("Please choose a valid number of players"); return; } axios.get('/api/factions/random/' + this.players).then(response => { this.randomPlayerFactions = response.data; }); }, getExpansions: function(){ axios.get("/api/expansions").then(response => { this.expansions = response.data;}); }, getFactions: function(){ axios.get("/api/factions/selected").then(response => { this.factions = response.data;}); }, getLatest: function() { axios.get('/api/factions/random/latest').then(response => { this.randomPlayerFactions = response.data; }); } }, watch: {}, });
javascript
20
0.476879
89
28.239437
71
starcoderdata
const { web3 } = window $(document).ready(function() { async function itemUploadButton() { if (window.ethereum) try { await window.ethereum.enable(); } catch (err) { return showError("Access to your Ethereum account rejected."); } if (typeof web3 === 'undefined') return showError("Please install MetaMask to access the Ethereum Web3 injected API from your Web browser."); const selectedAddress = web3.eth.defaultAccount console.log("selectedAddress: " , selectedAddress); } itemUploadButton(); });
javascript
16
0.649826
124
18.793103
29
starcoderdata
private void enableSyncPreferences(final String[] accountsForLogin, final String currentAccountName) { if (!ProductionFlags.ENABLE_USER_HISTORY_DICTIONARY_SYNC) { return; } mAccountSwitcher.setEnabled(true); mEnableSyncPreference.setEnabled(true); mEnableSyncPreference.setOnPreferenceClickListener(mEnableSyncClickListener); mSyncNowPreference.setEnabled(true); mSyncNowPreference.setOnPreferenceClickListener(mSyncNowListener); mClearSyncDataPreference.setEnabled(true); mClearSyncDataPreference.setOnPreferenceClickListener(mDeleteSyncDataListener); if (currentAccountName != null) { mAccountSwitcher.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { if (accountsForLogin.length > 0) { // TODO: Add addition of account. createAccountPicker(accountsForLogin, getSignedInAccountName(), new AccountChangedListener(null)).show(); } return true; } }); } }
java
20
0.625
91
41.433333
30
inline
#ifndef MATHS_H #define MATHS_H #include #include double degreesToRadians(double degrees); double radiansToDegrees(double radians); int mod(int value, int mod); double doubleAbs(double value); double doubleMod(double value, double maxValue); double doubleMax(double v1, double v2); #endif
c
6
0.776358
48
21.357143
14
starcoderdata
/* * Copyright 2017 AT&T * * 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 com.att.aro.datacollector.ioscollector.reader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; import com.att.aro.core.util.Util; import com.att.aro.datacollector.ioscollector.IExternalProcessReaderSubscriber; import com.att.aro.datacollector.ioscollector.IOSDeviceStatus; public class ExternalDeviceMonitorIOS extends Thread implements IExternalProcessReaderSubscriber { private static final Logger LOG = LogManager.getLogger(ExternalDeviceMonitorIOS.class); Process proc = null; String exepath; ExternalProcessReader procreader; int pid = 0; ExternalProcessRunner runner; volatile boolean shutdownSignal = false; List subscribers; public ExternalDeviceMonitorIOS() { this.runner = new ExternalProcessRunner(); init(); } public ExternalDeviceMonitorIOS(ExternalProcessRunner runner) { this.runner = runner; init(); } void init() { subscribers = new ArrayList exepath = Util.getVideoOptimizerLibrary() + Util.FILE_SEPARATOR + ".drivers" + Util.FILE_SEPARATOR + "libimobiledevice" + Util.FILE_SEPARATOR + "idevicesyslog_aro"; clearExe(); } public void clearExe() { try { String[] cmd = {"bash", "-c", "fuser -f "+exepath+"|xargs kill"}; runner.runCmd(cmd); } catch (IOException e) { LOG.error("IOException", e); } } public void subscribe(IOSDeviceStatus subscriber) { this.subscribers.add(subscriber); } @Override public void run() { String[] cmds = new String[] { "bash", "-c", this.exepath }; ProcessBuilder builder = new ProcessBuilder(cmds); builder.redirectErrorStream(true); try { proc = builder.start(); } catch (IOException e) { LOG.error("IOException :", e); return; } procreader = new ExternalProcessReader(proc.getInputStream()); procreader.addSubscriber(ExternalDeviceMonitorIOS.this); procreader.start(); setPid(exepath); try { proc.waitFor(); } catch (InterruptedException e) { LOG.warn("Thread interrupted", e); } } /** * locate first instance of theExec process and set the pid value in this.pid * * @param theExec */ private void setPid(String theExec) { String response = null; try { String cmd = "fuser -f " + theExec; response = runner.runCmd(cmd); String[] pids = response.trim().split("\\s+"); if (pids.length > 0 && !"".equals(pids[0])) { pid = Integer.parseInt(pids[0]); } } catch (IOException | NumberFormatException e) { LOG.error("IOException | NumberFormatException ", e); } } /** * signals pid process to */ public void stopMonitoring() { if (pid > 0) { this.shutdownSignal = false; try { Runtime.getRuntime().exec("kill -SIGINT " + pid); LOG.info("kill device monitor process pid: " + pid); } catch (IOException e) { LOG.error("IOException :", e); } int count = 0; while (!shutdownSignal && count < 10) { try { Thread.sleep(500); } catch (InterruptedException e) { break; } count++; } } } /** * stop everything and exit */ public void shutDown() { if (procreader != null) { procreader.interrupt(); procreader = null; proc.destroy(); } this.shutdownSignal = true; } @Override public void newMessage(String message) { if (message.equals("[connected]")) { LOG.info("Device connected"); notifyConnected(); } else if (message.equals("[disconnected]")) { LOG.info("Device disconnected"); notifyDisconnected(); } } @Override public void willExit() { this.shutDown(); } void notifyDisconnected() { for (IOSDeviceStatus sub : subscribers) { sub.onDisconnected(); } } void notifyConnected() { for (IOSDeviceStatus sub : subscribers) { sub.onConnected(); } } }
java
15
0.689376
131
23.945355
183
starcoderdata
//Header file of the characters #ifndef CHAR_H_INCLUDED #define CHAR_H_INCLUDED struct hero{ int orientation; int moveWithMouse; SDL_Surface *image; SDL_Rect position; SDL_Rect positionRelative; SDL_Rect clipsRight[20]; SDL_Rect clipsLeft[20]; int step; int vel; int frame; int status; }; typedef struct{ SDL_Surface *image; SDL_Rect position; SDL_Rect positionRelative; int state; }object; struct projectile{ SDL_Rect position; SDL_Rect where; SDL_Rect positionRelative; SDL_Surface* image; int active; int axe; }; typedef struct projectile projectile; typedef struct hero hero; #endif
c
7
0.696049
37
13.714286
42
starcoderdata
package updater import ( "testing" "github.com/stretchr/testify/assert" ) // gpg -u 0x2F752B2CA00248FC --armor --output testdata.sig --detach-sign testdata var testSignature = []byte(` -----BEGIN PGP SIGNATURE----- -----END PGP SIGNATURE----- `) var testData = []byte(`gosecret-sign-test `) func TestGPGVerify(t *testing.T) { ok, err := gpgVerify(testData, testSignature) assert.NoError(t, err) assert.True(t, ok) }
go
7
0.683603
81
17.041667
24
starcoderdata
/**************************************************************************//** * @file adc.c * @version V1.00 * $Revision: 13 $ * $Date: 14/05/29 1:13p $ * @brief NUC472/NUC442 ADC driver source file * * @note * Copyright (C) 2013 Nuvoton Technology Corp. All rights reserved. *****************************************************************************/ #include "NUC472_442.h" /** @addtogroup NUC472_442_Device_Driver NUC472/NUC442 Device Driver @{ */ /** @addtogroup NUC472_442_ADC_Driver ADC Driver @{ */ /** @addtogroup NUC472_442_ADC_EXPORTED_FUNCTIONS ADC Exported Functions @{ */ /** * @brief This API configures ADC module to be ready for convert the input from selected channel * @param[in] adc Base address of ADC module * @param[in] u32InputMode Input mode (single-end/differential). Valid values are: * - \ref ADC_INPUT_MODE_SINGLE_END * - \ref ADC_INPUT_MODE_DIFFERENTIAL * @param[in] u32OpMode Operation mode (single/single cycle/continuous). Valid values are: * - \ref ADC_OPERATION_MODE_SINGLE * - \ref ADC_OPERATION_MODE_SINGLE_CYCLE * - \ref ADC_OPERATION_MODE_CONTINUOUS * @param[in] u32ChMask Channel enable bit. Valid values are: * - \ref ADC_CH_0_MASK * - \ref ADC_CH_1_MASK * - \ref ADC_CH_2_MASK * - \ref ADC_CH_3_MASK * - \ref ADC_CH_4_MASK * - \ref ADC_CH_5_MASK * - \ref ADC_CH_6_MASK * - \ref ADC_CH_7_MASK * - \ref ADC_CH_8_MASK * - \ref ADC_CH_9_MASK * - \ref ADC_CH_10_MASK * - \ref ADC_CH_11_MASK * - \ref ADC_CH_TS_MASK * - \ref ADC_CH_BG_MASK * @return None * @note This API does not turn on ADC power nor does trigger ADC conversion */ void ADC_Open(ADC_T *adc, uint32_t u32InputMode, uint32_t u32OpMode, uint32_t u32ChMask) { ADC->CTL |= u32InputMode; ADC->CTL |= u32OpMode; ADC->CHEN = (ADC->CHEN & ~(ADC_CHEN_CHEN_Msk | ADC_CHEN_ADBGEN_Msk | ADC_CHEN_ADTSEN_Msk)) | u32ChMask; return; } /** * @brief Disable ADC module * @param[in] adc Base address of ADC module * @return None */ void ADC_Close(ADC_T *adc) { SYS->IPRST1 |= SYS_IPRST1_ADCRST_Msk; SYS->IPRST1 &= ~SYS_IPRST1_ADCRST_Msk; return; } /** * @brief Configure the hardware trigger condition and enable hardware trigger * @param[in] adc Base address of ADC module * @param[in] u32Source Decides the hardware trigger source. Valid values are: * - \ref ADC_TRIGGER_BY_EXT_PIN * - \ref ADC_TRIGGER_BY_PWM * @param[in] u32Param While ADC trigger by PWM, this parameter is used to set the delay between PWM * trigger and ADC conversion. Valid values are from 0 ~ 0xFF, and actual delay * time is (4 * u32Param * HCLK). While ADC trigger by external pin, this parameter * is used to set trigger condition. Valid values are: * - \ref ADC_LOW_LEVEL_TRIGGER * - \ref ADC_HIGH_LEVEL_TRIGGER * - \ref ADC_FALLING_EDGE_TRIGGER * - \ref ADC_RISING_EDGE_TRIGGER * @return None */ void ADC_EnableHWTrigger(ADC_T *adc, uint32_t u32Source, uint32_t u32Param) { ADC->CTL &= ~(ADC_TRIGGER_BY_PWM | ADC_RISING_EDGE_TRIGGER | ADC_CTL_HWTRGEN_Msk); if(u32Source == ADC_TRIGGER_BY_EXT_PIN) { ADC->CTL &= ~(ADC_CTL_HWTRGSEL_Msk | ADC_CTL_HWTRGCOND_Msk); ADC->CTL |= u32Source | u32Param | ADC_CTL_HWTRGEN_Msk; } else { ADC->CTL &= ~(ADC_CTL_HWTRGSEL_Msk | ADC_CTL_PWMTRGDLY_Msk); ADC->CTL |= u32Source | (u32Param << ADC_CTL_PWMTRGDLY_Pos) | ADC_CTL_HWTRGEN_Msk; } return; } /** * @brief Disable hardware trigger ADC function. * @param[in] adc Base address of ADC module * @return None */ void ADC_DisableHWTrigger(ADC_T *adc) { ADC->CTL &= ~(ADC_TRIGGER_BY_PWM | ADC_RISING_EDGE_TRIGGER | ADC_CTL_HWTRGEN_Msk); return; } /** * @brief Enable the interrupt(s) selected by u32Mask parameter. * @param[in] adc Base address of ADC module * @param[in] u32Mask The combination of interrupt status bits listed below. Each bit * corresponds to a interrupt status. This parameter decides which * interrupts will be enabled. * - \ref ADC_ADF_INT * - \ref ADC_CMP0_INT * - \ref ADC_CMP1_INT * @return None */ void ADC_EnableInt(ADC_T *adc, uint32_t u32Mask) { if(u32Mask & ADC_ADF_INT) ADC->CTL |= ADC_CTL_ADCIEN_Msk; if(u32Mask & ADC_CMP0_INT) ADC->CMP[0] |= ADC_CMP0_ADCMPIE_Msk; if(u32Mask & ADC_CMP1_INT) ADC->CMP[1] |= ADC_CMP1_ADCMPIE_Msk; return; } /** * @brief Disable the interrupt(s) selected by u32Mask parameter. * @param[in] adc Base address of ADC module * @param[in] u32Mask The combination of interrupt status bits listed below. Each bit * corresponds to a interrupt status. This parameter decides which * interrupts will be disabled. * - \ref ADC_ADF_INT * - \ref ADC_CMP0_INT * - \ref ADC_CMP1_INT * @return None */ void ADC_DisableInt(ADC_T *adc, uint32_t u32Mask) { if(u32Mask & ADC_ADF_INT) ADC->CTL &= ~ADC_CTL_ADCIEN_Msk; if(u32Mask & ADC_CMP0_INT) ADC->CMP[0] &= ~ADC_CMP0_ADCMPIE_Msk; if(u32Mask & ADC_CMP1_INT) ADC->CMP[1] &= ~ADC_CMP1_ADCMPIE_Msk; return; } /*@}*/ /* end of group NUC472_442_ADC_EXPORTED_FUNCTIONS */ /*@}*/ /* end of group NUC472_442_ADC_Driver */ /*@}*/ /* end of group NUC472_442_Device_Driver */ /*** (C) COPYRIGHT 2013 Nuvoton Technology Corp. ***/
c
12
0.553871
108
33.488636
176
starcoderdata
using System.Collections.Generic; using aera_core.Persistencia; using Bogus; namespace AeraIntegrationTest.Builders { public static class ProfessorDBBuilder { static Faker _faker => new Faker .RuleFor(p => p.name, f => f.Name.FullName()) .RuleFor(p => p.teacher, _ => true); public static ClienteDB Generate() => _faker.Generate(); public static IReadOnlyCollection Generate(int count) => _faker.Generate(count); } }
c#
16
0.648148
99
30.823529
17
starcoderdata
import React, { useState } from "react" import { toast } from "react-toastify" function generateData(num){ return Array.from(Array(num).keys()).map(i => { return { id: i, width: 100 * Math.random() + 1, height: 100 * Math.random() + 1, weight: 100 * Math.random() + 1 } }) } export function ModalDialog(){ let [data, setData] = useState(generateData(15)) const deleteRow = (r) => { data.splice(data.findIndex(e => e.id == r), 1) setData([...data]) toast.warning('Succesfully deleted!') } return ( <table className="container table"> { data.map(r => { return ( + 1} <a className="btn btn-danger" data-bs-toggle="modal" data-bs-target={`#deleteRowModal_${r.id}`}>Delete <div class="modal fade" id={`deleteRowModal_${r.id}`} tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Are you sure? <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> <div class="modal-body"> Are you sure you want to delete this row? <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close <button type="button" class="btn btn-danger" data-bs-dismiss="modal" onClick={() => deleteRow(r.id)}>Save changes ) }) } ) }
javascript
29
0.461758
148
33.152778
72
starcoderdata
def grn_model(self, rng=default_rng()): """Apply Gaussian Random Noise model to the CVGraph. Store quadrature or noise information as attributes depending on the sampling order. Args: rng (numpy.random.Generator, optional): a random number generator following the NumPy API. It can be seeded for reproducibility. By default, numpy.random.default_rng is used without a fixed seed. """ N = self._N delta = self._delta # For initial and final sampling, generate noise array depending on # quadrature and state. if self._sampling_order in ("initial", "final"): noise_q = {"p": 1 / (2 * delta) ** 0.5, "GKP": (delta / 2) ** 0.5} noise_p = {"p": (delta / 2) ** 0.5, "GKP": (delta / 2) ** 0.5} self._init_noise = np.zeros(2 * N, dtype=np.float32) for state, inds in self._states.items(): if self._perfect_inds: inds = np.array(list(set(inds).difference(self._perfect_inds))) if len(inds) > 0: self._init_noise[inds] = noise_q[state] self._init_noise[inds + N] = noise_p[state] # For final sampling, apply a symplectic CZ matrix to the initial noise # covariance. if self._sampling_order == "final": self._noise_cov = SCZ_apply(self._adj, sp.diags(self._init_noise) ** 2) # For two-step sampling, sample for initial (ideal) state-dependent # quadrature values. if self._sampling_order == "two-step": q_val_for_p = lambda n: rng.random(size=n) * (2 * np.sqrt(np.pi)) q_val_for_GKP = lambda n: rng.integers(0, 2, size=n) * np.sqrt(np.pi) val_funcs = {"p": q_val_for_p, "GKP": q_val_for_GKP} self._init_quads = np.zeros(2 * N, dtype=np.float32) for state, indices in self._states.items(): n_inds = len(indices) if n_inds > 0: self._init_quads[indices] = val_funcs[state](n_inds)
python
19
0.532995
83
47.295455
44
inline
using System.Collections.Generic; namespace Tetrifact.Core { public class PackageDeleteLocks { #region FIELDS public static PackageDeleteLocks Instance; private readonly IList _lockedPackages; #endregion #region CTORS static PackageDeleteLocks() { Reset(); } public PackageDeleteLocks() { _lockedPackages = new List } #endregion #region METHODS /// /// For testing only /// public static void Reset() { Instance = new PackageDeleteLocks(); } public void Lock(string packageId) { lock (_lockedPackages) { if (!_lockedPackages.Contains(packageId)) _lockedPackages.Add(packageId); } } public void Unlock(string packageId) { lock (Instance) { if (_lockedPackages.Contains(packageId)) _lockedPackages.Remove(packageId); } } public bool IsLocked(string packageId) { return _lockedPackages.Contains(packageId); } #endregion } }
c#
14
0.510638
57
19.969231
65
starcoderdata
/*L * Copyright Moxie Informatics. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/calims/LICENSE.txt for details. */ /** * */ package gov.nih.nci.calims2.ui.administration.customerservice.rate; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import gov.nih.nci.calims2.business.common.type.TypeEnumeration; import gov.nih.nci.calims2.business.generic.GenericService; import gov.nih.nci.calims2.domain.administration.Person; import gov.nih.nci.calims2.domain.administration.Quantity; import gov.nih.nci.calims2.domain.administration.StandardUnit; import gov.nih.nci.calims2.domain.administration.customerservice.Rate; import gov.nih.nci.calims2.domain.administration.customerservice.enumeration.RateStatus; import gov.nih.nci.calims2.domain.common.Type; import gov.nih.nci.calims2.domain.interfaces.EntityWithIdHelper; import gov.nih.nci.calims2.ui.generic.crud.CRUDController; import gov.nih.nci.calims2.ui.generic.crud.CRUDControllerConfig; import gov.nih.nci.calims2.ui.generic.crud.CRUDFormDecorator; import gov.nih.nci.calims2.ui.inventory.quantity.QuantityHelper; import gov.nih.nci.calims2.uic.descriptor.table.Table; import gov.nih.nci.calims2.util.enumeration.I18nEnumeration.I18nEnumerationHelper; /** * @author * */ @Controller @RequestMapping(RateController.URL_PREFIX) public class RateController extends CRUDController { /** Prefix of urls of this module. */ static final String URL_PREFIX = "/administration/customerservice/rate"; /** Create person sub flow. */ static final int PERSON_SUBFLOW_ID = 0; /** Create type sub flow. */ static final int TYPE_SUBFLOW_ID = 1; private static final String TYPE_QUERY = Type.class.getName() + ".findByDataElementCollection"; private GenericService personService; private GenericService typeService; private GenericService unitService; private QuantityHelper quantityHelper; /** * Default constructor. */ public RateController() { super(URL_PREFIX, "name"); CRUDControllerConfig config = getConfig(); config.setSubFlowUrls(new String[] {"/administration/person/create.do", "/common/type/create.do?dataElementCollection=" + TypeEnumeration.RATE }); config.setAdvancedSearch(true); } /** * * @param model The model to which the quantities must be added. * @param createMissing True if quantities missing in the container class must be added. */ void addQuantities(ModelAndView model, boolean createMissing) { Set quantities = new HashSet Object obj = ((RateForm) model.getModel().get("form")).getEntity().getQuantity(); if (obj != null) { quantities.add(((RateForm) model.getModel().get("form")).getEntity().getQuantity()); } model.addObject("quantities", quantityHelper.getQuantities(TypeEnumeration.RATE_QUANTITY, quantities, createMissing)); } /** * Calls a subflow. * * @param form The object containing the values of the entity to be saved. * @param subFlowId The id of the flow to call in the subFlowUrls array. * @return The next view to go to. It is a forward to the entry action of the subflow. */ @RequestMapping(CRUDControllerConfig.STD_CALL_COMMAND) public ModelAndView call(@ModelAttribute("form") RateForm form, @RequestParam("subFlowId") int subFlowId) { return super.doCall(form, subFlowId); } /** * {@inheritDoc} */ public ModelAndView completeDetailsModel(ModelAndView model, Locale locale) { addQuantities(model, false); return model; } /** * {@inheritDoc} */ public ModelAndView completeEditModel(ModelAndView model, Locale locale) { model.addObject("rateStatuses", I18nEnumerationHelper.getLocalizedValues(RateStatus.class, locale)); List persons = personService.findAll(Person.class, "familyName"); model.addObject("persons", persons); Map<String, Object> params = new HashMap<String, Object>(); params.put("dataElementCollection", TypeEnumeration.RATE.name()); List types = typeService.findByNamedQuery(TYPE_QUERY, params); model.addObject("types", types); List units = unitService.findAll(StandardUnit.class, "name"); model.addObject("standardUnits", units); addQuantities(model, true); return model; } /** * {@inheritDoc} */ public void doReturnFromFlow(ModelAndView model, int subFlowId, Long entityId) { if (entityId != null) { Rate rate = ((RateForm) model.getModel().get("form")).getEntity(); switch (subFlowId) { case PERSON_SUBFLOW_ID: { rate.setContactPerson(EntityWithIdHelper.createEntity(Person.class, entityId)); break; } case TYPE_SUBFLOW_ID: { rate.setType(EntityWithIdHelper.createEntity(Type.class, entityId)); break; } default: { throw new IllegalArgumentException("Wrong subFlowId"); } } } } /** * Saves an entity and returns a refreshed list type page. * * @param form The object containing the values of the entity to be saved. * @param locale The current locale. * @return The list type view. */ @RequestMapping(CRUDControllerConfig.STD_SAVE_COMMAND) public ModelAndView save(@ModelAttribute("form") RateForm form, Locale locale) { return doSave(form, locale); } /** * @param rateService the rateService to set */ @Resource(name = "rateService") public void setRateService(GenericService rateService) { super.setMainService(rateService); } /** * @param quantityHelper the quantityHelper to set */ @Resource(name = "quantityHelper") public void setQuantityHelper(QuantityHelper quantityHelper) { this.quantityHelper = quantityHelper; } /** * @param type the typeService to set */ @Resource(name = "typeService") public void setTypeService(GenericService type) { typeService = type; } /** * @param person the personService to set */ @Resource(name = "personService") public void setPersonService(GenericService person) { personService = person; } /** * @param unitService the unitService to set */ @Resource(name = "unitService") public void setUnitService(GenericService unitService) { this.unitService = unitService; } /** * @param formDecorator the formDecorator to set */ @Resource(name = "rateFormDecorator") public void setFormDecorator(CRUDFormDecorator formDecorator) { super.setFormDecorator(formDecorator); } /** * @param listTable the listTable to set */ @Resource(name = "rateTable") public void setListTable(Table listTable) { super.setListTable(listTable); } }
java
17
0.715818
122
31.600897
223
starcoderdata
#include #include using namespace stl; int main () { printf ("Results of bitset2_test:\n"); const bitset b = 0x1111; for (size_t i=0; i<b.digits; i++) printf ("b [%lu]=%s\n", i, b [i] ? "true" : "false"); return 0; }
c++
10
0.532374
57
14.352941
17
starcoderdata
// // UIImagePixelSource.h // Giraffe // // Created by on 11/5/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #import #import "ANGifImageFramePixelSource.h" #import "ANImageBitmapRep.h" @interface UIImagePixelSource : NSObject { ANImageBitmapRep * imageRep; } - (id)initWithImage:(UIImage *)anImage; + (UIImagePixelSource *)pixelSourceWithImage:(UIImage *)anImage; @end
c
8
0.738661
71
22.15
20
starcoderdata
export default { CREATE_DRIVER: 'CREATE_DRIVER', UPDATE_DRIVER: 'UPDATE_DRIVER', DELETE_DRIVER: 'DELETE_DRIVER', SELECT_DRIVER: 'SELECT_DRIVER' };
javascript
5
0.652695
35
23
7
starcoderdata
@Test (timeout = 300000) public void testUpgradeCommand() throws Exception { final String finalizedMsg = "Upgrade finalized for.*"; final String notFinalizedMsg = "Upgrade not finalized for.*"; final String failMsg = "Getting upgrade status failed for.*" + newLine + "upgrade: .*"; final String finalizeSuccessMsg = "Finalize upgrade successful for.*"; setUpHaCluster(false); MiniDFSCluster dfsCluster = cluster.getDfsCluster(); // Before upgrade is initialized, the query should return upgrade // finalized (as no upgrade is in progress) String message = finalizedMsg + newLine + finalizedMsg + newLine; verifyUpgradeQueryOutput(message, 0); // Shutdown the NNs dfsCluster.shutdownNameNode(0); dfsCluster.shutdownNameNode(1); // Start NN1 with -upgrade option dfsCluster.getNameNodeInfos()[0].setStartOpt( HdfsServerConstants.StartupOption.UPGRADE); dfsCluster.restartNameNode(0, true); // Running -upgrade query should return "not finalized" for NN1 and // connection exception for NN2 (as NN2 is down) message = notFinalizedMsg + newLine; verifyUpgradeQueryOutput(message, -1); String errorMsg = failMsg + newLine; verifyUpgradeQueryOutput(errorMsg, -1); // Bootstrap the standby (NN2) with the upgraded info. int rc = BootstrapStandby.run( new String[]{"-force"}, dfsCluster.getConfiguration(1)); assertEquals(0, rc); out.reset(); // Restart NN2. dfsCluster.restartNameNode(1); // Both NNs should return "not finalized" msg for -upgrade query message = notFinalizedMsg + newLine + notFinalizedMsg + newLine; verifyUpgradeQueryOutput(message, 0); // Finalize the upgrade int exitCode = admin.run(new String[] {"-upgrade", "finalize"}); assertEquals(err.toString().trim(), 0, exitCode); message = finalizeSuccessMsg + newLine + finalizeSuccessMsg + newLine; assertOutputMatches(message); // NNs should return "upgrade finalized" msg message = finalizedMsg + newLine + finalizedMsg + newLine; verifyUpgradeQueryOutput(message, 0); }
java
10
0.700843
76
37.160714
56
inline
from pylayers.gis.layout import * plt.ion() L = Layout('defstr.ini') # single point #p1 = np.array([3,3]) #p1 =np.append(L.Gt.pos[5],1) p1 =L.Gt.pos[5] # list of points #p2 = np.array([18,3]) #p2 = np.append(L.Gt.pos[2],2.7) p2 = L.Gt.pos[2] #tp2 = np.vstack((p2,p2+np.array([1,1,0]))).T tp2 = np.vstack((p2,p2+np.array([1,1]))).T #sgl = L.angleonlink3(p1,tp2) sgl = L.angleonlink(p1,tp2) L.showG('s',labels=1) plt.plot(np.array([p1[0],p2[0]]),np.array([p1[1],p2[1]])) plt.show() #L.sla[sgl['s']]
python
11
0.606786
57
25.368421
19
starcoderdata
void test_xonly_sort_api(void) { int ecount = 0; rustsecp256k1zkp_v0_4_0_xonly_pubkey pks[2]; const rustsecp256k1zkp_v0_4_0_xonly_pubkey *pks_ptr[2]; rustsecp256k1zkp_v0_4_0_context *none = api_test_context(SECP256K1_CONTEXT_NONE, &ecount); pks_ptr[0] = &pks[0]; pks_ptr[1] = &pks[1]; rand_xonly_pk(&pks[0]); rand_xonly_pk(&pks[1]); CHECK(rustsecp256k1zkp_v0_4_0_xonly_sort(none, pks_ptr, 2) == 1); CHECK(rustsecp256k1zkp_v0_4_0_xonly_sort(none, NULL, 2) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1zkp_v0_4_0_xonly_sort(none, pks_ptr, 0) == 1); /* Test illegal public keys */ memset(&pks[0], 0, sizeof(pks[0])); CHECK(rustsecp256k1zkp_v0_4_0_xonly_sort(none, pks_ptr, 2) == 1); CHECK(ecount == 2); memset(&pks[1], 0, sizeof(pks[1])); CHECK(rustsecp256k1zkp_v0_4_0_xonly_sort(none, pks_ptr, 2) == 1); CHECK(ecount > 2); rustsecp256k1zkp_v0_4_0_context_destroy(none); }
c
10
0.628931
94
35.730769
26
inline
def get_mime_type(filename, source_type): # check source_type source_type = source_type.lower() mimetypes.init() if source_type == "auto": # let's guess source_mime_type = mimetypes.guess_type(filename, False)[0] if source_mime_type is None: source_mime_type = "application/octet-stream" else: # user define the mime type suffix = mimetypes.guess_all_extensions(source_type, False) if len(suffix) < 1: return (False, None) source_mime_type = source_type return (True, source_mime_type)
python
10
0.612521
67
31.888889
18
inline
<?php namespace common\models; use Yii; use yii\base\Model; class UploadForm extends Model { public $file; public function rules() { return [ [['file'], 'required'], [['file'], 'file', 'extensions' => 'xls,xlsx', 'maxSize'=>1024*1024*5, 'on'=>'xls'], // [['file'], 'file', 'extensions' => 'xlsx', 'maxSize'=>1024*1024*5, 'on'=>'olt'], ]; } }
php
13
0.556054
88
19.272727
22
starcoderdata
#ifndef RED_DATA_JSON_ENCODER_H #define RED_DATA_JSON_ENCODER_H #include #include #include namespace Red { namespace Data { namespace JSON { class Encoder { public: typedef uint32_t EncodeFlags; static const EncodeFlags kEncodeFlags_None = 0; static const EncodeFlags kEncodeFlags_Pretty = 1; static const EncodeFlags kEncodeFlags_TrailingCommaLists = 2; static const EncodeFlags kEncodeFlags_SpaceIndentation = 4; static const EncodeFlags kEncodeFlags_NoObjectArrayNewlines = 8; static const EncodeFlags kEncodeFlags_AllArrayNewlines = 16; static const EncodeFlags kEncodeFlags_NoRecursiveObjectNewlines = 32; static const EncodeFlags kEncodeFlags_AllObjectNewlines = 64; static const EncodeFlags kEncodeFlags_MemberNameSeperator_PrefixSpace = 128; static const EncodeFlags kEncodeFlags_MemberNameSeperator_SuffixSpace = 256; static const EncodeFlags kEncodeFlags_ArrayObjectMemberSeperateLine = 512; static const EncodeFlags kEncodeFlags_PrettyPrint = kEncodeFlags_Pretty | kEncodeFlags_TrailingCommaLists | kEncodeFlags_MemberNameSeperator_SuffixSpace | kEncodeFlags_MemberNameSeperator_PrefixSpace | kEncodeFlags_AllObjectNewlines | kEncodeFlags_ArrayObjectMemberSeperateLine; static const EncodeFlags kEncodeFlags_Tight = kEncodeFlags_None; Encoder ( EncodeFlags Flags = kEncodeFlags_PrettyPrint, uint32_t IndentLevel = 1, const std :: string & NewlineSequence = "\n" ); ~Encoder (); bool Encode ( IType * RootObj, std :: string & OutString, uint32_t BaseIndent = 0 ); private: const std :: string NewlineSequence; EncodeFlags Flags; uint32_t IndentSize; }; } } } #endif
c
17
0.738919
282
29.327869
61
starcoderdata
const { DB, DEFAULT_QUERY_OPTIONS } = require('../constants'); const Manager = require("../../pdm-dsu-toolkit/managers/Manager"); const {DirectoryEntry, ROLE } = require('../model/DirectoryEntry'); /** * Stores references to some entities for quicker lookup on the front end (eg, products, suppliers, etc) * * @param {ParticipantManager} participantManager the top-level manager for this participant, which knows other managers. * @param {string} tableName the default table name for this manager eg: MessageManager will write to the messages table * @module managers * @class DirectoryManager * @extends Manager * @memberOf Managers */ class DirectoryManager extends Manager { constructor(participantManager, callback) { super(participantManager, DB.directory, ['role', 'id'], callback); } _testRoles(role){ return Object.values(ROLE).indexOf(role) !== -1; } saveEntry(role, id, callback){ if (!this._testRoles(role)) return callback(`invalid role provided`); const entry = new DirectoryEntry({ id: id, role: role }); return this.create(entry, callback) } /** * generates the db's key for the Directory entry * @param {string|number} role * @param {string|number} id * @return {string} * @protected */ _genCompostKey(role, id){ return `${role}-${id}`; } /** * Creates a {@link DirectoryEntry} * @param {string} key the readSSI to the order that generates the shipment * @param {string|number} [key] the table key * @param {DirectoryEntry} entry * @param {function(err, sReadSSI, dbPath)} callback where the dbPath follows a "tableName/shipmentId" template. * @override */ create(key, entry, callback) { let self = this; if (!callback){ callback = entry; entry = key; key = self._genCompostKey(entry.role, entry.id); } const matchEntries = function(fromDb){ try{ return entry.role === fromDb.role && entry.id === fromDb.id; } catch(e){ return false; } } self.getOne(key, (err, existing) => { if (!err && !!existing){ if (matchEntries(existing)) { console.log(`Entry already exists in directory. skipping`); return callback(undefined, existing); } else return callback(`Provided directory entry does not match existing.`); } self.insertRecord(key, entry, (err) => { if (err) return self._err(`Could not insert directory entry ${entry.id} on table ${self.tableName}`, err, callback); const path = `${self.tableName}/${key}`; console.log(`Directory entry for ${entry.id} as a ${entry.role} created stored at DB '${path}'`); callback(undefined, entry, path); }); }); } /** * Loads the Directory entry for the provided key * @param {string} key * @param {boolean} [readDSU] does nothing in this manager * @param {function(err, DirectoryEntry)} callback returns the Entry * @override */ getOne(key, readDSU, callback) { if (!callback){ callback = readDSU; readDSU = true; } let self = this; self.getRecord(key, (err, entry) => { if (err) return self._err(`Could not load record with key ${key} on table ${self._getTableName()}`, err, callback); callback(undefined, entry); }); } /** * @protected * @override */ _keywordToQuery(keyword) { keyword = keyword || '.*'; return [`role like /${keyword}/g`]; } /** * Lists all registered items according to query options provided * @param {boolean} [readDSU] defaults to true. decides if the manager loads and reads from the dsu's {@link INFO_PATH} or not * @param {object} [options] query options. defaults to {@link DEFAULT_QUERY_OPTIONS} * @param {function(err, object[])} callback * @override */ getAll(readDSU, options, callback){ const defaultOptions = () => Object.assign({}, DEFAULT_QUERY_OPTIONS, { query: ['role like /.*/g'] }); if (!callback){ if (!options){ callback = readDSU; options = defaultOptions(); readDSU = true; } if (typeof readDSU === 'boolean'){ callback = options; options = defaultOptions(); } if (typeof readDSU === 'object'){ callback = options; options = readDSU; readDSU = true; } } options = options || defaultOptions(); let self = this; console.log(`Db lock status for ${self.tableName}`, self.dbLock.isLocked()) self.query(options.query, options.sort, options.limit, (err, records) => { if (err) return self._err(`Could not perform query`, err, callback); if (!readDSU) return callback(undefined, records.map(r => r.id)); callback(undefined, records); }); } } /** * @param {ParticipantManager} participantManager * @param {function(err, Manager)} [callback] optional callback for when the assurance that the table has already been indexed is required. * @returns {DirectoryManager} * @memberOf Managers */ const getDirectoryManager = function (participantManager, callback) { let manager; try { manager = participantManager.getManager(DirectoryManager); if (callback) return callback(undefined, manager); } catch (e){ manager = new DirectoryManager(participantManager, callback); } return manager; } module.exports = getDirectoryManager;
javascript
22
0.567897
139
32.716667
180
starcoderdata
void TopologyKernel::set_edge(const EdgeHandle& _eh, const VertexHandle& _fromVertex, const VertexHandle& _toVertex) { Edge& e = edge(_eh); // Update bottom-up entries if(has_vertex_bottom_up_incidences()) { const VertexHandle& fv = e.from_vertex(); const VertexHandle& tv = e.to_vertex(); const HalfEdgeHandle heh0 = halfedge_handle(_eh, 0); const HalfEdgeHandle heh1 = halfedge_handle(_eh, 1); std::remove(outgoing_hes_per_vertex_[fv.idx()].begin(), outgoing_hes_per_vertex_[fv.idx()].end(), heh0); std::remove(outgoing_hes_per_vertex_[tv.idx()].begin(), outgoing_hes_per_vertex_[tv.idx()].end(), heh1); outgoing_hes_per_vertex_[_fromVertex.idx()].push_back(heh0); outgoing_hes_per_vertex_[_toVertex.idx()].push_back(heh1); } e.set_from_vertex(_fromVertex); e.set_to_vertex(_toVertex); }
c++
14
0.641403
118
37.478261
23
inline
#ifndef WBCOMPELDTHINKERTARGET_H #define WBCOMPELDTHINKERTARGET_H #include "wbcompeldthinker.h" class WBCompEldThinkerTarget : public WBCompEldThinker { public: WBCompEldThinkerTarget(); virtual ~WBCompEldThinkerTarget(); DEFINE_WBCOMP(EldThinkerTarget, WBCompEldThinker); virtual void Tick(float DeltaTime); protected: virtual void InitializeFromDefinition(const SimpleString& DefinitionName); private: HashedString m_OutputCombatTargetBlackboardKey; HashedString m_OutputSearchTargetBlackboardKey; float m_CombatTargetScoreThreshold; float m_SearchTargetScoreThreshold; }; #endif // WBCOMPELDTHINKERTARGET_H
c
9
0.815668
76
23.148148
27
starcoderdata
using System; using System.Collections.Generic; using System.Text; namespace tanks { public static class Globals { public static readonly double[] SinTable = new double[16]; public static readonly double[] CosTable = new double[16]; public static int GameLoopTick_ms = 4; public static int MaxBullets = 3; public static int BulletLifeSpan = 600; public static int WinningScore = 15; static Globals() { for (int i = 0; i < 16; i++) { SinTable[i] = Math.Sin(22.5 * i * Math.PI / 180); CosTable[i] = Math.Cos(22.5 * i * Math.PI / 180); } } public static readonly string OriginalMap = @"1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"; } }
c#
17
0.511352
97
52.315789
57
starcoderdata
import { useEffect } from 'react'; // import styles from '@/components/Carousel/Carousel.module.css'; const useKeyboard = (elementRef) => { useEffect(() => { const element = elementRef.current; const handleMouseDown = () => { // no need to check elementRef.current here, // because event listener is added on element if (!element) return; element.setAttribute('data-is-not-keyboard-user', 'true'); // cannot use classList due to classList will get changed // element.classList.add(styles.isNotKeyboardUser); }; const handleKeyDown = (event) => { if (!element) return; if (event.key !== 'Tab') return; element.setAttribute('data-is-not-keyboard-user', 'false'); }; if (element) { element.addEventListener('mousedown', handleMouseDown); element.addEventListener('keydown', handleKeyDown); } return () => { if (element) { element.removeEventListener('mousedown', handleMouseDown); element.removeEventListener('keydown', handleKeyDown); } }; }, [elementRef]); }; export default useKeyboard;
javascript
16
0.647863
66
29.789474
38
starcoderdata
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $("#form-cotizar").submit(function(event) { event.preventDefault(); if ($('#precio-peajes').val() !== '' && $('#distancia').val() !== '') { var peajesUnTrayecto = $('#precio-peajes').val(); var distanciaUnTrayecto = $('#distancia').val(); if ($('#idayRegreso').find(":selected").text() === 'Si') { $('#precio-peajes').val(2 * peajesUnTrayecto); $('#distancia').val(2 * parseInt(distanciaUnTrayecto)); } else { $('#precio-peajes').val(4 * peajesUnTrayecto); $('#distancia').val(4 * parseInt(distanciaUnTrayecto)); } $.ajax({ type: "POST", url: "/cotizar", data: $("#form-cotizar").serialize(), dataType: "json", success: function(data) { var url; if (data.codigo === '000') { dataSesion.storeUserDataInSession(data.valor, "cotizacion"); } else { var mensaje = 'Ha ocurrido un error, contactanos a var codigo = '001'; url = "/informativo.html?codigo=" + codigo + "&mensaje=" + mensaje; window.location.href = url; } url = "/Cotizacion.html"; window.location.href = url; } }); } else { if ($('#origen-id').val() === '') { $('#errorGenericoubOrigen').text("No reconocemos el lugar que ingresas, intenta ingresando \n\ barrio-ciudad (ejemplo: morato bogota) o algun centro comercial, universidad o lugar reconocido que sirva de punto de referencia"); $('#error-ub-origen').css('visibility', 'visible').hide().fadeIn().removeClass('hidden'); } if ($('#destino-id').val() === '') { $('#errorGenericoubDestino').text("No reconocemos el lugar que ingresas, intenta ingresando \n\ barrio-ciudad (ejemplo: morato bogota) o algun centro comercial, universidad o lugar reconocido que sirva de punto de referencia"); $('#error-ub-destino').css('visibility', 'visible').hide().fadeIn().removeClass('hidden'); } } }); $('#ubicacion-origen').on('blur', function() { if ($('#origen-id').val() === '') { $('#errorGenericoubOrigen').text("No reconocemos el lugar que ingresas, intenta ingresando \n\ barrio-ciudad (ejemplo: morato bogota) o algun centro comercial, universidad o lugar reconocido que sirva de punto de referencia"); $('#error-ub-origen').css('visibility', 'visible').hide().fadeIn().removeClass('hidden'); } else { $('#error-ub-origen').css('visibility', 'hidden').addClass('hidden'); } }); $('#ubicacion-destino').on('blur', function() { if ($('#destino-id').val() === '') { $('#errorGenericoubDestino').text("No reconocemos el lugar que ingresas, intenta ingresando \n\ barrio-ciudad (ejemplo: morato bogota) o algun centro comercial, universidad o lugar reconocido que sirva de punto de referencia"); $('#error-ub-destino').css('visibility', 'visible').hide().fadeIn().removeClass('hidden'); } else { $('#error-ub-destino').css('visibility', 'hidden').addClass('hidden'); } }); $('#ubicacion-destino').on('keypress', function() { $('#destino-id').val(''); }); $('#ubicacion-origen').on('keypress', function() { $('#origen-id').val(''); }); $(function() { $("[data-hide]").on("click", function() { $(this).closest("." + $(this).attr("data-hide")).hide(); }); });
javascript
24
0.560638
139
43.235294
85
starcoderdata
@BeforeEach @AfterEach public void resetDefaultBehaviour() { // Reset to default myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences()); myDaoConfig.setTreatBaseUrlsAsLocal(null); }
java
9
0.803653
86
30.428571
7
inline
def timestamp_differ(input_filenames, output_filenames): """ :returns: Two-tuple: [0] -- True if all input files are older than output files and all files exist [1] -- Path of youngest input. [2] -- Why we're able to skip (or not). """ # Always run things that don't produce a file if not output_filenames: # No longer covered in tests since magicinvoke.skippable gives a dummy # output_filename file for each function for storing its return value. # Preserved in case that changes + so that timestamp differ can remain # usable outside of its use in this module. return ( False, "has_inputs:{} has_outputs:{}".format( bool(input_filenames), bool(output_filenames) ), ) # If any files are missing (whether inputs or outputs), # run the task. We run when missing inputs because hopefully # their task will error out and notify the user, rather than silently # ignore that it was supposed to do something. paths = itertools.chain(input_filenames, output_filenames) for p in paths: if not Path(p).exists(): # HACK Not the youngest input, but it currently doesn't matter return False, "{} missing".format(p) if not input_filenames: return True, "task's outputs exist, but no inputs required" # All exist, now make sure oldest output is older than youngest input. PathInfo = collections.namedtuple("PathInfo", ["path", "modified"]) def sort_by_timestamps(l_param): l = (PathInfo(path, Path(path).stat().st_mtime) for path in l_param) return sorted(l, key=lambda pi: pi.modified) oldest_output = sort_by_timestamps(output_filenames)[0] youngest_input = sort_by_timestamps(input_filenames)[-1] skipping = youngest_input.modified < oldest_output.modified return ( skipping, "youngest_input={}, oldest_output={}".format( youngest_input, oldest_output ), )
python
15
0.641176
84
41.520833
48
inline
#include "args/args.h" #include "env/assert_fatal.h" namespace buildcc { void Args::Parse(int argc, const char *const *argv) { try { app_.parse(argc, argv); } catch (const CLI::ParseError &e) { env::assert_fatal } } } // namespace buildcc
c++
13
0.636364
53
17.333333
15
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using Framework.DomainDriven.DAL.Sql; using Framework.DomainDriven.Metadata; using Framework.Core; namespace Framework.DomainDriven.NHibernate.DALGenerator { internal static class DomainTypeMetadataExtension { public static IEnumerable GetManyToOneReference(this DomainTypeMetadata domainTypeMetadata) { return domainTypeMetadata.ReferenceFields.Except(domainTypeMetadata.GetOneToOneReference()); } public static IEnumerable GetOneToOneReference( this DomainTypeMetadata domainTypeMetadata) { var referencies = domainTypeMetadata.ReferenceFields; var toTypes = referencies.Select(z => z.ToType).Distinct(); var toDomainTypeMetadataReferencies = domainTypeMetadata.AssemblyMetadata.DomainTypes .Join(toTypes, z => z.DomainType, z => z, (d, t) => d.ReferenceFields).SelectMany(z => z).Distinct(); return referencies.Join(toDomainTypeMetadataReferencies, z => z.FromType, z => z.ToType, (f, s) => f); } public static FieldMetadata GetIdentityField(this DomainTypeMetadata source) { var request = from typeMetadata in source.GetAllElements (m => m.Parent) from fieldMetaData in typeMetadata.Fields where string.Equals (fieldMetaData.Name, "Id", StringComparison.InvariantCultureIgnoreCase) select fieldMetaData; return request.Single(() => new System.ArgumentException ( $"Domain type {source.DomainType.Name} has no identity field")); //var typeToDomainTypeMetadata = source.AssemblyMetadata.DomainTypes.ToDictionary (z => z.DomainType, z=>z); //var allDomainTypes = typeToDomainTypeMetadata.Join (allTypes, z => z.Key, z => z, // (type, domainTypeMetadata) => domainTypeMetadata).ToList (); //allDomainTypes.SelectMany (z=>z) //var identityField = // source.Fields.Single( // z => string.Equals (z.Name, "Id", StringComparison.InvariantCultureIgnoreCase), // () => new ArgumentException (string.Format ("Domain type {0} has no identity field", // source.DomainType.Name))); //return identityField; } public static string GetIdentityFieldName(this DomainTypeMetadata source, Func<DomainTypeMetadata, string> getIdentityFieldInBDFunc) { return source.GetIdentityField ().ToColumnName (z => getIdentityFieldInBDFunc (source)); } } }
c#
21
0.626829
140
46.644068
59
starcoderdata
void MechVM::showInstallWidgets() { // Remove other widgets clear(); createToolbar(); // Display install widgets size_t count = showCDROMWidgets(); if (count == 0) { label = new GLLabel (this, 20, (int)(105+count*40), 800, 30); label->setTitle(30); add(label); count = 1; } // Display import widgets GLLabel* label = new GLLabel (this, 20, (int)(105+count*40), 140, 30); label->setTitle(31); add(label); importPathEdit = new GLLineEdit (this, 140, (int)(100+count*40), 450, 30); #ifdef _WIN32 importPathEdit->setText ("D:\\"); #else importPathEdit->setText ("/media/"); #endif add (importPathEdit); GLButton* button = new GLButton (this, 600, (int)(100+count*40), 200, 30); button->setTitle(32); button->userData = startImportButtonID; button->setListener (this); add (button); button = new GLButton (this, 600, (int)(140+count*40), 200, 30); button->setTitle(33); button->userData = searchForCDButtonID; button->setListener (this); add (button); count += 2; showCDROMReportWidgets((int)(140+count*40)); }
c++
13
0.624334
77
25.209302
43
inline
<?php // catturo 'a' $a = $_GET['a']; // assegna $a su $c $c = $a[0]; // stampo $c echo $c; ?> <form action="prova.php"> a:<input type="text" name="a"> <input type="submit">
php
5
0.492462
30
5.862069
29
starcoderdata
import {src, dest, parallel, series, watch} from 'gulp' import autoprefixer from 'gulp-autoprefixer' import eslint from 'gulp-eslint' import rename from 'gulp-rename' import sass from 'gulp-sass' import sourcemaps from 'gulp-sourcemaps' import webpackStream from 'webpack-stream' import webpack from 'webpack' const webpackConfig = require('./webpack.config') const configDev = { mode: 'development', devtool: 'source-map', output: { filename: 'jquery.timeline.js' } } const configProd = { mode: 'production' } export const scripts = () => src('src/timeline.js') .pipe(webpackStream( Object.assign( webpackConfig, configDev ), webpack, (err) => { if ( err ) { console.error( err ) } })) .pipe(dest('dist')) export const deploy_scripts = () => src('src/timeline.js') .pipe(webpackStream( Object.assign( webpackConfig, configProd ), webpack, (err) => { if ( err ) { console.error( err ) } })) .pipe(dest('dist')) export const check = () => src('src/timeline.js') .pipe(eslint({useEslintrc: true})) .pipe(eslint.format()) .pipe(eslint.failAfterError()) export const styles = () => src('src/timeline.scss') .pipe(sourcemaps.init()) .pipe(sass({outputStyle:'compressed'})) .pipe(autoprefixer()) .pipe(rename('jquery.timeline.min.css')) .pipe(sourcemaps.write('.')) .pipe(dest('dist')) export const deploy_styles = () => src('src/timeline.scss') .pipe(sass({outputStyle:'compressed'})) .pipe(autoprefixer()) .pipe(rename('jquery.timeline.min.css')) .pipe(dest('dist')) export const docsJS = () => src([ 'dist/jquery.timeline.min.js', 'dist/jquery.timeline.min.js.map' ]) .pipe(dest('docs/js')) export const docsCSS = () => src([ 'dist/jquery.timeline.min.css', 'dist/jquery.timeline.min.css.map' ]) .pipe(dest('docs/css')) //export default series( scripts, styles, docsJS, docsCSS ) export default series( parallel( series( check, scripts ), styles ), docsJS, docsCSS ) export const prod = parallel( deploy_scripts, deploy_styles ) export const dev = () => { watch( 'src/timeline.js', series( check, scripts ) ) watch( 'src/timeline.scss', series( styles ) ) }
javascript
20
0.632135
112
30.131579
76
starcoderdata
package com.jenetics.smocker.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import com.jenetics.smocker.model.EntityWithId; import com.jenetics.smocker.model.Scenario; import com.jenetics.smocker.ui.SmockerUI; public class DaoManagerByModel { private static final String UNDEFINED = "undefined"; static { daoManagerByClass = new HashMap<>(); checkRootScenarioExist(); } private DaoManagerByModel() { super(); } private static Map DaoManager daoManagerByClass; private static Scenario UNDEFINED_SCENARIO; public static Scenario getUNDEFINED_SCENARIO() { DaoManager daoManagerScenario = getDaoManager(Scenario.class); if (daoManagerScenario != null) { return daoManagerScenario.findById(UNDEFINED_SCENARIO.getId()); } return null; } public static <T extends EntityWithId> DaoManager getDaoManager(Class typeParameterClass) { if (daoManagerByClass.containsKey(typeParameterClass)) { return (DaoManager daoManagerByClass.get(typeParameterClass); } if (isEntityDefinedInMetaModel( SmockerUI.getEm(), typeParameterClass)) { DaoManager daoManager = new DaoManager<>(typeParameterClass, SmockerUI.getEm()); daoManagerByClass.put(typeParameterClass, daoManager); return daoManager; } else if (isEntityDefinedInMetaModel(SmockerUI.getEmPersitant(), typeParameterClass)) { DaoManager daoManager = new DaoManager<>(typeParameterClass, SmockerUI.getEmPersitant()); daoManagerByClass.put(typeParameterClass, daoManager); return daoManager; } return null; } private static void checkRootScenarioExist() { DaoManager daoManagerScenario = getDaoManager(Scenario.class); if (daoManagerScenario != null) { if (daoManagerScenario.listAll().isEmpty()) { Scenario scenario = new Scenario(); scenario.setName(SmockerUI.getBundleValue(UNDEFINED)); scenario.setHost(SmockerUI.getBundleValue(UNDEFINED)); scenario.setIp(SmockerUI.getBundleValue(UNDEFINED)); scenario.setPort(0); scenario = daoManagerScenario.create(scenario); DaoManagerByModel.UNDEFINED_SCENARIO = scenario; } else { List listScenarios = daoManagerScenario.queryList("SELECT s FROM Scenario s WHERE s.name = 'undefined'"); if (!listScenarios.isEmpty()) { DaoManagerByModel.UNDEFINED_SCENARIO = listScenarios.get(0); } } } } private static <T extends EntityWithId> boolean isEntityDefinedInMetaModel(EntityManager em, Class typeParameterClass) { try { em.getMetamodel().entity(typeParameterClass); } catch (Exception e) { return false; } return true; } }
java
4
0.729893
124
29.943182
88
starcoderdata
#include #include #include #include #include bool verbose = true; template<typename T> void test(const T &msg) { std::string serialized; serialize(msg, serialized); if(verbose) std::cout << msg.type() << ": serialized: " << serialized << std::endl; T msg2; parse(msg2, serialized); std::string reserialized; serialize(msg2, reserialized); if(verbose) std::cout << msg.type() << ": re-serialized: " << reserialized << std::endl; if(serialized != reserialized) { std::cerr << "Test for " << msg.type() << " failed" << std::endl; exit(1); } } int main(int argc, char **argv) { b0::init(argc, argv); { b0::message::resolv::AnnounceNodeRequest msg; msg.node_name = "foo"; test(msg); } { b0::message::log::LogEntry msg; msg.node_name = "foo"; msg.level = b0::logger::levelInfo(b0::logger::Level::warn).str; msg.message = "Hello \x01\xff world"; msg.time_usec = (uint64_t(1) << 60) + 5978629785; test(msg); } { b0::message::graph::Graph g1; b0::message::graph::GraphNode n1; n1.node_name = "a"; g1.nodes.push_back(n1); b0::message::graph::GraphNode n2; n2.node_name = "b"; g1.nodes.push_back(n2); b0::message::graph::GraphNode n3; n3.node_name = "c"; g1.nodes.push_back(n3); b0::message::graph::GraphLink l1; l1.node_name = "a"; l1.other_name = "t"; l1.reversed = false; g1.node_topic.push_back(l1); b0::message::graph::GraphLink l2; l2.node_name = "b"; l2.other_name = "t"; l2.reversed = true; g1.node_topic.push_back(l2); b0::message::graph::GraphLink l3; l3.node_name = "c"; l3.other_name = "t"; l3.reversed = true; g1.node_topic.push_back(l3); test(g1); } return 0; }
c++
12
0.54901
84
25.197531
81
starcoderdata
[Test] public void LoggingFrameworkOnlyReportedOnce() { _agentHealthReporter.ReportLogForwardingFramework("log4net"); _agentHealthReporter.CollectMetrics(); Assert.True(_publishedMetrics.Any(x => x.MetricName.Name == "Supportability/Logging/DotNET/log4net/enabled")); // Clear out captured metrics, and recollect _publishedMetrics = new List<MetricWireModel>(); _agentHealthReporter.ReportLogForwardingFramework("log4net"); _agentHealthReporter.ReportLogForwardingFramework("serilog"); _agentHealthReporter.CollectMetrics(); Assert.True(_publishedMetrics.Any(x => x.MetricName.Name == "Supportability/Logging/DotNET/serilog/enabled")); Assert.False(_publishedMetrics.Any(x => x.MetricName.Name == "Supportability/Logging/DotNET/log4net/enabled")); }
c#
15
0.676339
123
51.764706
17
inline
/** * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * \author guonix * \date Nov 2020 * \brief */ #pragma once #include #include #include #include namespace proxima { namespace be { namespace meta { namespace sqlite { //! Predefine class class Statement; //! Alias for StatementPtr using StatementPtr = std::shared_ptr /*! * Statement object */ class Statement { public: //! Constructors Statement(); Statement(std::string database, const char *sql); Statement(std::string database, std::string sql); Statement(Statement &&stmt) noexcept; Statement(const Statement &stmt) = delete; //! Destructor ~Statement(); public: //! Initialize Statement, 0 for success, otherwise failed int initialize(); //! Cleanup statement, 0 for success, otherwise failed int cleanup(); //! Execute statement, 0 for success, otherwise failed //! @param binder: bind the params to statements //! @param fetcher: fetch the records returned from sqlite_step //! @param retry: the times retry exec sql int exec(const std::function<int(sqlite3_stmt *)> &binder = nullptr, const std::function<int(sqlite3_stmt *)> &fetcher = nullptr, uint32_t retry = 1); //! Prepare sql int prepare_sql(const std::string &sql); private: //! Reset the values banded to statement, 0 for success, otherwise failed int reset(); //! cleanup int do_cleanup(); //! compile sql int compile_sql(); private: //! the path of databases std::string database_{}; //! database connection sqlite3 *connection_{nullptr}; //! sql std::string sql_{}; //! statement of sqlite sqlite3_stmt *statement_{nullptr}; }; } // namespace sqlite } // namespace meta } // namespace be } // namespace proxima
c
17
0.684866
77
23.663366
101
starcoderdata
int main(int argc, const char** argv) { if (argc < 2) { fprintf(stderr, "usage: %s <task id>...\n", argv[0]); return -1; } bool errored = false; for (int i = 1; i < argc; i++) { const char* arg = argv[i]; if ((arg[0] == 'p' || arg[1] == 'j') && (arg[1] == ':')) { // Skip leading "p:" or "j:". arg += 2; } char* endptr; zx_koid_t task_id = strtoll(arg, &endptr, 10); if (*endptr != '\0') { fprintf(stderr, "\"%s\" is not a valid task id\n", arg); errored = true; continue; } zx_status_t status = walk_root_job_tree(callback, callback, NULL, &task_id); if (status == ZX_OK) { fprintf(stderr, "task %lu not found\n", task_id); errored = true; continue; } } return errored ? -1 : 0; }
c
12
0.498104
80
25.4
30
inline
#include #include // required for malloc #include "geg_node.h" int _geg_node_init_core(geg_nodes_t **node) { geg_nodes_t *_node = (geg_nodes_t *)malloc(sizeof(geg_nodes_t)); if (!_node) { return -1; } _node->prev = NULL; _node->next = NULL; *node = _node; return 0; } geg_nodes_t *_geg_node_get_tail(const geg_nodes_t **head) { geg_nodes_t *current_node = *head; geg_nodes_t *tail = NULL; while (current_node) { tail = current_node; current_node = current_node->next; } printf("tail node: %llu", *tail); return tail; } geg_nodes_t *_geg_node_append_core(geg_nodes_t **head, geg_nodes_t *node) { geg_nodes_t *tail = geg_node_tail(head); if (!tail) { *head = node; } else { tail->next = node; } node->prev = tail; node->next = NULL; return node; }
c
10
0.54476
73
16.634615
52
starcoderdata
<?php /** * Author: * Date: 18.03.13 * Time: 23:42 */ class TaskForm extends FormModel { public $description; public function rules() { return array( array('description', 'length', 'max'=>500), array('description', 'safe'), ); } public function attributeLabels() { return array( 'description'=>'Description', ); } }
php
11
0.5054
55
17.416667
24
starcoderdata
public IEnumerable<Term> Parse(IEnumerable<Token> tokens) { var runnerContext = ParseRunnerContext.Create(this); var runner = WaitingRunner.Instance; #if DEBUG var index = 0; #endif foreach (var token in tokens) { #if DEBUG if (index == BreakIndex) Debugger.Break(); index++; #endif switch (runner.Run(runnerContext, token)) { case ParseRunnerResult(ParseRunner next, Term term): yield return term; runner = next; break; case ParseRunnerResult(ParseRunner next, _): runner = next; break; } Debug.WriteLine($"{index - 1}: '{token}': {runnerContext}"); runnerContext.SetLastToken(token); } // Exhaust all saved scopes while (ParserUtilities.LeaveOneImplicitScope(runnerContext) != LeaveScopeResults.None); // Contains final result if (runnerContext.CurrentTerm is Term finalTerm) { // Iterate with unveiling hided terms. yield return finalTerm.VisitUnveil(); } }
c#
14
0.493976
99
33.076923
39
inline
namespace MoiteRecepti2.Services.Data.DTOs { public class CountsDTO { public int RecipesCount { get; set; } public int CategoriesCount { get; set; } public int IngredientsCount { get; set; } public int ImagesCount { get; set; } } }
c#
8
0.614286
49
20.538462
13
starcoderdata
public void ConfigureServices(IServiceCollection services) { CultureInfo.CurrentCulture = new CultureInfo("de"); services.AddOptions(); services.Configure<DataLoaderOptions>(Configuration.GetSection("DataLoader")); services.Configure<ViewOptions>(Configuration.GetSection("View")); services.Configure<ForwardedHeadersOptions>(options => { // Requests through Chrome Data Saver cause "Parameter count mismatch between X-Forwarded-For and X-Forwarded-Proto" if true options.RequireHeaderSymmetry = false; }); services.AddWebMarkupMin() .AddHttpCompression(options => { options.CompressorFactories = new List<ICompressorFactory> { new GZipCompressorFactory() }; }); services.AddRazorPages(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/"; options.LogoutPath = "/logout"; // Workaround to prevent redirect if access is denied options.Events = new CookieAuthenticationEvents { OnRedirectToAccessDenied = (ctx) => { ctx.Response.StatusCode = 403; return Task.CompletedTask; } }; }); services.AddAuthorization(); services.AddSingleton<VertretungsplanRepository, VertretungsplanRepository>(); services.AddSingleton<UserRepository, UserRepository>(); services.AddSingleton<DataLoader, DataLoader>(); services.AddSingleton<VertretungsplanHelper, VertretungsplanHelper>(); services.AddScoped<ResponseCachingHelper, ResponseCachingHelper>(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
c#
21
0.575238
140
45.688889
45
inline
Object::Object(string name) { setType(name); if (name == "blue") { //setHSVmin(Scalar(110, 50, 50)); //setHSVmax(Scalar(130, 256, 256)); setHSVmin(Scalar(103, 70, 50)); setHSVmax(Scalar(115, 255, 255)); // BGR value for Blue: setColor(Scalar(255, 0, 0)); } if (name == "green") { setHSVmin(Scalar(40, 100, 100)); setHSVmax(Scalar(70, 255, 255)); // BGR value for Green: setColor(Scalar(0, 255, 0)); } if (name == "yellow") { setHSVmin(Scalar(20, 124, 123)); setHSVmax(Scalar(30, 256, 256)); // BGR value for Yellow: setColor(Scalar(0, 255, 255)); } if (name == "red") { setHSVmin(Scalar(170, 135, 105)); setHSVmax(Scalar(184, 255, 255)); // BGR value for Red: setColor(Scalar(0, 0, 255)); } }
c++
10
0.507955
43
22.810811
37
inline
<?php namespace Tests\EventManager; use Virton\EventManager\EventManager; use PHPUnit\Framework\TestCase; use Psr\EventManager\EventInterface; class EventManagerTest extends TestCase { /** * @var EventManager */ private $manager; protected function setUp() { $this->manager = new EventManager(); } private function makeEvent(string $eventName = 'test.event', $target = 'target') { $event = $this->getMockBuilder(EventInterface::class)->getMock(); $event->method('getName')->willReturn($eventName); return $event; } public function testTriggerEvent() { $event = $this->makeEvent(); $this->manager->attach($event->getName(), function () { echo 'Event'; }); $this->manager->trigger($event->getName()); $this->expectOutputString('Event'); } public function testTriggerEventWithEventObject() { $event = $this->makeEvent(); $this->manager->attach($event->getName(), function () { echo 'Event'; }); $this->manager->trigger($event->getName()); $this->expectOutputString($event); $this->expectOutputString('Event'); } public function testTriggerMultipleEvent() { $event = $this->makeEvent(); $this->manager->attach($event->getName(), function () { echo 'EventA'; }); $this->manager->attach($event->getName(), function () { echo 'EventB'; }); $this->manager->trigger($event->getName()); $this->expectOutputRegex('/EventA/'); $this->expectOutputRegex('/EventB/'); } public function testTriggerOrderWithPriority() { $event = $this->makeEvent(); $this->manager->attach($event->getName(), function () { echo 'EventA'; }, 100); $this->manager->attach($event->getName(), function () { echo 'EventC'; }); $this->manager->attach($event->getName(), function () { echo 'EventB'; }, 10); $this->manager->trigger($event->getName()); $this->expectOutputString('EventAEventBEventC'); } public function testDetachListener() { $event = $this->makeEvent(); $callbackA = function () { echo 'EventA'; }; $callbackB = function () { echo 'EventB'; }; $this->manager->attach($event->getName(), $callbackA); $this->manager->attach($event->getName(), $callbackB); $this->manager->detach($event->getName(), $callbackB); $this->manager->trigger($event->getName()); $this->expectOutputString('EventA'); } public function testClearListeners() { $eventA = $this->makeEvent('a'); $eventB = $this->makeEvent('b'); $this->manager->attach($eventA->getName(), function () { echo 'EventA'; }); $this->manager->attach($eventA->getName(), function () { echo 'EventAA'; }); $this->manager->attach($eventB->getName(), function () { echo 'EventB'; }); $this->manager->clearListeners($eventA->getName()); $this->manager->trigger($eventA->getName()); $this->manager->trigger($eventB->getName()); $this->expectOutputString('EventB'); } }
php
13
0.551865
84
26.456
125
starcoderdata
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RequiredRefAttribute.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // Implements the required reference attribute class. // // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.AttributedModel { using System; using System.ComponentModel.DataAnnotations; using Kephas.Data.Resources; /// /// Attribute marking required references. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public class RequiredRefAttribute : ValidationAttribute { /// /// Initializes a new instance of the <see cref="RequiredRefAttribute"/> class. /// public RequiredRefAttribute() : base(() => Strings.RequiredRefAttribute_ValidationError) { } /// whether the specified value of the object is valid. /// if the specified value is valid; otherwise, false. /// <param name="value">The value of the object to validate. public override bool IsValid(object value) { if (value is IRef refValue) { return !refValue.IsEmpty; } return !Id.IsEmpty(value); } } }
c#
13
0.563788
142
38.043478
46
starcoderdata
#ifndef INC_TEST_GLV_H #define INC_TEST_GLV_H #include #include "glv.h" #include "glv_behavior.h" #include "glv_binding.h" #include "glv_icon.h" namespace glv{ struct CharView : public View{ CharView(const Rect& r=Rect(80, 110)) : View(r), input(0), thickness(2) { (*this) (Event::MouseDrag, Behavior::mouseMove) (Event::MouseDrag, Behavior::mouseResize); disable(CropSelf); } int input; float thickness; virtual void onDraw(GLV& g){ using namespace glv::draw; scale(w/8, h/11); // scale characters to extent of view color(colors().fore, 0.2); lineWidth(1); grid(g.graphicsData(), 0,0,8,11,8,11); color(colors().fore, 0.5); shape(Lines,0,8,8,8); // draw base line lineWidth(thickness); color(colors().fore); char str[2] = {input, '\0'}; text(str); } virtual bool onEvent(Event::t e, GLV& glv){ if(Event::KeyDown == e){ int key = glv.keyboard().key(); switch(key){ case Key::Up: thickness += 0.5; break; case Key::Down: thickness -= 0.5; if(thickness<1) thickness=1; break; default: input = key; } } return false; } }; struct ColorView : public View{ ColorView(const Rect& r=Rect(40)): View(r){} virtual void onDraw(GLV& g){ int divH = 32, divS = 16; float incH = 1./divH, incS = 1./divS; for(int i=0; i<divS; ++i){ float sat = (float)i * incS; Color col; for(int j=0; j<divH; ++j){ float hue = (float)j * incH; col.setHSV(hue, 1, sat*sat); draw::color(col); draw::rectangle(w * hue, h * sat, w * (hue + incH), h * (sat + incS)); } } } virtual bool onEvent(Event::t e, GLV& glv){ if(parent && glv.mouse().left()){ float sat = glv.mouse().yRel()/h; parent->colors().back.setHSV(glv.mouse().xRel()/w, 1, sat*sat); return false; } return true; } }; /// View that mimics another View class CopyCat : public View{ public: /// @param[in] src The View to mimic /// @param[in] controllable Whether to respond to input events CopyCat(View& src, bool controllable=true) : View(src), mSource(&src) { if(!controllable) disable(Controllable); } View& source() const { return *mSource; } CopyCat& source(View& v){ if(&v != this) mSource=&v; return *this; } virtual void onDraw(GLV& g){ space_t sw, sh; getDim(sw, sh); setDim(w, h); source().onDraw(g); setDim(sw, sh); } virtual bool onEvent(Event::t e, GLV& g){ space_t sw, sh; getDim(sw, sh); setDim(w, h); bool r = source().onEvent(e, g); setDim(sw, sh); return r; } protected: View * mSource; void getDim(space_t& sw, space_t& sh){ sw = source().w; sh = source().h; } void setDim(space_t sw, space_t sh){ source().w = sw; source().h = sh; } }; class RasterView : public View{ public: RasterView(const Rect& r, int nx, int ny) : View(r), mSizeX(nx), mSizeY(ny), mPrim(draw::LineStrip) { enable(DrawGrid); deselect(); } virtual void onDraw(GLV& g){ using namespace glv::draw; GraphicsData& gd = g.graphicsData(); if(enabled(DrawGrid)){ color(colors().fore, 0.25); grid(gd, 0,0,w,h,mSizeX,mSizeY, false); } color(colors().fore, 0.65); stroke(2); gd.reset(); for(unsigned i=0; i<mPoints.size(); ++i){ float x,y; indexToPoint(x,y, mPoints[i]); gd.addVertex(x,y); } paint(mPrim, gd); draw::enable(PointSmooth); stroke(6); gd.reset(); for(int i=0; i<(int)mPoints.size(); ++i){ float x,y; indexToPoint(x,y, mPoints[i]); if(isSelected() && mSelected == i){ gd.addColor(Color(1,0,0)); } else{ gd.addColor(colors().fore); } gd.addVertex(x,y); } paint(Points, gd); } virtual bool onEvent(Event::t e, GLV& g){ const Mouse& m = g.mouse(); const Keyboard& k = g.keyboard(); int idx; pointToIndex(idx, m.xRel(), m.yRel()); switch(e){ case Event::MouseDown: { if(k.shift()){ // append new point mPoints.push_back(idx); } else if(k.ctrl()){ // insert new point float dist = 1e7; int inear = -1; for(int i=mPoints.size()-1; i>0; --i){ int i1 = i-1; int i2 = i; float x1,y1, x2,y2, xn,yn; indexToPoint(x1,y1, mPoints[i1]); indexToPoint(x2,y2, mPoints[i2]); indexToPoint(xn,yn, idx); // measure distance to midpoint float xm = (x1+x2)*0.5; float ym = (y1+y2)*0.5; float d = (xm-xn)*(xm-xn) + (ym-yn)*(ym-yn); if(d < dist){ dist=d; inear=i2; } } if(inear >= 0){ mPoints.insert(mPoints.begin() + inear, idx); } } bool clickMatch=false; for(int i=mPoints.size()-1; i>=0; --i){ if(mPoints[i] == idx){ mSelected = i; clickMatch = true; break; } } if(!clickMatch) deselect(); } return false; case Event::MouseDrag: if(isSelected()){ mPoints[mSelected] = idx; } return false; case Event::KeyDown: switch(k.key()){ case 'c': mPoints.clear(); return false; case 'p': for(unsigned i=0; i<mPoints.size(); ++i){ printf("%c%d", i?',':'\0', mPoints[i]); } printf("\n"); return false; case '1': mPrim = draw::Lines; return false; case '2': mPrim = draw::LineStrip; return false; case '3': mPrim = draw::LineLoop; return false; case '4': mPrim = draw::Triangles; return false; case '5': mPrim = draw::TriangleStrip; return false; case '6': mPrim = draw::TriangleFan; return false; case '7': mPrim = draw::Quads; return false; case '8': mPrim = draw::QuadStrip; return false; case 'g': toggle(DrawGrid); return false; case Key::Delete: if(isSelected()) mPoints.erase(mPoints.begin()+mSelected); deselect(); return false; default:; } default:; } return true; } protected: int mSizeX, mSizeY; int mSelected; int mPrim; std::vector mPoints; float subDivX() const { return w/mSizeX; } float subDivY() const { return h/mSizeY; } bool isSelected(){ return mSelected>=0; } void deselect(){ mSelected=-1; } void pointToIndex(int& idx, float x, float y) const { int ix = glv::clip mSizeX-1); int iy = glv::clip mSizeY-1); idx = iy*mSizeX + ix; } void indexToPoint(float& x, float& y, int idx){ int ix = idx % mSizeX; int iy = idx / mSizeX; x = ((ix+0.5)/mSizeX) * w; y = ((iy+0.5)/mSizeY) * h; } }; } // glv:: #endif
c
25
0.58332
75
20.819728
294
starcoderdata
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Auth extends CI_Controller { private $siteUrl; private $userClass; private $language; function __construct() { parent::__construct(); $this->siteUrl = base_url(); $this->load->helper('language'); $this->language = language_selected(get_language(isset($_COOKIE['lang']) ? $_COOKIE['lang'] : '')); if (isset($_COOKIE['usr'])) { $this->user = $_COOKIE['usr']; $this->token = $_COOKIE['tkn']; $this->load->model('User_login', '', TRUE); $user = new User_login(); $result = $user->validate_hash($this->user, $this->token); if (!$result) { $user->unset_cookie($_COOKIE); header("Location: {$this->siteUrl}login"); exit; } else { header("Location: {$this->siteUrl}dashboard"); exit; } } } public function index() { $data['language'] = $this->language['login']['alert']; $data['content'] = $this->language['login']; $this->load->view('auth/common/header'); $this->load->view('auth/login', $data); $this->load->view('auth/common/footer'); } public function signin() { $data['language'] = $this->language['login']['alert']; $data['content'] = $this->language['register']; $this->load->view('auth/common/header'); $this->load->view('auth/register', $data); $this->load->view('auth/common/footer', $data); } public function recover() { $data['language'] = $this->language['recover']['alert']; $data['content'] = $this->language['recover']; $this->load->view('auth/common/header'); $this->load->view('auth/recover', $data); $this->load->view('auth/common/footer', $data); } public function register() { if ($this->input->is_ajax_request()) { $this->load->helper('escape'); $this->load->model('User_model', '', TRUE); $this->userClass = new User_model(); $el = escape_post($_POST, $this->db->conn_id); $password = if ($el['email'] != $el['email2']) { echo json_encode(array('login' => false)); die(); } else { $result = $this->userClass->select_user('email', $el['email']); } if (empty($result)) { $dateTime = date("Y-m-d H:i:s"); $numRandom = md5(rand()); $config = array( 'name' => $el['name'], 'pass' => 'email' => $el['email'], 'approved' => 0, 'initial_date' => $dateTime, 'token_recover' => $numRandom, ); if ($this->userClass->create_user($config)) { $this->load->library('Emails'); $data['email'] = $el['email']; $data['site'] = $this->siteUrl; $data['token'] = $data['language'] = $this->language['email']['register']; $assunto = $this->language['email']['register']['topic']; $mensagem = $this->load->view('auth/template/email/register', $data, TRUE); if ($this->emails->enviar($assunto, $mensagem, $el['email'])) { echo json_encode(array('login' => 1)); } else { echo json_encode(array('login' => 0)); } } } else { echo json_encode(array('login' => 2)); } } } public function validate() { if ($this->input->is_ajax_request()) { $this->load->helper('escape'); $el = escape_post($_POST, $this->db->conn_id); $password = $this->load->model('User_login', '', TRUE); $user = new User_login(); $result = $user->validate_login($el['email'], $password); if (!empty($result)) { if ($result[0]->approved) { $user->create_hash($el['email'], $password, $result[0]); echo json_encode(array('res' => 1)); } else { echo json_encode(array('res' => 2)); } } else { echo json_encode(array('res' => 0)); } } else { echo json_encode(array('res' => 0)); } } }
php
21
0.444285
107
30.79085
153
starcoderdata
package model type Search struct { Result struct { Item []SearchItem `json:"item"` TotalResults int `json:"total_results"` Status SearchStatus `json:"status"` PageSize string `json:"page_size"` } `json:"result"` RateLimit *RateLimit } type SearchItem struct { PromotionPrice string `json:"promotion_price"` Loc string `json:"loc"` NumIid int64 `json:"num_iid"` Usertype int `json:"usertype"` Pic string `json:"pic"` Title string `json:"title"` Sales int `json:"sales"` SellerId int64 `json:"seller_id"` SellerNick string `json:"seller_nick"` DeliveryFee string `json:"delivery_fee"` Price string `json:"price"` DetailUrl string `json:"detail_url"` ShopTitle string `json:"shop_title"` } type SearchStatus struct { Msg string `json:"msg"` ExecutionTime string `json:"execution_time"` Code int `json:"code"` Action int `json:"action"` } func (d Search) IsSuccess() bool { return d.Result.Status.Msg == "success" }
go
10
0.606884
50
28.052632
38
starcoderdata
int MaxHeap::removeTheHighestNumber() { int swap = 0; int size = numbers.size(); if (size <= 1) return -1; int removedNumber = numbers[1]; numbers[1] = numbers.back(); numbers.pop_back(); //remove o ultimo elemento size = numbers.size(); //atualiza o tamanho int index = 1; int higuestChildPos = 0; int rightChildPos = 0; while (index < size) { //verifica qual dos dois filhos é o menor higuestChildPos = leftChildRealPos(index); rightChildPos = rightChildRealPos(index); if (higuestChildPos < size && rightChildPos < size) { if (numbers[higuestChildPos] < numbers[rightChildPos]) higuestChildPos = rightChildPos; //Verifica se deve fazer a troca if (numbers[index] < numbers[higuestChildPos]) { swap = numbers[index]; numbers[index] = numbers[higuestChildPos]; numbers[higuestChildPos] = swap; index = higuestChildPos; } else break; } else if (higuestChildPos < size) { //Verifica se deve fazer a troca if (numbers[index] < numbers[higuestChildPos]) { swap = numbers[index]; numbers[index] = numbers[higuestChildPos]; numbers[higuestChildPos] = swap; index = higuestChildPos; } else break; } else break; //Não precisa continuar } return removedNumber; }
c++
15
0.529339
66
26.457627
59
inline
Projet_media ============ import os from subprocess import Popen, PIPE import shlex import re import fileinput mkvpath='<Chemin vers le dossier à lire>' for mkv in os.listdir(mkvpath): mkvSansext=mkv.split('.')[0] commandeMKVmerge = shlex.split('mkvmerge -I %s' %(mkv)) appelMKVmerge = Popen(commandeMKVmerge, stdout=PIPE, universal_newlines=True) lectureMKVmerge = appelMKVmerge.stdout.readlines() listePistes=[] for ligne in lectureMKVmerge: #ligne=ligne.decode('utf-8') if not 'video' in ligne and not 'audio' in ligne: recherche=re.search('Track ID ([0-9]{1}): (.*) (\(.*\)) .*language:([a-z]{3})',ligne) if recherche: numTrack=recherche.group(1) pisteNom=recherche.group(2) pisteGenre=recherche.group(3) pisteLangue=recherche.group(4) l=numTrack+pisteNom+pisteLangue listePistes.append([numTrack,pisteGenre,pisteLangue]) appelMKVmerge.stdout.close() for x in listePistes: langue=x[2] if x[1]=='(VobSub)': commande='%s:%s_%s' %(x[0],mkvSansext,x[2]) commandeMKVextract=shlex.split('mkvextract tracks %s %s' %(mkv,commande)) appelMKVextract=Popen(commandeMKVextract,stdout=PIPE) stopExtract=appelMKVextract.communicate() for idx_sub in os.listdir(mkvpath): if idx_sub.endswith('.idx'): idx=idx_sub idxSansext=idx_sub.split('.')[0] elif idx_sub.endswith('.sub'): sub=idx_sub subSansext=idx_sub.split('.')[0] commandeSub2tiff=shlex.split('subp2tiff --sid=0 -n %s %s' %(idxSansext,subSansext)) appelSub2tiff=Popen(commandeSub2tiff, stdout=PIPE) stopSub2tiff=appelSub2tiff.communicate() commandeSupidxsub=shlex.split('rm %s %s' %(idx,sub)) appelSupidxsub=Popen(commandeSupidxsub, stdout=PIPE) stopRMidxsub=appelSupidxsub.communicate() for tif in os.listdir(mkvpath): if tif.endswith('.tif'): tifsansExtention=tif.split('.')[0] # p=shlex.split('tesseract %s %s -l fra' %(tifsansExtention,tifsansExtention)) if langue == 'fre': langue=re.sub('fre','fra',langue) Commandetif2txt=shlex.split('tesseract %s %s -l %s -psm 6' %(tif,tifsansExtention,langue)) Appeltif2txt=Popen(Commandetif2txt,stdout=PIPE) stoptif2txt=Appeltif2txt.communicate() commandeSuptif=shlex.split('rm %s' %(tif)) appelSuptif=Popen(commandeSuptif,stdout=PIPE) stopRMtif=appelSuptif.communicate() for xml in os.listdir(mkvpath): if xml.endswith('.xml'): for line in fileinput.input(xml, inplace = 1): print (line.replace(".tif", "")) commandeSubptools=shlex.split('subptools -s -w -t srt -i %s -o %s_%s.srt' %(xml,mkvSansext,langue)) appelSubptools=Popen(commandeSubptools,stdout=PIPE) stopSubptools=appelSubptools.communicate() commandeSupxml=shlex.split('rm %s' % (xml)) appelSupxml=Popen(commandeSupxml,stdout=PIPE) stopRMxml=appelSupxml.communicate() for txt in os.listdir(mkvpath): if txt.endswith('.txt'): commandeSuptxt=shlex.split('rm %s' % (txt)) appelSuptxt=Popen(commandeSuptxt,stdout=PIPE) stopRMtxt=appelSuptxt.communicate()
python
17
0.704576
103
35.337349
83
starcoderdata
void arm7_resetMemory (void) { int i; u8 settings1, settings2; u32 settingsOffset = 0; REG_IME = 0; for (i=0; i<16; i++) { SCHANNEL_CR(i) = 0; SCHANNEL_TIMER(i) = 0; SCHANNEL_SOURCE(i) = 0; SCHANNEL_LENGTH(i) = 0; } REG_SOUNDCNT = 0; // Clear out ARM7 DMA channels and timers for (i=0; i<4; i++) { DMA_CR(i) = 0; DMA_SRC(i) = 0; DMA_DEST(i) = 0; TIMER_CR(i) = 0; TIMER_DATA(i) = 0; } // Clear out FIFO REG_IPC_SYNC = 0; REG_IPC_FIFO_CR = IPC_FIFO_ENABLE | IPC_FIFO_SEND_CLEAR; REG_IPC_FIFO_CR = 0; // clear IWRAM - 037F:8000 to 0380:FFFF, total 96KiB arm7_clearmem ((void*)0x037F8000, 96*1024); // clear most of EXRAM - except after 0x023FA800, which has the ARM9 code arm7_clearmem ((void*)0x02000000, 0x003FA800); // clear last part of EXRAM, skipping the ARM9's section arm7_clearmem ((void*)0x023FF000, 0x1000); REG_IE = 0; REG_IF = ~0; (*(vu32*)(0x04000000-4)) = 0; //IRQ_HANDLER ARM7 version (*(vu32*)(0x04000000-8)) = ~0; //VBLANK_INTR_WAIT_FLAGS, ARM7 version REG_POWERCNT = 1; //turn off power to stuffs // Get settings location arm7_readFirmware((u32)0x00020, (u8*)&settingsOffset, 0x2); settingsOffset *= 8; // Reload DS Firmware settings arm7_readFirmware(settingsOffset + 0x070, &settings1, 0x1); arm7_readFirmware(settingsOffset + 0x170, &settings2, 0x1); if ((settings1 & 0x7F) == ((settings2+1) & 0x7F)) { arm7_readFirmware(settingsOffset + 0x000, (u8*)0x027FFC80, 0x70); } else { arm7_readFirmware(settingsOffset + 0x100, (u8*)0x027FFC80, 0x70); } if (language >= 0 && language < 6) { *(u8*)(0x027FFCE4) = language; // Change language } // Load FW header arm7_readFirmware((u32)0x000000, (u8*)0x027FF830, 0x20); }
c
12
0.633787
74
25.353846
65
inline
// This is a a javascript (or similar language) file // sync-start:correct 249234014 __examples__/correct_checksums/b.py const someCode = "does a thing"; console.log(someCode); // sync-end:correct // sync-start:correct2 279463297 __examples__/correct_checksums/b.py // sync-start:correct2 1992689801 __examples__/correct_checksums/c.jsx const outputDir = path.join(rootDir, "genwebpack/khan-apollo"); // Handle auto-building the GraphQL Schemas + Fragment Types module.exports = new FileWatcherPlugin({ name: "GraphQL Schema Files", // The location of the Python files that are used to generate the // schema filesToWatch: [ path.join(rootDir, "*/graphql/**/*.py"), path.join(rootDir, "*/*/graphql/**/*.py"), ], // sync-end:correct2
javascript
6
0.699634
70
34.608696
23
starcoderdata
if(typeof window['_vue'] == 'undefined'){ window['_vue'] = {}; } class modalDatabaseDeleteDataComponent { request = null; url = null; loader = null; toast = null; databaseIndexIndexComponent = null; selectedData = {}; formField = { target_field_index: 'no', remove_in_database: false } constructor(){ this.request = window['opoink_system']['_request']; this.url = window['opoink_system']['_url']; } init(){ setTimeout(f => { this.loader = window['_vue']['loader-component']; this.toast = window['_vue']['toast-component']; }, 100); } resetFormFields() { this.selectedData = {}; this.formField = { target_field_index: 'no', remove_in_database: false } } setEditFormField(data, index){ $.each(this.databaseIndexIndexComponent.selectedTableFields.fields, (key, val) => { if(typeof data[val.name] == 'undefined'){ data[val.name] = { value: '', option: { is_hashed: false, primary: false } } } }); this.selectedData = data; this.formField.target_field_index = index; $('#modalDatabaseDeleteInstallData').modal('show'); } deleteInstallData(e){ e.preventDefault(); let jsonData = { module: this.databaseIndexIndexComponent.selectedModule, tablename: this.databaseIndexIndexComponent.selectedTableName, fields: this.selectedData, target_field_index: this.formField.target_field_index, remove_in_database: this.formField.remove_in_database } this.loader.setLoader(true, 'Deleting installation data...'); this.request.getFormKey().then(formkey => { jsonData['form_key'] = formkey; let url = '/' + this.url.getRoute() + '/database/deleteinstalldata'; this.request.makeRequest(url, jsonData, 'POST', true).then(result => { if(!result.error && result.result){ $.each(result.result, (key, val) => { this.toast.add(val, 'Success'); }); this.databaseIndexIndexComponent.setTableRows( this.databaseIndexIndexComponent.selectedModule, this.databaseIndexIndexComponent.selectedTableName, this.databaseIndexIndexComponent.selectedTableValue ); this.resetFormFields(); $('#modalDatabaseDeleteInstallData').modal('hide'); } else if(result.error && !result.result){ this.toast.add(result.error.responseText, 'Error'); } this.loader.reset(); }); }); } } window['_vue']['modal-database-delete-data-component'] = new modalDatabaseDeleteDataComponent(); Vue.component('modal-database-delete-data-component', { data: function(){ return { vue: window['_vue']['modal-database-delete-data-component'] } }, mounted: function() { this.vue.databaseIndexIndexComponent = this.databaseIndexIndexComponent; this.vue.init(); }, props: ['databaseIndexIndexComponent'], template: `{{template}}` });
javascript
26
0.642296
96
23.469565
115
starcoderdata
package io.quarkus.vertx.http.deployment; import io.quarkus.builder.item.SimpleBuildItem; public final class HttpRootPathBuildItem extends SimpleBuildItem { private final String rootPath; public HttpRootPathBuildItem(String rootPath) { this.rootPath = rootPath; } public String getRootPath() { return rootPath; } public String adjustPath(String path) { if (!path.startsWith("/")) { throw new IllegalArgumentException("Path must start with /"); } if (rootPath.equals("/")) { return path; } return rootPath + path; } }
java
11
0.633914
73
23.269231
26
starcoderdata
/* @flow */ import Heretic from 'heretic'; import {knex} from 'server/lib/knex'; export default new Heretic(process.env.AMQP_URL, knex, { socketOptions: { clientProperties: { Application: 'Workers', }, }, });
javascript
11
0.640351
56
19.727273
11
starcoderdata
package org.netmelody.cieye.server.response.responder; import java.io.IOException; import org.netmelody.cieye.server.CiEyeNewVersionChecker; import org.netmelody.cieye.server.CiEyeServerInformationFetcher; import org.netmelody.cieye.server.response.CiEyeResponder; import org.netmelody.cieye.server.response.CiEyeResponse; import org.netmelody.cieye.server.response.JsonTranslator; import org.simpleframework.http.Request; public final class CiEyeVersionResponder implements CiEyeResponder { public static final class VersionInformation { @SuppressWarnings("unused") private final String currentServerVersion; @SuppressWarnings("unused") private final String latestServerVersion; private VersionInformation(String currentServerVersion, String latestServerVersion) { this.currentServerVersion = currentServerVersion; this.latestServerVersion = latestServerVersion; } } private final CiEyeServerInformationFetcher configurationFetcher; private final CiEyeNewVersionChecker updateChecker; public CiEyeVersionResponder(CiEyeServerInformationFetcher configurationFetcher, CiEyeNewVersionChecker updateChecker) { this.configurationFetcher = configurationFetcher; this.updateChecker = updateChecker; } @Override public CiEyeResponse respond(Request request) throws IOException { final VersionInformation versionInformation = new VersionInformation(configurationFetcher.getVersion(), updateChecker.getLatestVersion()); return CiEyeResponse.withJson(new JsonTranslator().toJson(versionInformation)).expiringInMillis(10000L); } }
java
10
0.75864
124
43.85
40
starcoderdata
using System; namespace R5T.NetStandard { public static class LowercaseStringUnvalidatedExtensions { /// /// Determines if a string really is an uppercase string. /// public static bool IsValid(this LowercaseStringUnvalidated lowercaseStringUnvalidated) { // Is the result of ToLowerInvariant() the same as the input? var lowered = lowercaseStringUnvalidated.Value.ToLowerInvariant(); var output = lowercaseStringUnvalidated.Value == lowered; return output; } public static bool TryValidate(this LowercaseStringUnvalidated lowercaseStringUnvalidated, out LowercaseString lowercaseString) { var isValid = lowercaseStringUnvalidated.IsValid(); if (isValid) { lowercaseString = new LowercaseString(lowercaseStringUnvalidated.Value); } else { lowercaseString = LowercaseString.Invalid; } return isValid; } /// /// Throw an <see cref="Exception"/> if the upper-case string value is invalid. /// public static LowercaseString Validate(this LowercaseStringUnvalidated lowercaseStringUnvalidated) { var isValid = lowercaseStringUnvalidated.TryValidate(out var lowercaseString); if (!isValid) { throw new Exception($"Value '{lowercaseStringUnvalidated.Value}' was not a lower-case string."); } return lowercaseString; } } }
c#
16
0.617759
148
34.96
50
starcoderdata
lbool type_context_old::try_nat_offset_cnstrs(expr const & t, expr const & s) { /* We should not use this feature when transparency_mode is none. See issue #1295 */ if (m_transparency_mode == transparency_mode::None) return l_undef; lbool r; r = try_offset_eq_offset(t, s); if (r != l_undef) return r; r = try_offset_eq_numeral(t, s); if (r != l_undef) return r; { swap_update_flags_scope scope(*this); r = try_offset_eq_numeral(s, t); if (r != l_undef) return r; } return try_numeral_eq_numeral(t, s); }
c++
8
0.596522
79
35
16
inline
var TestRageFace = artifacts.require("./TestRageFace.sol"); module.exports = async function(deployer, network, accounts) { const [admin, _] = accounts; await deployer.deploy(TestRageFace, "Rage Face", "RF", "https://rageface.com/", "1633137803"); };
javascript
10
0.703125
96
35.571429
7
starcoderdata
package seedu.planner.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.chart.PieChart; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Shape; //@@author tenvinc /** * This class is a custom PieChart class that can be used to display statistics in FinancialPlanner */ public class CustomPieChart extends PieChart { public static final String CSS_FILE = "view/DarkTheme.css"; private ObservableList observableData; private CustomLegend legend; public CustomPieChart(List labelData, List legendData) { super(); getStylesheets().add(CSS_FILE); legend = new CustomLegend(this, legendData); setLegend(legend.getRoot()); setData(FXCollections.observableList(labelData)); labelData.forEach(data -> data.nameProperty().bind(Bindings.concat(customTextWrap(data.getName()), "\n", data.pieValueProperty(), "%"))); observableData = FXCollections.observableList(getData().stream() .map(d -> String.format("%s %f", d.getName(), d.getPieValue())) .collect(Collectors.toList())); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof CustomPieChart // instanceof handles nulls && legend.equals(((CustomPieChart) other).legend) && observableData.equals(((CustomPieChart) other).observableData)); } /** * It will slice the label input based on commas as delimiters. Each slice of the label will be on a new line to * simulate the text wrap feature of java * @param label label to be wrapped * @return wrapped label */ private String customTextWrap(String label) { List labelArr = Arrays.asList(label.split(",")); StringBuilder stringBuilder = new StringBuilder(); for (String s : labelArr) { s.trim(); stringBuilder.append(s); if (labelArr.indexOf(s) < labelArr.size() - 1) { stringBuilder.append("\n"); } } return stringBuilder.toString(); } /** * This class represents a customized legend panel for the pieChart */ class CustomLegend extends UiPart { private static final int defaultSymbolXPos = 10; private static final int defaultSymbolYPos = 10; private static final int defaultSymbolWidth = 10; private static final int defaultSymbolHeight = 10; private static final String FXML = "CustomLegend.fxml"; @FXML private GridPane legendGrid; private List labelList; CustomLegend(PieChart chart, List pieChartData) { super(FXML); labelList = new ArrayList<>(); int index = 0; for (Data d : pieChartData) { Label legendText = createLabel(d.getName() + " " + convertToMoney(d.getPieValue())); legendText.setWrapText(true); legendGrid.addRow(index, createSymbol(pieChartData.indexOf(d)), legendText); labelList.add(legendText.getText()); index++; } } private Label createLabel(String text) { Label label = new Label(text); label.getStyleClass().add("default-legend-text"); return label; } private String convertToMoney(Double data) { return String.format("$%.2f", data); } /** * Creates the symbol to be placed at the side of the label */ private Node createSymbol(int index) { Shape symbol = new Rectangle(defaultSymbolXPos, defaultSymbolYPos, defaultSymbolWidth, defaultSymbolHeight); symbol.getStyleClass().add(String.format("default-color%d-chart-pie-legend", index % 8)); return symbol; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof CustomLegend// instanceof handles nulls && labelList.equals((((CustomLegend) other).labelList))); } } }
java
18
0.626083
120
35.634921
126
starcoderdata
process.umask(077); process.env.DEBUG = true; var http = require('http'), fs = require('fs'), mkdirp = require('mkdirp'), inboxpath = '/data/inbox/post-me-anything/'; function postMeAnything(req, res) { console.log('hit', req.url); var str = ''; req.on('data', function(chunk) { console.log('chunk', chunk.toString()); str += chunk.toString(); }); req.on('end', function() { var msgPath = inboxpath+(new Date()).getTime().toString(); fs.writeFile(msgPath, new Buffer(str), function(err) { console.log('saved as', msgPath, str, err); res.writeHead(202, { 'Access-Control-Allow-Origin': req.headers.origin || '*' }); res.end('https://michielbdejong.com/blog/7.html#webmentions'); }); }); } mkdirp(inboxpath, function(err1) { http.createServer(postMeAnything).listen(7678); console.log('port 7678 running'); }); console.log('port 7678 running');
javascript
21
0.629553
68
28.121212
33
starcoderdata
namespace WavesBot.Data { public class AccountStamp { public string RsaPublicKey { get; set; } } }
c#
6
0.630769
48
15.375
8
starcoderdata
package cherry.gallery.web.login; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Setter @Getter @EqualsAndHashCode @ToString public class LoginFormBase { private String loginId; private String password; }
java
4
0.776596
90
17.842105
19
starcoderdata
package com.dm.data.domain.doc; /* * 这个仅仅用于smart-doc的类型替换,没有任何实际用途 */ /** * 限定范围的分页请求 */ public class RangePageableDto extends PageableDto { private static final long serialVersionUID = 4804864324327815933L; /** * 请求的最大范围值,可能是数字或者字符串,根据实际情况而定 */ private String max; public Object getMax() { return max; } public void setMax(String max) { this.max = max; } }
java
8
0.63658
70
15.84
25
starcoderdata
package algorithms.core; import java.awt.Point; import java.util.LinkedHashMap; /** * Базовый интерфейс состояния игры. * * Определяет базовый интерфейс состояния игры, позволяющий осуществлять * навигацию по графу состояния. * * @param тип действий, предпринимаемых игроками * @see BreadthFirstSearch */ public interface IBasicState { /** * Перечень доступных действий. * * Возвращает перечень действий, доступных из заданного расположения * в виде ассоциативного массива упорядоченных пар * "расположение в результате действия = действие". * * Для действий передвижения доступны проходимые клетки лабиринта. * * @param place расположение * @return перечень доступных действий */ public LinkedHashMap<Point, T> getLegalActionsAsMap(Point place); /** * Перечень доступных действий с учётом типа игрока. * * Возвращает перечень действий, доступных из заданного расположения * в виде ассоциативного массива упорядоченных пар * "расположение в результате действия = действие". * * Для действий передвижения доступны проходимые клетки лабиринта, исключая * клетки, занятые игроками того же типа, что тип * * @param place расположение * @param playerId идентификатор игрока * @return перечень доступных действий */ public LinkedHashMap<Point, T> getLegalActionsAsMapNoKins(Point place, int playerId); }
java
7
0.685209
89
32.391304
46
starcoderdata
using AutoMapper; using FavProducts.Domain; using FavProducts.Core.Rest.Transport; namespace FavProducts.Infrastructure.AutoMapper { public class AutoMapperProfile : Profile { public AutoMapperProfile() { CreateMap<User, UserRequest>(); CreateMap<UserRequest, User>(); } } }
c#
11
0.703791
85
25.4375
16
starcoderdata
package com.yiwen.guet.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import com.yiwen.guet.R; import com.yiwen.guet.adapter.MenuAdapter; import com.yiwen.guet.db.LinkNode; import com.yiwen.guet.service.CourseService; import com.yiwen.guet.service.LinkService; import com.yiwen.guet.utils.HttpUtil; import com.yiwen.guet.utils.LinkUtil; import com.yiwen.guet.utils.SharedPreferenceUtil; import java.io.UnsupportedEncodingException; import java.util.List; /** * @author lizhangqu * @date 2015-2-1 */ public class MainActivity extends Activity { private GridView gridView; private LinkService linkService; private CourseService courseService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initValue();// 变量初始化 initView();// 视图初始话 initEvent();// 事件初始化 } /** * 初始化变量 */ private void initValue() { linkService = LinkService.getLinkService(); courseService = CourseService.getCourseService(); } /** * 初始化View */ private void initView() { gridView = (GridView) findViewById(R.id.gridview); List objects = linkService.findAll(); gridView.setAdapter(new MenuAdapter(getApplicationContext(), R.layout.item_linknode_layout, objects)); } /** * 初始事件 */ private void initEvent() { // 一系列点击事件的初始化 gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { TextView temp = (TextView) view.findViewById(R.id.title); String title = temp.getText().toString(); Log.d("MainActivity", "onItemClick: "+title.equals(LinkUtil.KB)); if (title.equals(LinkUtil.KB)) { LinkService linkService=LinkService.getLinkService(); String res =LinkService.getLinkByName("修改口令"); Log.d("res", "onItemClick: "+res); // jump2Kb(false); } else { Toast.makeText(getApplicationContext(), title, Toast.LENGTH_SHORT).show(); } } }); } /** * 跳到课表页面 */ private void jump2Kb(boolean flag) { SharedPreferenceUtil util = new SharedPreferenceUtil( getApplicationContext(), "flag"); if (flag) { //flag为true直接跳转 util.setKeyData(LinkUtil.KB, "TRUE"); Intent intent = new Intent(MainActivity.this, CourseActivity.class); startActivity(intent); } else { //flag为false,则先判断是否获取过课表 //如果已经获取过课表,则跳转 String keyData = util.getKeyData(LinkUtil.KB); if (keyData.equals("TRUE")) { Intent intent = new Intent(MainActivity.this, CourseActivity.class); startActivity(intent); } else { //未获取则获取 HttpUtil.getQuery(MainActivity.this, linkService, LinkUtil.KB, new HttpUtil.QueryCallback() { @Override public String handleResult(byte[] result) { String ret = null; try { ret = courseService.parseCourse(new String(result, "gb2312")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } jump2Kb(true); return ret; } }); } } } }
java
25
0.569942
109
30.784615
130
starcoderdata
let model = require("../models/vip.js"); let async = require("async"); module.exports.vips = function (request, response) { response.title = "Administration vips"; response.render('vips', response); }; /////////////////////////////Ajout//////////////////////////// module.exports.AjouterVipTest = function (request, response) { response.title = "Administration vips"; model.nationalites(function (err, result) { if (err) { console.log(err); return; } response.nationalites = result; response.render('formulaireVip', response); }); }; module.exports.AjouterVip = function (request, response) { response.title = "Administration vips"; let nom = request.body.nom; let prenom = request.body.prenom; let sexe = request.body.sexe; let datenaissance = request.body.datenaissance; let nationalite = request.body.nationalite; let commentaire = request.body.commentaire; let photo_adresse = request.body.photo; let photo_sujet = request.body.photo_sujet; let photo_commentaire = request.body.photo_commentaire; let vip = { 'NATIONALITE_NUMERO': nationalite, 'VIP_NOM': nom, 'VIP_PRENOM': prenom, 'VIP_SEXE': sexe, 'VIP_NAISSANCE': datenaissance, 'VIP_TEXTE': commentaire }; let photoVip = {'PHOTO_SUJET': photo_sujet, 'PHOTO_COMMENTAIRE': photo_commentaire, 'PHOTO_ADRESSE': photo_adresse}; async.series([ function (callback) { model.nationalites(function (err, result) { callback(null, result) }); }, function (callback) { model.InsererVip(vip, function (err2, result2) { callback(null, result2); }); } ], function (err, result) { if (err) { console.log(err); return; } response.nationalites = result[0]; model.InsererPhotoVip(photoVip, result[1].insertId); response.render('formulaireVip', response); }); }; /////////////////////////////Modification//////////////////////////// module.exports.ModifierVipTest = function (request, response) { response.title = "Administration vips"; async.series([ function (callback) { model.nationalites(function (err, result) { callback(null, result) }); }, function (callback) { model.vips(function (err2, result2) { callback(null, result2); }); } ], function (err, result) { if (err) { console.log(err); return; } response.nationalites = result[0]; response.vips = result[1]; response.modif = true; response.render('formulaireVip', response); }); }; module.exports.ModifierVip = function (request, response) { response.title = "Administration vips"; let vipNum = request.body.vip; let nom = request.body.nom; let prenom = request.body.prenom; let sexe = request.body.sexe; let datenaissance = request.body.datenaissance; let nationalite = request.body.nationalite; let commentaire = request.body.commentaire; let photo_adresse = request.body.photo; let photo_sujet = request.body.photo_sujet; let photo_commentaire = request.body.photo_commentaire; let vip = { 'VIP_NUMERO': vipNum, 'NATIONALITE_NUMERO': nationalite, 'VIP_NOM': nom, 'VIP_PRENOM': prenom, 'VIP_SEXE': sexe, 'VIP_NAISSANCE': datenaissance, 'VIP_TEXTE': commentaire }; let photoVip = { 'VIP_NUMERO': vipNum, 'PHOTO_SUJET': photo_sujet, 'PHOTO_COMMENTAIRE': photo_commentaire, 'PHOTO_ADRESSE': photo_adresse }; async.series([ function (callback) { model.nationalites(function (err, result) { callback(null, result) }); }, function (callback) { model.vips(function (err2, result2) { callback(null, result2) }); }, function (callback) { model.UpdateVip(vip, function (err3, result3) { callback(null, result3); }); }, function (callback) { model.UpdatePhotoVip(photoVip, function (err4, result4) { callback(null, result4) }); } ], function (err, result) { if (err) { console.log(err); return; } response.nationalites = result[0]; response.vips = result[1]; response.modif = true; response.render('formulaireVip', response); }); }; /////////////////////////////Suppression////////////////////////////// module.exports.SupprimerVipTest = function (request, response) { response.title = "Administration vips"; model.vips(function (err, result) { if (err) { console.log(err); return; } response.vips = result; response.render('supprimerVip', response); }); }; module.exports.SupprimerVip = function (request, response) { response.title = "Administration vips"; let vipNum = request.body.vip; async.series([ function (callback) { model.vips(function (err, result) { callback(null, result) }); }, function (callback) { model.DeleteVip(vipNum, function (err3, result3) { callback(null, result3); }); } ], function (err, result) { if (err) { console.log(err); return; } response.vips = result[0]; response.render('supprimerVip', response); }); };
javascript
19
0.511336
120
27.791667
216
starcoderdata