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 |
|---|---|---|---|---|
lib.rs | //! # `peeking_take_while`
//!
//! Provides the `peeking_take_while` iterator adaptor method.
//!
//! The `peeking_take_while` method is very similar to `take_while`, but behaves
//! differently when used with a borrowed iterator (perhaps returned by
//! `Iterator::by_ref`).
//!
//! `peeking_take_while` peeks at the ne... | //! // or equal to 10.
//!
//! // ...except, when using plain old `take_while` we lost 10!
//! assert_eq!(iter_xs.next(), Some(11));
//!
//! // However, when using `peeking_take_while` we did not! Great!
//! assert_eq!(iter_ys.next(), Some(10));
//! # }
//! ```
use std::iter::Peekable;
/// The iterator returned by `p... | //! // And now we will do some other thing with the items that are greater than | random_line_split |
lib.rs | //! # `peeking_take_while`
//!
//! Provides the `peeking_take_while` iterator adaptor method.
//!
//! The `peeking_take_while` method is very similar to `take_while`, but behaves
//! differently when used with a borrowed iterator (perhaps returned by
//! `Iterator::by_ref`).
//!
//! `peeking_take_while` peeks at the ne... | <P>(&'a mut self, predicate: P) -> PeekingTakeWhile<I, P>
where P: FnMut(&<Self as Iterator>::Item) -> bool
{
PeekingTakeWhile {
iter: self,
predicate: predicate,
}
}
}
| peeking_take_while | identifier_name |
lib.rs | //! # `peeking_take_while`
//!
//! Provides the `peeking_take_while` iterator adaptor method.
//!
//! The `peeking_take_while` method is very similar to `take_while`, but behaves
//! differently when used with a borrowed iterator (perhaps returned by
//! `Iterator::by_ref`).
//!
//! `peeking_take_while` peeks at the ne... |
}
}
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
pub trait PeekableExt<'a, I>: Iterator
where I: 'a + Iterator
{
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// meth... | {
self.iter.next()
} | conditional_block |
project.py | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic i... | """
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of the project.
"""
self.set_up_basic_information(
MODEL_VERSION[OBJEC... | identifier_body | |
project.py | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic i... | MODEL_VERSION[OBJECT_CODES['Project']],
created_by_user_id
)
self.project_name = project_name
self.project_description = kwargs.get('project_description', None) | :param project_description: Description of the project.
"""
self.set_up_basic_information( | random_line_split |
project.py | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic i... | (self, project_name,
created_by_user_id,
**kwargs):
"""
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of th... | __init__ | identifier_name |
month.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | {
let cmd = rt.cli().subcommand().1.unwrap(); // checked in main
let filter = {
use chrono::offset::Local;
use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) ... | identifier_body | |
month.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | (rt: &Runtime) -> Result<()> {
let cmd = rt.cli().subcommand().1.unwrap(); // checked in main
let filter = {
use chrono::offset::Local;
use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
let start = match cmd.value_of("start").map(::chrono::nai... | month | identifier_name |
month.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | debug!(" -> tag = {:?}", tag);
let start = e.get_start_datetime()?;
debug!(" -> start = {:?}", start);
let end = e.get_end_datetime()?;
debug!(" -> end = {:?}", end);
rt.report_touched(e.get_location())
.map_err(Error::from)
... | debug!("Processing {:?}", e.get_location());
let tag = e.get_timetrack_tag()?; | random_line_split |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_st... | if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
elif is_integer(value) and (0 <= value < 2**256):
return if_number
elif is_hex_encoded_block_number(value):
... | identifier_body | |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_st... | return 0 <= value_as_int < 2**256
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
... | return False | random_line_split |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_st... | (value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
elif is_integer(value) and (0 <= value < 2**256):
return if_number
... | select_method_for_block_identifier | identifier_name |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_st... |
elif is_hex_encoded_block_hash(value):
return False
try:
value_as_int = int(value, 16)
except ValueError:
return False
return 0 <= value_as_int < 2**256
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
... | return False | conditional_block |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES ... | (BasePlugin):
DEFAULT_INTERVAL = 1
@threaded_method
def enable(self):
self.nics = {}
self.ignores = self.pkmeter.config.get(self.namespace, 'ignores', '')
self.ignores = list(filter(None, self.ignores.split(' ')))
super(Plugin, self).enable()
@never_raise
def update... | Plugin | identifier_name |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES ... |
return False
def _net_io_counters(self, io=None):
io = io or psutil.net_io_counters()
return {
'bytes_sent': io.bytes_sent,
'bytes_recv': io.bytes_recv,
'packets_sent': io.packets_sent,
'packets_recv': io.packets_recv,
'errin': io... | if iface.startswith(ignore):
return True | conditional_block |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES ... |
def _is_ignored(self, iface):
if self.ignores:
for ignore in self.ignores:
if iface.startswith(ignore):
return True
return False
def _net_io_counters(self, io=None):
io = io or psutil.net_io_counters()
return {
'bytes... | for iface, newio in psutil.net_io_counters(True).items():
if not iface.startswith('lo'):
netinfo = netifaces.ifaddresses(iface)
if netinfo.get(netifaces.AF_INET) and not self._is_ignored(iface):
newio = self._net_io_counters(newio)
newi... | identifier_body |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES ... | 'errin': io.errin,
'errout': io.errout,
'dropin': io.dropin,
'dropout': io.dropout,
}
def _deltas(self, previo, newio):
now = time.time()
tdelta = now - previo.get('updated',0)
for key in ['bytes_sent', 'bytes_recv']:
newio... | 'packets_recv': io.packets_recv, | random_line_split |
show_neighbors.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... |
main(sys.argv) | random_line_split | |
show_neighbors.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... | (argv):
host = argv[1]
community = argv[2]
dev = Discovery.get_manager(host, community)
Discovery.show_neighbors(dev)
main(sys.argv)
| main | identifier_name |
show_neighbors.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... |
main(sys.argv)
| host = argv[1]
community = argv[2]
dev = Discovery.get_manager(host, community)
Discovery.show_neighbors(dev) | identifier_body |
ActivityIndicatorExample.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
import type {Node} from 'React';
import {ActivityIndicator, StyleSheet, View} fr... | extends Component<Props, State> {
_timer: Timer;
constructor(props: Props) {
super(props);
this.state = {
animating: true,
};
}
componentDidMount() {
this.setToggleTimeout();
}
componentWillUnmount() {
clearTimeout(this._timer);
}
setToggleTimeout() {
this._timer = set... | ToggleAnimatingActivityIndicator | identifier_name |
ActivityIndicatorExample.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
import type {Node} from 'React';
import {ActivityIndicator, StyleSheet, View} fr... | }
}
const styles = StyleSheet.create({
centering: {
alignItems: 'center',
justifyContent: 'center',
padding: 8,
},
gray: {
backgroundColor: '#cccccc',
},
horizontal: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: 8,
},
});
exports.displayName = (undefined: ?... | random_line_split | |
move_.rs |
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?
pub direction: Direction,
}
impl Mo... | use std::convert::TryFrom;
use std::fmt; | random_line_split | |
move_.rs | use std::convert::TryFrom;
use std::fmt;
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?... |
c
}
}
/// Parse a string representation of moves.
pub fn parse(s: &str) -> Result<Vec<Move>, char> {
s.chars().map(Move::try_from).collect::<Result<Vec<_>, _>>()
}
impl fmt::Display for Move {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_char())
}... | {
c.make_ascii_uppercase();
} | conditional_block |
move_.rs | use std::convert::TryFrom;
use std::fmt;
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?... | (&self) -> char {
let mut c = match self.direction {
Direction::Left => 'l',
Direction::Right => 'r',
Direction::Up => 'u',
Direction::Down => 'd',
};
if self.moves_crate {
c.make_ascii_uppercase();
}
c
}
}
/// Pars... | to_char | identifier_name |
move_.rs | use std::convert::TryFrom;
use std::fmt;
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?... |
}
impl TryFrom<char> for Move {
type Error = char;
fn try_from(c: char) -> Result<Move, char> {
use crate::Direction::*;
let dir = match c {
'l' | 'L' => Left,
'r' | 'R' => Right,
'u' | 'U' => Up,
'd' | 'D' => Down,
_ => return Err(c... | {
write!(f, "{}", self.to_char())
} | identifier_body |
field_manager_mixin.js | odoo.define('web.FieldManagerMixin', function (require) {
"use strict";
/**
* The FieldManagerMixin is a mixin, designed to do the plumbing between field
* widgets and a basicmodel. Field widgets can be used outside of a view. In
* that case, someone needs to listen to events bubbling up from the widgets and
* c... | *
* @param {OdooEvent} event
* @param {number} [event.data.limit]
* @param {number} [event.data.offset]
* @param {function} [event.data.on_success] callback
*/
_onLoad: function (event) {
var self = this;
event.stopPropagation(); // prevent other field managers from han... | * that, it can trigger a load event. This will then ask the model to
* actually reload the data, then call the on_success callback. | random_line_split |
field_manager_mixin.js | odoo.define('web.FieldManagerMixin', function (require) {
"use strict";
/**
* The FieldManagerMixin is a mixin, designed to do the plumbing between field
* widgets and a basicmodel. Field widgets can be used outside of a view. In
* that case, someone needs to listen to events bubbling up from the widgets and
* c... |
});
},
/**
* This method will be called whenever a field value has changed (and has
* been confirmed by the model).
*
* @abstract
* @param {string} id basicModel Id for the changed record
* @param {string[]} fields the fields (names) that have been changed
* @para... | {
return self._confirmChange(dataPointID, result, event);
} | conditional_block |
actionManager.ts | import "reflect-metadata";
export const symbolRobotAction = Symbol("robotAction");
export function robotAction(name: string, ...args: string[]) {
return (target: any, propertyKey: string, descriptor: any) => {
if (descriptor.value) {
ActionManager.instance.registerClass(target.constructor);
... | className: string
func: Function
chineseName: string
chineseArgs: string[]
argTypes: any
}
export default class ActionManager {
private static readonly INSTANCE = new ActionManager();
public static get instance() {
return this.INSTANCE;
}
constructor() {
}
priva... | random_line_split | |
actionManager.ts | import "reflect-metadata";
export const symbolRobotAction = Symbol("robotAction");
export function robotAction(name: string, ...args: string[]) {
return (target: any, propertyKey: string, descriptor: any) => {
if (descriptor.value) {
ActionManager.instance.registerClass(target.constructor);
... | (name: string) {
return this._functionMap.get(name);
}
public getThisObj(name: string) {
return this._classMap.get(name);
}
}
export class Email {
addr: string;
server: string;
constructor(str: string) {
let data = str.split('@');
this.addr = data[0];
th... | getAction | identifier_name |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
... |
return urls
class Categories(BaseSitemap):
# Crawling category pages is important.
priority = 1.0
def items(self):
""" Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC)
def last_mod(self, ... | for url in urls:
url['location'] = url['location'].replace("http://"+site.domain, "", 1) | conditional_block |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
... | priority = 1.0
def items(self):
""" Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC)
def last_mod(self, category):
"""
The last time this URL has changed. For categories, we use the current tim... | # Crawling category pages is important. | random_line_split |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
... |
def last_mod(self, category):
"""
The last time this URL has changed. For categories, we use the current time because groups get posted to all
the time.
@TODO: Figure out a way to get a more precise last_mod time
"""
return datetime.now()
def locatio... | """ Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC) | identifier_body |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
... | (BaseSitemap):
# Crawling category pages is important.
priority = 1.0
def items(self):
""" Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC)
def last_mod(self, category):
"""
The last time t... | Categories | identifier_name |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors
use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>;
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if ... | {
let doors = calculate_doors().collect::<Vec<DoorState>>();
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert_eq!(doors[i*i - 1], DoorState::Open);
}
} | identifier_body | |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors
use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>;
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if ... |
}
(1u32..101).map(door_status as fn(u32) -> DoorState)
}
#[cfg(not(test))]
fn main() {
let doors = calculate_doors();
for (i, x) in doors.enumerate() { println!("Door {} is {:?}" , i + 1 , x); }
}
#[test]
fn solution() {
let doors = calculate_doors().collect::<Vec<DoorState>>();
// test tha... | { DoorState::Closed } | conditional_block |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors
use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>;
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if ... | () -> DoorIter {
fn door_status(door_number: u32) -> DoorState {
let x = (door_number as f64).sqrt();
if x == x.round() { DoorState::Open } else { DoorState::Closed }
}
(1u32..101).map(door_status as fn(u32) -> DoorState)
}
#[cfg(not(test))]
fn main() {
let doors = calculate_doors();
... | calculate_doors | identifier_name |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors |
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if they want to allocate or just process as a stream.
fn calculate_doors() -> DoorIter {
fn door_status(door_number: u32) -> DoorState {
let x = (door_number as ... | use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>; | random_line_split |
train_util.py | # Copyright 2022 The DDSP 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 wri... |
# Stop the training when the loss reaches given value
if (early_stop_loss_value is not None and
losses['total_loss'] <= early_stop_loss_value):
logging.info('Total loss reached early stopping value of %s',
early_stop_loss_value)
# Write a final checkpoint.
... | cloud.report_metric_to_hypertune(losses['total_loss'], step.numpy()) | conditional_block |
train_util.py | # Copyright 2022 The DDSP 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 wri... |
def expand_path(file_path):
return os.path.expanduser(os.path.expandvars(file_path))
def get_latest_file(dir_path, prefix='operative_config-', suffix='.gin'):
"""Returns latest file with pattern '/dir_path/prefix[iteration]suffix'.
Args:
dir_path: Path to the directory.
prefix: Filename prefix, not ... | """Create a distribution strategy for running on accelerators.
For CPU, single-GPU, or multi-GPU jobs on a single machine, call this function
without args to return a MirroredStrategy.
For TPU jobs, specify an address to the `tpu` argument.
For multi-machine GPU jobs, specify a `cluster_config` argument of t... | identifier_body |
train_util.py | # Copyright 2022 The DDSP 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 wri... | tick = time.time()
for iteration in range(num_steps):
step = trainer.step # Step is not iteration if restarting a model.
# Take a step.
losses = trainer.train_step(dataset_iter)
# Create training loss metrics when starting/restarting training.
if iteration == 0:
loss_na... | summary_writer = tf.summary.create_noop_writer()
# Train.
with summary_writer.as_default(): | random_line_split |
train_util.py | # Copyright 2022 The DDSP 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 wri... | (line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line
line = line[2:]
if line.startswith('===='):
return ''
if line.startswith('None'):
return ' # None.'
if line.endswith(':'):
return '#### ' + line
return line
... | format_for_tensorboard | identifier_name |
attr-stmt-expr.rs | // Copyright 2018 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 ... | (string: &'static str) {
// macros are handled a bit differently
#[expect_print_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
println!("{}", string)
}
fn main() {
#[expect_let]
let string = "Hell... | print_str | identifier_name |
attr-stmt-expr.rs | // Copyright 2018 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 ... | }
fn main() {
#[expect_let]
let string = "Hello, world!";
#[expect_print_stmt]
println!("{}", string);
#[expect_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
print_str("string")
} | #[expect_print_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
println!("{}", string) | random_line_split |
attr-stmt-expr.rs | // Copyright 2018 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 ... | {
#[expect_let]
let string = "Hello, world!";
#[expect_print_stmt]
println!("{}", string);
#[expect_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
print_str("string")
} | identifier_body | |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | ,
// To be listened to by the user.
DataAvailable(_) | DataCleared => (),
LeftChanged(text) => self.model.left_text = text,
RightChanged(text) => self.model.right_text = text,
Quit => gtk::main_quit(),
}
}
view! {
#[name="window"]
... | {
self.model.text = format!("{}{}", self.model.left_text, self.model.right_text);
self.model.relm.stream().emit(DataAvailable(self.model.text.clone()));
} | conditional_block |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | () {
let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let cancel_button = &widgets.cancel_button;
let concat_button = &widgets.concat_button;
let label = &widgets.label;
let left_entry = &widgets.left_entry;
let right_entry = &widgets.r... | label_change | identifier_name |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(C... | Inhibit,
prelude::ButtonExt,
prelude::EntryExt, | random_line_split |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... |
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
... | {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
} | identifier_body |
setup.py | import setuptools
import sys
import numpy as np
# NOTE: If edt.cpp does not exist:
# cython -3 --fast-fail -v --cplus edt.pyx
extra_compile_args = []
if sys.platform == 'win32':
extra_compile_args += [
'/std:c++11', '/O2'
]
else:
extra_compile_args += [
'-std=c++11', '-O3', '-ffast-math', '-pthread'
... |
setuptools.setup(
setup_requires=['pbr'],
python_requires="~=3.6", # >= 3.6 < 4.0
ext_modules=[
setuptools.Extension(
'edt',
sources=[ 'edt.cpp' ],
language='c++',
include_dirs=[ np.get_include() ],
extra_compile_args=extra_compile_args,
),
],
long_description_content_... | extra_compile_args += [ '-stdlib=libc++', '-mmacosx-version-min=10.9' ] | conditional_block |
setup.py | import setuptools
import sys
import numpy as np
# NOTE: If edt.cpp does not exist:
# cython -3 --fast-fail -v --cplus edt.pyx
extra_compile_args = []
if sys.platform == 'win32':
extra_compile_args += [
'/std:c++11', '/O2'
]
else:
extra_compile_args += [
'-std=c++11', '-O3', '-ffast-math', '-pthread'
... | setuptools.Extension(
'edt',
sources=[ 'edt.cpp' ],
language='c++',
include_dirs=[ np.get_include() ],
extra_compile_args=extra_compile_args,
),
],
long_description_content_type='text/markdown',
pbr=True
) | random_line_split | |
plugin.js | /**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('link', function(editor) {
var attachState = {};
f... |
function createLink() {
var linkAttrs = {
href: href,
target: data.target ? data.target : null,
rel: data.rel ? data.rel : null,
"class": data["class"] ? data["class"] : null,
title: data.title ? data.title : null
};
if (href === attachState.href) {
attachState.... | {
var rng = editor.selection.getRng();
tinymce.util.Delay.setEditorTimeout(editor, function() {
editor.windowManager.confirm(message, function(state) {
editor.selection.setRng(rng);
callback(state);
});
});
} | identifier_body |
plugin.js | /**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('link', function(editor) {
var attachState = {};
f... | (linkList) {
var data = {}, selection = editor.selection, dom = editor.dom, selectedElm, anchorElm, initialText;
var win, onlyText, textListCtrl, linkListCtrl, relListCtrl, targetListCtrl, classListCtrl, linkTitleCtrl, value;
function linkListChangeHandler(e) {
var textCtrl = win.find('#text');
if (!textC... | showDialog | identifier_name |
plugin.js | /**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('link', function(editor) {
var attachState = {};
f... | });
}); | onclick: createLinkList(showDialog),
stateSelector: 'a[href]',
context: 'insert',
prependToContext: true | random_line_split |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 |
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t =... | {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
} | identifier_body |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn | (&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_con... | test1 | identifier_name |
basic.rs | struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
pri... | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
| random_line_split | |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Ch... |
count = 0
for bad_item in bad_files:
count = count + 1
#Do in batches just to be kind of safe.
if count > 50:
break
file_id = bad_item['id']
revisions = service.revisions().list(fileId=file_id, fields='*').execute()
if len(revisions['revisions']) <... | revisions = service.revisions().list(fileId=bad_item['id'], fields='*').execute()
assert(len(revisions['revisions']) >= 2)
dt = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
if dt.day == DAY_OF_INFECTION and dt.month = MONTH_OF_INFECTION and dt.year == YEAR_OF_INFECTION:
... | conditional_block |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Ch... |
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
pp = pprint.PrettyPrinter()
#grab first batch of possible infected files
results = service.files().list(pageSize=1,
... | """Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.... | identifier_body |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Ch... | pp.pprint(file_meta)
print(' ')
pp.pprint(revisions)
continue
print("{}: {} revisions found".format(target_rev_name, len(revisions['revisions'])) )
#THESE ARE THE REALLY DANGEROUS STEPS, ONLY UNCOMMMENT IF YOU KNOW WHAT YOU ARE DOING!!!
rev_id_t... | #print out some debug info so we can figure out what we have multipe revisions with osiris | random_line_split |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Ch... | ():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
pp = pprint.PrettyPrinter()
#grab first batch of possible infected files
results = service.files().list(pageSize=1,
fields="ne... | main | identifier_name |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RT... |
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
}
| {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
} | identifier_body |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RT... | let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 {
let val = volatile_load((self.address + reg as usize) as *const u32... |
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET)); | random_line_split |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RT... | (&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1));
for frame in Frame::range_inclusive(sta... | init | identifier_name |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrase... | self.assertTrue(freq >= 200)
#endclass TestPhrasesModel
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main() |
freq = phrases.vocab[special_token] | random_line_split |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrase... | (self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(TestPhrasesModel.get_sentence(), min_count=1)
present = special_token in phrases.vocab
freq = phrases.vocab[special_token]
phrases.add_vocab([[special_token]])
f... | testUpdate | identifier_name |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrase... |
else:
yield [TestPhrasesModel.get_word() for i in range(random.randint(2, 10))] + ["."]
def testUpdate(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(TestPhrasesModel.get_sentence(), min_count=1)
prese... | yield [WORDS[random.randint(0, len(WORDS) -1)] for i in range(random.randint(2, 10))] + ["."] | conditional_block |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrase... |
def testUpdate(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(TestPhrasesModel.get_sentence(), min_count=1)
present = special_token in phrases.vocab
freq = phrases.vocab[special_token]
phrases.add_vocab([[special... | """Generator for random sentences.
10% probability to return sentence containing only preselected words"""
for i in range(size):
if random.random() > 0.9:
yield [WORDS[random.randint(0, len(WORDS) -1)] for i in range(random.randint(2, 10))] + ["."]
else:
... | identifier_body |
SelectionAnchor.ts | import { Insert, Remove, SimRange, SimSelection, SugarElement, SugarNode, Traverse, WindowSelection } from '@ephox/sugar';
import * as Descend from '../../alien/Descend';
import { AlloyComponent } from '../../api/component/ComponentApi';
import * as Fields from '../../data/Fields';
import * as Origins from '../layout/... | import { FieldSchema } from '@ephox/boulder';
import { Optional, Unicode } from '@ephox/katamari'; | random_line_split | |
setup.py | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHET... | #
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# | random_line_split |
see_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from dace.util import getSite
from dace.processinstance.core import DEFAULTMAPPING_A... |
DEFAULTMAPPING_ACTIONS_VIEWS.update({SeeImportService: SeeImportServiceView})
| self.execute(None)
result = {}
try:
navbars = generate_navbars(self, self.context, self.request)
except ObjectRemovedException:
return HTTPFound(self.request.resource_url(getSite(), ''))
values = {'object': self.context,
'navbar_body': navbars['... | identifier_body |
see_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from dace.util import getSite
from dace.processinstance.core import DEFAULTMAPPING_A... | (self):
self.execute(None)
result = {}
try:
navbars = generate_navbars(self, self.context, self.request)
except ObjectRemovedException:
return HTTPFound(self.request.resource_url(getSite(), ''))
values = {'object': self.context,
'navbar_... | update | identifier_name |
see_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL | from dace.util import getSite
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from lac.content.processes.services_processes.behaviors import (
SeeImportService)
from lac.content.service import ImportService
from lac.utilities.utils import (
ObjectRemovedExce... | # author: Amen Souissi
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
| random_line_split |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn | (&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
... | next | identifier_name |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> |
}
| {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Orderi... | identifier_body |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
... |
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| {
self.index += 1;
} | conditional_block |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
... | self.index += 1;
}
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
} | random_line_split | |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def get_sente... | (word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
return None
... | peek | identifier_name |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
|
def get_sentence(self):
self.sentence = ' '.join([self.subject, self.verb, self.object])
return self.sentence
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = wo... | self.subject = subject[1]
self.verb = verb[1]
self.object = object[1] | identifier_body |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def get_sente... | def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
retu... | self.sentence = ' '.join([self.subject, self.verb, self.object])
return self.sentence
| random_line_split |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def get_sente... |
else:
return None
else:
return None
def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
... | return word | conditional_block |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
if id == ref['handle']:
return ref
return None
def open_file(... | if funcLen < l:
funcLen = l
text = '%s\n' % globals.exception
globals.exception = None
for line in trace:
s = '\t%s (%s:%d:%d)\n' % (line['func'].ljust(funcLen), line['script'], line['line'], line['column'])
globals.clicks.add(sublime.Region(len(text), len(text + s)), open_file, line)
text = text + s
gl... | func = frame['func']['name'] or frame['func']['inferredName'] or 'Anonymous'
script = lookup_ref(frame['script']['ref'], refs)
trace.append({'func': func, 'script': script['name'], 'line': int(frame['line']) + 1, 'column': int(frame['column']) + 1})
l = len(func) | random_line_split |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
|
return None
def open_file(data):
if '/' not in data['script'].replace('\\', '/'):
print('[NDBG] Internal scripts (%s) doesn\'t supported for now. Sorry :(' % data['script'])
return
# TODO: fetch node's internal scripts with `scripts` request
window = sublime.active_window()
filename = '%s:%d:%d' % (data['scr... | if id == ref['handle']:
return ref | conditional_block |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
if id == ref['handle']:
return ref
return None
def open_file(... |
def trace_callback(data):
body = data['body']
refs = data['refs']
trace = []
funcLen = 0
for frame in body['frames']:
func = frame['func']['name'] or frame['func']['inferredName'] or 'Anonymous'
script = lookup_ref(frame['script']['ref'], refs)
trace.append({'func': func, 'script': script['name'], 'line': ... | if '/' not in data['script'].replace('\\', '/'):
print('[NDBG] Internal scripts (%s) doesn\'t supported for now. Sorry :(' % data['script'])
return
# TODO: fetch node's internal scripts with `scripts` request
window = sublime.active_window()
filename = '%s:%d:%d' % (data['script'], data['line'], 1) # it's better... | identifier_body |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
if id == ref['handle']:
return ref
return None
def open_file(... | (sublime_plugin.ApplicationCommand):
def run(self):
if globals.client:
globals.client.close()
address = config.get('address')
try:
globals.original_layout = sublime.active_window().get_layout()
globals.clicks = Clicks()
globals.client = client = DebugClient(address)
client.on_disconnect(disconne... | NodeDebuggerAttachCommand | identifier_name |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... |
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height... | let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc); | random_line_split |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... | (mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use wi... | v_align | identifier_name |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... |
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&s... | {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
} | identifier_body |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... | else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), ... | {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} | conditional_block |
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:neo4j@127.0.0.1:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
... | let lang: Language = row.get("n").unwrap();
assert_eq!(rust, lang);
graph.exec("MATCH (n:NTLY_INTG_TEST_MACROS_2) DELETE n").unwrap();
} | random_line_split | |
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:neo4j@127.0.0.1:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
... | () {
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("MATCH (n:NTLY_INTG_TEST_MACROS_1) RETURN n").unwrap();
let result = graph.exec(stmt);
assert!(result.is_ok());
}
#[test]
fn save_retrive_struct() {
let rust = Language {
name: "Rust".to_owned(),
level: "... | without_params | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, Drill... | {
pub issue_pattern: IssuePattern,
pub source: Source,
pub kind: Kind,
pub issued_at: DateTime<Utc>,
pub occurred_at: DateTime<Utc>,
pub id: String,
pub status: Status,
pub number: u32, // we don't accept an EEW which has no telegram number
pub detail: Option<EEWDetail>,
}
#[derive(PartialEq, Debug, Clone... | EEW | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, Drill... | #[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Status { Normal, Correction, CancelCorrection, LastWithCorrection, Last, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[deriv... | random_line_split | |
service_callback_api_schema.py | from app.schema_validation.definitions import https_url, uuid
create_service_callback_api_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST service callback/inbound api schema", | "updated_by_id": uuid
},
"required": ["url", "bearer_token", "updated_by_id"]
}
update_service_callback_api_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST service callback/inbound api schema",
"type": "object",
"title": "Create service callback/inb... | "type": "object",
"title": "Create service callback/inbound api",
"properties": {
"url": https_url,
"bearer_token": {"type": "string", "minLength": 10}, | random_line_split |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | ():
(parser, config_path) = C.load_config_file()
if parser.has_option('vault', 'username'):
username = parser.get('vault', 'username')
else:
username = getpass.getuser()
if parser.has_option('vault', 'keyname'):
keyname = parser.get('vault', 'keyname')
else:
keyname ... | main | identifier_name |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... |
if len(sys.argv) == 2 and sys.argv[1] == 'set':
intro = 'Storing password in "{}" user keyring using key name: {}\n'
sys.stdout.write(intro.format(username, keyname))
password = getpass.getpass()
confirm = getpass.getpass('Confirm password: ')
if password == confirm:
... | keyname = 'ansible' | conditional_block |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... |
if __name__ == '__main__':
main()
| (parser, config_path) = C.load_config_file()
if parser.has_option('vault', 'username'):
username = parser.get('vault', 'username')
else:
username = getpass.getuser()
if parser.has_option('vault', 'keyname'):
keyname = parser.get('vault', 'keyname')
else:
keyname = 'ansib... | identifier_body |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | if parser.has_option('vault', 'username'):
username = parser.get('vault', 'username')
else:
username = getpass.getuser()
if parser.has_option('vault', 'keyname'):
keyname = parser.get('vault', 'keyname')
else:
keyname = 'ansible'
if len(sys.argv) == 2 and sys.argv[1... | def main():
(parser, config_path) = C.load_config_file() | random_line_split |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait Even... | need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value... | identifier_body | |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize { | }
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn re... | self.n | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.