file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
abstract-model-rest.ts | import { logger } from '../../../lib/logger';
import { Modifier } from '../../../client/utils/utils';
import { ICommonOptions } from '../../../client/redux/reducers/solvers';
import { UseKeys } from '../../../lib/utils';
import { getValidationError } from '../../utils';
import { IValidationResult, IValidator, validateS... |
private static prepareFormula(formula: IFormula) {
const newFormula = cloneDeep(formula);
newFormula.text = AbstractModelRest.prepareText(newFormula.text);
return newFormula;
}
private static prepareModel(model: IModel) {
const newModel = [];
for (const formula of ... | {
return replace(text, /(\{|\})/g, "");
} | identifier_body |
abstract-model-rest.ts | import { logger } from '../../../lib/logger';
import { Modifier } from '../../../client/utils/utils';
import { ICommonOptions } from '../../../client/redux/reducers/solvers';
import { UseKeys } from '../../../lib/utils';
import { getValidationError } from '../../utils';
import { IValidationResult, IValidator, validateS... |
validator.obj.model = AbstractModelRest.prepareModel(validator.obj.model);
validator.obj.params = AbstractModelRest.prepareParameters(validator.obj.params);
if (this.modifyBody) {
this.modifyBody(validator.obj);
}
return {
model: _.map(validator.obj.model... | {
logger.error(validator.error.message);
throw "Validation error: " + validator.error.message
} | conditional_block |
abstract-model-rest.ts | import { logger } from '../../../lib/logger';
import { Modifier } from '../../../client/utils/utils';
import { ICommonOptions } from '../../../client/redux/reducers/solvers';
import { UseKeys } from '../../../lib/utils';
import { getValidationError } from '../../utils';
import { IValidationResult, IValidator, validateS... | options: validator.obj.options,
parameters: validator.obj.params
};
}
solveModel() {
return async (req: Request, res: Response) => {
try {
const body = this.prepareBody(req.body);
const solutionRes = await request.post(solverUr... | return {
model: _.map(validator.obj.model, x => x.text),
initialValues: _.map(validator.obj.model, x => x.initialValue), | random_line_split |
abstract-model-rest.ts | import { logger } from '../../../lib/logger';
import { Modifier } from '../../../client/utils/utils';
import { ICommonOptions } from '../../../client/redux/reducers/solvers';
import { UseKeys } from '../../../lib/utils';
import { getValidationError } from '../../utils';
import { IValidationResult, IValidator, validateS... | () {
return async (req: Request, res: Response) => {
try {
const body = this.prepareBody(req.body);
const solutionRes = await request.post(solverUrl + this.url).send(body);
const validator = this.responseValidator(body)(solutionRes.body);
... | solveModel | identifier_name |
ItemMgridTemplate.tsx | import React from 'react';
import {MediaPreview} from './MediaPreview';
import {MediaInfo} from './MediaInfo';
import {GridTypeIcon} from './GridTypeIcon';
import {IArticle} from 'superdesk-interfaces/Article';
import {IDesk} from 'superdesk-interfaces/Desk';
import {ItemPriority} from './ItemPriority';
import {ItemUrg... | svc: any;
ingestProvider: any;
onMultiSelect(): any;
broadcast(obj: any): any;
getActionsMenu(): any;
}
export class ItemMgridTemplate extends React.Component<IProps, never> {
render() {
const {item} = this.props;
return (
<div>
<MediaPreview
... | desk: IDesk;
swimlane: any; | random_line_split |
ItemMgridTemplate.tsx | import React from 'react';
import {MediaPreview} from './MediaPreview';
import {MediaInfo} from './MediaInfo';
import {GridTypeIcon} from './GridTypeIcon';
import {IArticle} from 'superdesk-interfaces/Article';
import {IDesk} from 'superdesk-interfaces/Desk';
import {ItemPriority} from './ItemPriority';
import {ItemUrg... | () {
const {item} = this.props;
return (
<div>
<MediaPreview
item={item}
desk={this.props.desk}
onMultiSelect={this.props.onMultiSelect}
swimlane={this.props.swimlane}
svc={th... | render | identifier_name |
files.rs | ::{cbor_stream_filtered_errors, get_repo};
use super::{EdenApiHandler, EdenApiMethod, HandlerInfo, HandlerResult};
/// XXX: This number was chosen arbitrarily.
const MAX_CONCURRENT_FILE_FETCHES_PER_REQUEST: usize = 10;
const MAX_CONCURRENT_UPLOAD_FILENODES_PER_REQUEST: usize = 1000;
#[derive(Debug, Deserialize, Sta... |
Ok(stream::iter(fetches)
.buffer_unordered(MAX_CONCURRENT_FILE_FETCHES_PER_REQUEST)
.inspect(move |response| {
if let Ok(result) = &response {
if result.result.is_ok() {
ctx.session().bump_load(Metric::GetpackFiles, 1.0);
... | {
let ctx = repo.ctx().clone();
let len = request.keys.len() + request.reqs.len();
let reqs = request
.keys
.into_iter()
.map(|key| FileSpec {
key,
attrs: FileAttributes {
content: true,
... | identifier_body |
files.rs | ());
ctx.perf_counters()
.add_to_counter(PerfCounterType::EdenapiFiles, len as i64);
let fetches = reqs.map(move |FileSpec { key, attrs }| fetch_file(repo.clone(), key, attrs));
Ok(stream::iter(fetches)
.buffer_unordered(MAX_CONCURRENT_FILE_FETCHES_PER_REQUEST)
... | random_line_split | ||
files.rs | ::{cbor_stream_filtered_errors, get_repo};
use super::{EdenApiHandler, EdenApiMethod, HandlerInfo, HandlerResult};
/// XXX: This number was chosen arbitrarily.
const MAX_CONCURRENT_FILE_FETCHES_PER_REQUEST: usize = 10;
const MAX_CONCURRENT_UPLOAD_FILENODES_PER_REQUEST: usize = 1000;
#[derive(Debug, Deserialize, Sta... |
}
})
.boxed())
}
}
async fn fetch_file_response(
repo: HgRepoContext,
key: Key,
attrs: FileAttributes,
) -> Result<FileResponse, Error> {
let result = fetch_file(repo, key.clone(), attrs)
.await
.map_err(|e| ServerError::generic(format!("{}",... | {
ctx.session().bump_load(Metric::GetpackFiles, 1.0);
} | conditional_block |
files.rs | type Request = FileRequest;
type Response = FileResponse;
const HTTP_METHOD: hyper::Method = hyper::Method::POST;
const API_METHOD: EdenApiMethod = EdenApiMethod::Files2;
const ENDPOINT: &'static str = "/files2";
fn sampling_rate(request: &Self::Request) -> NonZeroU64 {
// Sample trivi... | DownloadFileHandler | identifier_name | |
__init__.py | # Copyright 2022 Google LLC
#
# 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, s... | # -*- coding: utf-8 -*- | random_line_split | |
jquery.convenience_store.js | ;(function($, undefined) {
$.fn.convenience_store = function(brand_name, options) {
var brands = $.fn.convenience_store.available_brands;
if(brand_name === undefined || brand_name == '' || (brands.indexOf(brand_name) == -1)) return;
return this.each(function() {
$.fn.convenience_store.style($(this),... | "overflow": "hidden"
}).html('');
var p = 5;
var style_title = {
"color": "#018bd4",
"display": "inline-block",
"font-family": "PT Sans",
"font-style": "normal",
"font-weight": "bold",
"left": "2%",
"padding": "6px 0.1% 0",
"text-... | random_line_split | |
strings.js | define(
({
addLayer: "レイヤーの追加",
layerName: "レイヤー",
layerRefresh: "更新",
layerLabel: "ラベル",
actions: "操作",
popupOk: "OK",
popupCancel: "キャンセル",
mainPanelTextPlaceholder: "例: 高速道路の状態",
invalidInterval: "数字のみがサポートされています。",
| mainPanelText: "メイン パネルのテキスト",
mainPanelIcon: "メイン パネルの画像",
refreshIntervalInstruction: "更新間隔",
optionsText: "オプション",
symbolOptionsText: "シンボルのオプション",
iconOptionsText: "アイコンのオプション",
sympolPopupTitle: "シンボルの設定",
rdoLayer: "レイヤー シンボル",
rdoCustom: "カスタム シンボル",
chkCluster: "... | uploadImage: "画像のアップロード",
iconColumnText: "アイコン",
refreshInterval: "1 \'分単位の時間として評価されました\'",
refreshIntervalTitle: "分単位の時間として評価されました",
| random_line_split |
errors.rs | use tokio_timer::TimerError;
use getopts;
use log;
use nom;
use std::cell;
use std::io;
use std::sync;
use toml;
use serde_json;
error_chain! {
foreign_links {
Timer(TimerError);
IO(io::Error);
SetLogger(log::SetLoggerError);
Getopts(getopts::Fail);
BorrowMut(cell::BorrowMu... | ConfigSection(section: String) {
description("error in section")
display("error in section: {}", section)
}
ConfigField(field: String, reason: String) {
description("error in field")
display("error in field: {}: {}", field, reason)
}
... | description("error in config")
display("error in config: {}", path)
}
| random_line_split |
errors.rs | use tokio_timer::TimerError;
use getopts;
use log;
use nom;
use std::cell;
use std::io;
use std::sync;
use toml;
use serde_json;
error_chain! {
foreign_links {
Timer(TimerError);
IO(io::Error);
SetLogger(log::SetLoggerError);
Getopts(getopts::Fail);
BorrowMut(cell::BorrowMu... | (err: toml::DecodeError) -> Error {
if let Some(ref field) = err.field {
ErrorKind::ConfigField(field.clone(), format!("{}", err)).into()
} else {
ErrorKind::Message(format!("{}", err)).into()
}
}
}
| from | identifier_name |
errors.rs | use tokio_timer::TimerError;
use getopts;
use log;
use nom;
use std::cell;
use std::io;
use std::sync;
use toml;
use serde_json;
error_chain! {
foreign_links {
Timer(TimerError);
IO(io::Error);
SetLogger(log::SetLoggerError);
Getopts(getopts::Fail);
BorrowMut(cell::BorrowMu... |
}
impl From<nom::IError> for Error {
fn from(err: nom::IError) -> Error {
match err {
nom::IError::Error(err) => ErrorKind::Nom(err.to_string()).into(),
nom::IError::Incomplete(_) => ErrorKind::Nom("input incomplete".to_owned()).into(),
}
}
}
impl From<toml::DecodeErro... | {
ErrorKind::Poison(err.to_string()).into()
} | identifier_body |
custom-edit.component.ts | import {
Component,
ComponentFactoryResolver,
ViewChild,
ViewContainerRef,
SimpleChanges,
OnChanges,
OnDestroy,
} from '@angular/core';
import { EditCellDefault } from './edit-cell-default';
import { Cell } from '../../../lib/data-set/cell';
@Component({
selector: 'table-cell-custom-editor',
templat... | }
}
ngOnDestroy() {
if (this.customComponent) {
this.customComponent.destroy();
}
}
} | this.customComponent.instance.onClick.subscribe((event: any) => this.onClick(event)); | random_line_split |
custom-edit.component.ts | import {
Component,
ComponentFactoryResolver,
ViewChild,
ViewContainerRef,
SimpleChanges,
OnChanges,
OnDestroy,
} from '@angular/core';
import { EditCellDefault } from './edit-cell-default';
import { Cell } from '../../../lib/data-set/cell';
@Component({
selector: 'table-cell-custom-editor',
templat... |
}
}
| {
this.customComponent.destroy();
} | conditional_block |
custom-edit.component.ts | import {
Component,
ComponentFactoryResolver,
ViewChild,
ViewContainerRef,
SimpleChanges,
OnChanges,
OnDestroy,
} from '@angular/core';
import { EditCellDefault } from './edit-cell-default';
import { Cell } from '../../../lib/data-set/cell';
@Component({
selector: 'table-cell-custom-editor',
templat... | (changes: SimpleChanges) {
if (this.cell && !this.customComponent) {
const componentFactory = this.resolver.resolveComponentFactory(this.cell.getColumn().editor.component);
this.customComponent = this.dynamicTarget.createComponent(componentFactory);
// set @Inputs and @Outputs of custom component... | ngOnChanges | identifier_name |
custom-edit.component.ts | import {
Component,
ComponentFactoryResolver,
ViewChild,
ViewContainerRef,
SimpleChanges,
OnChanges,
OnDestroy,
} from '@angular/core';
import { EditCellDefault } from './edit-cell-default';
import { Cell } from '../../../lib/data-set/cell';
@Component({
selector: 'table-cell-custom-editor',
templat... |
ngOnDestroy() {
if (this.customComponent) {
this.customComponent.destroy();
}
}
}
| {
if (this.cell && !this.customComponent) {
const componentFactory = this.resolver.resolveComponentFactory(this.cell.getColumn().editor.component);
this.customComponent = this.dynamicTarget.createComponent(componentFactory);
// set @Inputs and @Outputs of custom component
this.customCompone... | identifier_body |
views.py | # -*- coding: utf-8 -*-
"""
Views to support exchange of authentication credentials. | 1st party (open-edx) OAuth 2.0 access token -> session cookie
"""
# pylint: disable=abstract-method
import django.contrib.auth as auth
import social_django.utils as social_utils
from django.conf import settings
from django.contrib.auth import login
from django.http import HttpResponse
from django.utils.decorat... | The following are currently implemented:
1. AccessTokenExchangeView:
3rd party (social-auth) OAuth 2.0 access token -> 1st party (open-edx) OAuth 2.0 access token
2. LoginWithAccessTokenView: | random_line_split |
views.py | # -*- coding: utf-8 -*-
"""
Views to support exchange of authentication credentials.
The following are currently implemented:
1. AccessTokenExchangeView:
3rd party (social-auth) OAuth 2.0 access token -> 1st party (open-edx) OAuth 2.0 access token
2. LoginWithAccessTokenView:
1st party (open-edx) ... | if not form.is_valid():
return self.error_response(form.errors) # pylint: disable=no-member
user = form.cleaned_data["user"]
scope = form.cleaned_data["scope"]
client = form.cleaned_data["client"]
return self.exchange_access_token(request, user, scope, client)
... | """
View for token exchange from 3rd party OAuth access token to 1st party
OAuth access token.
"""
@method_decorator(csrf_exempt)
@method_decorator(social_utils.psa("social:complete"))
def dispatch(self, *args, **kwargs):
return super(AccessTokenExchangeBase, self).dispatch(*args, **kwar... | identifier_body |
views.py | # -*- coding: utf-8 -*-
"""
Views to support exchange of authentication credentials.
The following are currently implemented:
1. AccessTokenExchangeView:
3rd party (social-auth) OAuth 2.0 access token -> 1st party (open-edx) OAuth 2.0 access token
2. LoginWithAccessTokenView:
1st party (open-edx) ... |
else:
edx_access_token = self.create_access_token(request, user, scope, client)
return self.access_token_response(edx_access_token) # pylint: disable=no-member
class DOPAccessTokenExchangeView(AccessTokenExchangeBase, DOPAccessTokenView):
"""
View for token exchange from 3rd part... | edx_access_token = self.get_access_token(request, user, scope, client) # pylint: disable=no-member | conditional_block |
views.py | # -*- coding: utf-8 -*-
"""
Views to support exchange of authentication credentials.
The following are currently implemented:
1. AccessTokenExchangeView:
3rd party (social-auth) OAuth 2.0 access token -> 1st party (open-edx) OAuth 2.0 access token
2. LoginWithAccessTokenView:
1st party (open-edx) ... | (self, request, user, scope, client):
"""
Create and return a new access token.
"""
_days = 24 * 60 * 60
token_generator = BearerToken(
expires_in=settings.OAUTH_EXPIRE_PUBLIC_CLIENT_DAYS * _days,
request_validator=oauth2_settings.OAUTH2_VALIDATOR_CLASS(),... | create_access_token | identifier_name |
to3015.py | from dependencies.dependency import aq_inner
from dependencies.dependency import aq_parent
from lims.permissions import *
from dependencies.dependency import BaseContent
from lims.upgrade import stub
def upgrade(tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bikalabs/... |
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'typeinfo')
stub('bika.lims.content.invoicelineitem', 'InvoiceLineItem',
BaseContent)
for inv in portal['invoices'].objectValues():
inv.invoice_lineitems = [... | return True | conditional_block |
to3015.py | from dependencies.dependency import aq_inner
from dependencies.dependency import aq_parent
from lims.permissions import *
from dependencies.dependency import BaseContent
from lims.upgrade import stub
def upgrade(tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bikalabs/... | Total=invl.Total,
)
inv.invoice_lineitems.append(item)
return True
| from lims.upgrade import skip_pre315
if skip_pre315(aq_parent(aq_inner(tool))):
return True
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'typeinfo')
stub('bika.lims.content.invoicelineitem', 'InvoiceLineItem',
... | identifier_body |
to3015.py | from dependencies.dependency import aq_inner
from dependencies.dependency import aq_parent
from lims.permissions import *
from dependencies.dependency import BaseContent
from lims.upgrade import stub
def upgrade(tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bikalabs/... | ItemDate=invl.ItemDate,
ItemDescription=invl.ItemDescription,
ClientOrderNumber=invl.ClientOrderNumber,
Subtotal=invl.Subtotal,
VATAmount=invl.VATAmount,
Total=invl.Total,
)
inv.invoice_lineitems.appe... | BaseContent)
for inv in portal['invoices'].objectValues():
inv.invoice_lineitems = []
for invl in inv.objectValues():
item = dict( | random_line_split |
to3015.py | from dependencies.dependency import aq_inner
from dependencies.dependency import aq_parent
from lims.permissions import *
from dependencies.dependency import BaseContent
from lims.upgrade import stub
def | (tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bikalabs/Bika-LIMS/pull/1484
from lims.upgrade import skip_pre315
if skip_pre315(aq_parent(aq_inner(tool))):
return True
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.ru... | upgrade | identifier_name |
task.rs | //! Helpers to program the task state segment.
//! See Intel 3a, Chapter 7, Section 7
use crate::Ring;
/// Although hardware task-switching is not supported in 64-bit mode,
/// a 64-bit task state segment (TSS) must exist.
///
/// The TSS holds information important to 64-bit mode and that is not
/// directly related... | /// The 16-bit offset to the I/O permission bit map from the 64-bit TSS base.
pub iomap_base: u16,
}
impl TaskStateSegment {
/// Creates a new empty TSS.
pub const fn new() -> TaskStateSegment {
TaskStateSegment {
reserved: 0,
rsp: [0; 3],
reserved2: 0,
... | pub ist: [u64; 7],
pub reserved3: u64,
pub reserved4: u16, | random_line_split |
task.rs | //! Helpers to program the task state segment.
//! See Intel 3a, Chapter 7, Section 7
use crate::Ring;
/// Although hardware task-switching is not supported in 64-bit mode,
/// a 64-bit task state segment (TSS) must exist.
///
/// The TSS holds information important to 64-bit mode and that is not
/// directly related... |
/// Sets the stack pointer (`stack_ptr`) to be used when
/// an interrupt with a corresponding IST entry in the Interrupt
/// Descriptor table pointing to the given `index` is raised.
pub fn set_ist(&mut self, index: usize, stack_ptr: u64) {
match index {
0 => self.ist[0] = stack_p... | {
match pl {
Ring::Ring0 => self.rsp[0] = stack_ptr,
Ring::Ring1 => self.rsp[1] = stack_ptr,
Ring::Ring2 => self.rsp[2] = stack_ptr,
Ring::Ring3 => unreachable!("Can't set stack for PL3"),
}
} | identifier_body |
task.rs | //! Helpers to program the task state segment.
//! See Intel 3a, Chapter 7, Section 7
use crate::Ring;
/// Although hardware task-switching is not supported in 64-bit mode,
/// a 64-bit task state segment (TSS) must exist.
///
/// The TSS holds information important to 64-bit mode and that is not
/// directly related... | (&mut self, pl: Ring, stack_ptr: u64) {
match pl {
Ring::Ring0 => self.rsp[0] = stack_ptr,
Ring::Ring1 => self.rsp[1] = stack_ptr,
Ring::Ring2 => self.rsp[2] = stack_ptr,
Ring::Ring3 => unreachable!("Can't set stack for PL3"),
}
}
/// Sets the sta... | set_rsp | identifier_name |
auto_suggest.js | 0,
'(':0,
'0':0,
')':0,
'-':0,
'_':0,
'=':0,
'+':0,
'q':0,
'Q':0,
'w':0,
'W':0,
'e':0,
'E':0,
'r':0,
'R':0,
't':0,
'T':0,
'y':0,
'Y':0,
'u':0,
'U':0,
'i':0,
'I':0,
'o':0,
'O':0,
'p':0,
'P':0,
'[':0,
'{':0,
']':0,
'}':0,
'a':0,
'A':0,
's':0,
'S':0,
... |
if( ch == '\n'){
if( line1Width + line2Width < width-1 ){
lines.push(line1 + line2);
}
else{
lines.push(line1);
lines.push(line2);
}
line1 = "";
line2 = "";
line1Width = 0;
line2Width = 0;
}
//else{
//line2 += ch;
//}
}
if( line1Width + l... | {
if( line1Width + line2Width < width-1 ){
line1 = line1 + line2;
line1Width = line1Width + line2Width;
line2 = "";
line2Width = 0;
}
else{
lines.push(line1);
line1= line2;
line1Width = line2Width;
line2= "";
line2Width = 0;
}
} | conditional_block |
auto_suggest.js | 0,
'(':0,
'0':0,
')':0,
'-':0,
'_':0,
'=':0,
'+':0,
'q':0,
'Q':0,
'w':0,
'W':0,
'e':0,
'E':0,
'r':0,
'R':0,
't':0,
'T':0,
'y':0,
'Y':0,
'u':0,
'U':0,
'i':0,
'I':0,
'o':0,
'O':0,
'p':0,
'P':0,
'[':0,
'{':0,
']':0,
'}':0,
'a':0,
'A':0,
's':0,
'S':0,
... | (data){
var ul = document.createElement("ul");
$(ul).addClass("auto-list");
document.body.appendChild(ul);
return ul;
}
function createClone(id){
var data = _data[id];
var div = document.createElement("div");
var offset = $(data.ta).offset();
offset.top = offset.top - parseInt($(data.ta).css("margin... | createList | identifier_name |
auto_suggest.js | 0,
'(':0,
'0':0,
')':0,
'-':0,
'_':0,
'=':0,
'+':0,
'q':0,
'Q':0,
'w':0,
'W':0,
'e':0,
'E':0,
'r':0,
'R':0,
't':0,
'T':0,
'y':0,
'Y':0,
'u':0,
'U':0,
'i':0,
'I':0,
'o':0,
'O':0,
'p':0, | 'P':0,
'[':0,
'{':0,
']':0,
'}':0,
'a':0,
'A':0,
's':0,
'S':0,
'd':0,
'D':0,
'f':0,
'F':0,
'g':0,
'G':0,
'h':0,
'H':0,
'j':0,
'J':0,
'k':0,
'K':0,
'l':0,
'L':0,
';':0,
':':0,
'\'':0,
'"':0,
'\\':0,
'|':0,
'z':0,
'Z':0,
'x':0,
'X':0,
'c':0,
'C':0,
'... | random_line_split | |
auto_suggest.js | 'C':0,
'v':0,
'V':0,
'b':0,
'B':0,
'n':0,
'N':0,
'm':0,
'M':0,
',':0,
'<':0,
'.':0,
'>':0,
'/':0,
'?':0,
' ':0
};
}
function setCharSize(data){
for( var ch in data.chars ){
if( ch == ' ' ) $(data.clone).html("<span id='test-width_"+data.id+"' style='line-block'> </span>"... | {
var selected = $(data.list).find("[data-selected=true]");
if( selected.length == 1) return selected.get(0);
return null;
} | identifier_body | |
SelectField.js | /* eslint-disable react/default-props-match-prop-types */
/* eslint-disable react/require-default-props */
/* eslint-disable react/forbid-prop-types */
/* eslint-disable jsx-a11y/label-has-for */
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable react/prop-types */
/* eslint-disable react/jsx... |
const { text, value, ...restProps } = option;
return (
<option key={key} value={value} {...restProps}>
{text}
</option>
);
};
const SelectField = ({
className,
defaultOption,
error,
label,
modifiers,
options,
styleOverride,
topRightLabel,
...rest
}) => {
const [defaultKey, de... | {
const { subOptions, text, value, ...restProps } = option;
return (
<optgroup
key={`optgroup-${key}`}
label={text}
value={value}
{...restProps}
>
{subOptions.map((o, j) => renderOption(o, `${key}-${j}`))}
</optgroup>
);
} | conditional_block |
SelectField.js | /* eslint-disable react/default-props-match-prop-types */
/* eslint-disable react/require-default-props */
/* eslint-disable react/forbid-prop-types */
/* eslint-disable jsx-a11y/label-has-for */
/* eslint-disable jsx-a11y/label-has-associated-control */ | /* eslint-disable react/jsx-filename-extension */
/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Typography } from '@mui/material';
import styles from '../../styles/partials/form/_form.scss';
import... | /* eslint-disable react/prop-types */ | random_line_split |
HeaderView.js | /**
* This view shows the header in the layout.
*/ | girder.views.LayoutHeaderView = girder.View.extend({
events: {
'click .g-app-title': function () {
girder.router.navigate('', {trigger: true});
}
},
initialize: function () {
this.userView = new girder.views.LayoutHeaderUserView({
parentView: this
});... | random_line_split | |
echo.test.js | /*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* 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 app... |
const shortNumberArray = sequentialNumberArray(10);
const longNumberArray = sequentialNumberArray(1000);
const inputList = [shortNumberArray, longNumberArray];
const inputPreprocessorFunctions = [JSON.stringify, Buffer.from];
const preprocessedInput = inputList.map((input) => {
return inputPreprocessorFunctions.m... | {
return [].concat.apply([], array)
} | identifier_body |
echo.test.js | /*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* 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 app... | const inputPreprocessorFunctions = [JSON.stringify, Buffer.from];
const preprocessedInput = inputList.map((input) => {
return inputPreprocessorFunctions.map((fun) => {
return fun(input);
});
});
const messages = flattenArray(preprocessedInput);
function initTlsCommunicationEncrypted() {
const serverSuffix =... |
const inputList = [shortNumberArray, longNumberArray]; | random_line_split |
echo.test.js | /*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* 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 app... | (count) {
return Array.from(Array(count).keys());
}
function flattenArray(array) {
return [].concat.apply([], array)
}
const shortNumberArray = sequentialNumberArray(10);
const longNumberArray = sequentialNumberArray(1000);
const inputList = [shortNumberArray, longNumberArray];
const inputPreprocessorFunctions = ... | sequentialNumberArray | identifier_name |
base.py | import tempfile
from datetime import datetime
import flask_testing
from flask import url_for
import iis
from iis.models import User
from iis.extensions import db
class BaseTestCase(flask_testing.TestCase):
DB_FILE = tempfile.mkstemp()
SQLALCHEMY_DATABASE_URI = "sqlite:///" + DB_FILE[1]
LOGGING = {"versi... |
def create_user(self, username, password):
user = User(username=username,
password=self.user_manager.hash_password(password),
email=username + "@localhost",
confirmed_at=datetime.fromtimestamp(0.0),
active=True)
db.ses... | self.client.get(url_for("user.logout")) | identifier_body |
base.py | import tempfile
from datetime import datetime
import flask_testing
from flask import url_for
import iis
from iis.models import User
from iis.extensions import db
class BaseTestCase(flask_testing.TestCase):
DB_FILE = tempfile.mkstemp()
SQLALCHEMY_DATABASE_URI = "sqlite:///" + DB_FILE[1]
LOGGING = {"versi... | (self, username, password):
user = User(username=username,
password=self.user_manager.hash_password(password),
email=username + "@localhost",
confirmed_at=datetime.fromtimestamp(0.0),
active=True)
db.session.add(user)
... | create_user | identifier_name |
base.py | import tempfile
from datetime import datetime
import flask_testing
from flask import url_for
import iis
from iis.models import User
from iis.extensions import db
class BaseTestCase(flask_testing.TestCase):
DB_FILE = tempfile.mkstemp()
SQLALCHEMY_DATABASE_URI = "sqlite:///" + DB_FILE[1]
LOGGING = {"versi... | self.logout()
res = self.client.get(url)
self.assertEqual(302, res.status_code)
self.assertIn(url_for('user.login'), res.headers['Location']) | def assertLoginRequired(self, url): | random_line_split |
expr.rs | use crate::position::Pos;
use crate::tokenizer::{Kind, TokenStream};
/// Error of expression checking
///
/// See [check][].
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{}: tokenizer error: {}", _1, _0)]
Tokenizer(String, Pos),
#[error(
"{}: closing bracket mismatch, opened {:?} at... | pub fn check(text: &str) -> Result<(), Error> {
use crate::tokenizer::Kind::*;
use Error::*;
let mut brackets = Vec::new();
let mut parser = &mut TokenStream::new(text);
let mut empty = true;
for token in &mut parser {
let (token, pos) = match token {
Ok(t) => (t.token, t.st... | /// semicolon `;` outside of brackets.
///
/// This is NOT a security measure. | random_line_split |
expr.rs | use crate::position::Pos;
use crate::tokenizer::{Kind, TokenStream};
/// Error of expression checking
///
/// See [check][].
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{}: tokenizer error: {}", _1, _0)]
Tokenizer(String, Pos),
#[error(
"{}: closing bracket mismatch, opened {:?} at... | (tok: Kind) -> Kind {
use crate::tokenizer::Kind::*;
match tok {
OpenBracket => CloseBracket,
OpenBrace => CloseBrace,
OpenParen => CloseParen,
_ => unreachable!("token is not a bracket"),
}
}
/// Minimal validation of expression
///
/// This is used for substitutions in mi... | matching_bracket | identifier_name |
expr.rs | use crate::position::Pos;
use crate::tokenizer::{Kind, TokenStream};
/// Error of expression checking
///
/// See [check][].
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{}: tokenizer error: {}", _1, _0)]
Tokenizer(String, Pos),
#[error(
"{}: closing bracket mismatch, opened {:?} at... |
Ok(())
}
| {
return Err(Empty);
} | conditional_block |
expr.rs | use crate::position::Pos;
use crate::tokenizer::{Kind, TokenStream};
/// Error of expression checking
///
/// See [check][].
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{}: tokenizer error: {}", _1, _0)]
Tokenizer(String, Pos),
#[error(
"{}: closing bracket mismatch, opened {:?} at... | match token.kind {
Comma | Semicolon if brackets.is_empty() => {
return Err(UnexpectedToken(token.value.to_string(), pos));
}
OpenParen | OpenBracket | OpenBrace => {
brackets.push((token.kind, pos));
}
CloseParen | Clos... | {
use crate::tokenizer::Kind::*;
use Error::*;
let mut brackets = Vec::new();
let mut parser = &mut TokenStream::new(text);
let mut empty = true;
for token in &mut parser {
let (token, pos) = match token {
Ok(t) => (t.token, t.start),
Err(combine::easy::Error::Un... | identifier_body |
helpers.py | import json
from mflow_nodes.processors.base import BaseProcessor
from mflow_nodes.stream_node import get_processor_function, get_receiver_function
from mflow_nodes.node_manager import NodeManager
def setup_file_writing_receiver(connect_address, output_filename):
"""
Setup a node that writis the message head... |
processor = BaseProcessor()
processor.process_message = process_message
receiver = NodeManager(processor_function=get_processor_function(processor=processor,
connection_address=connect_address),
receiver_functi... | with open(output_filename, 'r') as input_file:
test_data = json.load(input_file)
test_data.append(message.get_header())
with open(output_filename, 'w') as output:
output.write(json.dumps(test_data, indent=4)) | identifier_body |
helpers.py | import json |
from mflow_nodes.processors.base import BaseProcessor
from mflow_nodes.stream_node import get_processor_function, get_receiver_function
from mflow_nodes.node_manager import NodeManager
def setup_file_writing_receiver(connect_address, output_filename):
"""
Setup a node that writis the message headers into an ... | random_line_split | |
helpers.py | import json
from mflow_nodes.processors.base import BaseProcessor
from mflow_nodes.stream_node import get_processor_function, get_receiver_function
from mflow_nodes.node_manager import NodeManager
def | (connect_address, output_filename):
"""
Setup a node that writis the message headers into an output file for later inspection.
:param connect_address: Address the node connects to.
:param output_filename: Output file.
:return: Instance of ExternalProcessWrapper.
"""
# Format the output file.... | setup_file_writing_receiver | identifier_name |
abstractPropertyInConstructor.ts | abstract class AbstractClass {
constructor(str: string, other: AbstractClass) {
this.method(parseInt(str));
let val = this.prop.toLowerCase();
if (!str) {
this.prop = "Hello World";
}
this.cb(str);
// OK, reference is inside function
c... | (str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) {
super(str, other, yetAnother);
this.cb(this.prop);
}
method(n: number) {
this.cb(this.prop + n);
}
}
class User {
constructor(a: AbstractClass) {
a.prop;
a.cb("hi");
a.... | constructor | identifier_name |
abstractPropertyInConstructor.ts | abstract class AbstractClass {
constructor(str: string, other: AbstractClass) {
this.method(parseInt(str));
let val = this.prop.toLowerCase();
if (!str) {
this.prop = "Hello World";
}
this.cb(str);
// OK, reference is inside function
c... | super(str, other);
// there is no implementation of 'prop' in any base class
this.cb(this.prop.toLowerCase());
this.method(1);
// OK, references are to another instance
other.cb(other.prop);
yetAnother.cb(yetAnother.prop);
}
}
class Implementati... | cb = (s: string) => {};
constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) {
| random_line_split |
abstractPropertyInConstructor.ts | abstract class AbstractClass {
constructor(str: string, other: AbstractClass) {
this.method(parseInt(str));
let val = this.prop.toLowerCase();
if (!str) |
this.cb(str);
// OK, reference is inside function
const innerFunction = () => {
return this.prop;
}
// OK, references are to another instance
other.cb(other.prop);
}
abstract prop: string;
abstract cb: (s: string) => void;
a... | {
this.prop = "Hello World";
} | conditional_block |
abstractPropertyInConstructor.ts | abstract class AbstractClass {
constructor(str: string, other: AbstractClass) {
this.method(parseInt(str));
let val = this.prop.toLowerCase();
if (!str) {
this.prop = "Hello World";
}
this.cb(str);
// OK, reference is inside function
c... |
}
| {
a.prop;
a.cb("hi");
a.method(12);
a.method2();
} | identifier_body |
generator.py |
""" generator.py: Contains the Generator class. """
import random
import copy
import graphics
from helpers import *
# Just to check we have generated the correct number of polyominoes
# {order: number of omiones}
counts = {1: 1, 2: 1, 3: 2, 4: 7, 5: 18, 6: 60}
class Generator:
""" A class for generatin... | (self, n):
""" Generate n unique colours and return as a list of RGB triples.
Colours are as contrasted as possible.
generate_colours(int) -> list<(int, int, int)>
"""
# This divides the 360 degrees of hue in the HSV colour space by n,
# and so chooses n... | generate_colours | identifier_name |
generator.py |
""" generator.py: Contains the Generator class. """
import random
import copy
import graphics
from helpers import *
# Just to check we have generated the correct number of polyominoes
# {order: number of omiones}
counts = {1: 1, 2: 1, 3: 2, 4: 7, 5: 18, 6: 60}
class Generator:
""" A class for generatin... |
return colours
def _normalise(self, polyomino):
""" Return a copy of the given polyomino with its rotation and position
normalised. That is, in its left- and bottom-most position and rotation.
_normalise(list<list<bool>>) -> list<list<bool>>
"""
... | hsv = (degrees * i, 1.0, 0.78)
rgb = graphics.hsv2rgb(hsv)
colours.append(rgb) | conditional_block |
generator.py | """ generator.py: Contains the Generator class. """
import random
import copy
import graphics
from helpers import *
# Just to check we have generated the correct number of polyominoes
# {order: number of omiones}
counts = {1: 1, 2: 1, 3: 2, 4: 7, 5: 18, 6: 60}
class Generator:
""" A class for generating... | moved[row][col] = moved[row - 1][col]
moved[0] = [False] * self._order
while [moved[row][0] for row in xrange(self._order)].count(True) == 0:
# While left column is empty, move left
for row in xrange(self._order):
for col in xrange(self._or... | while moved[self._order - 1].count(True) == 0:
# While bottom row is empty, move down
for row in xrange(self._order - 1, 0, -1):
for col in xrange(self._order): | random_line_split |
generator.py |
""" generator.py: Contains the Generator class. """
import random
import copy
import graphics
from helpers import *
# Just to check we have generated the correct number of polyominoes
# {order: number of omiones}
counts = {1: 1, 2: 1, 3: 2, 4: 7, 5: 18, 6: 60}
class Generator:
""" A class for generatin... |
def _number_adjacent_squares(self, polyomino, coordinates, \
numbered_squares, max_number):
""" Return a pair with a dictionary of all the adjacent squares in the
given polyomino, keyed by their number, where they are numbered
clockwise from the top, an... | """ Return a copy of the given polyomino rotated clockwise 90 degrees.
_rotate(list<list<bool>>) -> list<list<bool>>
"""
rotated = rect_list(self._order, self._order, False)
for row in xrange(self._order):
for col in xrange(self._order):
rota... | identifier_body |
pdf.js | export class PDF
{
constructor()
{
this.styles = {}
this.content = []
this.pdf = null
}
setStyle( name, style )
{
if ( ! name ) throw new Error('Missing required parameter name');
if ( ! style ) throw new Error('Missing required parameter style');
this.styles[ name ] = style
}
removeStyle( nam... |
} | {
this.pdf.open();
} | identifier_body |
pdf.js | export class PDF
{
constructor()
{
this.styles = {}
this.content = []
this.pdf = null
}
setStyle( name, style )
{
if ( ! name ) throw new Error('Missing required parameter name');
if ( ! style ) throw new Error('Missing required parameter style');
this.styles[ name ] = style
}
removeStyle( nam... | ( content )
{
if ( ! content ) throw new Error('Missing required parameter content');
this.content.push( content );
}
removeContent( content )
{
if ( ! content ) throw new Error('Missing required parameter content');
this.content.splice( this.content.indexOf( content ), 1 );
}
generatePDF()
{
... | addContent | identifier_name |
pdf.js | export class PDF
{
constructor()
{
this.styles = {}
this.content = []
this.pdf = null
}
setStyle( name, style )
{
if ( ! name ) throw new Error('Missing required parameter name');
if ( ! style ) throw new Error('Missing required parameter style');
this.styles[ name ] = style
}
removeStyle( nam... | self.pdf.getDataUrl(( url )=>
{
if ( url )
{
return resolve( url );
}
throw new Error('URL not generated');
})
})
}
openPDF()
{
this.pdf.open();
}
} | console.log( JSON.stringify( this.pdf ) ) | random_line_split |
pdf.js | export class PDF
{
constructor()
{
this.styles = {}
this.content = []
this.pdf = null
}
setStyle( name, style )
{
if ( ! name ) throw new Error('Missing required parameter name');
if ( ! style ) throw new Error('Missing required parameter style');
this.styles[ name ] = style
}
removeStyle( nam... |
throw new Error('URL not generated');
})
})
}
openPDF()
{
this.pdf.open();
}
} | {
return resolve( url );
} | conditional_block |
REM_console.py | #!/usr/bin/python3
import rem_backend.query_data as qd
import rem_backend.propagation_model_estimation as pm | import _thread
__author__ = "Daniel Denkovski", "Valentin Rakovic"
__copyright__ = "Copyright (c) 2017, Faculty of Electrical Engineering and Information Technologies, UKIM, Skopje, Macedonia"
__version__ = "0.1.0"
__email__ = "{danield, valentin}@feit.ukim.edu.mk"
'''
REM console module
Showcases the REM backend cap... | import threading | random_line_split |
REM_console.py | #!/usr/bin/python3
import rem_backend.query_data as qd
import rem_backend.propagation_model_estimation as pm
import threading
import _thread
__author__ = "Daniel Denkovski", "Valentin Rakovic"
__copyright__ = "Copyright (c) 2017, Faculty of Electrical Engineering and Information Technologies, UKIM, Skopje, Macedonia"... | devind = input(" >> ")
print(dev_list[int(devind)-1][0])
try:
location = qd.estimate_tx_location(str(dev_list[int(devind)-1][0]),10)
print("The location of devices {} is:".format(str(dev_list[int(devind)-1][0])))
print("x:{} y:{} z:{} Pt:{} dBm".format(location[0],location[1],location[2],lo... | run = 1;
while (run):
print("Please choose from the selection:")
print("1. WiFi device localization")
print("2. Duty cycle calculation")
print("3. Path loss model estimation")
print("0. Quit")
choice = input(" >> ")
if (choice == '0'):
run = 0
elif (choice == '1'):
print("Loc:Enter the channel... | identifier_body |
REM_console.py | #!/usr/bin/python3
import rem_backend.query_data as qd
import rem_backend.propagation_model_estimation as pm
import threading
import _thread
__author__ = "Daniel Denkovski", "Valentin Rakovic"
__copyright__ = "Copyright (c) 2017, Faculty of Electrical Engineering and Information Technologies, UKIM, Skopje, Macedonia"... | ():
run = 1;
while (run):
print("Please choose from the selection:")
print("1. WiFi device localization")
print("2. Duty cycle calculation")
print("3. Path loss model estimation")
print("0. Quit")
choice = input(" >> ")
if (choice == '0'):
run = 0
elif (choice == '1'):
print("Loc:Enter the ch... | main | identifier_name |
REM_console.py | #!/usr/bin/python3
import rem_backend.query_data as qd
import rem_backend.propagation_model_estimation as pm
import threading
import _thread
__author__ = "Daniel Denkovski", "Valentin Rakovic"
__copyright__ = "Copyright (c) 2017, Faculty of Electrical Engineering and Information Technologies, UKIM, Skopje, Macedonia"... | e__=="__main__":
main()
| L:Enter the channel of interest")
chann = input(" >> ")
try:
val = pm.get_chann_model(10,chann)
print(val)
except:
print("not sufficient data for modeling")
print("")
if __nam | conditional_block |
statusHandler.spec.js | /* eslint-disable max-len */
const Parse = require('parse/node');
const { dropDB } = require('parse-server-test-runner');
const { getScheduledPushes } = require('../src/query');
const { addOffsetCounts, markAsComplete } = require('../src/statusHandler');
const { stripTimezone } = require('./util');
describe('statusH... | (pushTime, inLocalTime=true) {
const pushStatus = new Parse.Object('_PushStatus');
return pushStatus.save({
pushTime: inLocalTime ? stripTimezone(pushTime) : pushTime.toISOString(),
status: 'scheduled',
query: '{}',
payload: '{"alert":"alert!"}',
title: 'title',
expiry: +new ... | send | identifier_name |
statusHandler.spec.js | /* eslint-disable max-len */
const Parse = require('parse/node');
const { dropDB } = require('parse-server-test-runner');
const { getScheduledPushes } = require('../src/query');
const { addOffsetCounts, markAsComplete } = require('../src/statusHandler');
const { stripTimezone } = require('./util');
describe('statusH... |
beforeAll((done) => {
dropDB().then(done).catch(done.fail);
});
describe('addOffsetCounts', () => {
it('should set the success/failure counts to 0 if not previously set', (done) => {
const now = new Date('2017-07-20T12:20:40.730Z');
send(new Date(now + 5000))
.then(getScheduledPushe... | {
const pushStatus = new Parse.Object('_PushStatus');
return pushStatus.save({
pushTime: inLocalTime ? stripTimezone(pushTime) : pushTime.toISOString(),
status: 'scheduled',
query: '{}',
payload: '{"alert":"alert!"}',
title: 'title',
expiry: +new Date(pushTime + 5000),
... | identifier_body |
statusHandler.spec.js | /* eslint-disable max-len */
const Parse = require('parse/node'); | const { getScheduledPushes } = require('../src/query');
const { addOffsetCounts, markAsComplete } = require('../src/statusHandler');
const { stripTimezone } = require('./util');
describe('statusHandler', () => {
function send(pushTime, inLocalTime=true) {
const pushStatus = new Parse.Object('_PushStatus');
... | const { dropDB } = require('parse-server-test-runner');
| random_line_split |
archive.rs | //! Creation of ar archives like for the lib and staticlib crate type
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::fs::File;
use std::io::{self, Read, Seek};
use std::path::{Path, PathBuf};
use rustc_codegen_ssa::back::archive::ArchiveBuilder;
use rustc_session::Session;
use object::read::arch... |
fn add_file(&mut self, file: &Path) {
self.entries.push((
file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
ArchiveEntry::File(file.to_owned()),
));
}
fn add_archive<F>(&mut self, archive_path: &Path, mut skip: F) -> std::io::Result<()>
wher... | {
let index = self
.entries
.iter()
.position(|(entry_name, _)| entry_name == name.as_bytes())
.expect("Tried to remove file not existing in src archive");
self.entries.remove(index);
} | identifier_body |
archive.rs | //! Creation of ar archives like for the lib and staticlib crate type
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::fs::File;
use std::io::{self, Read, Seek};
use std::path::{Path, PathBuf};
use rustc_codegen_ssa::back::archive::ArchiveBuilder;
use rustc_session::Session;
use object::read::arch... |
}
}
}
entries.push((entry_name, data));
}
let mut builder = if self.use_gnu_style_archive {
BuilderKind::Gnu(
ar::GnuBuilder::new(
File::create(&self.dst).unwrap_or_else(|err| {
... | {
sess.fatal(&format!(
"error parsing `{}` during archive creation: {}",
String::from_utf8_lossy(&entry_name),
err
));
} | conditional_block |
archive.rs | //! Creation of ar archives like for the lib and staticlib crate type
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::fs::File;
use std::io::{self, Read, Seek};
use std::path::{Path, PathBuf};
use rustc_codegen_ssa::back::archive::ArchiveBuilder;
use rustc_session::Session;
use object::read::arch... | ));
}
(vec![read_cache.into_inner()], entries)
} else {
(vec![], Vec::new())
};
ArArchiveBuilder {
sess,
dst: output.to_path_buf(),
use_gnu_style_archive: sess.target.archive_format == "gnu",
//... | ArchiveEntry::FromArchive { archive_index: 0, file_range: entry.file_range() }, | random_line_split |
archive.rs | //! Creation of ar archives like for the lib and staticlib crate type
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::fs::File;
use std::io::{self, Read, Seek};
use std::path::{Path, PathBuf};
use rustc_codegen_ssa::back::archive::ArchiveBuilder;
use rustc_session::Session;
use object::read::arch... | (
&mut self,
_lib_name: &str,
_dll_imports: &[rustc_session::cstore::DllImport],
_tmpdir: &rustc_data_structures::temp_dir::MaybeTempDir,
) {
bug!("injecting dll imports is not supported");
}
}
| inject_dll_import_lib | identifier_name |
monorail.py | # Copyright 2021 Google LLC
#
# 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, ... | (self, project, service_account_info):
self.project = project
self._service_account_info = service_account_info
def get_issue(self, issue_id):
"""Get issue data."""
credentials = service_account.IDTokenCredentials.from_service_account_info(
self._service_account_info, target_audience=_TARGET_... | __init__ | identifier_name |
monorail.py | # Copyright 2021 Google LLC
#
# 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, ... | _XSSI_PREFIX = ')]}\'\n'
class Client:
"""Monorail client."""
def __init__(self, project, service_account_info):
self.project = project
self._service_account_info = service_account_info
def get_issue(self, issue_id):
"""Get issue data."""
credentials = service_account.IDTokenCredentials.from_s... | random_line_split | |
monorail.py | # Copyright 2021 Google LLC
#
# 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, ... |
return json.loads(result)
| result = result[len(_XSSI_PREFIX):] | conditional_block |
monorail.py | # Copyright 2021 Google LLC
#
# 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, ... |
return json.loads(result)
| """Get issue data."""
credentials = service_account.IDTokenCredentials.from_service_account_info(
self._service_account_info, target_audience=_TARGET_AUDIENCE)
credentials.refresh(google_requests.Request())
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'... | identifier_body |
borrowck-newtype-issue-2573.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
// Override default mode so that we are passing by value
fn really_impure(++bar: baz) {
bar.baz = 3;
}
pub fn main() {}
| {
really_impure(self.bar);
} | identifier_body |
borrowck-newtype-issue-2573.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl frob for foo {
fn frob(&self) {
really_impure(self.bar);
}
}
// Override default mode so that we are passing by value
fn really_impure(++bar: baz) {
bar.baz = 3;
}
pub fn main() {} | fn frob(&self);
} | random_line_split |
borrowck-newtype-issue-2573.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) {
really_impure(self.bar);
}
}
// Override default mode so that we are passing by value
fn really_impure(++bar: baz) {
bar.baz = 3;
}
pub fn main() {}
| frob | identifier_name |
charmhub.py | from .client import client | from .errors import JujuError
class CharmHub:
def __init__(self, model):
self.model = model
async def info(self, name, channel=None):
"""info displays detailed information about a CharmHub charm. The charm
can be specified by the exact name.
Channel is a hint for providing th... | random_line_split | |
charmhub.py | from .client import client
from .errors import JujuError
class CharmHub:
def __init__(self, model):
self.model = model
async def info(self, name, channel=None):
"""info displays detailed information about a CharmHub charm. The charm
can be specified by the exact name.
Channel... |
facade = self._facade()
return await facade.Find(query=query, category=category, channel=channel,
type_=charm_type, platforms=platforms, publisher=publisher,
relation_provides=relation_provides, relation_requires=relation_requires)
... | raise JujuError("expected either charm or bundle for charm_type") | conditional_block |
charmhub.py | from .client import client
from .errors import JujuError
class CharmHub:
def __init__(self, model):
|
async def info(self, name, channel=None):
"""info displays detailed information about a CharmHub charm. The charm
can be specified by the exact name.
Channel is a hint for providing the metadata for a given channel.
Without the channel hint then only the default release will have ... | self.model = model | identifier_body |
charmhub.py | from .client import client
from .errors import JujuError
class | :
def __init__(self, model):
self.model = model
async def info(self, name, channel=None):
"""info displays detailed information about a CharmHub charm. The charm
can be specified by the exact name.
Channel is a hint for providing the metadata for a given channel.
Withou... | CharmHub | identifier_name |
func.rs | //! Module for working with `Function`s
//!
//! This module contains a type alias for `Rc<Fn(f64) -> f64>`,
//! which is used in many other modules, and functions for
//! working with the alias.
pub use std::rc::Rc;
/// Type alias used to represent functions.
///
/// A `Function` is a `Fn` that takes a single `f64`,
... | /// ```
/// # #[macro_use]
/// # extern crate reikna;
/// # fn main() {
/// use reikna::func::*;
/// let f: Function = func!(|x| x * x);
/// assert_eq!(f(5.0), 25.0);
/// # }
/// ```
#[macro_export]
macro_rules! func {
($e:expr) => (Rc::new($e) as Function);
} | /// More idiomatic than calling `Rc::new()`.
///
/// # Examples
/// | random_line_split |
sso.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from '../../../../src/environments/environment';
import {SsoService} from './sso.service';
@Component({
selector: 'app-sso',
templateUrl: './sso.component.html',
styleUrls: ['./sso.component.scss']... | else {
this.ssoService.callSsoLogin();
}
} else {
this.router.navigateByUrl('/');
}
setTimeout(() => {
this.status = 'Your session has timed out, please re-login!';
}, 5000);
}
}
| {
this.ssoService.obtainAuthCode();
} | conditional_block |
sso.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from '../../../../src/environments/environment';
import {SsoService} from './sso.service';
@Component({
selector: 'app-sso',
templateUrl: './sso.component.html',
styleUrls: ['./sso.component.scss']... | }
} | setTimeout(() => {
this.status = 'Your session has timed out, please re-login!';
}, 5000); | random_line_split |
sso.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from '../../../../src/environments/environment';
import {SsoService} from './sso.service';
@Component({
selector: 'app-sso',
templateUrl: './sso.component.html',
styleUrls: ['./sso.component.scss']... | () {
if (environment.authorization.ALLOW_SSO) {
if (!localStorage.getItem('auth-code')) {
this.ssoService.obtainAuthCode();
} else {
this.ssoService.callSsoLogin();
}
} else {
this.router.navigateByUrl('/');
}
setTimeout(() => {
this.status = 'Your session ... | ngOnInit | identifier_name |
expr-alt-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let rs = match true { true => R {i: 100}, _ => fail!() };
assert!((rs.i == 100));
}
enum mood { happy, sad, }
impl cmp::Eq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool { !(*self).eq(other) }
}
fn test_tag... | test_rec | identifier_name |
expr-alt-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { test_rec(); test_tag(); } | identifier_body | |
expr-alt-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// -*- rust -*-
... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
en-CA.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
exp... | ]; | ['21:00', '06:00']
] | random_line_split |
container.rs | #![macro_use]
pub trait FromEcs<E: ContainsSystem> where Self: Sized {
fn from_ecs(ecs: &E) -> &Self;
}
pub trait FromEcsMut<E: ContainsMutSystem>: FromEcs<E> {
fn from_ecs_mut(ecs: &mut E) -> &mut Self;
}
pub trait ContainsSystem where Self: Sized {
fn get_system<S>(&self) -> &S
where S: FromEcs... |
pub struct EcsContainer {
pub entity_factory: EntityFactory,
$(pub $sys_id: $sys_type,)+
$(pub $upd_id: $upd_type,)+
}
impl EcsContainer {
pub fn new_entity(&mut self) -> EntityConfiguration<Self> {
let entity = self.entity_factory.new_entity();
self... |
pub trait ConfiguresComponent<C> {
fn with_component(self, component: C) -> Self;
} | random_line_split |
alexa.spec.ts | /*
* Copyright (c) 2018 Rain Agency <contact@rain.agency>
* Author: Rain Agency <contact@rain.agency>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including wi... | });
it("Runs the alexa skill and does not like voxa", async () => {
let reply = await alexa.launch();
expect(reply.prompt()).to.equal(
"<speak>Welcome to this voxa app, are you enjoying voxa so far?</speak>",
);
reply = (await alexa.utter("no")) as SkillResponse;
expect(reply.prompt()).t... | expect(reply.prompt()).to.include(views.en.translation.doesLikeVoxa); | random_line_split |
WithPermission.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import { ApplicationState } from '../state/ApplicationState';
import { matchesPermissions } from '../state/Selectors';
import { createSelector } from 'reselect';
import { memoizeWith, toString } from 'ramda';
type StateProps = {
readonly show: bo... | show,
alternative,
children,
}) => {
if (show) {
return <>{children}</> || null;
}
if (alternative) {
const Alt = alternative;
return <Alt />;
}
return null;
};
const memoizedStateSelector = memoizeWith(toString, (perms: string | string[]) =>
createSelector(matchesPermissions(perms), s... |
const WithPermissionComponent: React.FunctionComponent<StateProps & WithPermissionProps> = ({ | random_line_split |
WithPermission.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import { ApplicationState } from '../state/ApplicationState';
import { matchesPermissions } from '../state/Selectors';
import { createSelector } from 'reselect';
import { memoizeWith, toString } from 'ramda';
type StateProps = {
readonly show: bo... |
return null;
};
const memoizedStateSelector = memoizeWith(toString, (perms: string | string[]) =>
createSelector(matchesPermissions(perms), show => ({
show,
})),
);
export const WithPermission = connect<StateProps, {}, WithPermissionProps>(
(state: ApplicationState, props?: WithPermissionProps): StatePr... | {
const Alt = alternative;
return <Alt />;
} | conditional_block |
card_skip.js | import React from 'react';
export default class | extends React.Component{
render(){
const colour = this.props.card.colour ? this.props.card.colour : 'gray';
return(
<svg className="card-skip-component" onClick={this.props.onClick}
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 158.7 243.8">
<g id="Layer_3">
... | CardSkip | identifier_name |
card_skip.js | import React from 'react';
export default class CardSkip extends React.Component{
render() | </g>
<g id="Layer_9">
<g id="XMLID_45_">
<g id="XMLID_33_">
<text id="XMLID_35_" transform="rotate(180 72.547 104.114)" className="skip2 skip3 skip4">S</text>
</g>
<g id="XMLID_29_">
<t... | {
const colour = this.props.card.colour ? this.props.card.colour : 'gray';
return(
<svg className="card-skip-component" onClick={this.props.onClick}
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 158.7 243.8">
<g id="Layer_3">
<path id="XMLID_5_" className="c... | identifier_body |
card_skip.js | import React from 'react';
export default class CardSkip extends React.Component{
render(){
const colour = this.props.card.colour ? this.props.card.colour : 'gray';
return(
<svg className="card-skip-component" onClick={this.props.onClick}
xmlns="http://www.w3.org/2000/svg" viewBox="... | <g id="XMLID_45_">
<g id="XMLID_33_">
<text id="XMLID_35_" transform="rotate(180 72.547 104.114)" className="skip2 skip3 skip4">S</text>
</g>
<g id="XMLID_29_">
<text id="XMLID_31_" transform="rotate(180 71.84... | <g id="Layer_9"> | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.