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 |
|---|---|---|---|---|
tictactoe.py | # Tic Tac Toe
# Tic Tac Toe
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
p... | (bo, le):
# Given a board and a player's letter, this function returns True if that player has won.
# We use bo instead of board and le instead of letter so we don't have to type as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == ... | isWinner | identifier_name |
tictactoe.py | # Tic Tac Toe
# Tic Tac Toe
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
p... |
# Check if the player could win on his next move, and block them.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i
# Try to take one of the corners, i... | makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i | random_line_split |
tictactoe.py | # Tic Tac Toe
# Tic Tac Toe
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
p... |
def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (ye... | letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = input().upper()
# the first element in the tuple is the player's letter, the second is the computer's letter.
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X'] | identifier_body |
maintenance_controller.py | # Copyright (C) 2019 OpenMotics BV
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribu... |
logger = logging.getLogger(__name__)
@Injectable.named('maintenance_controller')
@Singleton
class MaintenanceController(object):
SOCKET_TIMEOUT = 60
@Inject
def __init__(self, maintenance_communicator=INJECTED, ssl_private_key=INJECTED, ssl_certificate=INJECTED):
# type: (MaintenanceCommunicat... | from typing import Dict, Optional, Callable, Any, ByteString
from master.maintenance_communicator import MaintenanceCommunicator | conditional_block |
maintenance_controller.py | # Copyright (C) 2019 OpenMotics BV
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribu... | # type: (int) -> None
connection_timeout = MaintenanceController.SOCKET_TIMEOUT
logger.info('Starting maintenance socket on port %s', port)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout... |
def _run_socket_server(self, port): | random_line_split |
maintenance_controller.py | # Copyright (C) 2019 OpenMotics BV
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribu... | (self):
# type: () -> None
if not self._maintenance_communicator.is_active():
self._maintenance_communicator.activate()
def _deactivate(self):
# type: () -> None
if self._maintenance_communicator.is_active():
self._maintenance_communicator.deactivate()
#... | _activate | identifier_name |
maintenance_controller.py | # Copyright (C) 2019 OpenMotics BV
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribu... |
#######################
# Internal management #
#######################
def start(self):
# type: () -> None
if self._maintenance_communicator:
self._maintenance_communicator.start()
def stop(self):
# type: () -> None
if self._maintenance_communicator:
... | """
:type maintenance_communicator: gateway.maintenance_communicator.MaintenanceCommunicator
"""
self._consumers = {} # type: Dict[int, Callable[[str], Any]]
self._privatekey_filename = ssl_private_key
self._certificate_filename = ssl_certificate
self._maintenance_commun... | identifier_body |
peertube-dock-component.ts | import videojs from 'video.js'
const Component = videojs.getComponent('Component')
export type PeerTubeDockComponentOptions = {
title?: string
description?: string
avatarUrl?: string
}
class PeerTubeDockComponent extends Component {
| () {
const options = this.options_ as PeerTubeDockComponentOptions
const el = super.createEl('div', {
className: 'peertube-dock'
})
if (options.avatarUrl) {
const avatar = videojs.dom.createEl('img', {
className: 'peertube-dock-avatar',
src: options.avatarUrl
})
... | createEl | identifier_name |
peertube-dock-component.ts | import videojs from 'video.js'
const Component = videojs.getComponent('Component')
export type PeerTubeDockComponentOptions = {
title?: string
description?: string
avatarUrl?: string
}
class PeerTubeDockComponent extends Component {
createEl () | if (options.title) {
const title = videojs.dom.createEl('div', {
className: 'peertube-dock-title',
title: options.title,
innerHTML: options.title
})
elWrapperTitleDescription.appendChild(title)
}
if (options.description) {
const description = videojs.dom.cre... | {
const options = this.options_ as PeerTubeDockComponentOptions
const el = super.createEl('div', {
className: 'peertube-dock'
})
if (options.avatarUrl) {
const avatar = videojs.dom.createEl('img', {
className: 'peertube-dock-avatar',
src: options.avatarUrl
})
e... | identifier_body |
peertube-dock-component.ts | import videojs from 'video.js'
const Component = videojs.getComponent('Component')
export type PeerTubeDockComponentOptions = {
title?: string
description?: string
avatarUrl?: string
}
class PeerTubeDockComponent extends Component {
createEl () {
const options = this.options_ as PeerTubeDockComponentOpt... | PeerTubeDockComponent
} | export { | random_line_split |
peertube-dock-component.ts | import videojs from 'video.js'
const Component = videojs.getComponent('Component')
export type PeerTubeDockComponentOptions = {
title?: string
description?: string
avatarUrl?: string
}
class PeerTubeDockComponent extends Component {
createEl () {
const options = this.options_ as PeerTubeDockComponentOpt... |
const elWrapperTitleDescription = super.createEl('div', {
className: 'peertube-dock-title-description'
})
if (options.title) {
const title = videojs.dom.createEl('div', {
className: 'peertube-dock-title',
title: options.title,
innerHTML: options.title
})
e... | {
const avatar = videojs.dom.createEl('img', {
className: 'peertube-dock-avatar',
src: options.avatarUrl
})
el.appendChild(avatar)
} | conditional_block |
origin.rs | // Copyright 2016 The rust-url developers.
//
// 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 ... | (&self) -> usize {
match *self {
Origin::Tuple(ref scheme, ref host, _) => {
scheme.heap_size_of_children() +
host.heap_size_of_children()
},
_ => 0,
}
}
}
impl Origin {
/// Creates a new opaque origin that is only equal to it... | heap_size_of_children | identifier_name |
origin.rs | // Copyright 2016 The rust-url developers.
//
// 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 ... |
/// https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin
pub fn ascii_serialization(&self) -> String {
match *self {
Origin::Opaque(_) => "null".to_owned(),
Origin::Tuple(ref scheme, ref host, port) => {
if default_port(scheme) == Some(port) ... | {
matches!(*self, Origin::Tuple(..))
} | identifier_body |
origin.rs | // Copyright 2016 The rust-url developers.
//
// 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 ... | matches!(*self, Origin::Tuple(..))
}
/// https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin
pub fn ascii_serialization(&self) -> String {
match *self {
Origin::Opaque(_) => "null".to_owned(),
Origin::Tuple(ref scheme, ref host, port) => {
... | }
/// Return whether this origin is a (scheme, host, port) tuple
/// (as opposed to an opaque origin).
pub fn is_tuple(&self) -> bool { | random_line_split |
casesModel.ts | import { IUsers, ICompanies } from './usersModel';
export interface ICases {
CaseName: string;
RTRAmt?: number;
SubmissionDate?: Date;
DefaultDate?: Date;
TotalAmtCollected?: number;
CurrentStage?: CaseStagesEnum;
LastUpdateDate?: Date;
AssociatedCompany?: string;
CurrentAction?: Ca... | PaybackComplete,
Submission,
Targetting
}
export enum CaseActionsEnum {
PrepareCOJ = 1,
RestrainingNotice,
InfoSubpoena,
Execution,
NOE,
UCCNotice
}
export enum CaseDefaultReasonsEnum {
R01_InsufficientFunds = 1,
R08_StoppedPayment,
Missed_BouncingPayment
} | Assignment = 1,
Collection,
Enforcement,
KillDeal, | random_line_split |
global.js | .76.119.16:8888/jojosns/",
// baseImgUrl:"http://120.76.119.16:8888/jojosns/",
// 开发环境
baseUrl: "http://27.61.80.50:8080/jojosns/",
baseImgUrl: "http://27.61.80.50:8080/jojosns/", //图片服务器,若没有单独服务,可忽略此项
staticPath: process.env.NODE_ENV !== 'development' ? config.build.stat... | * @objD 必填,格式为毫秒数
*/
formatDate: function (objD) {
if (!objD) {
return '';
}
objD = new Date(objD);
var str;
var yy = objD.getYear();
if (yy < 1900) yy = yy + 1900;
var MM = objD.get... |
/**
* author lss
* 日期格式化,传入为毫秒数,转出时间格式为 :2016-6-6 12:00:00
| random_line_split |
global.js | 76.119.16:8888/jojosns/",
// baseImgUrl:"http://120.76.119.16:8888/jojosns/",
// 开发环境
baseUrl: "http://27.61.80.50:8080/jojosns/",
baseImgUrl: "http://27.61.80.50:8080/jojosns/", //图片服务器,若没有单独服务,可忽略此项
staticPath: process.env.NODE_ENV !== 'development' ? config.build.stati... | _idCounter_ += 1 : window._idCounter_ = 1;
},
/**
* 统一接口处理:get请求方法封装。this.$http.get(url, [options])
* @param url { String } -必选 接口url
* @param options { Object } -必选 含官方的所有options对象。传参为{params:{key:11}}
* @param sucCb { Function } -必选 成功回调
* ... | ef = path;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
},
/**
* 全局ID计数器,保证返回的是一个全局的id标识(数字)
*/
globalId: function () {
return window._idC... | identifier_body |
global.js | 76.119.16:8888/jojosns/",
// baseImgUrl:"http://120.76.119.16:8888/jojosns/",
// 开发环境
baseUrl: "http://27.61.80.50:8080/jojosns/",
baseImgUrl: "http://27.61.80.50:8080/jojosns/", //图片服务器,若没有单独服务,可忽略此项
staticPath: process.env.NODE_ENV !== 'development' ? config.build.stati... | ink.href = path;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
},
/**
* 全局ID计数器,保证返回的是一个全局的id标识(数字)
*/
globalId: function () {
return windo... | l | identifier_name |
tickets.component.ts | import { Component } from '@angular/core';
import { NgFor } from '@angular/common';
import { Http } from '@angular/http';
let page_name = "tickets";
@Component({
selector: page_name,
templateUrl: 'templates/'+page_name+'.html'
})
export class TicketsComponent {
projects: Object[];
http: Http;
editing = false;
... | }
refresh(){
this.http.get('crud/'+page_name).subscribe(res => {
this.projects = res.json();
});
}
add_edit(){
this.http.get('schema/'+page_name).subscribe(res => {
this.editing = true;
this.form = res.json().blank_form;
});
//TODO: create a new changeset either based on exising dev
//TODO: or ... | random_line_split | |
tickets.component.ts | import { Component } from '@angular/core';
import { NgFor } from '@angular/common';
import { Http } from '@angular/http';
let page_name = "tickets";
@Component({
selector: page_name,
templateUrl: 'templates/'+page_name+'.html'
})
export class | {
projects: Object[];
http: Http;
editing = false;
public form = {};
constructor(private http_client: Http){
this.http = http_client;
this.refresh();
}
refresh(){
this.http.get('crud/'+page_name).subscribe(res => {
this.projects = res.json();
});
}
add_edit(){
this.http.get('schema/'+page_name).s... | TicketsComponent | identifier_name |
forms.py | import new
from django import forms
from ostinato.statemachine import InvalidTransition
def sm_form_factory(sm_class, state_field='state'):
"""
A factory to create a custom StateMachineModelForm class
"""
class StateMachineModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
... |
return StateMachineModelForm
| """
Override the save method so that we can perform statemachine
actions.
For most simple cases this is all that is required. If however
you want to do more advanced processing based on the state/action,
then you should override the save method and call ``tak... | identifier_body |
forms.py | import new
from django import forms
from ostinato.statemachine import InvalidTransition
def sm_form_factory(sm_class, state_field='state'):
"""
A factory to create a custom StateMachineModelForm class
"""
class StateMachineModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
... | """
self._sm_action = self.cleaned_data[state_field]
try:
return sm.action_result(self._sm_action)
except InvalidTransition:
return self.old_state
setattr(self, 'clean_%s' % state_field,
... | the actual form cleaned_data, since it can cause validation
issues on the field. | random_line_split |
forms.py | import new
from django import forms
from ostinato.statemachine import InvalidTransition
def sm_form_factory(sm_class, state_field='state'):
"""
A factory to create a custom StateMachineModelForm class
"""
class StateMachineModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
... | (self, *args, **kwargs):
"""
Override the save method so that we can perform statemachine
actions.
For most simple cases this is all that is required. If however
you want to do more advanced processing based on the state/action,
then you should ov... | save | identifier_name |
forms.py | import new
from django import forms
from ostinato.statemachine import InvalidTransition
def sm_form_factory(sm_class, state_field='state'):
"""
A factory to create a custom StateMachineModelForm class
"""
class StateMachineModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
... |
def save(self, *args, **kwargs):
"""
Override the save method so that we can perform statemachine
actions.
For most simple cases this is all that is required. If however
you want to do more advanced processing based on the state/action,
... | sm.take_action(self._sm_action) | conditional_block |
client.py | from __future__ import absolute_import
import datetime
import jwt
import re
import logging
from six.moves.urllib.parse import parse_qs, urlparse, urlsplit
from sentry.integrations.atlassian_connect import get_query_hash
from sentry.shared_integrations.exceptions import ApiError
from sentry.integrations.client import... | (self, issue_id):
return self.get(self.ISSUE_URL % (issue_id,))
def search_issues(self, query):
# check if it looks like an issue id
if ISSUE_KEY_RE.match(query):
jql = 'id="%s"' % query.replace('"', '\\"')
else:
jql = 'text ~ "%s"' % query.replace('"', '\\"'... | get_issue | identifier_name |
client.py | from __future__ import absolute_import
import datetime
import jwt
import re
import logging
from six.moves.urllib.parse import parse_qs, urlparse, urlsplit
from sentry.integrations.atlassian_connect import get_query_hash
from sentry.shared_integrations.exceptions import ApiError
from sentry.integrations.client import... |
def transition_issue(self, issue_key, transition_id):
return self.post(self.TRANSITION_URL % issue_key, {"transition": {"id": transition_id}})
def assign_issue(self, key, name_or_account_id):
user_id_field = self.user_id_field()
return self.put(self.ASSIGN_URL % key, data={user_id_fie... | return self.get_cached(self.TRANSITION_URL % issue_key)["transitions"] | identifier_body |
client.py | from __future__ import absolute_import
import datetime
import jwt
import re
import logging
from six.moves.urllib.parse import parse_qs, urlparse, urlsplit
from sentry.integrations.atlassian_connect import get_query_hash
from sentry.shared_integrations.exceptions import ApiError
from sentry.integrations.client import... |
jwt_payload = {
"iss": JIRA_KEY,
"iat": datetime.datetime.utcnow(),
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=5 * 60),
"qsh": get_query_hash(path, method.upper(), url_params),
}
encoded_jwt = jwt.encode(jwt_payload, self.share... | url_params = dict(parse_qs(urlsplit(path).query))
url_params.update(params or {})
path = path.split("?")[0] | random_line_split |
client.py | from __future__ import absolute_import
import datetime
import jwt
import re
import logging
from six.moves.urllib.parse import parse_qs, urlparse, urlsplit
from sentry.integrations.atlassian_connect import get_query_hash
from sentry.shared_integrations.exceptions import ApiError
from sentry.integrations.client import... |
projects = self.get_projects_list()
for project in projects:
if project["id"] == project_id:
return project["key"].encode("utf-8")
return ""
def get_create_meta_for_project(self, project):
params = {"expand": "projects.issuetypes.fields", "projectIds": p... | return "" | conditional_block |
setup.py | """
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project: |
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Versi... | http://www.smartdeveloperhub.org | random_line_split |
niche-filling.rs | // Copyright 2016 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 ... | <T> { None, Some(T) }
impl<T> Default for MyOption<T> {
fn default() -> Self { MyOption::None }
}
pub enum EmbeddedDiscr {
None,
Record { pre: u8, val: NonZeroU32, post: u16 },
}
impl Default for EmbeddedDiscr {
fn default() -> Self { EmbeddedDiscr::None }
}
#[derive(Default)]
pub struct IndirectNon... | MyOption | identifier_name |
niche-filling.rs | // Copyright 2016 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 ... |
}
#[derive(Default)]
pub struct IndirectNonZero {
pre: u8,
nested: NestedNonZero,
post: u16,
}
pub struct NestedNonZero {
pre: u8,
val: NonZeroU32,
post: u16,
}
impl Default for NestedNonZero {
fn default() -> Self {
NestedNonZero { pre: 0, val: NonZeroU32::new(1).unwrap(), post:... | { EmbeddedDiscr::None } | identifier_body |
niche-filling.rs | // Copyright 2016 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 ... | }
}
pub enum Enum4<A, B, C, D> {
One(A),
Two(B),
Three(C),
Four(D)
}
#[start]
fn start(_: isize, _: *const *const u8) -> isize {
let _x: MyOption<NonZeroU32> = Default::default();
let _y: EmbeddedDiscr = Default::default();
let _z: MyOption<IndirectNonZero> = Default::default();
le... | }
impl Default for NestedNonZero {
fn default() -> Self {
NestedNonZero { pre: 0, val: NonZeroU32::new(1).unwrap(), post: 0 } | random_line_split |
models.py | '''
Project: Farnsworth
Author: Karandeep Singh Nagra
'''
from django.contrib.auth.models import User, Group, Permission
from django.core.urlresolvers import reverse
from django.db import models
from base.models import UserProfile
class Thread(models.Model):
'''
The Thread model. Used to group messages.
... | )
subject = models.CharField(
blank=False,
null=False,
max_length=254,
help_text="Subject of this thread.",
)
start_date = models.DateTimeField(
auto_now_add=True,
help_text="The date this thread was started.",
)
change_date = models.Da... | random_line_split | |
models.py | '''
Project: Farnsworth
Author: Karandeep Singh Nagra
'''
from django.contrib.auth.models import User, Group, Permission
from django.core.urlresolvers import reverse
from django.db import models
from base.models import UserProfile
class Thread(models.Model):
'''
The Thread model. Used to group messages.
... |
def post_save_thread(sender, instance, created, **kwargs):
thread = instance
if not created and thread.number_of_messages == 0:
thread.delete()
def post_save_message(sender, instance, created, **kwargs):
message = instance
thread = message.thread
if created:
thread.change_date = ... | thread = instance
thread.number_of_messages = thread.message_set.count() | identifier_body |
models.py | '''
Project: Farnsworth
Author: Karandeep Singh Nagra
'''
from django.contrib.auth.models import User, Group, Permission
from django.core.urlresolvers import reverse
from django.db import models
from base.models import UserProfile
class Thread(models.Model):
'''
The Thread model. Used to group messages.
... |
thread.save()
def post_delete_message(sender, instance, **kwargs):
message = instance
message.thread.save()
# Connect signals with their respective functions from above.
# When a message is created, update that message's thread's change_date to the post_date of that message.
models.signals.post_save.con... | thread.change_date = message.post_date | conditional_block |
models.py | '''
Project: Farnsworth
Author: Karandeep Singh Nagra
'''
from django.contrib.auth.models import User, Group, Permission
from django.core.urlresolvers import reverse
from django.db import models
from base.models import UserProfile
class Thread(models.Model):
'''
The Thread model. Used to group messages.
... | :
ordering = ['post_date']
def is_message(self):
return True
def pre_save_thread(sender, instance, **kwargs):
thread = instance
thread.number_of_messages = thread.message_set.count()
def post_save_thread(sender, instance, created, **kwargs):
thread = instance
if not created and th... | Meta | identifier_name |
mod.rs | _store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub static VIC_INTENABLE: *mut u32 = (0x10140000 +... |
while j < CURSOR_HEIGHT
{
while i < CURSOR_WIDTH
{
if ((map[CURSOR_HEIGHT - j] >> 4*(CURSOR_WIDTH - i)) & 1) == 1
{
*(addr as *mut u32) = FG_COLOR;
}
else
{
*(addr as *mut u32) = BG_COLOR;
}
addr -= 4;
i += 1;
}
addr += 4*(i+SCREEN_WIDTH);
i = 0;
j +=... |
let mut i = -1;
let mut j = 0;
let mut addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + 1 + SCREEN_WIDTH*CURSOR_Y); | random_line_split |
mod.rs | _store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub static VIC_INTENABLE: *mut u32 = (0x10140000 +... |
let font_offset = (c as u8) - 0x20;
let map = font::bitmaps[font_offset];
let mut i = -1;
let mut j = 0;
let mut addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + 1 + SCREEN_WIDTH*CURSOR_Y);
while j < CURSOR_HEIGHT
{
while i < CURSOR_WIDTH
{
if ((map[CURSOR_HEIGHT - j] >> 4*(CURSOR_... | {
scrollup();
} | conditional_block |
mod.rs | _store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub static VIC_INTENABLE: *mut u32 = (0x10140000 +... | ()
{
let mut i = CURSOR_HEIGHT*SCREEN_WIDTH;
while i < (SCREEN_WIDTH*SCREEN_HEIGHT)
{
*((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32);
i += 1;
}
i = 4*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH);
while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT
{
... | scrollup | identifier_name |
mod.rs | _store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub static VIC_INTENABLE: *mut u32 = (0x10140000 +... |
pub unsafe fn paint(color: u32)
{
let mut i = 0;
while i < SCREEN_WIDTH*SCREEN_HEIGHT
{
*((START_ADDR as u32 + i*4) as *mut u32) = color;
i+=1;
}
}
pub unsafe fn fill_bg()
{
paint(BG_COLOR);
}
#[allow(dead_code)]
pub unsafe fn read(addr: u32) -> u32
{
*(addr as *mut u32)
}
pub unsafe fn ... | {
let mut i = 0;
let mut j = 0;
while j < CURSOR_HEIGHT
{
while i < CURSOR_WIDTH
{
let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j));
*(addr as *mut u32) = CURSOR_COLOR;
i += 1;
}
i = 0;
j += 1;
}
} | identifier_body |
webpackfile.js | const Webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const package = require('./package.json')
const { join } = require('path')
const externals = () => {
const dependencies = package.dependencies | return Object
.keys(dependencies)
.reduce((modules, module) =>
Object.assign({}, modules, { [module]: `commonjs ${module}` }),
{}
)
}
module.exports = {
context: join(__dirname, './build'),
entry: {
boleto: './resources/boleto/index.js',
database: './functions/database/index.js'
... | random_line_split | |
data-method.js | (function(){
module('data-method', {
setup: function() {
$('#qunit-fixture').append($('<a />', {
href: '/echo', 'data-method': 'delete', text: 'destroy!'
}));
},
teardown: function() {
$(document).unbind('iframe:loaded');
}
});
function | (fn, options) {
$(document).bind('iframe:loaded', function(e, data) {
fn(data);
start();
});
$('#qunit-fixture').find('a')
.trigger('click');
}
asyncTest('link with "data-method" set to "delete"', 3, function() {
submit(function(data) {
equal(data.REQUEST_METHOD, 'DELETE');
strictEqual(dat... | submit | identifier_name |
data-method.js | (function(){
module('data-method', {
setup: function() {
$('#qunit-fixture').append($('<a />', {
href: '/echo', 'data-method': 'delete', text: 'destroy!'
}));
},
teardown: function() {
$(document).unbind('iframe:loaded');
}
});
function submit(fn, options) {
$(document).bind('iframe:loaded... | asyncTest('link with "data-method" set to "delete"', 3, function() {
submit(function(data) {
equal(data.REQUEST_METHOD, 'DELETE');
strictEqual(data.params.authenticity_token, undefined);
strictEqual(data.HTTP_X_CSRF_TOKEN, undefined);
});
});
asyncTest('link with "data-method" and CSRF', 1, function() ... | $('#qunit-fixture').find('a')
.trigger('click');
}
| random_line_split |
data-method.js | (function(){
module('data-method', {
setup: function() {
$('#qunit-fixture').append($('<a />', {
href: '/echo', 'data-method': 'delete', text: 'destroy!'
}));
},
teardown: function() {
$(document).unbind('iframe:loaded');
}
});
function submit(fn, options) |
asyncTest('link with "data-method" set to "delete"', 3, function() {
submit(function(data) {
equal(data.REQUEST_METHOD, 'DELETE');
strictEqual(data.params.authenticity_token, undefined);
strictEqual(data.HTTP_X_CSRF_TOKEN, undefined);
});
});
asyncTest('link with "data-method" and CSRF', 1, function(... | {
$(document).bind('iframe:loaded', function(e, data) {
fn(data);
start();
});
$('#qunit-fixture').find('a')
.trigger('click');
} | identifier_body |
handlers.py | import logging
from event_consumer.conf import settings
from event_consumer.errors import PermanentFailure
from event_consumer.handlers import message_handler
_logger = logging.getLogger(__name__)
class IntegrationTestHandlers(object):
"""
Basic message handlers that log or raise known exceptions to allow
... |
@staticmethod
def py_integration_raise_permanent(body):
"""
Should cause the message to be archived on first go.
"""
msg = 'py_integration_raise_permanent, {}'.format(body)
_logger.info(msg)
raise PermanentFailure(msg)
if settings.TEST_ENABLED:
# Add tasks... | """
Should retry until there are no attempts left, then archive.
"""
msg = 'py_integration_raise, {}'.format(body)
_logger.info(msg)
raise Exception(msg) | identifier_body |
handlers.py | import logging
from event_consumer.conf import settings
from event_consumer.errors import PermanentFailure
from event_consumer.handlers import message_handler
_logger = logging.getLogger(__name__)
class | (object):
"""
Basic message handlers that log or raise known exceptions to allow
interactive testing of the RabbitMQ config.
"""
@staticmethod
def py_integration_ok(body):
"""
Should always succeed, never retry, never archive.
"""
msg = 'py_integration_ok, {}'.fo... | IntegrationTestHandlers | identifier_name |
handlers.py | import logging
from event_consumer.conf import settings
from event_consumer.errors import PermanentFailure
from event_consumer.handlers import message_handler
_logger = logging.getLogger(__name__)
class IntegrationTestHandlers(object):
"""
Basic message handlers that log or raise known exceptions to allow
... | message_handler('py.integration.ok')(
IntegrationTestHandlers.py_integration_ok)
message_handler('py.integration.raise')(
IntegrationTestHandlers.py_integration_raise)
message_handler('py.integration.raise.permanent')(
IntegrationTestHandlers.py_integration_raise_permanent) | conditional_block | |
handlers.py | import logging
from event_consumer.conf import settings
from event_consumer.errors import PermanentFailure
from event_consumer.handlers import message_handler
|
class IntegrationTestHandlers(object):
"""
Basic message handlers that log or raise known exceptions to allow
interactive testing of the RabbitMQ config.
"""
@staticmethod
def py_integration_ok(body):
"""
Should always succeed, never retry, never archive.
"""
m... | _logger = logging.getLogger(__name__) | random_line_split |
improv_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | (unused_argv):
tf.logging.set_verbosity(FLAGS.log)
config = improv_rnn_config_flags.config_from_flags()
pipeline_instance = improv_rnn_pipeline.get_pipeline(
config, FLAGS.eval_ratio)
FLAGS.input = os.path.expanduser(FLAGS.input)
FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir)
pipeline.run_p... | main | identifier_name |
improv_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | console_entry_point() | conditional_block | |
improv_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
def console_entry_point():
tf.disable_v2_behavior()
tf.app.run(main)
if __name__ == '__main__':
console_entry_point()
| tf.logging.set_verbosity(FLAGS.log)
config = improv_rnn_config_flags.config_from_flags()
pipeline_instance = improv_rnn_pipeline.get_pipeline(
config, FLAGS.eval_ratio)
FLAGS.input = os.path.expanduser(FLAGS.input)
FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir)
pipeline.run_pipeline_serial(
... | identifier_body |
improv_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | FLAGS.output_dir)
def console_entry_point():
tf.disable_v2_behavior()
tf.app.run(main)
if __name__ == '__main__':
console_entry_point() | pipeline.run_pipeline_serial(
pipeline_instance,
pipeline.tf_record_iterator(FLAGS.input, pipeline_instance.input_type), | random_line_split |
items.js | /** Items controller **/
// Load dependencies
var Boom = require('boom');
module.exports.get = function(request, reply) {
// `this` - is a reference to sensihome scope
this.items.get(request.params.id, function(err, items) {
if (err) |
// 200 : Success
reply(items);
});
};
module.exports.add = function(request, reply) {
// `this` - is a reference to sensihome scope
this.items.add(request.payload, function(err, item) {
if (err)
return reply(err.toBoomError());
// 201 : Created
reply(item).code(201);
});
};
mo... | {
return reply(err.toBoomError());
} | conditional_block |
items.js | /** Items controller **/
// Load dependencies
var Boom = require('boom');
module.exports.get = function(request, reply) {
// `this` - is a reference to sensihome scope
this.items.get(request.params.id, function(err, items) {
if (err) {
return reply(err.toBoomError());
} | };
module.exports.add = function(request, reply) {
// `this` - is a reference to sensihome scope
this.items.add(request.payload, function(err, item) {
if (err)
return reply(err.toBoomError());
// 201 : Created
reply(item).code(201);
});
};
module.exports.update = function(request, re... | // 200 : Success
reply(items);
}); | random_line_split |
requestHandler.py | Expired(False)
self.caching = caching
self.ignoreErrors = ignoreErrors
self.compression = compression
self.cacheTime = int(cConfig().getSetting('cacheTime', 600))
self.requestTimeout = int(cConfig().getSetting('requestTimeout', 60))
self.removeBreakLines(True)
sel... |
if (self.__bRemoveBreakLines == True):
sContent = sContent.replace(" ", "")
self.__sRealUrl = oResponse.geturl()
oResponse.close()
if self.caching and self.cacheTime > 0:
self.writeCache(self.getRequestUri(), sContent)
return sContent
def __... | sContent = sContent.replace("\n", "")
sContent = sContent.replace("\r\t", "") | conditional_block |
requestHandler.py | .__sRealUrl
def request(self):
self.__sUrl = self.__sUrl.replace(' ', '+')
return self.__callRequest()
def getRequestUri(self):
return self.__sUrl + '?' + urllib.urlencode(self.__aParameters)
def __setDefaultHeader(self):
self.addHeaderEntry('User-Agent', common.FF_USER_AG... | newHTTPSConnection | identifier_name | |
requestHandler.py | .ignoreExpired(False)
self.caching = caching
self.ignoreErrors = ignoreErrors
self.compression = compression
self.cacheTime = int(cConfig().getSetting('cacheTime', 600))
self.requestTimeout = int(cConfig().getSetting('requestTimeout', 60))
self.removeBreakLines(True)
... | sContent = sContent.replace("\n", "")
sContent = sContent.replace("\r\t", "")
if (self.__bRemoveBreakLines == True):
sContent = sContent.replace(" ", "")
self.__sRealUrl = oResponse.geturl()
oResponse.close()
if self.caching and self.cacheTime ... | cookie_helper.check_cookies(cookieJar)
cookieJar.save(ignore_discard=self.__bIgnoreDiscard, ignore_expires=self.__bIgnoreExpired)
if (self.__bRemoveNewLines == True): | random_line_split |
requestHandler.py | (str(value))
def addResponse(self, key, value):
self.__aResponses[key] = value
def setFormIndex(self, index):
self.__formIndex = index
def getResponseHeader(self):
return self.__sResponseHeader
# url after redirects
def getRealUrl(self):
return self.__sRealUrl
... | files = os.listdir(self.__cachePath)
for file in files:
cacheFile = os.path.join(self.__cachePath, file)
fileAge = self.getFileAge(cacheFile)
if fileAge > self.cacheTime:
os.remove(cacheFile) | identifier_body | |
error.rs | use ::{CATCH_STRUCT_PREFIX, CATCH_FN_PREFIX, CATCHER_ATTR};
use parser::ErrorParams;
use utils::*;
use syntax::codemap::{Span};
use syntax::ast::{MetaItem, Ident, TyKind};
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::tokenstream::TokenTree;
use syntax::parse::token;
const ERR_PARAM: &'static str = "__er... | let response = ::rocket::response::Responder::respond_to(user_response,
$req_ident)?;
let status = ::rocket::http::Status::raw($code);
::rocket::response::Response::build().status(status).merge(response).ok()
... | {
let mut output = Vec::new();
// Parse the parameters from the error annotation.
let error = ErrorParams::from(ecx, sp, meta_item, &annotated);
// Get all of the information we learned from the attribute + function.
let user_fn_name = error.annotated_fn.ident();
let catch_fn_name = user_fn_na... | identifier_body |
error.rs | use ::{CATCH_STRUCT_PREFIX, CATCH_FN_PREFIX, CATCHER_ATTR};
use parser::ErrorParams;
use utils::*;
use syntax::codemap::{Span};
use syntax::ast::{MetaItem, Ident, TyKind};
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::tokenstream::TokenTree;
use syntax::parse::token;
const ERR_PARAM: &'static str = "__er... | (ecx: &mut ExtCtxt,
sp: Span,
meta_item: &MetaItem,
annotated: Annotatable)
-> Vec<Annotatable>
{
let mut output = Vec::new();
// Parse the parameters from the error annotation.
let error = ErrorParams::from(ecx, sp, meta_item, &annot... | error_decorator | identifier_name |
error.rs | use ::{CATCH_STRUCT_PREFIX, CATCH_FN_PREFIX, CATCHER_ATTR};
use parser::ErrorParams;
use utils::*;
use syntax::codemap::{Span};
use syntax::ast::{MetaItem, Ident, TyKind};
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::tokenstream::TokenTree;
use syntax::parse::token;
const ERR_PARAM: &'static str = "__er... |
// Push the static catch info. This is what the errors! macro refers to.
let struct_name = user_fn_name.prepend(CATCH_STRUCT_PREFIX);
emit_item(&mut output, quote_item!(ecx,
#[allow(non_upper_case_globals)]
pub static $struct_name: ::rocket::StaticCatchInfo =
::rocket::StaticCat... | random_line_split | |
glidera.js | 'use strict';
angular.module('copayApp.controllers').controller('glideraController',
function($scope, $timeout, $ionicModal, $log, storageService, glideraService, ongoingProcess, platformInfo, externalLinkService, popupService, lodash) {
$scope.openExternalLink = function(url) {
externalLinkService.open(u... | $scope.openExternalLink(glideraUrl);
}
$scope.openSupportWindow = function() {
var url = glideraService.getSupportUrl();
var optIn = true;
var title = 'Glidera Support';
var message = 'You can email glidera at support@glidera.io for direct support, or you can contact Glidera on Tw... | var glideraUrl = ($scope.network === 'testnet') ? 'https://sandbox.glidera.io/login' : 'https://glidera.io/login'; | random_line_split |
glidera.js | 'use strict';
angular.module('copayApp.controllers').controller('glideraController',
function($scope, $timeout, $ionicModal, $log, storageService, glideraService, ongoingProcess, platformInfo, externalLinkService, popupService, lodash) {
$scope.openExternalLink = function(url) {
externalLinkService.open(u... |
$scope.account['token'] = data.token;
$scope.account['status'] = data.status;
init();
});
};
$scope.openTxModal = function(tx) {
$scope.tx = tx;
glideraService.getTransaction($scope.account.token, tx.transactionUuid, function(err, tx) {
if (err) {
p... | {
popupService.showAlert('Authorisation error', err);
return;
} | conditional_block |
auth.effects.ts | import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/exhaustMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Effect, Actions } from '@ngrx/effects';
import { of } fr... | {
@Effect()
login$ = this.actions$
.ofType(Auth.LOGIN)
.map((action: Auth.Login) => action.payload)
.exhaustMap(auth =>
this.authService
.login(auth)
.map(user => new Auth.LoginSuccess({user}))
.catch(error => of(new Auth.LoginFailure(error)))
);
@Effect({dispatch: ... | AuthEffects | identifier_name |
auth.effects.ts | import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/exhaustMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Effect, Actions } from '@ngrx/effects';
import { of } fr... | private router: Router) {
}
} | random_line_split | |
alpha.py | #csv module.
import csv
from geopy import geocoders
from collections import defaultdict
import json
def checkgeocode(geocode):
#return len(geocode)
|
with open('casualty.csv', 'rb') as f:
reader = csv.reader(f)
codelist = dict()
for row in reader:
codelist[row[3]] = row[5]
#print codelist
print codelist
for k,v in codelist.iteritems():
print k,v
writer = csv.writer(open("geocodes.csv", 'wb+'))
for k,v in code... | if len(geocode) < 9:
return "0"+str(geocode)
else:
return geocode | identifier_body |
alpha.py | #csv module.
import csv
from geopy import geocoders
from collections import defaultdict
import json
def | (geocode):
#return len(geocode)
if len(geocode) < 9:
return "0"+str(geocode)
else:
return geocode
with open('casualty.csv', 'rb') as f:
reader = csv.reader(f)
codelist = dict()
for row in reader:
codelist[row[3]] = row[5]
#print codelist
print codelist
for k,v in codelis... | checkgeocode | identifier_name |
alpha.py | #csv module.
import csv
from geopy import geocoders
from collections import defaultdict
import json
def checkgeocode(geocode):
#return len(geocode)
if len(geocode) < 9:
return "0"+str(geocode)
else:
return geocode
with open('casualty.csv', 'rb') as f:
reader = csv.reader(f)
codelist = dict()
f... | #g = geocoders.GoogleV3()
#place, (lat, lng) = g.geocode(row[3])
#print "%s: %.5f, %.5f" % (place, lat, lng) | writer.writerow([k ,v,codelist[k]])
print counts
json.dump(counts, open('dead.counts.json', 'w')) | random_line_split |
alpha.py | #csv module.
import csv
from geopy import geocoders
from collections import defaultdict
import json
def checkgeocode(geocode):
#return len(geocode)
if len(geocode) < 9:
return "0"+str(geocode)
else:
return geocode
with open('casualty.csv', 'rb') as f:
reader = csv.reader(f)
codelist = dict()
f... |
for k,v in counts.iteritems():
print k,v
writer = csv.writer(open("injuredcounts.csv", 'wb+'))
for k,v in counts.iteritems():
writer.writerow([k ,v,codelist[k]])
print counts
json.dump(counts, open('dead.counts.json', 'w'))
#g = geocoders.GoogleV3()
#place, (lat, lng) = g.geocode(row[... | counts[row[3]] += 1 | conditional_block |
flock.rs | // Copyright 2014 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 mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() };
let ret = unsafe {
LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK, 0, 100, 0,
&mut overlapped)
};
if ret == 0 {
unsafe { libc::CloseHandle(handle); }
... | {
fail!("create file error: {}", os::last_os_error());
} | conditional_block |
flock.rs | // Copyright 2014 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 ... | (p: &Path) -> Lock {
let fd = p.with_c_str(|s| unsafe {
libc::open(s, libc::O_RDWR | libc::O_CREAT, libc::S_IRWXU)
});
assert!(fd > 0);
let flock = os::flock {
l_start: 0,
l_len: 0,
l_pid: 0,
... | new | identifier_name |
flock.rs | // Copyright 2014 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 ... | }
}
#[cfg(windows)]
mod imp {
use libc;
use std::mem;
use std::os::win32::as_utf16_p;
use std::os;
use std::ptr;
static LOCKFILE_EXCLUSIVE_LOCK: libc::DWORD = 0x00000002;
#[allow(non_snake_case_functions)]
extern "system" {
fn LockFileEx(hFile: libc::HANDLE,
... | random_line_split | |
dynamicQueriesRule.ts | /**
* @license
* Copyright Google LLC 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
*/
import {Replacement, RuleFailure, Rules} from 'tslint';
import * as ts from 'typescript';
import {identifyDynamicQue... | (sourceFile: ts.SourceFile, program: ts.Program): RuleFailure[] {
const printer = ts.createPrinter();
const failures: RuleFailure[] = [];
const result = identifyDynamicQueryNodes(program.getTypeChecker(), sourceFile);
result.removeProperty.forEach(node => {
failures.push(new RuleFailure(
... | applyWithProgram | identifier_name |
dynamicQueriesRule.ts | /**
* @license
* Copyright Google LLC 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
*/
import {Replacement, RuleFailure, Rules} from 'tslint';
import * as ts from 'typescript';
import {identifyDynamicQue... | failures.push(new RuleFailure(
sourceFile, node.getStart(), node.getEnd(), FAILURE_MESSAGE, RULE_NAME,
new Replacement(
node.getStart(), node.getWidth(),
printer.printNode(ts.EmitHint.Unspecified, removeStaticFlag(node), sourceFile))));
});
result.removePar... | const failures: RuleFailure[] = [];
const result = identifyDynamicQueryNodes(program.getTypeChecker(), sourceFile);
result.removeProperty.forEach(node => { | random_line_split |
main.py | """
File Adapter Module
"""
import time
import uuid
from flask import request, jsonify
from ..base import BaseAdapter
class FileAdapter(BaseAdapter):
""" File Adapter Class """
def create_routes(self, app, mongo):
""" Routes Creator """
@app.route('/api/upload', methods=['POST'])
de... |
def run(self):
""" Main Entry for Adapter """
self.create_routes(self.app, self.scope["mongo"])
print('Hello from FileAdapter')
| """ File Upload GET Route """
response = mongo.send_file(filename, base = "datas")
response.cache_control.public = False
response.cache_control.max_age = 0
response.cache_control.no_cache = True
return response | identifier_body |
main.py | """
File Adapter Module
"""
import time
import uuid
from flask import request, jsonify
from ..base import BaseAdapter
class FileAdapter(BaseAdapter):
""" File Adapter Class """
def create_routes(self, app, mongo):
""" Routes Creator """ | """ File Upload POST Route """
filename = uuid.uuid3(uuid.NAMESPACE_DNS, request.files['file'].filename.split('.')[0] + str(time.time())).hex + "." + request.files['file'].filename.split('.')[1]
mongo.save_file(filename, request.files['file'], base = "datas")
return jsoni... | @app.route('/api/upload', methods=['POST'])
def save_upload(): | random_line_split |
main.py | """
File Adapter Module
"""
import time
import uuid
from flask import request, jsonify
from ..base import BaseAdapter
class FileAdapter(BaseAdapter):
""" File Adapter Class """
def | (self, app, mongo):
""" Routes Creator """
@app.route('/api/upload', methods=['POST'])
def save_upload():
""" File Upload POST Route """
filename = uuid.uuid3(uuid.NAMESPACE_DNS, request.files['file'].filename.split('.')[0] + str(time.time())).hex + "." + request.files['f... | create_routes | identifier_name |
module.ts | /**
* @license
* Copyright Google LLC 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
*/
import {ENTER} from '@angular/cdk/keycodes';
import {CommonModule} from '@angular/common';
import {NgModule} from '@a... | {
}
| MatChipsModule | identifier_name |
module.ts | /**
* @license
* Copyright Google LLC 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
*/
import {ENTER} from '@angular/cdk/keycodes';
import {CommonModule} from '@angular/common';
import {NgModule} from '@a... | MatChipTrailingIcon,
];
@NgModule({
imports: [MatCommonModule, CommonModule, MatRippleModule],
exports: [MatCommonModule, CHIP_DECLARATIONS],
declarations: CHIP_DECLARATIONS,
providers: [
ErrorStateMatcher,
{
provide: MAT_CHIPS_DEFAULT_OPTIONS,
useValue: {
separatorKeyCodes: [ENTE... | MatChipOption,
MatChipRemove,
MatChipRow,
MatChipSet, | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this | #![feature(ptr_as_ref)]
#![feature(custom_derive)]
#![feature(plugin)]
#![plugin(heapsize_plugin)]
#![plugin(plugins)]
extern crate app_units;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate cssparser;
extern crate euclid;
extern crate heapsize;
#[macro_use]
extern crate lazy_static;
extern crate libc;
... | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(as_unsafe_cell)]
#![feature(box_syntax)] | random_line_split |
cargo_alias_test.rs | use super::*;
use std::collections::HashMap;
#[test]
fn load_from_file_no_file() {
let tasks = load_from_file("./badfile.toml");
assert!(tasks.is_empty());
}
#[test]
fn load_from_file_parse_error() {
let tasks = load_from_file("./src/lib/test/cargo/invalid_config.toml");
assert!(tasks.is_empty());
}... | } | random_line_split | |
cargo_alias_test.rs | use super::*;
use std::collections::HashMap;
#[test]
fn load_from_file_no_file() {
let tasks = load_from_file("./badfile.toml");
assert!(tasks.is_empty());
}
#[test]
fn load_from_file_parse_error() {
let tasks = load_from_file("./src/lib/test/cargo/invalid_config.toml");
assert!(tasks.is_empty());
}... |
#[test]
fn load_from_file_aliases_found() {
let tasks = load_from_file("./src/lib/test/cargo/config.toml");
assert_eq!(tasks.len(), 4);
let mut map = HashMap::new();
for pair in &tasks {
map.insert(pair.0.clone(), pair.1.clone());
}
let mut task = map.get("b2").unwrap();
assert_... | {
let tasks = load_from_file("./Cargo.toml");
assert!(tasks.is_empty());
} | identifier_body |
cargo_alias_test.rs | use super::*;
use std::collections::HashMap;
#[test]
fn load_from_file_no_file() {
let tasks = load_from_file("./badfile.toml");
assert!(tasks.is_empty());
}
#[test]
fn | () {
let tasks = load_from_file("./src/lib/test/cargo/invalid_config.toml");
assert!(tasks.is_empty());
}
#[test]
fn load_from_file_no_alias_data() {
let tasks = load_from_file("./Cargo.toml");
assert!(tasks.is_empty());
}
#[test]
fn load_from_file_aliases_found() {
let tasks = load_from_file(".... | load_from_file_parse_error | identifier_name |
types.rs | // Copyright 2016-2021 Matthew D. Michelotti
//
// 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 ... |
macro_rules! const_fns {
($type:ty, $raw:ty) => {
impl $type {
/// A const constructor that does not check whether `value` is valid.
///
/// WARNING: This constructor does not panic even in debug mode.
/// As always, it is the user's responsibility to ensure... | {
R64::new(value)
} | identifier_body |
types.rs | // Copyright 2016-2021 Matthew D. Michelotti
//
// 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 ... | (value: f64) -> N64 {
N64::new(value)
}
/// Shorthand for `R32::new(value)`.
#[inline]
pub fn r32(value: f32) -> R32 {
R32::new(value)
}
/// Shorthand for `R64::new(value)`.
#[inline]
pub fn r64(value: f64) -> R64 {
R64::new(value)
}
macro_rules! const_fns {
($type:ty, $raw:ty) => {
impl $typ... | n64 | identifier_name |
types.rs | // Copyright 2016-2021 Matthew D. Michelotti
//
// 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 ... |
const_fns!(N32, f32);
const_fns!(N64, f64);
const_fns!(R32, f32);
const_fns!(R64, f64); | } | random_line_split |
subtree.ts | import {DataSourceType} from '../../data';
import {AggregateNode} from './aggregate';
import {DataFlowNode, OutputNode} from './dataflow';
import {FacetNode} from './facet';
import {JoinAggregateTransformNode} from './joinaggregate';
import {FACET_SCALE_PREFIX} from './optimize';
import {StackNode} from './stack';
impo... | (node: DataFlowNode) {
if (node instanceof OutputNode && node.type === DataSourceType.Main) {
if (node.numChildren() === 1) {
const child = node.children[0];
if (!(child instanceof FacetNode)) {
child.swapWithParent();
moveMainDownToFacet(node);
}
}
}
}
| moveMainDownToFacet | identifier_name |
subtree.ts | import {DataSourceType} from '../../data';
import {AggregateNode} from './aggregate';
import {DataFlowNode, OutputNode} from './dataflow';
import {FacetNode} from './facet';
import {JoinAggregateTransformNode} from './joinaggregate';
import {FACET_SCALE_PREFIX} from './optimize';
import {StackNode} from './stack';
impo... | return [copy];
}
return node.children.flatMap(clone);
}
return clone;
}
/**
* Move facet nodes down to the next fork or output node. Also pull the main output with the facet node.
* After moving down the facet node, make a copy of the subtree and make it a child of the main output.
*/
export fun... | {
const copy = node.clone();
if (copy instanceof OutputNode) {
const newName = FACET_SCALE_PREFIX + copy.getSource();
copy.setSource(newName);
facet.model.component.data.outputNodes[newName] = copy;
} else if (
copy instanceof AggregateNode ||
copy instanceof ... | conditional_block |
subtree.ts | import {DataSourceType} from '../../data';
import {AggregateNode} from './aggregate';
import {DataFlowNode, OutputNode} from './dataflow';
import {FacetNode} from './facet';
import {JoinAggregateTransformNode} from './joinaggregate';
import {FACET_SCALE_PREFIX} from './optimize';
import {StackNode} from './stack';
impo... |
return [copy];
}
return node.children.flatMap(clone);
}
return clone;
}
/**
* Move facet nodes down to the next fork or output node. Also pull the main output with the facet node.
* After moving down the facet node, make a copy of the subtree and make it a child of the main output.
*/
export fu... | {
if (!(node instanceof FacetNode)) {
const copy = node.clone();
if (copy instanceof OutputNode) {
const newName = FACET_SCALE_PREFIX + copy.getSource();
copy.setSource(newName);
facet.model.component.data.outputNodes[newName] = copy;
} else if (
copy instanceof A... | identifier_body |
subtree.ts | import {DataSourceType} from '../../data';
import {AggregateNode} from './aggregate';
import {DataFlowNode, OutputNode} from './dataflow';
import {FacetNode} from './facet';
import {JoinAggregateTransformNode} from './joinaggregate';
import {FACET_SCALE_PREFIX} from './optimize';
import {StackNode} from './stack';
impo... |
facet.model.component.data.outputNodes[newName] = copy;
} else if (
copy instanceof AggregateNode ||
copy instanceof StackNode ||
copy instanceof WindowTransformNode ||
copy instanceof JoinAggregateTransformNode
) {
copy.addDimensions(facet.fields);
}
... |
if (copy instanceof OutputNode) {
const newName = FACET_SCALE_PREFIX + copy.getSource();
copy.setSource(newName); | random_line_split |
ITaskState.ts | import IBaseState from './IBaseState'
import IRetrier from './IRetrier'
import ICatcher from './ICatcher'
/**
* https://docs.aws.amazon.com/step-functions/latest/dg/awl-ref-states-task.html
* | interface TaskState extends IBaseState {
Type: 'Task'
/**
* A URI, especially an Amazon Resource Name (ARN) that uniquely identifies the specific
* task to execute. [Required]
*/
Resource: string
/**
* Specifies where (in the input) to place the results of executing the task specified in
* Res... | * A Task state ("Type": "Task") represents a single unit of work performed by a state machine.
*/ | random_line_split |
apns.py | """
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import credentials as apns2_c... |
else:
apns2_alert = alert
if callable(badge):
badge = badge(token)
return apns2_payload.Payload(
apns2_alert, badge, sound, content_available, mutable_content, category,
url_args, custom=extra, thread_id=thread_id)
def _apns_send(
registration_id, alert, batch=False, application_id=None, creds... | apns2_alert = apns2_payload.PayloadAlert(
body=alert if alert else {}, body_localized_key=loc_key,
body_localized_args=loc_args, action_localized_key=action_loc_key) | conditional_block |
apns.py | """
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import credentials as apns2_c... | # create a credential, you could also pass the lifetime and
# algorithm. Neither of those settings are exposed in the
# settings API at the moment.
creds = creds or apns2_credentials.TokenCredentials(keyPath, keyId, teamId)
client = apns2_client.APNsClient(
creds,
use_sandbox=get_manager().get_apns_use... | # No use getting a lifetime because this credential is
# ephemeral, but if you're looking at this to see how to | random_line_split |
apns.py | """
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import credentials as apns2_c... | (creds=None, application_id=None):
if creds is None:
if not get_manager().has_auth_token_creds(application_id):
cert = get_manager().get_apns_certificate(application_id)
creds = apns2_credentials.CertificateCredentials(cert)
else:
keyPath, keyId, teamId = get_manager().get_apns_auth_creds(application_id)
... | _apns_create_socket | identifier_name |
apns.py | """
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import credentials as apns2_c... |
def _apns_send(
registration_id, alert, batch=False, application_id=None, creds=None, **kwargs
):
client = _apns_create_socket(creds=creds, application_id=application_id)
notification_kwargs = {}
# if expiration isn"t specified use 1 month from now
notification_kwargs["expiration"] = kwargs.pop("expiration", ... | if action_loc_key or loc_key or loc_args:
apns2_alert = apns2_payload.PayloadAlert(
body=alert if alert else {}, body_localized_key=loc_key,
body_localized_args=loc_args, action_localized_key=action_loc_key)
else:
apns2_alert = alert
if callable(badge):
badge = badge(token)
return apns2_paylo... | identifier_body |
DragUploader.ts | ', this.dragUploader.fileListColumnCount - this.$row.find('td').length).appendTo(this.$row);
this.$progressContainer = $('<div />').addClass('upload-queue-progress').appendTo(this.$progress);
this.$progressBar = $('<div />').addClass('upload-queue-progress-bar').appendTo(this.$progressContainer);
this.$prog... | fileSizeAsString | identifier_name | |
DragUploader.ts | -striped table-hover upload-queue')
.html('<tbody></tbody>').hide();
if (this.dropZoneInsertBefore) {
this.$fileList.insertAfter(this.$dropzone);
} else {
this.$fileList.insertBefore(this.$dropzone);
}
this.fileListColumnCount = 8;
this.manualTable = true;
}
... | ),
$('<td />').html(
this.askForOverride[i].uploaded.name + ' (' + (DragUploader.fileSizeAsString(this.askForOverride[i].uploaded.size)) + ')' +
'<br>' +
moment(
this.askForOverride[i].uploaded.lastModified
? this.askForOverride[i].uploaded.lastMod... | this.askForOverride[i].original.name + ' (' + (DragUploader.fileSizeAsString(this.askForOverride[i].original.size)) + ')' +
'<br>' + moment(this.askForOverride[i].original.mtime).format('YYYY-MM-DD HH:mm'), | random_line_split |
DragUploader.ts | table-hover upload-queue')
.html('<tbody></tbody>').hide();
if (this.dropZoneInsertBefore) {
this.$fileList.insertAfter(this.$dropzone);
} else {
this.$fileList.insertBefore(this.$dropzone);
}
this.fileListColumnCount = 8;
this.manualTable = true;
}
this.... | {
label: TYPO3.lang['file_upload.reload.filelist.actions.reload'],
action: new ImmediateAction( (): void => {
top.list_frame.document.location.href = this.reloadUrl
})
}
]
... | {
if (this.queueLength > 0) {
this.queueLength--;
if (this.queueLength === 0) {
new AjaxRequest(TYPO3.settings.ajaxUrls.flashmessages_render).get({cache: 'no-cache'}).then(async (response: AjaxResponse): Promise<void> => {
const data = await response.resolve();
for (let flash... | identifier_body |
DragUploader.ts | readonly file: InternalFile;
private readonly override: Action;
private readonly $selector: JQuery;
private $iconCol: JQuery;
private $fileName: JQuery;
private $progressBar: JQuery;
private $progressPercentage: JQuery;
private $progressMessage: JQuery;
private dragUploader: DragUploaderPlugin;
cons... | {
permissions += '<strong class="text-danger">' + TYPO3.lang['permissions.read'] + '</strong>';
} | conditional_block | |
process.py | #!/usr/bin/env python3
delineator = "//"
hashtag = "#"
# generate poems from a file
# out: list of poem lines
def generate_poems(filename):
|
# convert a list of strings
# into a poem dictionary
def to_dictionary(poem_lines):
d = {}
d['content'] = []
d['tags'] = []
tags = []
for line in poem_lines:
if line.startswith( delineator ):
d['title'] = line.lstrip( delineator ).strip()
elif line.startswith( hashtag )... | g = []
# get to the first poem in the file
with open(filename, 'r') as f:
for line in f:
line = line.rstrip()
if line.startswith( delineator ) and g:
yield g
g = []
if line:
g.append(line)
yield g | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.