file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
video.rs | use ffmpeg::frame;
use glium::texture::{SrgbTexture2d};
use glium::{Program, Display, VertexBuffer, Surface};
use glium::buffer::BufferView;
use glium::buffer::BufferMode::Persistent;
use glium::buffer::BufferType::PixelUnpackBuffer;
use glium::index::PrimitiveType::TriangleStrip;
use glium::index::NoIndices;
use gliu... | self.texture = Some(SrgbTexture2d::empty_with_format(self.display,
U8U8U8U8, NoMipmap, frame.width(), frame.height()).unwrap());
}
// write to the buffer
self.buffer.as_mut().unwrap().write(frame.plane(0));
// write the buffer to the texture
self.texture.as_mut().unwrap().main_level()
.raw... | random_line_split | |
LayersLayergroupSimpleController.js | app.controller("LayersLayergroupSimpleController", [ "$scope", function($scope) {
angular.extend($scope, {
center: {
lat: 39,
lng: -100,
zoom: 3
},
layers: {
baselayers: {
... | visible: true,
pluginOptions: {
maxZoom: 5,
resolution: 4
}
};
var group = {
name: 'Group Layer',
type: 'group',
visible: true,
layerOptions: {
layers... | random_line_split | |
di.d.ts | import { Type } from 'angular2/src/facade/lang';
import { DependencyMetadata } from 'angular2/src/core/di/metadata';
/**
* Specifies that a constant attribute value should be injected.
*
* The directive can inject constant string literals of host element attributes.
*
* ### Example
*
* Suppose we have a... | *
* In this case the object that is injected depend on the type of the variable
* binding. It can be an ElementRef, a directive or a component.
*
* Passing in a comma separated list of variable bindings will query for all of them.
*
* ```html
* <seeker>
* <div #find-me>...</div>
* <div #find-me-t... | random_line_split | |
di.d.ts | import { Type } from 'angular2/src/facade/lang';
import { DependencyMetadata } from 'angular2/src/core/di/metadata';
/**
* Specifies that a constant attribute value should be injected.
*
* The directive can inject constant string literals of host element attributes.
*
* ### Example
*
* Suppose we have a... | extends DependencyMetadata {
attributeName: string;
constructor(attributeName: string);
token: AttributeMetadata;
toString(): string;
}
/**
* Declares an injectable parameter to be a live list of directives or variable
* bindings from the content children of a directive.
*
* ### Example (... | AttributeMetadata | identifier_name |
type_channel.rs | //! Type channel.
//!
//! A type channel is a number that represents the number of channel a type is associated with. For
//! instance, most people people might already be used to RGB and RGBA colors. They can for instance
//! be encoded as 4D-floating numbers. Type channels encode such information.
use std::fmt;
use ... |
fn visit_u64<E>(self, x: u64) -> Result<Self::Value, E> where E: de::Error {
match x {
1 => Ok(TypeChan::One),
2 => Ok(TypeChan::Two),
3 => Ok(TypeChan::Three),
4 => Ok(TypeChan::Four),
x => Err(E::invalid_value(Unexpected::Unsigned(x as u64), &"1, 2, 3 ... | {
f.write_str("a valid type channel")
} | identifier_body |
type_channel.rs | //! Type channel.
//!
//! A type channel is a number that represents the number of channel a type is associated with. For
//! instance, most people people might already be used to RGB and RGBA colors. They can for instance
//! be encoded as 4D-floating numbers. Type channels encode such information.
use std::fmt;
use ... | (&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.write_str("a valid type channel")
}
fn visit_u64<E>(self, x: u64) -> Result<Self::Value, E> where E: de::Error {
match x {
1 => Ok(TypeChan::One),
2 => Ok(TypeChan::Two),
3 => Ok(TypeChan::Three),
... | expecting | identifier_name |
type_channel.rs | //! Type channel.
//!
//! A type channel is a number that represents the number of channel a type is associated with. For
//! instance, most people people might already be used to RGB and RGBA colors. They can for instance
//! be encoded as 4D-floating numbers. Type channels encode such information.
use std::fmt;
use ... | }
}
}
impl<'de> Deserialize<'de> for TypeChan {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de> {
struct V;
impl<'de> Visitor<'de> for V {
type Value = TypeChan;
fn expecting(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
... | TypeChan::One => serializer.serialize_u8(1),
TypeChan::Two => serializer.serialize_u8(2),
TypeChan::Three => serializer.serialize_u8(3),
TypeChan::Four => serializer.serialize_u8(4), | random_line_split |
test_config.py | # Copyright (c) 2011 Florian Mounier
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# 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... | xc = xcore.XCore()
f = confreader.Config.from_file(xc, os.path.join(tests_dir, "configs", "basic.py"))
# We just care that it has a default, we don't actually care what the
# default is; don't assert anything at all about the default in case
# someone changes it down the road.
assert hasattr(f,... |
def test_falls_back(): | random_line_split |
test_config.py | # Copyright (c) 2011 Florian Mounier
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# 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... | ():
def cmd(x):
return None
btn = config.EzClick('M-1', cmd)
assert btn.button == 'Button1'
assert btn.modifiers == [config.EzClick.modifier_keys['M']]
btn = config.EzDrag('A-2', cmd)
assert btn.button == 'Button2'
assert btn.modifiers == [config.EzClick.modifier_keys['A']]
| test_ezclick_ezdrag | identifier_name |
test_config.py | # Copyright (c) 2011 Florian Mounier
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# 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... |
def test_falls_back():
xc = xcore.XCore()
f = confreader.Config.from_file(xc, os.path.join(tests_dir, "configs", "basic.py"))
# We just care that it has a default, we don't actually care what the
# default is; don't assert anything at all about the default in case
# someone changes it down the r... | xc = xcore.XCore()
f = confreader.Config.from_file(xc, os.path.join(tests_dir, "configs", "basic.py"))
assert f.keys | identifier_body |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import logging
import os
import sys
import time # Needed fo... |
class Settings(BaseSettings):
def __init__(self, settings_module):
# update this dict from global settings (but only for ALL_CAPS settings)
for setting in dir(global_settings):
if setting == setting.upper():
setattr(self, setting, getattr(global_settings, setting))
... | if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'):
raise ImproperlyConfigured("If set, %s must end with a slash" % name)
elif name == "ALLOWED_INCLUDE_ROOTS" and isinstance(value, six.string_types):
raise ValueError("The ALLOWED_INCLUDE_ROOTS setting must be se... | identifier_body |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import logging
import os
import sys
import time # Needed fo... |
def __setattr__(self, name, value):
self._deleted.discard(name)
return super(UserSettingsHolder, self).__setattr__(name, value)
def __delattr__(self, name):
self._deleted.add(name)
return super(UserSettingsHolder, self).__delattr__(name)
def __dir__(self):
return l... | raise AttributeError
return getattr(self.default_settings, name) | random_line_split |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import logging
import os
import sys
import time # Needed fo... | (self, default_settings):
"""
Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).
"""
self.__dict__['_deleted'] = set()
self.default_settings = default_settings
def __getattr__(self, name):... | __init__ | identifier_name |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import logging
import os
import sys
import time # Needed fo... |
# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module
try:
mod = importlib.import_module(self.SETTINGS_MODULE)
except ImportError as e:
raise ImportError(
"Could not import settings '%s' (Is it on sys.pat... | setattr(self, setting, getattr(global_settings, setting)) | conditional_block |
ex41.py | """
********************************************************************************
Learn Python the Hard Way Third Edition, by
Zed A. Shaw
ISBN: 978-0321884916
********************************************************************************
"""
import random
from urllib import urlopen
import sys
#debug ... | (snippet, phrase):
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
other_names = random.sample(WORDS, snippet.count("***"))
results = []
param_names = []
for i in range(0, snippet.count("@@@")):
param_count = random.randint(1,3)
... | convert | identifier_name |
ex41.py | """
********************************************************************************
Learn Python the Hard Way Third Edition, by
Zed A. Shaw
ISBN: 978-0321884916
********************************************************************************
"""
import random
from urllib import urlopen
import sys
#debug ... |
#fake parameter lists
for word in param_names:
result = result.replace("@@@", word, 1)
results.append(result)
return results
# keep going until EOF
try:
while True:
snippets = PHRASES.keys()
#print debug + "3"
random.shuffle(snippets)
for... | class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
other_names = random.sample(WORDS, snippet.count("***"))
results = []
param_names = []
for i in range(0, snippet.count("@@@")):
param_count = random.randint(1,3)
param_names.append(', ... | identifier_body |
ex41.py | """
********************************************************************************
Learn Python the Hard Way Third Edition, by
Zed A. Shaw
ISBN: 978-0321884916
********************************************************************************
"""
import random
from urllib import urlopen
import sys
#debug ... |
#fake other names
for word in other_names:
result = result.replace("***", word, 1)
#fake parameter lists
for word in param_names:
result = result.replace("@@@", word, 1)
results.append(result)
return results
# keep going until EOF
try:
while ... | result = result.replace("%%%", word, 1) | conditional_block |
ex41.py | """
********************************************************************************
Learn Python the Hard Way Third Edition, by
Zed A. Shaw
ISBN: 978-0321884916
********************************************************************************
"""
import random
from urllib import urlopen
import sys
#debug ... | result = result.replace("@@@", word, 1)
results.append(result)
return results
# keep going until EOF
try:
while True:
snippets = PHRASES.keys()
#print debug + "3"
random.shuffle(snippets)
for snippet in snippets:
#print debug + "4"
... | for word in other_names:
result = result.replace("***", word, 1)
#fake parameter lists
for word in param_names: | random_line_split |
mod.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ma... | (&self) -> io::Result<TcpStream> {
self.accept().map(|res| res.0)
}
}
impl<F, T> TransportServer for F
where F: Fn() -> io::Result<T>, T: Transport {
type Transport = T;
fn accept(&self) -> io::Result<T> { self() }
}
| accept | identifier_name |
mod.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ma... | type Transport = TcpStream;
fn accept(&self) -> io::Result<TcpStream> {
self.accept().map(|res| res.0)
}
}
impl<F, T> TransportServer for F
where F: Fn() -> io::Result<T>, T: Transport {
type Transport = T;
fn accept(&self) -> io::Result<T> { self() }
} | random_line_split | |
mod.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ma... |
}
| { self() } | identifier_body |
saveAddress.ts | import { UpdateUserAddressMutationResponse } from "v2/__generated__/UpdateUserAddressMutation.graphql"
import { CreateUserAddressMutationResponse } from "v2/__generated__/CreateUserAddressMutation.graphql"
import { DeleteUserAddressMutationResponse } from "v2/__generated__/DeleteUserAddressMutation.graphql"
export con... | country: "US",
postalCode: "11111",
},
},
}
export const updateAddressSuccess: UpdateUserAddressMutationResponse = {
updateUserAddress: {
userAddressOrErrors: {
internalID: "address-id",
id: "graphql-id",
name: "Bob Ross",
addressLine1: "1 Main St",
addressLine2: "... | random_line_split | |
rpc-client.ts | "use strict"
import net = require("net")
import rpc = require("./rpc")
export class RpcClient {
connect(port:Number = 63342) {
var socket = net.connect({port: port}, function () {
console.log('Connected to IJ RPC server localhost:' + port)
});
var jsonRpc = new rpc.JsonRpc(new SocketTransport(soc... | } | } | random_line_split |
rpc-client.ts | "use strict"
import net = require("net")
import rpc = require("./rpc")
export class RpcClient {
connect(port:Number = 63342) {
var socket = net.connect({port: port}, function () {
console.log('Connected to IJ RPC server localhost:' + port)
});
var jsonRpc = new rpc.JsonRpc(new SocketTransport(soc... |
var totalBuffer:Buffer
if (this.buffers.length === 0) {
totalBuffer = buffer
}
else {
this.buffers.push(buffer)
totalBuffer = Buffer.concat(this.buffers, this.totalBufferLength)
this.buffers.length = 0
}
this.... | {
this.buffers.push(buffer)
return
} | conditional_block |
rpc-client.ts | "use strict"
import net = require("net")
import rpc = require("./rpc")
export class RpcClient {
| (port:Number = 63342) {
var socket = net.connect({port: port}, function () {
console.log('Connected to IJ RPC server localhost:' + port)
});
var jsonRpc = new rpc.JsonRpc(new SocketTransport(socket))
var decoder:MessageDecoder = new MessageDecoder(jsonRpc.messageReceived)
socket.on('data', de... | connect | identifier_name |
mk_regions.py | #!/usr/bin/env python
# File: mk_regions.py
# Created on: Sun May 27 21:56:23 2012
# Last Change: Tue May 29 16:13:20 2012
# Purpose of script: <+INSERT+>
# Author: Steven Boada
import sys
import os
import numpy as np
#def mk_regions(coords):
def mk_regions():
| f1 = open(coords.rstrip('txt') + 'reg', 'wt')
f1.writelines('# Region file formart: DS9 version 4.1\n')
f1.writelines('# Filename: ' + coords.rstrip('txt') + 'reg\n')
#f1.writelines('global color=green\n')
for i in range(len(d)):
f1.writelines... | for coords in os.listdir('.'):
if coords.endswith('.txt'):
d = np.loadtxt(coords, dtype=str) | random_line_split |
mk_regions.py | #!/usr/bin/env python
# File: mk_regions.py
# Created on: Sun May 27 21:56:23 2012
# Last Change: Tue May 29 16:13:20 2012
# Purpose of script: <+INSERT+>
# Author: Steven Boada
import sys
import os
import numpy as np
#def mk_regions(coords):
def | ():
for coords in os.listdir('.'):
if coords.endswith('.txt'):
d = np.loadtxt(coords, dtype=str)
f1 = open(coords.rstrip('txt') + 'reg', 'wt')
f1.writelines('# Region file formart: DS9 version 4.1\n')
f1.writelines('# Filename: ' + coords.rstrip('txt') + 'reg... | mk_regions | identifier_name |
mk_regions.py | #!/usr/bin/env python
# File: mk_regions.py
# Created on: Sun May 27 21:56:23 2012
# Last Change: Tue May 29 16:13:20 2012
# Purpose of script: <+INSERT+>
# Author: Steven Boada
import sys
import os
import numpy as np
#def mk_regions(coords):
def mk_regions():
|
if __name__ == '__main__':
#mk_regions(sys.argv[1])
mk_regions()
| for coords in os.listdir('.'):
if coords.endswith('.txt'):
d = np.loadtxt(coords, dtype=str)
f1 = open(coords.rstrip('txt') + 'reg', 'wt')
f1.writelines('# Region file formart: DS9 version 4.1\n')
f1.writelines('# Filename: ' + coords.rstrip('txt') + 'reg\n')
... | identifier_body |
mk_regions.py | #!/usr/bin/env python
# File: mk_regions.py
# Created on: Sun May 27 21:56:23 2012
# Last Change: Tue May 29 16:13:20 2012
# Purpose of script: <+INSERT+>
# Author: Steven Boada
import sys
import os
import numpy as np
#def mk_regions(coords):
def mk_regions():
for coords in os.listdir('.'):
if coords.en... | mk_regions() | conditional_block | |
models.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software 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 SOFTWA... | self, revision):
return revision.date
register_update_type(Revision)
def _proxy_property(name):
def _proxy(self):
return getattr(self.vcs_revision, name)
setattr(Revision, name, property(_proxy))
_proxy_property('short_id')
_proxy_property('author_email')
_proxy_property('author_name')... | ate( | identifier_name |
models.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies. | # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE... | #
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | random_line_split |
models.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software 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 SOFTWA... |
@classmethod
def project(self, revision):
return revision.project
@classmethod
def summary(self, revision):
return 'Revision %s' % revision.short_id
@classmethod
def descrip... | eturn revision.author_user
| identifier_body |
models.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software 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 SOFTWA... | return self._vcs_revision
class Update:
@classmethod
def user(self, revision):
return revision.author_user
@classmethod
def project(self, revision):
return revision.project
... | elf._vcs_revision = project_repository(self.project).revision(self.id)
| conditional_block |
forms.py | from django import forms
from django.forms import ModelForm
from models import *
from django.forms import Textarea
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group
class OgretimElemaniFormu(ModelForm):
parolasi=forms.CharField(label="Parolasi",
help_text='Paro... | instance.password=make_password(self.cleaned_data['parolasi'])
if commit:
instance.save()
if instance.group.filter(name='ogretimelemanlari'):
grp = Group.objects.get(name='ogretimelemanlari')
instance.group.add(grp)
return instance
class DersFormu(ModelForm):
class Meta:
model = Ders... | 'username','parolasi','email','telefonu')
def save(self,commit=True):
instance = super(OgretimElemaniFormu,self).save(commit=False)
if self.cleaned_data.get('parolasi'): | random_line_split |
forms.py | from django import forms
from django.forms import ModelForm
from models import *
from django.forms import Textarea
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group
class OgretimElemaniFormu(ModelForm):
parolasi=forms.CharField(label="Parolasi",
help_text='Paro... |
return instance
class DersFormu(ModelForm):
class Meta:
model = Ders
widgets = {
'tanimi':Textarea(attrs={'cols':35, 'rows':5}),
}
#class OgretimElemaniAltFormu(ModelForm):
# class Meta:
# model = OgretimElemani
# fields = ('username','parolasi','email')
#exclude=('unvani'... | instance.save()
if instance.group.filter(name='ogretimelemanlari'):
grp = Group.objects.get(name='ogretimelemanlari')
instance.group.add(grp) | conditional_block |
forms.py | from django import forms
from django.forms import ModelForm
from models import *
from django.forms import Textarea
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group
class OgretimElemaniFormu(ModelForm):
parolasi=forms.CharField(label="Parolasi",
help_text='Paro... |
class DersFormu(ModelForm):
class Meta:
model = Ders
widgets = {
'tanimi':Textarea(attrs={'cols':35, 'rows':5}),
}
#class OgretimElemaniAltFormu(ModelForm):
# class Meta:
# model = OgretimElemani
# fields = ('username','parolasi','email')
#exclude=('unvani','telefonu') bu da ayn... | instance = super(OgretimElemaniFormu,self).save(commit=False)
if self.cleaned_data.get('parolasi'):
instance.password=make_password(self.cleaned_data['parolasi'])
if commit:
instance.save()
if instance.group.filter(name='ogretimelemanlari'):
grp = Group.objects.get(name='ogretimelemanlari')
instanc... | identifier_body |
forms.py | from django import forms
from django.forms import ModelForm
from models import *
from django.forms import Textarea
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group
class | (ModelForm):
parolasi=forms.CharField(label="Parolasi",
help_text='Parola yazilmazsa onceki parola gecerlidir',
required=False)
class Meta:
model = OgretimElemani
fields = ('unvani','first_name','last_name',
'username','parolasi','email','telefonu')
def save(self,commit=True):
... | OgretimElemaniFormu | identifier_name |
location.rs | //! Fractal Global Location module
//!
//! This module holds the Fractal Global Address, and Geological location data type objects.
#[cfg(feature = "json-types")]
use rustc_serialize::json;
/// The particulars of the place where an organization or person resides
#[derive(PartialEq, Debug, Clone, RustcEncodable, Rustc... |
/// Returns the city
pub fn get_city(&self) -> &str {
&self.city
}
/// Returns the state
pub fn get_state(&self) -> &str {
&self.state
}
/// Returns the zip code
pub fn get_zip(&self) -> &str {
&self.zip
}
/// Returns the country
pub fn get_countr... | {
match self.address2 {
Some(ref addr2) => Some(addr2),
None => None,
}
} | identifier_body |
location.rs | //! Fractal Global Location module
//!
//! This module holds the Fractal Global Address, and Geological location data type objects.
#[cfg(feature = "json-types")]
use rustc_serialize::json;
/// The particulars of the place where an organization or person resides
#[derive(PartialEq, Debug, Clone, RustcEncodable, Rustc... | pub fn get_address1(&self) -> &str {
&self.address1
}
/// Returns address line 2
pub fn get_address2(&self) -> Option<&str> {
match self.address2 {
Some(ref addr2) => Some(addr2),
None => None,
}
}
/// Returns the city
pub fn get_city(&self) ... | }
}
/// Returns address line 1 | random_line_split |
location.rs | //! Fractal Global Location module
//!
//! This module holds the Fractal Global Address, and Geological location data type objects.
#[cfg(feature = "json-types")]
use rustc_serialize::json;
/// The particulars of the place where an organization or person resides
#[derive(PartialEq, Debug, Clone, RustcEncodable, Rustc... | (&self) -> &str {
&self.address1
}
/// Returns address line 2
pub fn get_address2(&self) -> Option<&str> {
match self.address2 {
Some(ref addr2) => Some(addr2),
None => None,
}
}
/// Returns the city
pub fn get_city(&self) -> &str {
&self... | get_address1 | identifier_name |
index.ts | Array<Column> {
span: boolean;
}
interface Line {
hidden?: boolean;
text: string;
span?: boolean;
}
interface Mixin {
stringWidth: Function;
stripAnsi: Function;
wrap: Function;
}
export class UI {
width: number;
wrap: boolean;
rows: ColumnArray[];
constructor (opts: UIOptions) {
this.wid... | (col: Column) {
const padding = col.padding || []
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
if (col.border) {
return minWidth + 4
}
| _minWidth | identifier_name |
index.ts | Array<Column> {
span: boolean;
}
interface Line {
hidden?: boolean;
text: string;
span?: boolean;
}
interface Mixin {
stringWidth: Function;
stripAnsi: Function;
wrap: Function;
}
export class UI {
width: number;
wrap: boolean;
rows: ColumnArray[];
constructor (opts: UIOptions) {
this.wid... |
if (ts.trim().length !== 0) {
return style
}
return ' '
}
return ''
}
// calculates the minimum width of
// a column, based on padding preferences.
function _minWidth (col: Column) {
const padding = col.padding || []
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
if ... | {
return ''
} | conditional_block |
index.ts | Array<Column> {
span: boolean;
}
interface Line {
hidden?: boolean;
text: string;
span?: boolean;
}
interface Mixin {
stringWidth: Function;
stripAnsi: Function;
wrap: Function;
}
export class UI {
width: number;
wrap: boolean;
rows: ColumnArray[];
constructor (opts: UIOptions) {
this.wid... | }
toString (): string {
const lines: Line[] = []
this.rows.forEach(row => {
this.rowToString(row, lines)
})
// don't display any lines with the
// hidden flag set.
return lines
.filter(line => !line.hidden)
.map(line => line.text)
.join('\n')
}
rowToString (ro... |
private measurePadding (str: string): number[] {
// measure padding without ansi escape codes
const noAnsi = mixin.stripAnsi(str)
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length] | random_line_split |
use-permissions.ts | import api from '@/api';
import { Permission } from '@directus/shared/types';
import { ref, Ref, watch } from 'vue';
type UsablePermissions = {
loading: Ref<boolean>;
error: Ref<null>;
permissions: Ref<Permission[] | null>;
fetchPermissions: () => Promise<void>;
savePermission: (updates: Partial<Permission>) => P... |
await fetchPermissions();
} catch (err: any) {
error.value = err;
}
}
}
| {
await api.patch(`/permissions`, update);
} | conditional_block |
use-permissions.ts | import api from '@/api';
import { Permission } from '@directus/shared/types';
import { ref, Ref, watch } from 'vue';
type UsablePermissions = {
loading: Ref<boolean>;
error: Ref<null>;
permissions: Ref<Permission[] | null>;
fetchPermissions: () => Promise<void>;
savePermission: (updates: Partial<Permission>) => P... | (updates: Partial<Permission>) {
try {
if (updates.id !== undefined) {
await api.patch(`/permissions/${updates.id}`, {
...updates,
});
} else {
await api.post(`/permissions`, updates);
}
await fetchPermissions();
} catch (err: any) {
error.value = err;
}
}
async function saveAl... | savePermission | identifier_name |
use-permissions.ts | import api from '@/api';
import { Permission } from '@directus/shared/types';
import { ref, Ref, watch } from 'vue';
type UsablePermissions = {
loading: Ref<boolean>;
error: Ref<null>;
permissions: Ref<Permission[] | null>;
fetchPermissions: () => Promise<void>;
savePermission: (updates: Partial<Permission>) => P... |
async function savePermission(updates: Partial<Permission>) {
try {
if (updates.id !== undefined) {
await api.patch(`/permissions/${updates.id}`, {
...updates,
});
} else {
await api.post(`/permissions`, updates);
}
await fetchPermissions();
} catch (err: any) {
error.value = err... | {
loading.value = true;
try {
const response = await api.get(`/permissions`, {
params: {
'filter[role][_eq]': role.value,
},
});
permissions.value = response.data.data;
} catch (err: any) {
error.value = err;
} finally {
loading.value = false;
}
} | identifier_body |
use-permissions.ts | import api from '@/api';
import { Permission } from '@directus/shared/types';
import { ref, Ref, watch } from 'vue';
type UsablePermissions = {
loading: Ref<boolean>;
error: Ref<null>;
permissions: Ref<Permission[] | null>;
fetchPermissions: () => Promise<void>;
savePermission: (updates: Partial<Permission>) => P... |
return { loading, error, permissions, fetchPermissions, savePermission, saveAll };
function reset() {
loading.value = false;
error.value = null;
permissions.value = null;
}
async function fetchPermissions() {
loading.value = true;
try {
const response = await api.get(`/permissions`, {
params: {... | fetchPermissions();
}
}); | random_line_split |
add-ebook.component.ts | import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { LearnService } from '../../services/learn.service';
import { AuthService } from '../../services/auth.service';
import { MainService ... |
}
| {
this.serverAddress = this.mainService.getServerAddress();
this.activatedRoute.queryParams.subscribe((params: Params) => {
this.subtopic = params['subtopic'];
this.topic = params['topic'];
});
} | identifier_body |
add-ebook.component.ts | import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { LearnService } from '../../services/learn.service';
import { AuthService } from '../../services/auth.service';
import { MainService ... |
@Component({
selector: 'app-add-ebook',
templateUrl: './add-ebook.component.html',
styleUrls: ['./add-ebook.component.css']
})
export class AddEbookComponent implements OnInit {
subtopic: String;
topic: String;
name: String;
description: String;
serverAddress: String;
constructor(
private route... | random_line_split | |
add-ebook.component.ts | import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { LearnService } from '../../services/learn.service';
import { AuthService } from '../../services/auth.service';
import { MainService ... | (
private router: Router,
private activatedRoute: ActivatedRoute,
private flashMessagesService: FlashMessagesService,
private learnService: LearnService,
private authService: AuthService,
private mainService: MainService,
) { }
ngOnInit() {
this.serverAddress = this.mainService.getServe... | constructor | identifier_name |
subscriber.py | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('project', help='Your Google Cloud project ID')
subparsers = parser.add_subparsers(dest='command')
list_parser = subparsers... | """Receives messages from a pull subscription with flow control."""
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(
project, subscription_name)
def callback(message):
print('Received message: {}'.format(message))
message.ack()
# Limit... | identifier_body |
subscriber.py | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
def create_subscription(project, topic_name, subscription_name):
"""Create a new pull subscription on the given topic."""
subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path(project, topic_name)
subscription_path = subscriber.subscription_path(
project, subscription_n... | print(subscription.name) | conditional_block |
subscriber.py | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
def delete_subscription(project, subscription_name):
"""Deletes an existing Pub/Sub topic."""
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(
project, subscription_name)
subscriber.delete_subscription(subscription_path)
print('Subscription dele... | subscription_path, topic_path)
print('Subscription created: {}'.format(subscription)) | random_line_split |
subscriber.py | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | (project, topic_name, subscription_name):
"""Create a new pull subscription on the given topic."""
subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path(project, topic_name)
subscription_path = subscriber.subscription_path(
project, subscription_name)
subscription = s... | create_subscription | identifier_name |
UseLoadView.ts | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; withou... | import usePluginEntities from '../usePluginEntities';
const useLoadView = (view: Promise<View>, query: { [key: string]: any }) => {
const loadingViewHooks: Array<ViewHook> = usePluginEntities('views.hooks.loadingView');
const executingViewHooks: Array<ViewHook> = usePluginEntities('views.hooks.executingView');
... | import type { ViewHook } from '../hooks/ViewHook'; | random_line_split |
UseLoadView.ts | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; withou... |
setHookComponent(e);
});
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[executingViewHooks, loadingViewHooks, view]);
return [loaded, hookComponent];
};
export default useLoadView;
| {
throw e;
} | conditional_block |
test_phishing.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2017 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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/... |
self.assertTrue(flag)
def test_check_phishing(self):
results = phishing.check_phishing(
email=self.email,
attachments=self.attachments,
urls_body=self.urls,
urls_attachments=self.urls,
target_keys=self.targets,
subject_keys=s... | flag = True | conditional_block |
test_phishing.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2017 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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/... | self.email = parser.mail
self.attachments = parser.attachments
parser = mailparser.parse_from_file(mail_form)
self.email_form = parser.mail
body = self.email_form.get("body")
self.urls = utils.urls_extractor(body, self.faup)
d = {"generic": "conf/keywords/targe... | faup = Faup()
def setUp(self):
parser = mailparser.parse_from_file(mail_thug) | random_line_split |
test_phishing.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2017 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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/... | (self):
body = self.email_form.get("body")
flag_form = phishing.check_form(body)
self.assertTrue(flag_form)
body = self.email.get("body")
flag_form = phishing.check_form(body)
self.assertFalse(flag_form)
def test_form_value_error(self):
parser = mailparser.p... | test_check_form | identifier_name |
test_phishing.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2017 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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/... |
def test_check_phishing_form(self):
results = phishing.check_phishing(
email=self.email_form,
attachments=self.attachments,
urls_body=self.urls,
urls_attachments=self.urls,
target_keys=self.targets,
subject_keys=self.subjects)
... | results = phishing.check_phishing(
email=self.email,
attachments=self.attachments,
urls_body=self.urls,
urls_attachments=self.urls,
target_keys=self.targets,
subject_keys=self.subjects)
self.assertIsInstance(results, dict)
self.ass... | identifier_body |
LoaderHooks.js | // Copyright 2013 Traceur 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 ... | (normalizedName, module) {
this.moduleStore_.set(normalizedName, module);
}
normalize(name, referrerName, referrerAddress) {
var normalizedName =
this.moduleStore_.normalize(name, referrerName, referrerAddress);
if (System.map)
return systemjs.applyMap(System.map, normalizedName, referrer... | set | identifier_name |
LoaderHooks.js | // Copyright 2013 Traceur 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 ... | if (baseURL) {
load.metadata.baseURL = baseURL;
return resolveUrl(baseURL, asJS);
}
return asJS;
}
nameTrace(load) {
var trace = '';
if (load.metadata.locateMap) {
trace += this.locateMapTrace(load);
}
var base = load.metadata.baseURL || this.baseURL;
if (base) {
... | return asJS;
var baseURL = load.metadata && load.metadata.baseURL;
baseURL = baseURL || this.baseURL; | random_line_split |
LoaderHooks.js | // Copyright 2013 Traceur 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 ... |
analyzeDependencies(dependencies, loader) {
var deps = []; // metadata for each dependency
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
// We should not have gotten here if not all are PARSED or larget.
assert(codeUnit.state >= PARSED);
if (codeU... | {
// Source for modules compile into calls to registerModule(url, fnc).
//
// TODO(arv): Eval in the right context.
var result = ('global', eval)(codeUnit.metadata.transcoded);
codeUnit.metadata.transformedTree = null;
return result;
} | identifier_body |
LoaderHooks.js | // Copyright 2013 Traceur 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 ... |
this.exportListBuilder_.buildExportList(deps, loader);
}
get options() {
return options;
}
bundledModule(name) {
return this.moduleStore_.bundleStore[name];
}
}
| {
var codeUnit = dependencies[i];
// We should not have gotten here if not all are PARSED or larget.
assert(codeUnit.state >= PARSED);
if (codeUnit.state == PARSED) {
deps.push(codeUnit.metadata);
}
} | conditional_block |
improc.py | cv2
import numpy as np
def pad_image(im, width, height, border=255):
"""pad char image in a larger image"""
xoff = abs(int((im.shape[1] - width) / 2))
yoff = abs(int((im.shape[0] - height) / 2))
if width >= im.shape[1]:
x_min_old = 0
x_max_old = im.shape[1]
x_min_new = xoff
... |
def column_ex(gray):
"""experimental feature - something like the center of mass of
overlapping columns of the image"""
width = 2
# mul_mat = np.arange(y_size)[:, np.newaxis]
# for some reason, it works a lot better to not divide by the sum of the
# whole window but only the first column.
... | """perform multiple levels of max pooling and unravel
to create a feature vector"""
# TODO: move this to a higher level
# image_gray = _grayscale(image)
if 1 in ns:
res = [image]
else:
res = []
for n in range(2, max(ns) + 1):
image = max_pool(image)
if n in ns:
... | identifier_body |
improc.py | cv2
import numpy as np
def pad_image(im, width, height, border=255):
"""pad char image in a larger image"""
xoff = abs(int((im.shape[1] - width) / 2))
yoff = abs(int((im.shape[0] - height) / 2))
if width >= im.shape[1]:
x_min_old = 0
x_max_old = im.shape[1]
x_min_new = xoff
... |
else:
y_shift = 0.0
tmat = np.float32(
[[1, 0, x_shift],
[0, 1, y_shift]])
new_image = cv2.warpAffine(
image, tmat, (image.shape[1], image.shape[0]), borderValue=(255, 255, 255))
# cv2.imshow("image", image)
# cv2.imshow("new_image", new_image)
# cv2.waitKey()... | y_size = image.shape[0]
y_mean = np.sum(np.sum(gray, axis=1) * np.arange(y_size)) / np.sum(gray)
y_shift = y_size / 2.0 - y_mean | conditional_block |
improc.py | cv2
import numpy as np
def pad_image(im, width, height, border=255):
"""pad char image in a larger image"""
xoff = abs(int((im.shape[1] - width) / 2))
yoff = abs(int((im.shape[0] - height) / 2))
if width >= im.shape[1]:
x_min_old = 0
x_max_old = im.shape[1]
x_min_new = xoff
... | """perform 2x2 max pooling"""
return np.max(
np.stack(
(im[0::2, 0::2],
im[0::2, 1::2],
im[1::2, 0::2],
im[1::2, 1::2]),
axis=-1),
axis=-1)
def max_pool_multi(image, ns):
"""perform multiple levels of max pooling and unravel
... |
def max_pool(im): | random_line_split |
improc.py | 2
import numpy as np
def pad_image(im, width, height, border=255):
"""pad char image in a larger image"""
xoff = abs(int((im.shape[1] - width) / 2))
yoff = abs(int((im.shape[0] - height) / 2))
if width >= im.shape[1]:
x_min_old = 0
x_max_old = im.shape[1]
x_min_new = xoff
... | (image):
"""convert RGB ubyte image to grayscale"""
return np.sum(image, axis=2) / 3.0
def downsample(image, scale_factor):
"""downsample an image and unravel to create a feature vector"""
feats = cv2.resize(
image,
(int(image.shape[0] * scale_factor),
int(image.shape[1] * sc... | grayscale | identifier_name |
rustc.rs | use std::path::Path;
use util::{self, CargoResult, internal, ChainError};
pub struct Rustc {
pub verbose_version: String,
pub host: String,
pub cap_lints: bool,
}
impl Rustc {
/// Run the compiler at `path` to learn varioues pieces of information about
/// it.
///
/// If successful this f... | () -> Rustc {
Rustc {
verbose_version: String::new(),
host: String::new(),
cap_lints: false,
}
}
}
| blank | identifier_name |
rustc.rs | use std::path::Path;
use util::{self, CargoResult, internal, ChainError};
pub struct Rustc {
pub verbose_version: String,
pub host: String,
pub cap_lints: bool,
}
impl Rustc {
/// Run the compiler at `path` to learn varioues pieces of information about
/// it.
///
/// If successful this f... | cmd.arg("-vV");
let mut ret = Rustc::blank();
let mut first = cmd.clone();
first.arg("--cap-lints").arg("allow");
let output = match first.exec_with_output() {
Ok(output) => { ret.cap_lints = true; output }
Err(..) => try!(cmd.exec_with_output()),
... | random_line_split | |
cell.rs | had not let the previous borrow
//! // of the cache fall out of scope then the subsequent
//! // recursive borrow would cause a dynamic task panic.
//! // This is the major hazard of using `RefCell`.
//! self.minimum_spanning_tree()
//! }
//! # fn calc_span_tree(&self) -> Vec<(uin... | /// Panics if the value is currently mutably borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let borrowed_five = c.borrow();
/// let borrowed_five2 = c.borrow();
/// ```
///
/// An example of panic:
... | /// | random_line_split |
cell.rs | /// ```
/// use std::cell::RefCell;
/// use std::thread::Thread;
///
/// let result = Thread::scoped(move || {
/// let c = RefCell::new(5);
/// let m = c.borrow_mut();
///
/// let b = c.borrow_mut(); // this causes a panic
/// }).join();
///
/// assert!(result.is... | get | identifier_name | |
cell.rs | () = value;
}
}
/// Get a reference to the underlying `UnsafeCell`.
///
/// # Unsafety
///
/// This function is `unsafe` because `UnsafeCell`'s field is public.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
... | {
&self.value
} | identifier_body | |
config.rs | //! Defines configuration file format.
use anyhow::{anyhow, Result};
use glob::Pattern;
use lazy_static::lazy_static;
use serde::Deserialize;
use std::{
fs,
io::Read,
ops::{Deref, DerefMut},
path::{Path, PathBuf},
};
lazy_static! {
static ref CONFIG_PATH: PathBuf = dirs::config_dir()
.map(... | (raw: RawConfigData) -> Result<Self> {
let root_dir = raw.root.as_deref().unwrap_or("~/rhq");
let root_dir = crate::util::make_path_buf(root_dir)?;
let include_dirs = raw
.includes
.as_deref()
.unwrap_or(&[])
.iter()
.filter_map(|root|... | from_raw | identifier_name |
config.rs | //! Defines configuration file format.
use anyhow::{anyhow, Result};
use glob::Pattern;
use lazy_static::lazy_static;
use serde::Deserialize;
use std::{
fs,
io::Read,
ops::{Deref, DerefMut}, | };
lazy_static! {
static ref CONFIG_PATH: PathBuf = dirs::config_dir()
.map(|config_path| config_path.join("rhq/config.toml"))
.expect("failed to determine the configuration path");
}
/// configuration load from config files
#[derive(Deserialize)]
struct RawConfigData {
root: Option<String>,
... | path::{Path, PathBuf}, | random_line_split |
config.rs | //! Defines configuration file format.
use anyhow::{anyhow, Result};
use glob::Pattern;
use lazy_static::lazy_static;
use serde::Deserialize;
use std::{
fs,
io::Read,
ops::{Deref, DerefMut},
path::{Path, PathBuf},
};
lazy_static! {
static ref CONFIG_PATH: PathBuf = dirs::config_dir()
.map(... |
}
| {
&mut self.data
} | identifier_body |
config.rs | //! Defines configuration file format.
use anyhow::{anyhow, Result};
use glob::Pattern;
use lazy_static::lazy_static;
use serde::Deserialize;
use std::{
fs,
io::Read,
ops::{Deref, DerefMut},
path::{Path, PathBuf},
};
lazy_static! {
static ref CONFIG_PATH: PathBuf = dirs::config_dir()
.map(... |
let mut content = String::new();
fs::File::open(config_path)?.read_to_string(&mut content)?;
let data = ::toml::from_str(&content)?;
Ok(Config {
path: config_path.into(),
data: ConfigData::from_raw(data)?,
})
}
pub fn cache_dir(&self) -> PathBu... | {
return Err(anyhow!(
"Failed to load configuration file (config_path = {})",
config_path.display()
));
} | conditional_block |
CTMC.py | """Code for constructing CTMCs and computing transition probabilities
in them."""
from numpy import zeros
from scipy import matrix
from scipy.linalg import expm
class CTMC(object):
"""Class representing the CTMC for the back-in-time coalescent."""
def | (self, state_space, rates_table):
"""Create the CTMC based on a state space and a mapping
from transition labels to rates.
:param state_space: The state space the CTMC is over.
:type state_space: IMCoalHMM.CoalSystem
:param rates_table: A table where transition rates can
... | __init__ | identifier_name |
CTMC.py | """Code for constructing CTMCs and computing transition probabilities
in them."""
from numpy import zeros
from scipy import matrix
from scipy.linalg import expm
class CTMC(object):
"""Class representing the CTMC for the back-in-time coalescent."""
def __init__(self, state_space, rates_table):
"""Cre... | :param delta_t: The time period the CTMC should run for.
:type delta_t: float
:returns: The probability transition matrix
:rtype: matrix
"""
if not delta_t in self.prob_matrix_cache:
self.prob_matrix_cache[delta_t] = expm(self.rate_matrix * delta_t)
r... | def probability_matrix(self, delta_t):
"""Computes the transition probability matrix for a
time period of delta_t.
| random_line_split |
CTMC.py | """Code for constructing CTMCs and computing transition probabilities
in them."""
from numpy import zeros
from scipy import matrix
from scipy.linalg import expm
class CTMC(object):
"""Class representing the CTMC for the back-in-time coalescent."""
def __init__(self, state_space, rates_table):
"""Cre... |
# We cache the CTMCs because in the optimisations, especially the models with a large number
# of parameters, we are creating the same CTMCs again and again and computing the probability
# transition matrices is where we spend most of the time.
from cache import Cache
CTMC_CACHE = Cache()
def make_ctmc(state_space... | """Computes the transition probability matrix for a
time period of delta_t.
:param delta_t: The time period the CTMC should run for.
:type delta_t: float
:returns: The probability transition matrix
:rtype: matrix
"""
if not delta_t in self.prob_matrix_cache:
... | identifier_body |
CTMC.py | """Code for constructing CTMCs and computing transition probabilities
in them."""
from numpy import zeros
from scipy import matrix
from scipy.linalg import expm
class CTMC(object):
"""Class representing the CTMC for the back-in-time coalescent."""
def __init__(self, state_space, rates_table):
"""Cre... |
for i in xrange(len(state_space.states)):
self.rate_matrix[i, i] = - self.rate_matrix[i, :].sum()
self.prob_matrix_cache = dict()
def probability_matrix(self, delta_t):
"""Computes the transition probability matrix for a
time period of delta_t.
:param delta_t... | self.rate_matrix[src, dst] = rates_table[trans] | conditional_block |
opcode.rs | enum_from_primitive! {
#[derive(Debug)]
pub enum Opcode {
Special = 0b000000,
RegImm = 0b000001,
Addi = 0b001000,
Addiu = 0b001001,
Andi = 0b001100,
Ori = 0b001101,
Lui = 0b001111,
Mtc0 = 0b010000,
Beq = 0b000100... |
enum_from_primitive! {
#[derive(Debug)]
pub enum SpecialOpcode {
Sll = 0b000000,
Srl = 0b000010,
Sllv = 0b000100,
Srlv = 0b000110,
Jr = 0b001000,
Multu = 0b011001,
Mfhi = 0b010000,
Mflo = 0b010010,
Addu = 0b100001,
... | random_line_split | |
StyleButton.tsx | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {gettext} from 'core/utils';
const StyleIcons = {
bold: 'icon-bold',
italic: 'icon-italic',
underline: 'icon-underline',
strikethrough: 'icon-strikethrough',
h1: 'icon-heading-1',
h2: 'ico... |
render() {
const {active, label} = this.props;
const iconClass = StyleIcons[label];
const cx = classNames({
'Editor3-styleButton': true,
'Editor3-activeButton': active,
});
const styleTooltips = {
bold: gettext('Bold (Ctrl+B)'),
... | {
e.preventDefault();
this.props.onToggle(this.props.style, this.props.active);
} | identifier_body |
StyleButton.tsx | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {gettext} from 'core/utils';
const StyleIcons = {
bold: 'icon-bold',
italic: 'icon-italic',
underline: 'icon-underline',
strikethrough: 'icon-strikethrough',
h1: 'icon-heading-1',
h2: 'ico... | }; | random_line_split | |
StyleButton.tsx | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {gettext} from 'core/utils';
const StyleIcons = {
bold: 'icon-bold',
italic: 'icon-italic',
underline: 'icon-underline',
strikethrough: 'icon-strikethrough',
h1: 'icon-heading-1',
h2: 'ico... | (e) {
e.preventDefault();
this.props.onToggle(this.props.style, this.props.active);
}
render() {
const {active, label} = this.props;
const iconClass = StyleIcons[label];
const cx = classNames({
'Editor3-styleButton': true,
'Editor3-activeButton':... | onToggle | identifier_name |
included_file.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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 Free Software Foundation, either version 3 of the License, or
# (at your option) an... | (host):
if host.name in inventory._hosts_cache:
return inventory._hosts_cache[host.name]
else:
return inventory.get_host(host.name)
for res in results:
original_host = res._host
original_task = res._task
if original_t... | get_original_host | identifier_name |
included_file.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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 Free Software Foundation, either version 3 of the License, or
# (at your option) an... |
def __eq__(self, other):
return other._filename == self._filename and other._args == self._args
def __repr__(self):
return "%s (%s): %s" % (self._filename, self._args, self._hosts)
@staticmethod
def process_include_results(results, tqm, iterator, inventory, loader, variable_manager):... | if host not in self._hosts:
self._hosts.append(host) | identifier_body |
included_file.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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 Free Software Foundation, either version 3 of the License, or
# (at your option) an... | include_results = [res._result]
for include_result in include_results:
# if the task result was skipped or failed, continue
if 'skipped' in include_result and include_result['skipped'] or 'failed' in include_result:
con... | if original_task.loop:
if 'results' not in res._result:
continue
include_results = res._result['results']
else: | random_line_split |
included_file.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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 Free Software Foundation, either version 3 of the License, or
# (at your option) an... |
else:
parent_include = parent_include._parent
if include_file is None:
if original_task._role:
include_target = templar.template(include_result['include'])
... | break | conditional_block |
Measure.js | (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptB, ptD, ptC, vTemp, vTemp2, plane), pt) >= 0)) return false;
var d = JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptA, ptB, ptC, vTemp, vTemp2, plane), pt);
if (fullyEnclosed) return (b == (d >= 0));
var d1 = JU.Measure.distanceToPlan... | {
ptAnew.sub2 (ptsA[i], cA);
q.transform2 (ptAnew, ptAnew).add (cB);
sum2 += ptAnew.distanceSquared (ptsB[i]);
} | conditional_block | |
Measure.js | c$.computeTorsion = Clazz.defineMethod (c$, "computeTorsion",
function (p1, p2, p3, p4, asDegrees) {
var ijx = p1.x - p2.x;
var ijy = p1.y - p2.y;
var ijz = p1.z - p2.z;
var kjx = p3.x - p2.x;
var kjy = p3.y - p2.y;
var kjz = p3.z - p2.z;
var klx = p3.x - p4.x;
var kly = p3.y - p4.y;
var klz = p3.z - p4.z;
... | random_line_split | ||
processCss.js | const CSSFlatError = require('./error')
const postcss = require('postcss')
const _ = require('lodash')
const cssnano = require('cssnano')
const getSelectorName = require('./getSelectorName')
const getSelectorType = require('./getSelectorType')
const cacheLocalRuleInfo = {}
const parserPlugin = postcss.plugin('postcss-... | atRules = [],
htmlClass = 'css-flat',
plugins = [],
sourceMap,
} = options.params || {}
const atRulesConfig = {}
atRules.forEach((atRule, i) => {
for (let key in atRule) {
const value = atRule[key]
atRulesConfig[key.replace(/ /g, '')] = {
... | random_line_split | |
processCss.js | const CSSFlatError = require('./error')
const postcss = require('postcss')
const _ = require('lodash')
const cssnano = require('cssnano')
const getSelectorName = require('./getSelectorName')
const getSelectorType = require('./getSelectorType')
const cacheLocalRuleInfo = {}
const parserPlugin = postcss.plugin('postcss-... |
rule.selector.split(',').forEach((sel) => {
const selectorType = getSelectorType(sel, localsMap)
const { isGlobal, isClassSelector, selectorHalf = '' } = selectorType
if (isGlobal) {
const globalSel = _.trim(sel)
const... | {
parentName = rule.parent.name
if (parentName === 'supports' || parentName === 'media') {
parentParams = rule.parent.params
} else {
return
}
} | conditional_block |
git-tab-item.js | import React from 'react';
import PropTypes from 'prop-types';
import RefHolder from '../models/ref-holder';
import GitTabContainer from '../containers/git-tab-container';
export default class GitTabItem extends React.Component {
static propTypes = {
repository: PropTypes.object.isRequired,
}
static uriPat... | () {
return this.props.repository.getWorkingDirectoryPath();
}
// Forwarded to the controller instance when one is present
rememberLastFocus(...args) {
return this.refController.map(c => c.rememberLastFocus(...args));
}
restoreFocus(...args) {
return this.refController.map(c => c.restoreFocus(.... | getWorkingDirectory | identifier_name |
git-tab-item.js | import React from 'react';
import PropTypes from 'prop-types';
import RefHolder from '../models/ref-holder';
import GitTabContainer from '../containers/git-tab-container';
export default class GitTabItem extends React.Component {
static propTypes = {
repository: PropTypes.object.isRequired,
}
static uriPat... |
focus() {
return this.refController.map(c => c.restoreFocus());
}
focusAndSelectStagingItem(...args) {
return this.refController.map(c => c.focusAndSelectStagingItem(...args));
}
focusAndSelectCommitPreviewButton() {
return this.refController.map(c => c.focusAndSelectCommitPreviewButton());
... | {
return this.refController.map(c => c.hasFocus(...args));
} | identifier_body |
git-tab-item.js | import React from 'react';
import PropTypes from 'prop-types';
import RefHolder from '../models/ref-holder';
import GitTabContainer from '../containers/git-tab-container';
export default class GitTabItem extends React.Component {
static propTypes = {
repository: PropTypes.object.isRequired,
}
static uriPat... | }
focus() {
return this.refController.map(c => c.restoreFocus());
}
focusAndSelectStagingItem(...args) {
return this.refController.map(c => c.focusAndSelectStagingItem(...args));
}
focusAndSelectCommitPreviewButton() {
return this.refController.map(c => c.focusAndSelectCommitPreviewButton());... | random_line_split | |
sync.rs | #![crate_name = "sync"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alexander Fomin <xander.fomin@ya.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Last synced with: sync (GNU coreutils) 8.13 */
exte... | (name: &str) {
let name_buffer = name.to_c_str().as_ptr();
if 0x00000003 == GetDriveTypeA(name_buffer) { // DRIVE_FIXED
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
let sliced_name_buffer = sliced_name.to_c_str().as_ptr();
match CreateFil... | flush_volume | identifier_name |
sync.rs | #![crate_name = "sync"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alexander Fomin <xander.fomin@ya.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Last synced with: sync (GNU coreutils) 8.13 */
exte... |
}
}
#[allow(unused_unsafe)]
unsafe fn find_all_volumes() -> Vec<String> {
match find_first_volume() {
(first_volume, next_volume_handle) => {
let mut volumes = vec![first_volume];
loop {
let mut name: [libc::c_char; 260] = mem... | {
(string::raw::from_buf(name.as_ptr() as *const u8), handle)
} | conditional_block |
sync.rs | #![crate_name = "sync"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alexander Fomin <xander.fomin@ya.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Last synced with: sync (GNU coreutils) 8.13 */
exte... | unsafe fn flush_volume(name: &str) {
let name_buffer = name.to_c_str().as_ptr();
if 0x00000003 == GetDriveTypeA(name_buffer) { // DRIVE_FIXED
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
let sliced_name_buffer = sliced_name.to_c_str().as_ptr();
... |
#[allow(unused_unsafe)] | random_line_split |
sync.rs | #![crate_name = "sync"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alexander Fomin <xander.fomin@ya.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Last synced with: sync (GNU coreutils) 8.13 */
exte... |
#[allow(unused_unsafe)]
unsafe fn find_all_volumes() -> Vec<String> {
match find_first_volume() {
(first_volume, next_volume_handle) => {
let mut volumes = vec![first_volume];
loop {
let mut name: [libc::c_char; 260] = mem::uninitialized(... | {
let mut name: [libc::c_char; 260] = mem::uninitialized(); // MAX_PATH
match FindFirstVolumeA(name.as_mut_ptr(),
name.len() as libc::uint32_t) {
-1 => { // INVALID_HANDLE_VALUE
crash!(GetLastError(), "failed to find first volume");
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.