file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
mod.rs | use communication::Message;
pub use self::counter::Counter;
| /// may conservatively over-flush, if the defensive implementation isn't well done (e.g. now).
/// An alternate design is for a Pullable<T, D> to return a (&T, Session<D>), where Session<D> is a
/// new type implementing Iterator<Item=Message<D>>, or Iterator<Item=D>, or PullableSession<D>, or
/// something like that.... | pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must constantly check this. This complicates data exchange, which | random_line_split |
movemant.rs | extern crate ggez;
extern crate rand;
use rand::Rng;
use ggez::graphics::{Point};
use ::MainState;
#[derive(Clone)]
pub struct Rabbit{
pub x:i32,
pub y:i32,
pub point:Point,
}
pub fn | (tself:&mut MainState){
let mut next_rabbits = Vec::new();
for obj in tself.rabbits_hash.iter(){
let cor_prev = obj.1;
let rab = rabbit_run(cor_prev);
let mut cor_next = rab.0;
cor_next.point = match tself.map_hash.get(&(cor_next.x, cor_next.y)) {
Some(n) => *n,
None => Point{x:150.0,y:150.0},
... | rabbits_run | identifier_name |
movemant.rs | extern crate ggez;
extern crate rand;
use rand::Rng;
use ggez::graphics::{Point};
use ::MainState;
#[derive(Clone)]
pub struct Rabbit{
pub x:i32,
pub y:i32,
pub point:Point,
}
pub fn rabbits_run (tself:&mut MainState){
let mut next_rabbits = Vec::new();
for obj in tself.rabbits_hash.iter(){
let cor_prev = obj.... | point: cor_prev.point,
};
let right = Rabbit{
x: (cor_prev.x + 1),
y: cor_prev.y,
point: cor_prev.point,
};
let up_left = Rabbit{
x: (cor_prev.x - 1),
y: (cor_prev.y - 1),
point: cor_prev.point,
};
let down_right = Rabbit{
x: (cor_prev.x + 1),
y: (cor_prev.y + 1),
point: cor_prev.point,
};
l... | random_line_split | |
index.js | window.onload = function() {
var prod_img = document.getElementById("prod_img");
// Set an interval o keep rotating the image every 256 milliseconds
setInterval(function(){
prod_img.src = getImageSrc();
},1000);
var imgIndex = 1;
function | () {
imgIndex = (imgIndex + 1) > 5? 1 : imgIndex + 1;
return imgIndex + ".jpeg";
}
var home = document.getElementById("pic");
var details = document.getElementById("inf");
var review = document.getElementById("rev");
document.getElementById("home").onclick = function() {
home.style.display = "block";
... | getImageSrc | identifier_name |
index.js | window.onload = function() {
var prod_img = document.getElementById("prod_img");
// Set an interval o keep rotating the image every 256 milliseconds
setInterval(function(){
prod_img.src = getImageSrc();
},1000);
var imgIndex = 1;
function getImageSrc() |
var home = document.getElementById("pic");
var details = document.getElementById("inf");
var review = document.getElementById("rev");
document.getElementById("home").onclick = function() {
home.style.display = "block";
details.style.display = "none";
review.style.display = "none";
}
document.getEleme... | {
imgIndex = (imgIndex + 1) > 5? 1 : imgIndex + 1;
return imgIndex + ".jpeg";
} | identifier_body |
index.js | window.onload = function() {
var prod_img = document.getElementById("prod_img");
// Set an interval o keep rotating the image every 256 milliseconds
setInterval(function(){
prod_img.src = getImageSrc();
},1000);
var imgIndex = 1;
function getImageSrc() {
imgIndex = (imgIndex + 1) > 5? 1 : imgIndex + 1;
... | document.getElementById("home").onclick = function() {
home.style.display = "block";
details.style.display = "none";
review.style.display = "none";
}
document.getElementById("details").onclick = function() {
home.style.display = "none";
details.style.display = "block";
review.style.display = "none";
}
... | var home = document.getElementById("pic");
var details = document.getElementById("inf");
var review = document.getElementById("rev");
| random_line_split |
perf_context.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PerfLevel {
Uninitialized,
Disable,
EnableCount,
EnableTimeExceptForMutex,
EnableTimeAndCPUTimeExceptForMutex,
EnableTime,
OutOfBounds,
}
/// Extensions for measuring engine... | {
RaftstoreApply,
RaftstoreStore,
}
/// Reports metrics to prometheus
///
/// For alternate engines, it is reasonable to make `start_observe`
/// and `report_metrics` no-ops.
pub trait PerfContext: Send {
/// Reinitializes statistics and the perf level
fn start_observe(&mut self);
/// Reports the... | PerfContextKind | identifier_name |
perf_context.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PerfLevel {
Uninitialized,
Disable,
EnableCount,
EnableTimeExceptForMutex,
EnableTimeAndCPUTimeExceptForMutex,
EnableTime,
OutOfBounds,
}
/// Extensions for measuring engine... | }
/// The raftstore subsystem the PerfContext is being created for.
///
/// This is a leaky abstraction that supports the encapsulation of metrics
/// reporting by the two raftstore subsystems that use `report_metrics`.
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum PerfContextKind {
RaftstoreApply,
RaftstoreS... | fn get_perf_context(&self, level: PerfLevel, kind: PerfContextKind) -> Self::PerfContext; | random_line_split |
CommandHandler.js | /**
* CommandHandler: for handling script commands.
* @TODO: Flesh this out!
**/
var _ = require('underscore');
var $ = require('jquery');
var Radio = require('backbone.radio');
class | {
constructor(opts) {
this.channel = opts.channel;
this.broadcastChannel = this.channel;
this.plugins = opts.plugins;
this.widgetRegistry = opts.widgetRegistry;
// @TODO: later, should probably decouple theatre from commandhandler.
this.theatreChannel = opts.theatre... | CommandHandler | identifier_name |
CommandHandler.js | /**
* CommandHandler: for handling script commands. |
var _ = require('underscore');
var $ = require('jquery');
var Radio = require('backbone.radio');
class CommandHandler {
constructor(opts) {
this.channel = opts.channel;
this.broadcastChannel = this.channel;
this.plugins = opts.plugins;
this.widgetRegistry = opts.widgetRegistry;
... | * @TODO: Flesh this out!
**/ | random_line_split |
setting_util.py | #!/usr/bin/env python
import glob
import inspect
import os
import keyring
import getpass
import sys
import signal
from i3pystatus import Module, SettingsBase
from i3pystatus.core import ClassFinder
from collections import defaultdict, OrderedDict
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.... |
modules = [os.path.basename(m.replace('.py', ''))
for m in glob.glob(os.path.join(os.path.dirname(__file__), "i3pystatus", "*.py"))
if not os.path.basename(m).startswith('_')]
protected_settings = SettingsBase._SettingsBase__PROTECTED_SETTINGS
class_finder = ClassFinder(Module)
credential_modul... | answer = input(prompt)
try:
n = int(answer.strip())
if n in _range:
return n
else:
print("Value out of range!")
except ValueError:
print("Invalid input!") | conditional_block |
setting_util.py | #!/usr/bin/env python
import glob
import inspect
import os
import keyring
import getpass
import sys
import signal
from i3pystatus import Module, SettingsBase
from i3pystatus.core import ClassFinder
from collections import defaultdict, OrderedDict
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.... |
modules = [os.path.basename(m.replace('.py', ''))
for m in glob.glob(os.path.join(os.path.dirname(__file__), "i3pystatus", "*.py"))
if not os.path.basename(m).startswith('_')]
protected_settings = SettingsBase._SettingsBase__PROTECTED_SETTINGS
class_finder = ClassFinder(Module)
credential_modul... | while True:
answer = input(prompt)
try:
n = int(answer.strip())
if n in _range:
return n
else:
print("Value out of range!")
except ValueError:
print("Invalid input!") | identifier_body |
setting_util.py | #!/usr/bin/env python
import glob
import inspect
import os
import keyring
import getpass
import sys
import signal
from i3pystatus import Module, SettingsBase
from i3pystatus.core import ClassFinder
from collections import defaultdict, OrderedDict
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.... | n = int(answer.strip())
if n in _range:
return n
else:
print("Value out of range!")
except ValueError:
print("Invalid input!")
modules = [os.path.basename(m.replace('.py', ''))
for m in glob.glob(os.path.join(os.path.dir... | answer = input(prompt)
try: | random_line_split |
setting_util.py | #!/usr/bin/env python
import glob
import inspect
import os
import keyring
import getpass
import sys
import signal
from i3pystatus import Module, SettingsBase
from i3pystatus.core import ClassFinder
from collections import defaultdict, OrderedDict
def | (signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def get_int_in_range(prompt, _range):
while True:
answer = input(prompt)
try:
n = int(answer.strip())
if n in _range:
return n
else:
print("Value out of... | signal_handler | identifier_name |
page.component.ts | /**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import { Component, Inject, NgZone, OnDestroy, OnInit, ViewChild, AfterContentChecked } from '@angular/core';
import { Meta, Title } from '@angular/platform-brows... | () {
this.activatedRoute.params
.pipe(
takeWhile(() => this.alive),
filter((params: any) => params.subPage),
map((params: any) => {
const slag = `${params.page}_${params.subPage}`;
return this.structureService.findPageBySlag(this.structureService.getPreparedStructur... | handlePageNavigation | identifier_name |
page.component.ts | /**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import { Component, Inject, NgZone, OnDestroy, OnInit, ViewChild, AfterContentChecked } from '@angular/core';
import { Meta, Title } from '@angular/platform-brows... |
return '';
}
}
| {
return this.tabbedBlock.currentTab.tab;
} | conditional_block |
page.component.ts | /**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import { Component, Inject, NgZone, OnDestroy, OnInit, ViewChild, AfterContentChecked } from '@angular/core'; | import { NB_WINDOW } from '@nebular/theme';
import { NgdTabbedBlockComponent } from '../../blocks/components/tabbed-block/tabbed-block.component';
import { NgdStructureService } from '../../@theme/services';
@Component({
selector: 'ngd-page',
templateUrl: './page.component.html',
styleUrls: ['./page.component.sc... | import { Meta, Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { filter, map, publishReplay, refCount, tap, takeWhile } from 'rxjs/operators'; | random_line_split |
page.component.ts | /**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import { Component, Inject, NgZone, OnDestroy, OnInit, ViewChild, AfterContentChecked } from '@angular/core';
import { Meta, Title } from '@angular/platform-brows... |
ngAfterContentChecked() {
const currentTabName = this.getCurrentTabName();
if (this.currentTabName !== currentTabName) {
Promise.resolve().then(() => this.currentTabName = currentTabName);
}
}
ngOnDestroy() {
this.alive = false;
}
handlePageNavigation() {
this.activatedRoute.para... | {
this.handlePageNavigation();
this.window.history.scrollRestoration = 'manual';
} | identifier_body |
conf.py | # -*- coding: utf-8 -*-
#
# RedPipe documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 19 13:22:45 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | #
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'RedPipe.tex', u'%s Documentation' % project,
u'John Loehrer', 'manual'),
]
... | # Latex figure (float) alignment | random_line_split |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num... | if current_value == DEFAULT {
matrix[x as usize][y as usize] = entry.num;
//matrix[x as usize][y as usize] = "1";
} else {
if current_value != MULTIPLE {
matrix[x as usize][y as usize] = MULTIPLE;
}
... |
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.height {
let current_value = matrix[x as usize][y as usize]; | random_line_split |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct | {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();... | Entry | identifier_name |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num... | else if *col == -1 as i32 {
print!("X");
} else {
print!("{}", col);
}
}
println!();
}
}
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.heig... | {
print!(".");
} | conditional_block |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result |
}
fn paint_matrix(matrix: &mut [[i32; 10]; 10]) {
for (i, row) in matrix.iter_mut().enumerate() {
for (y, col) in row.iter_mut().enumerate() {
if *col == 0 as i32 {
print!(".");
} else if *col == -1 as i32 {
print!("X");
} else {
... | {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();
let str_index_y = "index_y=".to_string() + &self.index_y.to_string();
let str_w = "w=".to_string() + &self.width.to_string();
let str_h = "h=".to_strin... | identifier_body |
functional_tests.py | import pytest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
@pytest.fixture(scope='function')
def browser(request):
browser_ = webdriver.Firefox()
def | ():
browser_.quit()
request.addfinalizer(fin)
return browser_
def test_can_show_a_relevant_code_snippet(browser):
# Jan visits the site
browser.get('http://localhost:8000')
# He notices the title and header reference the site name
site_name = 'Scout'
assert site_name in browser.t... | fin | identifier_name |
functional_tests.py | import pytest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
@pytest.fixture(scope='function')
def browser(request):
browser_ = webdriver.Firefox()
def fin():
browser_.quit()
request.addfinalizer(fin)
return browser_
def test_can_show_a_relevant_code_snippet... | # (the highest-voted python page on StackOverflow.com is
# /questions/231767/what-does-the-yield-keyword-do-in-python)
snippets = browser.find_elements_by_tag_name('code')
assert any(['mylist' in snippet.text and 'mygenerator' in snippet.text
for snippet in snippets]) | # that uses the dummy variables "mylist" and "mygenerator" | random_line_split |
functional_tests.py | import pytest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
@pytest.fixture(scope='function')
def browser(request):
|
def test_can_show_a_relevant_code_snippet(browser):
# Jan visits the site
browser.get('http://localhost:8000')
# He notices the title and header reference the site name
site_name = 'Scout'
assert site_name in browser.title
header_text = browser.find_element_by_tag_name('h1').text
assert ... | browser_ = webdriver.Firefox()
def fin():
browser_.quit()
request.addfinalizer(fin)
return browser_ | identifier_body |
kraken_v5.py | import logging
from pajbot.apiwrappers.response_cache import ListSerializer
from pajbot.apiwrappers.twitch.base import BaseTwitchAPI
from pajbot.models.emote import Emote
log = logging.getLogger(__name__)
class TwitchKrakenV5API(BaseTwitchAPI):
authorization_header_prefix = "OAuth"
def __init__(self, clien... |
online = "stream" in data and data["stream"] is not None
def rest_data():
nonlocal online
if online:
return rest_data_online()
else:
return rest_data_offline()
return {"online": online, **rest_data()}
def set_game(self,... | stream = data["stream"]
return {
"viewers": stream["viewers"],
"game": stream["game"],
"title": stream["channel"]["status"],
"created_at": stream["created_at"],
"followers": stream["channel"]["followers"],
"view... | identifier_body |
kraken_v5.py | import logging
from pajbot.apiwrappers.response_cache import ListSerializer
from pajbot.apiwrappers.twitch.base import BaseTwitchAPI
from pajbot.models.emote import Emote
log = logging.getLogger(__name__)
class TwitchKrakenV5API(BaseTwitchAPI):
authorization_header_prefix = "OAuth"
def __init__(self, clien... | def default_authorization(self):
return self.client_credentials
def get_stream_status(self, user_id):
data = self.get(["streams", user_id])
def rest_data_offline():
return {
"viewers": -1,
"game": None,
"title": None,
... | random_line_split | |
kraken_v5.py | import logging
from pajbot.apiwrappers.response_cache import ListSerializer
from pajbot.apiwrappers.twitch.base import BaseTwitchAPI
from pajbot.models.emote import Emote
log = logging.getLogger(__name__)
class TwitchKrakenV5API(BaseTwitchAPI):
authorization_header_prefix = "OAuth"
def __init__(self, clien... | (self, channel_name):
return self.get(["channels", channel_name, "videos"], {"broadcast_type": "archive"})
def fetch_global_emotes(self):
# circular import prevention
from pajbot.managers.emote import EmoteManager
resp = self.get("/chat/emoticon_images", params={"emotesets": "0"})
... | get_vod_videos | identifier_name |
kraken_v5.py | import logging
from pajbot.apiwrappers.response_cache import ListSerializer
from pajbot.apiwrappers.twitch.base import BaseTwitchAPI
from pajbot.models.emote import Emote
log = logging.getLogger(__name__)
class TwitchKrakenV5API(BaseTwitchAPI):
authorization_header_prefix = "OAuth"
def __init__(self, clien... |
return {"online": online, **rest_data()}
def set_game(self, user_id, game, authorization):
self.put(["channels", user_id], json={"channel": {"game": game}}, authorization=authorization)
def set_title(self, user_id, title, authorization):
self.put(["channels", user_id], json={"channel... | return rest_data_offline() | conditional_block |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... |
pub fn mq_getattr(mqd: MQd) -> Result<MqAttr> {
let mut attr = MqAttr::new(0, 0, 0, 0);
let res = unsafe { ffi::mq_getattr(mqd, &mut attr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(attr)
}
| {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
} | identifier_body |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... | }
Ok(res)
}
pub fn mq_close(mqdes: MQd) -> Result<()> {
let res = unsafe { ffi::mq_close(mqdes) };
from_ffi(res)
}
pub fn mq_receive(mqdes: MQd, message: &mut [u8], msq_prio: u32) -> Result<usize> {
let len = message.len() as size_t;
let res = unsafe { ffi::mq_receive(mqdes, message.as_mut_... | return Err(Error::Sys(Errno::last())); | random_line_split |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... | (mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn mq_getattr(... | mq_send | identifier_name |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... |
Ok(res as usize)
}
pub fn mq_send(mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
... | {
return Err(Error::Sys(Errno::last()));
} | conditional_block |
19180cf98af6_nsx_gw_devices.py | # Copyright 2014 OpenStack Foundation
#
# 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 ... |
op.drop_table('networkgatewaydevices')
# Re-create previous version of networkgatewaydevices table
op.create_table(
'networkgatewaydevices',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('network_gateway_id', sa.String(length=36), nullable=True),
sa.Colum... | return | conditional_block |
19180cf98af6_nsx_gw_devices.py | # Copyright 2014 OpenStack Foundation
#
# 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 ... | (active_plugins=None, options=None):
if not migration.should_run(active_plugins, migration_for_plugins):
return
op.create_table(
'networkgatewaydevicereferences',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('network_gateway_id', sa.String(length=36), nullabl... | upgrade | identifier_name |
19180cf98af6_nsx_gw_devices.py | # Copyright 2014 OpenStack Foundation
#
# 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 ... | "id, network_gateway_id, interface_name FROM "
"networkgatewaydevices")
# drop networkgatewaydevices
op.drop_table('networkgatewaydevices')
op.create_table(
'networkgatewaydevices',
sa.Column('tenant_id', sa.String(length=255), nullable=True),
sa.Column(... | sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'),
mysql_engine='InnoDB')
# Copy data from networkgatewaydevices into networkgatewaydevicereference
op.execute("INSERT INTO networkgatewaydevicereferences SELECT " | random_line_split |
19180cf98af6_nsx_gw_devices.py | # Copyright 2014 OpenStack Foundation
#
# 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 ... |
def downgrade(active_plugins=None, options=None):
if not migration.should_run(active_plugins, migration_for_plugins):
return
op.drop_table('networkgatewaydevices')
# Re-create previous version of networkgatewaydevices table
op.create_table(
'networkgatewaydevices',
sa.Column(... | if not migration.should_run(active_plugins, migration_for_plugins):
return
op.create_table(
'networkgatewaydevicereferences',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('network_gateway_id', sa.String(length=36), nullable=True),
sa.Column('interface_nam... | identifier_body |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Log entry type definition.
use std::ops::Deref;
use util::{H256, Address, Bytes, HeapSizeOf, Hashable};
use util::bloom::Bloomable;
use rlp::*;
use basic_types::LogBloom;
use he... | random_line_split | |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | () {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000... | test_empty_log_bloom | identifier_name |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
| {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000... | identifier_body |
dhash.py | __author__ = 'anicca'
# core
import math
import sys
from itertools import izip
# 3rd party
from PIL import Image, ImageChops
import argh
def dhash(image, hash_size=8):
# Grayscale and shrink the image in one step.
image = image.convert('L').resize(
(hash_size + 1, hash_size),
Image.ANTIALIAS... |
def rmsdiff_2011(im1, im2):
"Calculate the root-mean-square difference between two images"
im1 = Image.open(im1)
im2 = Image.open(im2)
diff = ImageChops.difference(im1, im2)
h = diff.histogram()
sq = (value * (idx ** 2) for idx, value in enumerate(h))
sum_of_squares = sum(sq)
rms = m... | i1 = Image.open(image1)
i2 = Image.open(image2)
assert i1.mode == i2.mode, "Different kinds of images."
print i1.size, i2.size
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(... | identifier_body |
dhash.py | __author__ = 'anicca'
# core
import math
import sys
from itertools import izip
# 3rd party
from PIL import Image, ImageChops
import argh
def dhash(image, hash_size=8):
# Grayscale and shrink the image in one step.
image = image.convert('L').resize(
(hash_size + 1, hash_size),
Image.ANTIALIAS... |
else:
dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2))
ncomponents = i1.size[0] * i1.size[1] * 3
retval = (dif / 255.0 * 100) / ncomponents
return retval
def rmsdiff_2011(im1, im2):
"Calculate the root-mean-square difference between two images"
im1 = Image.open(... | dif = sum(abs(p1 - p2) for p1, p2 in pairs) | conditional_block |
dhash.py | __author__ = 'anicca'
# core
import math
import sys
from itertools import izip
# 3rd party
from PIL import Image, ImageChops
import argh
def dhash(image, hash_size=8):
# Grayscale and shrink the image in one step.
image = image.convert('L').resize(
(hash_size + 1, hash_size),
Image.ANTIALIAS... | return retval
def rmsdiff_2011(im1, im2):
"Calculate the root-mean-square difference between two images"
im1 = Image.open(im1)
im2 = Image.open(im2)
diff = ImageChops.difference(im1, im2)
h = diff.histogram()
sq = (value * (idx ** 2) for idx, value in enumerate(h))
sum_of_squares = su... | dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2))
ncomponents = i1.size[0] * i1.size[1] * 3
retval = (dif / 255.0 * 100) / ncomponents | random_line_split |
dhash.py | __author__ = 'anicca'
# core
import math
import sys
from itertools import izip
# 3rd party
from PIL import Image, ImageChops
import argh
def dhash(image, hash_size=8):
# Grayscale and shrink the image in one step.
image = image.convert('L').resize(
(hash_size + 1, hash_size),
Image.ANTIALIAS... | (image_filename1, image_filename2, dhash=False, rosetta=False, rmsdiff=False):
pass
if __name__ == '__main__':
argh.dispatch_command(main)
| main | identifier_name |
grants.py | # -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from kgrants.items import KgrantsItem
from scrapy.http import Request
import time
class GrantsSpider(Spider):
name = "grants"
allowed_domains = ["www.knightfoundation.org"]
pages = 1
base_url = 'http://www.k... |
def parse_project(self,response):
hxs = Selector(response)
grants = response.meta['grants']
details = hxs.xpath('//section[@id="grant_info"]')
fields = hxs.xpath('//dt')
values = hxs.xpath('//dd')
self.log('field: <%s>' % fields.extract())
for item in det... | hxs = Selector(response)
projects = hxs.xpath('//article')
for project in projects:
time.sleep(2)
project_url = self.base_url + ''.join(project.xpath('a/@href').extract())
grants = KgrantsItem()
grants['page'] = project_url
grants['project'] =... | identifier_body |
grants.py | # -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from kgrants.items import KgrantsItem
from scrapy.http import Request
import time
class GrantsSpider(Spider):
name = "grants"
allowed_domains = ["www.knightfoundation.org"]
pages = 1
base_url = 'http://www.k... | super(GrantsSpider, self).__init__(*args, **kwargs)
if pages is not None:
self.pages = pages
self.start_urls = [ self.start_url_str % str(page) for page in xrange(1,int(self.pages)+1)]
def parse(self, response):
hxs = Selector(response)
projects = hxs.x... | start_url_str = 'http://www.knightfoundation.org/grants/?sort=title&page=%s'
def __init__(self, pages=None, *args, **kwargs): | random_line_split |
grants.py | # -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from kgrants.items import KgrantsItem
from scrapy.http import Request
import time
class GrantsSpider(Spider):
name = "grants"
allowed_domains = ["www.knightfoundation.org"]
pages = 1
base_url = 'http://www.k... |
count += 1
grants['grantee_contact_email'] = ''.join(
item.xpath('section[@id="grant_contact"]/ul/li[@class="email"]/a/@href').extract()).replace('mailto:','').strip()
grants['grantee_contact_name'] = ''.join(
item.xpath('section[@id="grant_conta... | grants[normalized_field] = values.xpath('a/text()').extract()[0] | conditional_block |
grants.py | # -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from kgrants.items import KgrantsItem
from scrapy.http import Request
import time
class GrantsSpider(Spider):
name = "grants"
allowed_domains = ["www.knightfoundation.org"]
pages = 1
base_url = 'http://www.k... | (self, response):
hxs = Selector(response)
projects = hxs.xpath('//article')
for project in projects:
time.sleep(2)
project_url = self.base_url + ''.join(project.xpath('a/@href').extract())
grants = KgrantsItem()
grants['page'] = project_url
... | parse | identifier_name |
preprocess.py | #!/usr/bin/python
import re, csv, sys
from urlparse import urlparse
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.text import TextCollection
#process command line arguments
if len(sys.argv) < 2:
print "ERROR: arg1: must specify the input file"
print " ... | count_pos = 0
for gw in gaz_pos:
count_pos += tweet.count(gw)
count_neg = 0
for gw in gaz_neg:
count_neg += tweet.count(gw)
gaz_count.append( (count_pos, count_neg) )
# USE THIS SECTION FOR TRAINING
# extract only words used >1 times, and ignore stopwords
if not test :
tweet_sents = se... | # count gazetteer words
| random_line_split |
preprocess.py | #!/usr/bin/python
import re, csv, sys
from urlparse import urlparse
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.text import TextCollection
#process command line arguments
if len(sys.argv) < 2:
print "ERROR: arg1: must specify the input file"
print " ... |
elif sent == 'negative':
sent = 'NEG'
else:
sent = 'OTHER'
sentiments.append(sent)
# standardize URLs
w = tweet.split()
for i in range(len(w)):
r = urlparse(w[i])
if r[0] != '' and r[1] != '':
w[i] = 'URL'
tweet = ' '.join(w)
tweets.append(tweet)
# count emoticons
... | sent = 'POS' | conditional_block |
common.js | /* |
var lang = {
anon: 'Anonymous',
search: 'Search',
show: 'Show',
hide: 'Hide',
report: 'Report',
focus: 'Focus',
expand: 'Expand',
last: 'Last',
see_all: 'See all',
bottom: 'Bottom',
expand_images: 'Expand Images',
live: 'live',
catalog: 'Catalog',
return: 'Return',
top: 'Top',
reply: 'Reply',
newThrea... | * Shared by the server and client
*/ | random_line_split |
common.js | /*
* Shared by the server and client
*/
var lang = {
anon: 'Anonymous',
search: 'Search',
show: 'Show',
hide: 'Hide',
report: 'Report',
focus: 'Focus',
expand: 'Expand',
last: 'Last',
see_all: 'See all',
bottom: 'Bottom',
expand_images: 'Expand Images',
live: 'live',
catalog: 'Catalog',
return: 'Return... |
return html;
}
};
module.exports = lang;
| {
html += ' <span class="act"><a href="' + url + '" class="history">'
+ lang.see_all + '</a></span>';
} | conditional_block |
filterPanel.styles.ts | /**
* @copyright 2009-2020 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import { styleFactory } from "@library/styles/styleUtils";
import { useThemeCache } from "@library/styles/themeCache";
import { styleUnit } from "@library/styles/styleUnit";
import { Mixins } from "@library/styles/Mixins";
import { globalVar... | ...{
"&&": {
...Mixins.font({
...globalVars.fontSizeAndWeightVars("large", "bold"),
}),
},
},
});
return {
header,
body,
footer,
title,
};
}); | },
},
});
const title = style("title", { | random_line_split |
test_pep277.py | # Test the Unicode versions of normal file functions
# open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir
import sys, os, unittest
from unicodedata import normalize
from test import test_support
filenames = [
'1_abc',
u'2_ascii',
u'3_Gr\xfc\xdf-Gott',
u'4_\... | (self):
sf0 = set(self.files)
f1 = os.listdir(test_support.TESTFN)
f2 = os.listdir(unicode(test_support.TESTFN,
sys.getfilesystemencoding()))
sf2 = set(os.path.join(unicode(test_support.TESTFN), f) for f in f2)
self.assertEqual(sf0, sf2)
... | test_listdir | identifier_name |
test_pep277.py | # Test the Unicode versions of normal file functions
# open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir
import sys, os, unittest
from unicodedata import normalize
from test import test_support
filenames = [
'1_abc',
u'2_ascii',
u'3_Gr\xfc\xdf-Gott',
u'4_\... |
def test_failures(self):
# Pass non-existing Unicode filenames all over the place.
for name in self.files:
name = "not_" + name
self._apply_failure(open, name, IOError)
self._apply_failure(os.stat, name, OSError)
self._apply_failure(os.chdir,... | with self.assertRaises(expected_exception) as c:
fn(filename)
exc_filename = c.exception.filename
# the "filename" exception attribute may be encoded
if isinstance(exc_filename, str):
filename = filename.encode(sys.getfilesystemencoding())
if check_fn_in_exc... | identifier_body |
test_pep277.py | # Test the Unicode versions of normal file functions
# open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir
import sys, os, unittest
from unicodedata import normalize
from test import test_support
filenames = [
'1_abc',
u'2_ascii',
u'3_Gr\xfc\xdf-Gott',
u'4_\... |
os.rmdir(dirname)
class UnicodeFileTests(unittest.TestCase):
files = set(filenames)
normal_form = None
def setUp(self):
try:
os.mkdir(test_support.TESTFN)
except OSError:
pass
files = set()
for name in self.files:
... | os.unlink(os.path.join(dirname, fname)) | conditional_block |
test_pep277.py | # Test the Unicode versions of normal file functions
# open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir
import sys, os, unittest
from unicodedata import normalize
from test import test_support
filenames = [
'1_abc',
u'2_ascii',
u'3_Gr\xfc\xdf-Gott',
u'4_\... | if not os.path.supports_unicode_filenames:
fsencoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
try:
for name in filenames:
name.encode(fsencoding)
except UnicodeEncodeError:
raise unittest.SkipTest("only NT+ and systems with "
... | ])
# Is it Unicode-friendly?
| random_line_split |
vDialing.py | # vDial-up client
# Copyright (C) 2015 - 2017 Nathaniel Olsen
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This pr... |
def vdialing(vNumber_to_connect, vNumber_IP):
if core.config['use_ipv6_when_possible']:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("vDialing %s..." % (vNumber_to_connect))
if... | sleep(20)
sock.sendall(bytes("SERVPING" + "\n", "utf-8"))
if main.listen_for_data(sock) == "PONG":
break
else:
print("Disconnected: Connection timeout.") | conditional_block |
vDialing.py | # vDial-up client
# Copyright (C) 2015 - 2017 Nathaniel Olsen
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This pr... | ():
def send_msg(sock, msg):
# Prefix each message with a 4-byte length (network byte order)
msg = struct.pack('>I', len(msg)) + str.encode(msg)
sock.sendall(msg)
def recv_msg(sock):
# Read message length and unpack it into an integer
raw_msglen = main.recvall(sock, 4)
... | main | identifier_name |
vDialing.py | # vDial-up client
# Copyright (C) 2015 - 2017 Nathaniel Olsen
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This pr... | from multiprocessing import Process
import sys
import struct
def MD5SUM_mismatch(vNumber_to_connect, sock):
print("*Warning: The server's MD5SUM does not match with the one listed on file, Do you wish to continue? (Y/N)")
if vNumber_to_connect == core.RegServ_vNumber:
MD5SUM_on_file = core.RegServ_MD5S... | random_line_split | |
vDialing.py | # vDial-up client
# Copyright (C) 2015 - 2017 Nathaniel Olsen
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This pr... |
def servping(sock):
while 1:
sleep(20)
sock.sendall(bytes("SERVPING" + "\n", "utf-8"))
if main.listen_for_data(sock) == "PONG":
break
else:
print("Disconnected: Connection timeout.")
def vdialing(vNumber_to_connect, vNumb... | data = ''
while len(data) < n:
packet = (sock.recv(n - len(data)).decode('utf-8'))
if not packet:
return None
data += packet
return data | identifier_body |
che-stack.factory.ts | /*
* Copyright (c) 2015-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Coden... | return this.remoteStackAPI.createStack({}, stack).$promise;
}
/**
* Fetch pointed stack.
* @param stackId stack's id
* @returns {$promise|*|T.$promise}
*/
fetchStack(stackId) {
return this.remoteStackAPI.getStack({stackId: stackId}).$promise;
}
/**
* Update pointed stack.
* @param ... | random_line_split | |
che-stack.factory.ts | /*
* Copyright (c) 2015-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Coden... | {
/**
* Default constructor that is using resource
* @ngInject for Dependency injection
*/
constructor($resource) {
// keep resource
this.$resource = $resource;
// stacks per id
this.stacksById = {};
// stacks
this.stacks = [];
// remote call
this.remoteStackAPI = this... | CheStack | identifier_name |
prism.py | __author__ = 'jbellino'
import os
import csv
import gdal
import gdalconst
import zipfile as zf
import numpy as np
import pandas as pd
from unitconversion import *
prismGrid_shp = r'G:\archive\datasets\PRISM\shp\prismGrid_p.shp'
prismGrid_pts = r'G:\archive\datasets\PRISM\shp\prismGrid_p.txt'
prismProj = r'G:\archive\d... |
def __clean_up(self):
try:
os.remove(os.path.join(self.pth, self.bil_file))
os.remove(os.path.join(self.pth, self.hdr_file))
except:
pass
if __name__ == '__main__':
grid_id = getGridIdFromRowCol(405, 972)
print grid_id
row, col = getRowColFromGridI... | with zf.ZipFile(parent_zip, 'r') as myzip:
if self.bil_file in myzip.namelist():
myzip.extract(self.bil_file, self.pth)
myzip.extract(self.hdr_file, self.pth)
return | identifier_body |
prism.py | __author__ = 'jbellino'
import os
import csv
import gdal
import gdalconst
import zipfile as zf
import numpy as np
import pandas as pd
from unitconversion import *
prismGrid_shp = r'G:\archive\datasets\PRISM\shp\prismGrid_p.shp'
prismGrid_pts = r'G:\archive\datasets\PRISM\shp\prismGrid_p.txt'
prismProj = r'G:\archive\d... | """
Writes the PRISM grid id, row, and col for each feature in the PRISM grid shapefile.
"""
import arcpy
data = []
rowends = range(ncol, max_grid_id+1, ncol)
with arcpy.da.SearchCursor(prismGrid_shp, ['grid_code', 'row', 'col']) as cur:
rowdata = []
for rec in cur:
... |
def writeGridPointsToTxt(prismGrid_shp=prismGrid_shp, out_file=prismGrid_pts): | random_line_split |
prism.py | __author__ = 'jbellino'
import os
import csv
import gdal
import gdalconst
import zipfile as zf
import numpy as np
import pandas as pd
from unitconversion import *
prismGrid_shp = r'G:\archive\datasets\PRISM\shp\prismGrid_p.shp'
prismGrid_pts = r'G:\archive\datasets\PRISM\shp\prismGrid_p.txt'
prismProj = r'G:\archive\d... | (grid_id):
"""
Determines the row, col based on a PRISM grid id.
"""
assert 1 <= grid_id <= max_grid_id, 'Valid Grid IDs are bewteen 1 and {}, inclusively.'.format(max_grid_id)
q, r = divmod(grid_id, ncol)
return q+1, r
def writeGridPointsToTxt(prismGrid_shp=prismGrid_shp, out_file=prismGrid_p... | getRowColFromGridId | identifier_name |
prism.py | __author__ = 'jbellino'
import os
import csv
import gdal
import gdalconst
import zipfile as zf
import numpy as np
import pandas as pd
from unitconversion import *
prismGrid_shp = r'G:\archive\datasets\PRISM\shp\prismGrid_p.shp'
prismGrid_pts = r'G:\archive\datasets\PRISM\shp\prismGrid_p.txt'
prismProj = r'G:\archive\d... |
local_f = os.path.join(output_dir, str(year), f)
with open(local_f, 'wb') as file:
f_path = '{}/{}'.format(dir_string, f)
ftp.retrbinary('RETR ' + f_path, handleDownload)
except Exception as e:
print e
finally:
print('Closi... | os.makedirs(os.path.join(output_dir, str(year))) | conditional_block |
meta.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
*/
import {computeDecimalDigest, computeDigest, decimalDigest} from '../../../i18n/digest';
import * as i18n from '../.... | (element: html.Element, context: any): any {
if (hasI18nAttrs(element)) {
const attrs: html.Attribute[] = [];
const attrsMeta: {[key: string]: string} = {};
for (const attr of element.attrs) {
if (attr.name === I18N_ATTR) {
// root 'i18n' node attribute
const i18n = el... | visitElement | identifier_name |
meta.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
*/
import {computeDecimalDigest, computeDigest, decimalDigest} from '../../../i18n/digest';
import * as i18n from '../.... | export function i18nMetaToDocStmt(meta: I18nMeta): o.JSDocCommentStmt|null {
const tags: o.JSDocTag[] = [];
if (meta.description) {
tags.push({tagName: o.JSDocTagName.Desc, text: meta.description});
}
if (meta.meaning) {
tags.push({tagName: o.JSDocTagName.Meaning, text: meta.meaning});
}
return tags... | // to a JsDoc statement formatted as expected by the Closure compiler. | random_line_split |
meta.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
*/
import {computeDecimalDigest, computeDigest, decimalDigest} from '../../../i18n/digest';
import * as i18n from '../.... |
/**
* Serialize the given `placeholderName` and `messagePart` into strings that can be used in a
* `$localize` tagged string.
*
* @param placeholderName The placeholder name to serialize
* @param messagePart The following message string after this placeholder
*/
export function serializeI18nTemplatePart(placeho... | {
let metaBlock = meta.description || '';
if (meta.meaning) {
metaBlock = `${meta.meaning}|${metaBlock}`;
}
if (meta.customId || meta.legacyId) {
metaBlock = `${metaBlock}@@${meta.customId || meta.legacyId}`;
}
if (metaBlock === '') {
// There is no metaBlock, so we must ensure that any starting... | identifier_body |
meta.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
*/
import {computeDecimalDigest, computeDigest, decimalDigest} from '../../../i18n/digest';
import * as i18n from '../.... | else {
return `:${placeholderName}:${messagePart}`;
}
}
// Converts i18n meta information for a message (id, description, meaning)
// to a JsDoc statement formatted as expected by the Closure compiler.
export function i18nMetaToDocStmt(meta: I18nMeta): o.JSDocCommentStmt|null {
const tags: o.JSDocTag[] = [];
... | {
// There is no placeholder name block, so we must ensure that any starting colon is escaped.
return escapeStartingColon(messagePart);
} | conditional_block |
server-events-once.ts | // from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener
import { Request, ResponseToolkit, Server, ServerRoute } from "hapi";
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request, h) |
};
declare module 'hapi' {
interface ServerEvents {
once(event: 'test1', listener: (update: string) => void): this;
once(event: 'test2', listener: (...updates: string[]) => void): this;
}
}
const server = new Server({
port: 8000,
});
server.route(serverRoute);
server.event('test1');
serve... | {
return 'oks: ' + request.path;
} | identifier_body |
server-events-once.ts | // from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener
import { Request, ResponseToolkit, Server, ServerRoute } from "hapi";
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
| (request, h) {
return 'oks: ' + request.path;
}
};
declare module 'hapi' {
interface ServerEvents {
once(event: 'test1', listener: (update: string) => void): this;
once(event: 'test2', listener: (...updates: string[]) => void): this;
}
}
const server = new Server({
port: 8000,
... | handler | identifier_name |
server-events-once.ts | // from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener
import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; | path: '/',
method: 'GET',
handler(request, h) {
return 'oks: ' + request.path;
}
};
declare module 'hapi' {
interface ServerEvents {
once(event: 'test1', listener: (update: string) => void): this;
once(event: 'test2', listener: (...updates: string[]) => void): this;
}
}
... |
const serverRoute: ServerRoute = { | random_line_split |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct Philosopher {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: nam... |
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())
]
});
let philosophers = vec![
Philosopher::new("Philosopher 1", 0, 1),
Philos... | {
let _left = table.forks[self.left_index].lock().unwrap();
let _right = table.forks[self.right_index].lock().unwrap();
println!("{} started eating", self.name);
thread::sleep_ms(1000);
println!("{} is done eating.", self.name);
} | identifier_body |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct | {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left_index: left_index,
right_index: right_index
}
}
... | Philosopher | identifier_name |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct Philosopher {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: nam... | fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())
]
});
let philosophers = vec![
Philosopher::new("Philosopher 1", 0, 1),
Philosophe... | }
| random_line_split |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... | {
let depot_client = Client::new(url, PRODUCT, VERSION, None)?;
ui.begin(format!("Promoting {} to channel '{}'", ident, channel))?;
if channel != "stable" && channel != "unstable" {
match depot_client.create_channel(&ident.origin, channel, token) {
Ok(_) => (),
Err(depot_cl... | identifier_body | |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... | (
ui: &mut UI,
url: &str,
ident: &PackageIdent,
channel: &str,
token: &str,
) -> Result<()> {
let depot_client = Client::new(url, PRODUCT, VERSION, None)?;
ui.begin(format!("Promoting {} to channel '{}'", ident, channel))?;
if channel != "stable" && channel != "unstable" {
matc... | start | identifier_name |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... | //! ```
//!//! This will promote the acme package specified to the stable channel.
//!
//! Notes:
//! The package should already have been uploaded to Builder.
//! If the specified channel does not exist, it will be created.
//!
use common::ui::{Status, UIWriter, UI};
use depot_client::{self, Client};
use hcore:... | //!
//! ```bash
//! $ hab pkg promote acme/redis/2.0.7/2112010203120101 stable | random_line_split |
skyway-tests.ts | const peerByOption: Peer = new Peer({
key: 'peerKey',
debug: 3
});
peerByOption.listAllPeers((items) => {
for (let item in items) {
console.log(decodeURI(items[item]));
}
});
const peerByIdAndOption: Peer = new Peer('peerid', {
key: 'peerKey',
debug: 3
});
let id = peerByOption.id;
le... | peerByOption.on("call", (media) => console.log("call"));
peerByOption.on("close", () => console.log("close"));
peerByOption.on("disconnected", () => console.log("disconnected"));
peerByOption.on("error", (err) => console.log(err)); | peerByOption.on("connection", (c) => console.log("connection")); | random_line_split |
expandFile.spec.ts | /// <reference path="../../typings/tsd.d.ts" />
import mocha = require('mocha')
import path = require('path')
import async = require('async')
import {readFile} from 'fs'
import {expect} from 'chai'
import {expandFile} from '../../lib/expand'
describe('expandFile', () => {
it('should stream file with expanded conten... | next => {
readFile(filePath, (err, data: Buffer) => {
original = data.toString()
result = output.join('')
next(null)
})
}
], () => {
expect(result).to.equal(original)
done()
});
})
}) | }, | random_line_split |
train.py | import numpy as np
from model import GAN, discriminator_pixel, discriminator_image, discriminator_patch1, discriminator_patch2, generator, discriminator_dummy
import utils
import os
from PIL import Image
import argparse
from keras import backend as K
# arrange arguments
parser=argparse.ArgumentParser()
parser.add_arg... |
else:
d, d_out_shape = discriminator_dummy(img_size, n_filters_d,init_lr)
gan=GAN(g,d,img_size, n_filters_g, n_filters_d,alpha_recip, init_lr)
g.summary()
d.summary()
gan.summary()
# start training
scheduler=utils.Scheduler(n_train_imgs//batch_size, n_train_imgs//batch_size, schedules, init_lr) if alpha_rec... | d, d_out_shape = discriminator_image(img_size, n_filters_d,init_lr) | conditional_block |
train.py | import numpy as np
from model import GAN, discriminator_pixel, discriminator_image, discriminator_patch1, discriminator_patch2, generator, discriminator_dummy
import utils
import os
from PIL import Image
import argparse
from keras import backend as K
# arrange arguments
parser=argparse.ArgumentParser()
parser.add_arg... | )
parser.add_argument(
'--gpu_index',
type=str,
help="gpu index",
required=True
)
parser.add_argument(
'--discriminator',
type=str,
help="type of discriminator",
required=True
)
parser.add_argument(
'--batch_size',
type=int,
help="batch size",
required=True
... | required=True | random_line_split |
baidu.js | var mongoose = require('mongoose');
var Post = require('../models/Post').Post;
var config = require('../config');
var http = require('http');
var site = "";
var token = "";
var options = {
host: 'data.zz.baidu.com',
path: '/urls?site=' + site + '&token=' + token,
method: 'POST',
headers: {
'Accept': '*/*'... | var callback = function (res) {
var buffers = [];
var nread = 0;
res.on('data', function (chunk) {
buffers.push(chunk);
nread += chunk.length;
});
res.on('end', function () {
console.log(buffers);
});
}
var req = http.request(options, callback);
mongoose.connect(config.db.production);
var db = mo... | 'Connection': 'Keep-Alive',
'User-Agent': 'curl/7.12.1 '
}
};
| random_line_split |
search-test.ts | import { assert } from 'chai';
import * as figc from 'figc';
import { createClient } from '../lib/solr';
import { dataOk } from './utils/sassert'; | const client = createClient(config.client);
[config.client.path, config.client.core].join('/').replace(/\/$/, '');
describe('Client', function () {
describe('#search("q=*:*")', function () {
it('should find all documents', async function () {
const data = await client.search('q=*:*');
dataOk(data);
... |
const config = figc(__dirname + '/config.json'); | random_line_split |
ga_event_viewer.user.js | // ==UserScript==
// @name GAイベントの引数をコンソール出力
// @namespace https://github.com/hosoyama-mediba/userscript
// @version 0.5
// @description GAのイベントパラメータをコンソールにデバッグ出力します
// @author Terunobu Hosoyama <hosoyama@mediba.jp>
// @match http://*/*
// @match https://*/*
// @require https://ajax.go... | console.log('GAイベントの引数をデバッグ出力します');
var gaOrig = window.ga;
window.ga = function(...args) {
console.log('ga:', ...args);
gaOrig.apply(window, arguments);
};
clearInterval(gaTimer);
};
gaTimer = setInterval(funct... | (function($) {
var script = $('<script/>').text(`
var gaTimer;
var gaReadyCallback = function() { | random_line_split |
setting.js | // ----------------------------------------------------------------------------
// Module initialization
var Config = require("config").config;
var utils = require("utils");
var validators = require("validators");
// ----------------------------------------------------------------------------
// Setting class.
functio... | },
value: initial,
validator: validator
};
utils.openWindowWithBottomClicksDisabled(this.args.controllerName, arg);
};
Setting.prototype.clickHandler = function() {
var initial = Config.getProperty(this.args.propertyName).get();
var validator = typeof this.args.validator !== '... | self.updateValue();
} else {
alert(Alloy.Globals.L("illegal_value"));
} | random_line_split |
setting.js | // ----------------------------------------------------------------------------
// Module initialization
var Config = require("config").config;
var utils = require("utils");
var validators = require("validators");
// ----------------------------------------------------------------------------
// Setting class.
functio... | (e) {
setting.clickHandler();
}
| onClick | identifier_name |
setting.js | // ----------------------------------------------------------------------------
// Module initialization
var Config = require("config").config;
var utils = require("utils");
var validators = require("validators");
// ----------------------------------------------------------------------------
// Setting class.
functio... |
// Inherits from Controller...
Setting.prototype = new (require("controller"))(
arguments[0], [$.title_label]
);
// Read the actual value of the property that this setting is responsible for
Setting.prototype.updateValue = function() {
$.setting_value.text =
Alloy.Globals.L(Config.getProperty(this.ar... | {
$.title_label.text_id = this.args.title_id;
$.title_label.text = Alloy.Globals.L(this.args.title_id);
// This will trigger UI update. Ugly solution I know.
$.setting.top = this.args.top || 0;
if (typeof this.args.width !== 'undefined') {
$.setting.width = this.args.width;
}
// Lis... | identifier_body |
setting.js | // ----------------------------------------------------------------------------
// Module initialization
var Config = require("config").config;
var utils = require("utils");
var validators = require("validators");
// ----------------------------------------------------------------------------
// Setting class.
functio... |
// Listen to the "SettingChanges" event. It simply updates the string
// representation of the property that the view shows.
this.addSettingsChangedHandler(this.updateValue);
}
// Inherits from Controller...
Setting.prototype = new (require("controller"))(
arguments[0], [$.title_label]
);
// Read the... | {
$.setting.width = this.args.width;
} | conditional_block |
settings.py | """
Django settings for todo project.
Generated by 'django-admin startproject' using Django 1.9.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Bu... | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N... | { | random_line_split |
forms.py | from django import forms
from .models import Question, Answer, Categories, Customuser
from django.contrib import auth
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class add_Question_Form(forms.ModelForm): # just a regular form
question_text = forms.CharField(l... | (self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = auth.authenticate(username=username,
password=password)
if self.user_cache is None:
... | clean | identifier_name |
forms.py | from django import forms
from .models import Question, Answer, Categories, Customuser
from django.contrib import auth
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class add_Question_Form(forms.ModelForm): # just a regular form
question_text = forms.CharField(l... |
def save(self,commit=True):
question = super(add_Question_Form, self).save(commit=False)
question.question_text = self.cleaned_data["question_text"]
if commit:
question.save()
return question
class add_Answer_Form(forms.ModelForm):
class Meta:
model = Answer
... | if question_text == "":
raise forms.ValidationError(
"Need a question",)
else:
return True | identifier_body |
forms.py | from django import forms
from .models import Question, Answer, Categories, Customuser
from django.contrib import auth
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class add_Question_Form(forms.ModelForm): # just a regular form
question_text = forms.CharField(l... |
else:
return True
def save(self,commit=True):
question = super(add_Question_Form, self).save(commit=False)
question.question_text = self.cleaned_data["question_text"]
if commit:
question.save()
return question
class add_Answer_Form(forms.Model... | raise forms.ValidationError(
"Need a question",) | conditional_block |
forms.py | from django import forms | class add_Question_Form(forms.ModelForm): # just a regular form
question_text = forms.CharField(label=_("question_text"),
widget=forms.Textarea({'cols': '40', 'rows': '5'}))
class Meta:
model = Question
fields = ['question_text', 'upload',
'category1','category2',
... | from .models import Question, Answer, Categories, Customuser
from django.contrib import auth
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
| random_line_split |
NSEC.py | # Copyright (C) 2004-2007, 2009, 2010 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... | v = cmp(self.next, other.next)
if v == 0:
b1 = cStringIO.StringIO()
for (window, bitmap) in self.windows:
b1.write(chr(window))
b1.write(chr(len(bitmap)))
b1.write(bitmap)
b2 = cStringIO.StringIO()
for (window, bitma... | identifier_body | |
NSEC.py | # Copyright (C) 2004-2007, 2009, 2010 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... |
return cls(rdclass, rdtype, next, windows)
from_wire = classmethod(from_wire)
def choose_relativity(self, origin = None, relativize = True):
self.next = self.next.choose_relativity(origin, relativize)
def _cmp(self, other):
v = cmp(self.next, other.next)
if v == 0:
... | next = next.relativize(origin) | conditional_block |
NSEC.py | # Copyright (C) 2004-2007, 2009, 2010 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... | b2.write(chr(window))
b2.write(chr(len(bitmap)))
b2.write(bitmap)
v = cmp(b1.getvalue(), b2.getvalue())
return v | b2 = cStringIO.StringIO()
for (window, bitmap) in other.windows: | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.