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 |
|---|---|---|---|---|
4chan.py | import re
import json
import requests
from util import irc
from util.handler_utils import cmdhook, authenticate, get_target
from qtbot3_common.types.message import Message
def scrape(board: str, filtertext: str):
try:
data = requests.get("http://boards.4chan.org/{board}/catalog".format(board=board)).tex... | board = match['board']
filtertext = match['filtertext']
print("searching 4chan's {board} board for {filtertext}...".format(**match))
baseurl = "http://boards.4chan.org/{board}/thread/{number}/{semantic_url}"
lines = []
for number, thread in scrape(board, filtertext):
title = (thread['sub']... | identifier_body | |
4chan.py | import re
import json
import requests
from util import irc
from util.handler_utils import cmdhook, authenticate, get_target
from qtbot3_common.types.message import Message | match = re.match(".*var catalog = (?P<catalog>\{.*\});.*", data)
if not match:
print("Couldn't scrape catalog")
catalog = json.loads(match.group('catalog'))
for number, thread in catalog['threads'].items():
sub, teaser = thread['sub'], thread['teaser']
... |
def scrape(board: str, filtertext: str):
try:
data = requests.get("http://boards.4chan.org/{board}/catalog".format(board=board)).text | random_line_split |
4chan.py | import re
import json
import requests
from util import irc
from util.handler_utils import cmdhook, authenticate, get_target
from qtbot3_common.types.message import Message
def scrape(board: str, filtertext: str):
try:
data = requests.get("http://boards.4chan.org/{board}/catalog".format(board=board)).tex... |
except Exception as ex:
print("scraping exception:", ex)
@cmdhook('4chan (?P<board>[^\s]+) (?P<filtertext>.+)')
@authenticate
def handle_scrape(message: Message, match, nick: str):
board = match['board']
filtertext = match['filtertext']
print("searching 4chan's {board} board for {filtertext... | yield(number, thread) | conditional_block |
08 Enter Webpack.js | /* Create a static build with webpack
Thus far, we've been running all of our code with Node.js. Now Redux does work, and can be used on the server or in
native applications built with Node.js.
However, Redux is primarily used to manage state and client applications. So at this point, we're going to start running
o... |
* babel-loader and json-loader
The first loader that I want to install is the babel loader. This is the loader used by babel to transpile our ES6 and
other emerging Javascript syntax into ES5 compatible Javascript. Additionally we want to make sure any JSON documents
make it inside of our bundle. I'm going to need ... | Now, with web pack, we need to use loaders. Loaders are the instructions that web pack follows when transpiling our code and | random_line_split |
cii_atom_hashing_distribution.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# 2017-01-12T12:23:35+08:00
# C Interfaces and Implementations
# Exercise 3.1
import os
import os.path
import sys
import cppimport
import matplotlib.pyplot as plt
same_dir = lambda entry: os.path.join(os.path.dirname(__file__), entry)
sys.path.append(os.getcwd())
... | ():
#bucket_sizes = 2048, 2039
bucket_sizes = (2039, )
fig = plt.figure("Atom string hashing distribution")
for plot_number, size in enumerate(bucket_sizes):
m = cppimport.imp('cii_atom_cppimport')
with open(same_dir('wordlist'), encoding='utf-8') as f:
for word in f:
... | bucket_size_benchmark | identifier_name |
cii_atom_hashing_distribution.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# 2017-01-12T12:23:35+08:00
# C Interfaces and Implementations
# Exercise 3.1
import os
import os.path
import sys
import cppimport
import matplotlib.pyplot as plt
same_dir = lambda entry: os.path.join(os.path.dirname(__file__), entry)
sys.path.append(os.getcwd())
... |
# References:
# [GitHub: pybind/python_example](https://github.com/pybind/python_example)
# Matplotlib documentation
#
# Download a file over HTTP:
# [How do I download a file over HTTP using Python?](http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python)
# https://github.com/Host... | if not os.path.isfile(same_dir('wordlist')):
urllib.request.urlretrieve('http://www-personal.umich.edu/~jlawler/wordlist', same_dir('wordlist'))
bucket_size_benchmark() | conditional_block |
cii_atom_hashing_distribution.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# 2017-01-12T12:23:35+08:00
# C Interfaces and Implementations
# Exercise 3.1
import os
import os.path
import sys
import cppimport
import matplotlib.pyplot as plt
same_dir = lambda entry: os.path.join(os.path.dirname(__file__), entry)
sys.path.append(os.getcwd())
... |
if __name__ == '__main__':
if not os.path.isfile(same_dir('wordlist')):
urllib.request.urlretrieve('http://www-personal.umich.edu/~jlawler/wordlist', same_dir('wordlist'))
bucket_size_benchmark()
# References:
# [GitHub: pybind/python_example](https://github.com/pybind/python_example)
# Matplo... | bucket_sizes = (2039, )
fig = plt.figure("Atom string hashing distribution")
for plot_number, size in enumerate(bucket_sizes):
m = cppimport.imp('cii_atom_cppimport')
with open(same_dir('wordlist'), encoding='utf-8') as f:
for word in f:
word = word.strip()
... | identifier_body |
cii_atom_hashing_distribution.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# 2017-01-12T12:23:35+08:00
# C Interfaces and Implementations
# Exercise 3.1
import os
import os.path
import sys
import cppimport
import matplotlib.pyplot as plt
same_dir = lambda entry: os.path.join(os.path.dirname(__file__), entry)
sys.path.append(os.getcwd())
... | if __name__ == '__main__':
if not os.path.isfile(same_dir('wordlist')):
urllib.request.urlretrieve('http://www-personal.umich.edu/~jlawler/wordlist', same_dir('wordlist'))
bucket_size_benchmark()
# References:
# [GitHub: pybind/python_example](https://github.com/pybind/python_example)
# Matplotli... | random_line_split | |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C: 'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a... |
}
}
/// Fetch a component from given entity. Do not search parent entities.
pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> {
self.data.get(&idx).map_or(None, |x| x.as_ref())
}
}
/// Mutable component access.
pub struct ComponentRefMut<'a, C: 'static> {
ecs: &'a mut E... | { self.data.get(&idx).expect("missing component").as_ref() } | conditional_block |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C: 'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a... |
/// Fetch a component from given entity. Do not search parent entities.
pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> {
self.data.get(&idx).map_or(None, |x| x.as_ref())
}
}
/// Mutable component access.
pub struct ComponentRefMut<'a, C: 'static> {
ecs: &'a mut Ecs,
/// Some... | {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx)) => { self.data.get(&idx).expect("missing component").as_ref() }
}
} | identifier_body |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C: 'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn | (ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a, C> {
ComponentRef {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent.
pub fn get(self, Entity(idx): Entity) -> Option<&'a C> {
match find_parent(|Entity(idx... | new | identifier_name |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C: 'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a... | // Copy-on-write: Make a local copy of inherited component
// when asking for mutable access.
let cow = self.data.get(&idx2)
.expect("parent component lost").as_ref()
.expect("missing component").clone();
self.data.i... | random_line_split | |
aws_rds_endpoint_port_from_instance_name.py | # (c) 2015, Jon Hadfield <jon@lessknown.co.uk>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
_... | (LookupBase):
def run(self, terms, variables=None, **kwargs):
region = terms[0][0]
instance_name = terms[0][1]
session=boto3.session.Session(region_name=region)
try:
rds_client=session.client('rds')
except botocore.exceptions.NoRegionError:
raise Ans... | LookupModule | identifier_name |
aws_rds_endpoint_port_from_instance_name.py | # (c) 2015, Jon Hadfield <jon@lessknown.co.uk>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
_... |
return None
| return [result.get('DBInstances')[0].get('Endpoint').get('Port').encode('utf-8')] | conditional_block |
aws_rds_endpoint_port_from_instance_name.py | # (c) 2015, Jon Hadfield <jon@lessknown.co.uk>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
_... | def run(self, terms, variables=None, **kwargs):
region = terms[0][0]
instance_name = terms[0][1]
session=boto3.session.Session(region_name=region)
try:
rds_client=session.client('rds')
except botocore.exceptions.NoRegionError:
raise AnsibleError("AWS reg... | identifier_body | |
aws_rds_endpoint_port_from_instance_name.py | # (c) 2015, Jon Hadfield <jon@lessknown.co.uk>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
_... |
if result and result.get('DBInstances'):
return [result.get('DBInstances')[0].get('Endpoint').get('Port').encode('utf-8')]
return None | random_line_split | |
example_5.py | "Run the keyword-names example pipeline, which has keyword-style inputs."
import kiveapi
import example_tools
# Use HTTPS on a real server, so your password is encrypted.
# Don't put your real password in source code, store it in a text file
# that is only readable by your user account or some more secure storage.
ses... |
print("Example run finished")
| dataset = session.get(run_dataset["dataset"]).json()
filename = dataset["name"]
print(f" downloading {filename}")
with open(filename, "wb") as outf:
session.download_file(outf, dataset["download_url"]) | conditional_block |
example_5.py | "Run the keyword-names example pipeline, which has keyword-style inputs." | # that is only readable by your user account or some more secure storage.
session = kiveapi.KiveAPI("http://localhost:8000")
session.login('kive', 'kive')
# Get datasets to collate
names_dataset = session.find_datasets(name="example_names.csv")[0]
salutations_dataset = session.find_datasets(name="salutations.csv")[0]
... | import kiveapi
import example_tools
# Use HTTPS on a real server, so your password is encrypted.
# Don't put your real password in source code, store it in a text file | random_line_split |
language-container-directive.js | // NOTE: nbApp is defined in app.js
nbApp.directive("languageContainerDirective", function() {
return {
restrict : 'E',
templateUrl : 'js/templates/language-container.html',
scope: {
color: "@",
language: "@",
reading: "@",
writing: "@",
list... |
// chart.config.w;
// chart.config.h;
// chart.config.axisText = true;
// chart.config.levels = 5;
// chart.config.maxValue = 5;
// chart.config.circles = true;
// chart.config.actorLegend = 1;
... | {
return data.map(function(d) {
return {
className: d.className,
axes: d.axes.map(function(axis) {
return {axis: axis.axis, value: axis.value};
})
};
});
... | identifier_body |
language-container-directive.js | // NOTE: nbApp is defined in app.js
nbApp.directive("languageContainerDirective", function() {
return {
restrict : 'E',
templateUrl : 'js/templates/language-container.html',
scope: {
color: "@",
language: "@",
reading: "@",
writing: "@",
list... | className: attrs.language, // optional can be used for styling
axes: [
{axis: "Reading", value: attrs.reading},
{axis: "Writing", value: attrs.writing},
{axis: "Listening", value: attrs.listening},
... | {
RadarChart.defaultConfig.color = function() {};
RadarChart.defaultConfig.radius = 3;
RadarChart.defaultConfig.w = 250;
RadarChart.defaultConfig.h = 250;
/*
* 0 - No Practical Proficiency
* 1 - Elementary... | conditional_block |
language-container-directive.js | // NOTE: nbApp is defined in app.js
nbApp.directive("languageContainerDirective", function() {
return {
restrict : 'E',
templateUrl : 'js/templates/language-container.html',
scope: { | language: "@",
reading: "@",
writing: "@",
listening: "@",
speaking: "@",
flag: "@",
},
link: function(scope, element, attrs) {
scope.color = attrs.color;
scope.language = attrs.language;
scope.reading = attrs.read... | color: "@", | random_line_split |
language-container-directive.js | // NOTE: nbApp is defined in app.js
nbApp.directive("languageContainerDirective", function() {
return {
restrict : 'E',
templateUrl : 'js/templates/language-container.html',
scope: {
color: "@",
language: "@",
reading: "@",
writing: "@",
list... | () {
return data.map(function(d) {
return {
className: d.className,
axes: d.axes.map(function(axis) {
return {axis: axis.axis, value: axis.value};
})
};
}... | mapData | identifier_name |
parser.rs | str::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirec... | named_parsed_symbol!(duration<Duration>);
named_parsed_symbol!(port<Port>);
named_parsed_symbol!(file_descriptor<FileDescriptor>);
fn map_opt_duration(duration: Duration) -> Option<Duration> {
if duration < 0.0 {
None
} else {
Some(duration)
}
}
named!(opt_duration<&[u8], Option<Duration> ... | named_parsed_symbol!(fech_mode<FetchMode>);
named_parsed_symbol!(status<Status>);
named_parsed_symbol!(time_stamp<TimeStamp>); | random_line_split |
parser.rs | ::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirectio... |
}
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration));
// VSL record message parsers by tag
named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Type (b"sess", "req" or "bereq")
vsl_ident, // Parent vxid
symbol)); // Reason
named!(pub s... | {
Some(duration)
} | conditional_block |
parser.rs | str::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirec... | (duration: Duration) -> Option<Duration> {
if duration < 0.0 {
None
} else {
Some(duration)
}
}
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration));
// VSL record message parsers by tag
named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!(
symbo... | map_opt_duration | identifier_name |
parser.rs | ::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirectio... |
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration));
// VSL record message parsers by tag
named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Type (b"sess", "req" or "bereq")
vsl_ident, // Parent vxid
symbol)); // Reason
named!(pub slt... | {
if duration < 0.0 {
None
} else {
Some(duration)
}
} | identifier_body |
proto-files-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import { AsyncButton } from 'insomnia-components';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { GrpcRequestEventEnum } from '../../../common/grp... | (protoDirectory: ProtoDirectory) {
return protoManager.deleteDirectory(protoDirectory, deletedIds => {
// if previously selected protoFile has been deleted, clear the selection
if (deletedIds.includes(this.state.selectedProtoFileId)) {
this.setState({
selectedProtoFileId: '',
}... | _handleDeleteDirectory | identifier_name |
proto-files-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import { AsyncButton } from 'insomnia-components';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { GrpcRequestEventEnum } from '../../../common/grp... |
return protoManager.addFile(workspace._id, createdId => {
this.setState({
selectedProtoFileId: createdId,
});
});
}
_handleUpload(protoFile: ProtoFile) {
const { grpcDispatch } = this.props;
return protoManager.updateFile(protoFile, async updatedId => {
const action = aw... | {
return;
} | conditional_block |
proto-files-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import { AsyncButton } from 'insomnia-components';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { GrpcRequestEventEnum } from '../../../common/grp... |
async show(options: ProtoFilesModalOptions) {
this.onSave = options.onSave;
this.setState({
selectedProtoFileId: options.preselectProtoFileId || '',
});
this.modal?.show();
}
async _handleSave(e: React.SyntheticEvent<HTMLButtonElement>) {
e.preventDefault();
this.hide();
if (... | {
this.modal = ref;
} | identifier_body |
proto-files-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import { AsyncButton } from 'insomnia-components';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { GrpcRequestEventEnum } from '../../../common/grp... | <ModalBody className="wide pad">
<div className="row-spaced margin-bottom bold">
Files
<span>
<AsyncButton
className="margin-right-sm"
onClick={this._handleAddDirectory}
loadingNode={spinner}
>
... | <Modal ref={this._setModalRef}>
<ModalHeader>Select Proto File</ModalHeader> | random_line_split |
win_volume_object.py | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities, fields
import cybox.bindings.win_volume_object as win_volume_binding
from cybox.objects.volume_object import Volume
from cybox.common import BaseProperty, String
class WindowsDrive(Ba... | _binding = win_volume_binding
_binding_class = win_volume_binding.WindowsVolumeObjectType
_namespace = "http://cybox.mitre.org/objects#WinVolumeObject-2"
_XSI_NS = "WinVolumeObj"
_XSI_TYPE = "WindowsVolumeObjectType"
attributes_list = fields.TypedField("Attributes_List", WindowsVolumeAttributesList... | identifier_body | |
win_volume_object.py | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities, fields
import cybox.bindings.win_volume_object as win_volume_binding
from cybox.objects.volume_object import Volume
from cybox.common import BaseProperty, String
class WindowsDrive(Ba... | (entities.EntityList):
_binding = win_volume_binding
_binding_class = win_volume_binding.WindowsVolumeAttributesListType
_namespace = "http://cybox.mitre.org/objects#WinVolumeObject-2"
attribute = fields.TypedField("Attribute", WindowsVolumeAttribute, multiple=True)
class WinVolume(Volume):
_bind... | WindowsVolumeAttributesList | identifier_name |
win_volume_object.py | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities, fields
import cybox.bindings.win_volume_object as win_volume_binding
from cybox.objects.volume_object import Volume
from cybox.common import BaseProperty, String
class WindowsDrive(Ba... | TYPE_DRIVE_RAMDISK = "DRIVE_RAMDISK"
class WindowsVolumeAttribute(BaseProperty):
_binding = win_volume_binding
_binding_class = win_volume_binding.WindowsVolumeAttributeType
_namespace = "http://cybox.mitre.org/objects#WinVolumeObject-2"
TYPE_READ_ONLY = "ReadOnly"
TYPE_HIDDEN = "Hidden"
... | TYPE_DRIVE_FIXED = "DRIVE_FIXED"
TYPE_DRIVE_REMOTE = "DRIVE_REMOTE"
TYPE_DRIVE_CDROM = "DRIVE_CDROM" | random_line_split |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() | buffer[offset + 2] = 0;
}
}
}).unwrap();
renderer.clear();
renderer.copy(&texture, None, Some(Rect::new_unwrap(100, 100, 256, 256)));
renderer.copy_ex(&texture, None, Some(Rect::new_unwrap(450, 100, 256, 256)), 30.0, None, (false, false));
renderer.present();
... | {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwrap()... | identifier_body |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 6... | } | // The rest of the game loop goes here...
} | random_line_split |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 6... |
}
}
// The rest of the game loop goes here...
}
}
| {} | conditional_block |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn | () {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwra... | main | identifier_name |
views.py | from io import BytesIO
from itertools import groupby
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from flask import make_response, render_template, abort
from webapp import app
from webapp.evaluation import *
from ... | (timestamp):
features, importances = get_feature_importances(timestamp)
importance_fig = plot_feature_importances(features, importances)
return serve_matplotlib_fig(importance_fig)
@app.route("/<timestamp>/precision-recall")
def precision_recall(timestamp):
test_labels, test_predictions = get_labels_... | feature_importances | identifier_name |
views.py | from io import BytesIO
from itertools import groupby
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from flask import make_response, render_template, abort
from webapp import app
from webapp.evaluation import *
from ... |
@app.route("/<timestamp>/precision-recall")
def precision_recall(timestamp):
test_labels, test_predictions = get_labels_predictions(timestamp)
prec_recall_fig = plot_precision_recall_n(test_labels, test_predictions)
return serve_matplotlib_fig(prec_recall_fig)
@app.route("/<timestamp>/precision-cutoff"... | features, importances = get_feature_importances(timestamp)
importance_fig = plot_feature_importances(features, importances)
return serve_matplotlib_fig(importance_fig) | identifier_body |
views.py | from io import BytesIO
from itertools import groupby
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from flask import make_response, render_template, abort
from webapp import app
from webapp.evaluation import *
from ... | return response | canvas=FigureCanvas(fig)
png_output = BytesIO()
canvas.print_png(png_output)
response = make_response(png_output.getvalue())
response.headers['Content-Type'] = 'image/png' | random_line_split |
picture.rs | use chrono::naive::NaiveDateTime;
use exif::{Exif, In, Tag};
use serde::{Deserialize, Serialize};
use validator::Validate;
use anyhow::{Error, Result};
use image::GenericImageView;
use image::{imageops, DynamicImage};
use crate::schema::pictures;
use crate::utils::image_base_path;
#[derive(Debug, Clone, Queryable, I... | } else {
img.crop(mid_x - (width / 2), mid_y - (width / 2), width, width)
}
} else {
img
};
let new_img = img.resize_exact(600, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
Ok(())
} | random_line_split | |
picture.rs | use chrono::naive::NaiveDateTime;
use exif::{Exif, In, Tag};
use serde::{Deserialize, Serialize};
use validator::Validate;
use anyhow::{Error, Result};
use image::GenericImageView;
use image::{imageops, DynamicImage};
use crate::schema::pictures;
use crate::utils::image_base_path;
#[derive(Debug, Clone, Queryable, I... | let path = format!("{}/{}/large/{}", image_base_path(), picture.id, picture.image_file_name);
let new_img = img.resize(800, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
let path = format!(
"{}/{}/thumbnail/{}",
image_base_path(),
picture.id,
picture.image... | {
let path = format!(
"{}/{}/original/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let exif = read_exif(&path)?;
let orientation = match exif.get_field(Tag::Orientation, In::PRIMARY) {
Some(orientation) => match orientation.value.get_uint(0) {
... | identifier_body |
picture.rs | use chrono::naive::NaiveDateTime;
use exif::{Exif, In, Tag};
use serde::{Deserialize, Serialize};
use validator::Validate;
use anyhow::{Error, Result};
use image::GenericImageView;
use image::{imageops, DynamicImage};
use crate::schema::pictures;
use crate::utils::image_base_path;
#[derive(Debug, Clone, Queryable, I... | (picture: &Picture) -> Result<()> {
let path = format!(
"{}/{}/original/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let exif = read_exif(&path)?;
let orientation = match exif.get_field(Tag::Orientation, In::PRIMARY) {
Some(orientation) => match... | generate_pictures | identifier_name |
main.py | raph):
"""
Compute a targeted attack order consisting
of nodes of maximal degree
Returns:
A list of nodes
"""
# copy the graph
new_graph = copy_graph(ugraph)
order = []
while len(new_graph) > 0:
max_degree = -1
for node in new_graph:
... |
def compute_resilience(ugraph, attack_order):
""" takes an undirected graph and a list of nodes, attack_order;
iterates through the nodes in attack_order.
For each node, removes the given node and its edges from ugraph and then computes the size of the largest cc for the resulting graph.
returns a list ... | """ computes and returns the size of the largest connected component of ugraph; returns an int """
largest_num = 0
c_comp = cc_visited(ugraph)
for group in c_comp:
if len(group) > largest_num:
largest_num = len(group)
return largest_num | identifier_body |
main.py | []
while len(new_graph) > 0:
max_degree = -1
for node in new_graph:
if len(new_graph[node]) > max_degree:
max_degree = len(new_graph[node])
max_degree_node = node
neighbors = new_graph[max_degree_node]
new_graph.pop(m... | # test_random_order()
# test_gen_er_graph()
# End Test calls ---------------------------------------
# Questions---------------------------------------------
| random_line_split | |
main.py |
def targeted_order(ugraph):
"""
Compute a targeted attack order consisting
of nodes of maximal degree
Returns:
A list of nodes
"""
# copy the graph
new_graph = copy_graph(ugraph)
order = []
while len(new_graph) > 0:
max_degree = -1
... | ugraph[neighbor].remove(node) | conditional_block | |
main.py | raph):
"""
Compute a targeted attack order consisting
of nodes of maximal degree
Returns:
A list of nodes
"""
# copy the graph
new_graph = copy_graph(ugraph)
order = []
while len(new_graph) > 0:
max_degree = -1
for node in new_graph:
... | (ugraph, start_node):
""" takes undirected graph and node as input;
returns set of all nodes visited by breadth-first search starting at start_node """
queue = deque()
visited = set([start_node])
queue.append(start_node)
# print "start_node:", start_node
while len(queue) > 0:
current_node = queue.p... | bfs_visited | identifier_name |
wasm.rs | pub struct NativeManager {
}
impl NativeManager {
pub(crate) fn new() -> NativeManager {
NativeManager { /*devices: Vec::new()*/ }
}
/// Do a search for controllers. Returns number of controllers.
pub(crate) fn search(&mut self) -> (usize, usize) {
/* let devices = find_devices();
// Add devices
for mut ... | (&self, _i: usize, _state: &mut crate::hid::HidState) {
/* if (state.output & crate::hid::Output::HapticStart as u32) != 0 {
self.rumble(i, true);
state.output = 0;
} else if (state.output & crate::hid::Output::HapticStop as u32) != 0 {
self.rumble(i, false);
... | poll_event | identifier_name |
wasm.rs | pub struct NativeManager {
}
impl NativeManager {
pub(crate) fn new() -> NativeManager |
/// Do a search for controllers. Returns number of controllers.
pub(crate) fn search(&mut self) -> (usize, usize) {
/* let devices = find_devices();
// Add devices
for mut i in devices {
if self.devices.contains(&i) {
continue;
}
open_joystick(&mut i);
// Setup device for asynchronous reads... | {
NativeManager { /*devices: Vec::new()*/ }
} | identifier_body |
wasm.rs | pub struct NativeManager {
}
impl NativeManager {
pub(crate) fn new() -> NativeManager {
NativeManager { /*devices: Vec::new()*/ }
}
/// Do a search for controllers. Returns number of controllers.
pub(crate) fn search(&mut self) -> (usize, usize) {
/* let devices = find_devices();
// Add devices
for mut ... | let effect = joystick_haptic(self.devices[index].fd);
self.devices[index].min = min;
self.devices[index].max = max;
self.devices[index].id = id;
self.devices[index].effect = effect;
return (self.devices.len(), index);
}
}*/
(s... | let (_, id, _) = joystick_id(self.devices[index].fd); | random_line_split |
IsolateFormDirective.js | angular.module('RadCalc').directive('isolateForm', [function () {
return {
restrict: 'A',
require: '?form',
link: function (scope, elm, attrs, ctrl) {
if (!ctrl) |
// Do a copy of the controller
var ctrlCopy = {};
angular.copy(ctrl, ctrlCopy);
// Get the parent of the form
var parent = elm.parent().controller('form');
// Remove parent link to the controller
parent.$removeControl(ctrl);
... | {
return;
} | conditional_block |
IsolateFormDirective.js | angular.module('RadCalc').directive('isolateForm', [function () {
return {
restrict: 'A',
require: '?form',
link: function (scope, elm, attrs, ctrl) {
if (!ctrl) {
return;
}
// Do a copy of the controller
var ctrlCopy = {};
... | };
}]); | random_line_split | |
export_emails.py | from django.core.management.base import BaseCommand, CommandError
try:
from django.contrib.auth import get_user_model # Django 1.5
except ImportError:
from django_extensions.future_1_5 import get_user_model
from django.contrib.auth.models import Group
from optparse import make_option
from sys import stdout
fro... | card.add('fn').value = full_name(**ent)
if not ent['last_name'] and not ent['first_name']:
# fallback to fullname, if both first and lastname are not declared
card.add('n').value = vobject.vcard.Name(full_name(**ent))
else:
card.add('n'... | print(self.style.ERROR("Please install python-vobject to use the vcard export format."))
import sys
sys.exit(1)
for ent in qs:
card = vobject.vCard() | random_line_split |
export_emails.py | from django.core.management.base import BaseCommand, CommandError
try:
from django.contrib.auth import get_user_model # Django 1.5
except ImportError:
from django_extensions.future_1_5 import get_user_model
from django.contrib.auth.models import Group
from optparse import make_option
from sys import stdout
fro... | (first_name, last_name, username, **extra):
name = six.u(" ").join(n for n in [first_name, last_name] if n)
if not name:
return username
return name
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--group', '-g', action='store', dest='group', default=... | full_name | identifier_name |
export_emails.py | from django.core.management.base import BaseCommand, CommandError
try:
from django.contrib.auth import get_user_model # Django 1.5
except ImportError:
from django_extensions.future_1_5 import get_user_model
from django.contrib.auth.models import Group
from optparse import make_option
from sys import stdout
fro... | card = vobject.vCard()
card.add('fn').value = full_name(**ent)
if not ent['last_name'] and not ent['first_name']:
# fallback to fullname, if both first and lastname are not declared
card.add('n').value = vobject.vcard.Name(full_name(**ent))
else:
... | conditional_block | |
export_emails.py | from django.core.management.base import BaseCommand, CommandError
try:
from django.contrib.auth import get_user_model # Django 1.5
except ImportError:
from django_extensions.future_1_5 import get_user_model
from django.contrib.auth.models import Group
from optparse import make_option
from sys import stdout
fro... |
def emails(self, qs, out):
"""simpler single entry with email only in the format of:
my@address.com,
"""
out.write(six.u(",\n").join(ent['email'] for ent in qs).encode(self.encoding))
out.write("\n")
def google(self, qs, out):
"""CSV format suitable for imp... | """simple single entry per line in the format of:
"full name" <my@address.com>;
"""
out.write(six.u("\n").join('"%s" <%s>;' % (full_name(**ent), ent['email'])
for ent in qs).encode(self.encoding))
out.write("\n") | identifier_body |
data-manager-config.ts | import { SkyDataManagerSortOption } from './data-manager-sort-option';
/**
* The data manager config contains settings that apply to the data manager across all views,
* such as the sort and filter settings.
*/
export interface SkyDataManagerConfig {
/**
* An untyped property that can track any config informat... | * The modal component to launch when the filter button is selected. The same filter options are
* used for all views, but views can use `SkyDataViewConfig` to indicate whether to display
* the filter button. The modal receives the `filterData` in the data state as context.
*/
filterModalComponent?: any;
... | random_line_split | |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces,
Differentiable,
Function,
Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate"... | lse {
let ns = t.to.state();
let na = self.policy.sample(&mut thread_rng(), ns);
let nqsna = self.fa_theta.evaluate((ns, na));
let residual = t.reward + self.gamma * nqsna - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha *... | let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
residual
} e | conditional_block |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces,
Differentiable,
Function,
Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate"... | let nqsna = self.fa_theta.evaluate((ns, na));
let residual = t.reward + self.gamma * nqsna - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
... | let s = t.from.state();
let qsa = self.fa_theta.evaluate((s, &t.action));
// Update trace with latest feature vector:
self.trace.update(&self.fa_theta.grad((s, &t.action)));
// Update weight vectors:
let td_error = if t.terminated() {
let residual = t.reward... | identifier_body |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces,
Differentiable,
Function,
Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate"... | , P, T> {
#[weights]
pub fa_theta: Q,
pub policy: P,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, P, R> Handler<&'m Transition<S, P::Action>> for SARSALambda<
Q, P, Tr<&'m S, &'m P::Action,... | RSALambda<Q | identifier_name |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces, | Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// On-policy variant of Watkins' Q-learning with eligibility traces (aka
/// "modified... | Differentiable,
Function, | random_line_split |
tsm_vte.rs | #![feature(libc)]
extern crate libc;
extern crate regex; |
use libc::c_char;
use libc::c_void;
use libc::size_t;
use std::ptr;
use std::slice;
use tsm_sys::*;
#[test]
fn tsm_vte_stuff_works() {
let mut screen = ptr::null_mut();
let err = unsafe { tsm::tsm_screen_new(&mut screen, None, ptr::null_mut()) };
assert_eq!(0, err);
let mut vte = ptr::null_mut();
... | extern crate tsm_sys; | random_line_split |
tsm_vte.rs | #![feature(libc)]
extern crate libc;
extern crate regex;
extern crate tsm_sys;
use libc::c_char;
use libc::c_void;
use libc::size_t;
use std::ptr;
use std::slice;
use tsm_sys::*;
#[test]
fn tsm_vte_stuff_works() {
let mut screen = ptr::null_mut();
let err = unsafe { tsm::tsm_screen_new(&mut screen, None, ptr... | { string: String }
let mut output = Output { string: "".to_string() };
let output_ptr: *mut c_void = &mut output as *mut _ as *mut c_void;
unsafe { tsm::tsm_vte_new(&mut vte, screen, write_cb, output_ptr, None, ptr::null_mut() ) };
unsafe { tsm::tsm_vte_reset(vte) }
unsafe { tsm::tsm_vte_hard_res... | Output | identifier_name |
gpa.py | # Quick script to calculate GPA given a class list file.
# Class list file should be a csv with COURSE_ID,NUM_UNITS,GRADE
# GRADE should be LETTER with potential modifiers after that
# registrar.mit.edu/classes-grades-evaluations/grades/calculating-gpa
import argparse
import pandas as pd
def get_parser():
# Get ... | (self):
# Map grades to grade points
grade_points = self.__data.grade.apply(self.__grade_point_mapper)
# Multiply pointwise by units
grade_points_weighted = grade_points * self.__data.units
# Sum weighted units
weighted_units_sum = grade_points_weighted.sum()
#... | calc_gpa | identifier_name |
gpa.py | # Quick script to calculate GPA given a class list file.
# Class list file should be a csv with COURSE_ID,NUM_UNITS,GRADE
# GRADE should be LETTER with potential modifiers after that
# registrar.mit.edu/classes-grades-evaluations/grades/calculating-gpa
import argparse
import pandas as pd
def get_parser():
# Get ... |
# Divide by total units
gpa_raw = weighted_units_sum / self.__data.units.sum()
# Round to nearest tenth
return round(gpa_raw, 1)
def __grade_point_mapper(self, grade):
# Maps a string letter grade to a numerical value
# MIT 5.0 scale
grade_map = {
... |
# Sum weighted units
weighted_units_sum = grade_points_weighted.sum() | random_line_split |
gpa.py | # Quick script to calculate GPA given a class list file.
# Class list file should be a csv with COURSE_ID,NUM_UNITS,GRADE
# GRADE should be LETTER with potential modifiers after that
# registrar.mit.edu/classes-grades-evaluations/grades/calculating-gpa
import argparse
import pandas as pd
def get_parser():
# Get ... |
if __name__ == '__main__':
# Set up argument parsing
parser = get_parser()
args = parser.parse_args()
# Make sure filename is present
if not args.filename:
raise ValueError('Must provide filename via -F, --filename')
# Create calculator
calc = GPACalculator(args.filename)
#... | grade_map = {
'A': 5,
'B': 4,
'C': 3,
'D': 2,
'F': 0,
}
first_char = grade[0].upper()
try:
return grade_map[first_char]
except:
raise ValueError('Invalid grade {grade}'.format(grade=grade)) | identifier_body |
gpa.py | # Quick script to calculate GPA given a class list file.
# Class list file should be a csv with COURSE_ID,NUM_UNITS,GRADE
# GRADE should be LETTER with potential modifiers after that
# registrar.mit.edu/classes-grades-evaluations/grades/calculating-gpa
import argparse
import pandas as pd
def get_parser():
# Get ... | parser = get_parser()
args = parser.parse_args()
# Make sure filename is present
if not args.filename:
raise ValueError('Must provide filename via -F, --filename')
# Create calculator
calc = GPACalculator(args.filename)
# Execute and print
gpa = calc.calc_gpa()
print(gpa) | conditional_block | |
battlelog.mohw.inject.js | /// <reference path="windowbutton/battlelog.windowbutton.js" />
/// <reference path="playbar/battlelog.bf3.playbar.js" />
/// <reference path="dialog/battlelog.bf3.dialog.js" />
/// <reference path="stats/battlelog.bf3.stats.js" />
var baseurl = 'http://battlelogium.github.io/Battlelogium/Battlelogium.Core/Javascript'... | {
if (document.getElementById('_windowbutton') == null) {
injectScript('_windowbutton', baseurl+'/windowbutton/battlelog.windowbutton.min.js');
}
if (document.getElementById('css_windowbutton') == null) {
injectCSS('css_windowbutton', baseurl + '/windowbutton/battlelog.windowbutton.min.css'... | jectOnce() | identifier_name |
battlelog.mohw.inject.js | /// <reference path="windowbutton/battlelog.windowbutton.js" />
/// <reference path="playbar/battlelog.bf3.playbar.js" />
/// <reference path="dialog/battlelog.bf3.dialog.js" />
/// <reference path="stats/battlelog.bf3.stats.js" />
var baseurl = 'http://battlelogium.github.io/Battlelogium/Battlelogium.Core/Javascript'... | if (document.getElementById('_battlelogstats') == null) {
injectScript('_battlelogstats', baseurl + '/stats/battlelog.mohw.stats.min.js');
}
if (document.getElementById('_battlelogsettings') == null) {
injectScript('_battlelogsettings', baseurl + '/settings/battlelog.mohw.settings.min.js');
... | injectScript('_battlelogplaybar', baseurl + '/playbar/battlelog.mohw.playbar.min.js');
}
| conditional_block |
battlelog.mohw.inject.js | /// <reference path="windowbutton/battlelog.windowbutton.js" />
/// <reference path="playbar/battlelog.bf3.playbar.js" />
/// <reference path="dialog/battlelog.bf3.dialog.js" />
/// <reference path="stats/battlelog.bf3.stats.js" />
var baseurl = 'http://battlelogium.github.io/Battlelogium/Battlelogium.Core/Javascript'... | if (window.location.href == 'http://battlelog.battlefield.com/mohw/profile/edit/') {
battlelogsettings.addSettingsSection();
}
}
function injectScript(id, url) {
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('id', id);
docum... | if (window.location.href.match(/\/soldier\//) != null) {
battlelogstats.overview();
} | random_line_split |
battlelog.mohw.inject.js | /// <reference path="windowbutton/battlelog.windowbutton.js" />
/// <reference path="playbar/battlelog.bf3.playbar.js" />
/// <reference path="dialog/battlelog.bf3.dialog.js" />
/// <reference path="stats/battlelog.bf3.stats.js" />
var baseurl = 'http://battlelogium.github.io/Battlelogium/Battlelogium.Core/Javascript'... | unction injectCSS(id, url) {
var script = document.createElement('link');
script.setAttribute('rel', 'stylesheet');
script.setAttribute('type', 'text/css');
script.setAttribute('href', url);
script.setAttribute('id', id);
document.getElementsByTagName('head')[0].appendChild(script);
}
injectOnc... | var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('id', id);
document.getElementsByTagName('head')[0].appendChild(script);
}
f | identifier_body |
domain.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | ():
return domain_policies
| list_rules | identifier_name |
domain.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # License for the specific language governing permissions and limitations
# under the License.
from oslo_log import versionutils
from oslo_policy import policy
from keystone.common.policies import base
DEPRECATED_REASON = (
"The domain API is now aware of system scope and default roles."
)
deprecated_list_domai... | random_line_split | |
domain.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | return domain_policies | identifier_body | |
metrics.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use prometheus::*;
use prometheus_static_metric::*;
make_static_metric! {
pub label_enum MvccConflictKind {
prewrite_write_conflict,
rolled_back,
commit_lock_not_found,
rollback_committed,
acquire_pessimisti... | MvccDuplicateCmdCounterVec,
"tikv_storage_mvcc_duplicate_cmd_counter",
"Total number of duplicated commands",
&["type"]
)
.unwrap()
};
pub static ref MVCC_CHECK_TXN_STATUS_COUNTER_VEC: MvccCheckTxnStatusCounterVec = {
register_static_int_co... | .unwrap()
};
pub static ref MVCC_DUPLICATE_CMD_COUNTER_VEC: MvccDuplicateCmdCounterVec = {
register_static_int_counter_vec!( | random_line_split |
main.rs | use std::io::File;
use map_generator::HeightMap;
use coordinate_formula::CoordinateFormula;
mod map_generator;
mod coordinate_formula;
static FILENAME: &'static str = "height_map.out";
fn main() | map_generator::drop_particles(drop_point.as_slice(), (x, y), &mut height_map);
coordinate_formula = coordinate_formula.change_iteration();
}
// output height map in YAML format
let path = Path::new(FILENAME);
let mut file = match File::create(&path) {
Err(why) => fail!("couldn't create {}: {}", FIL... | {
let size = 50;
let number_of_drop_points = 20;
let min_particles = 400;
let max_particles = 2000;
let number_of_passes = 5;
let mut coordinate_formula = CoordinateFormula::new();
let mut height_map: HeightMap = HeightMap::new(size);
let drops: Vec<Box<Vec<int>>>;
drops = Vec::from_fn(number_of_pas... | identifier_body |
main.rs | use std::io::File;
use map_generator::HeightMap;
use coordinate_formula::CoordinateFormula;
mod map_generator;
mod coordinate_formula;
static FILENAME: &'static str = "height_map.out";
fn | () {
let size = 50;
let number_of_drop_points = 20;
let min_particles = 400;
let max_particles = 2000;
let number_of_passes = 5;
let mut coordinate_formula = CoordinateFormula::new();
let mut height_map: HeightMap = HeightMap::new(size);
let drops: Vec<Box<Vec<int>>>;
drops = Vec::from_fn(number_of_... | main | identifier_name |
main.rs | use std::io::File;
use map_generator::HeightMap;
use coordinate_formula::CoordinateFormula;
mod map_generator;
mod coordinate_formula;
static FILENAME: &'static str = "height_map.out";
fn main() {
let size = 50;
let number_of_drop_points = 20;
let min_particles = 400;
let max_particles = 2000;
let number_o... | for n in range(0u, size * size) {
file.write_line(format!("- {}", *height_map.map.get_mut(n)).as_slice());
}
} | random_line_split | |
scrapingUtils.py | Name = '(?:f*id|ch)'
jsName = '([^\"\']+?\.js[^\"\']*?)'
regex = "(?:java)?scr(?:'\+')?ipt.*?" + idName + "\s*=\s*[\"']([^\"']+)[\"'][^<]*</scr(?:'\+')?ipt\s*>[^<]*<scr(?:'\+')?ipt[^<]*src=[\"']" + jsName + "[\"']"
jscript = regexUtils.findall(data, regex)
if jscript:
jscript = filter(lambd... | (url):
scheme = urlparse.urlparse(url)
if scheme:
return scheme.netloc.replace('www.','')
return None
def findFrames(data):
if data.lower().find('frame') == -1:
return None
return regexUtils.findall(data, "(frame[^>]*)>")
def findContentRefreshLink(data):
regex = '0;\s*u... | getHostName | identifier_name |
scrapingUtils.py | Name = '(?:f*id|ch)'
jsName = '([^\"\']+?\.js[^\"\']*?)'
regex = "(?:java)?scr(?:'\+')?ipt.*?" + idName + "\s*=\s*[\"']([^\"']+)[\"'][^<]*</scr(?:'\+')?ipt\s*>[^<]*<scr(?:'\+')?ipt[^<]*src=[\"']" + jsName + "[\"']"
jscript = regexUtils.findall(data, regex)
if jscript:
jscript = filter(lambd... |
if swfUrl:
finalSwfUrl = swfUrl[0]
if not finalSwfUrl.startswith('http'):
finalSwfUrl = urlparse.urljoin(url, finalSwfUrl)
regex = '://(.*?)/'
server = regexUtils.findall(tmpRtmp... | if not swfUrl:
swfUrl = regexUtils.findall(data, sep1 + '([^\'"& ]+\.swf)') | random_line_split |
scrapingUtils.py | Name = '(?:f*id|ch)'
jsName = '([^\"\']+?\.js[^\"\']*?)'
regex = "(?:java)?scr(?:'\+')?ipt.*?" + idName + "\s*=\s*[\"']([^\"']+)[\"'][^<]*</scr(?:'\+')?ipt\s*>[^<]*<scr(?:'\+')?ipt[^<]*src=[\"']" + jsName + "[\"']"
jscript = regexUtils.findall(data, regex)
if jscript:
jscript = filter(lambd... |
def findFrames(data):
if data.lower().find('frame') == -1:
return None
return regexUtils.findall(data, "(frame[^>]*)>")
def findContentRefreshLink(data):
regex = '0;\s*url=([^\'" ]+)'
links = regexUtils.findall(data, regex)
if links:
return links[0]
regex = 'window... | scheme = urlparse.urlparse(url)
if scheme:
return scheme.netloc.replace('www.','')
return None | identifier_body |
scrapingUtils.py | Name = '(?:f*id|ch)'
jsName = '([^\"\']+?\.js[^\"\']*?)'
regex = "(?:java)?scr(?:'\+')?ipt.*?" + idName + "\s*=\s*[\"']([^\"']+)[\"'][^<]*</scr(?:'\+')?ipt\s*>[^<]*<scr(?:'\+')?ipt[^<]*src=[\"']" + jsName + "[\"']"
jscript = regexUtils.findall(data, regex)
if jscript:
jscript = filter(lambd... |
if method1:
playpath = regexUtils.findall(area, sep1 + 'file' + sep2 + value)
if method2:
playpath = regexUtils.findall(area, sep1 + 'id' + sep2 + value)
if playpath:
tmpRtmp = tmpRtmp + '/' + playpath[0]
... | text = text[clipStart:] | conditional_block |
Tools.tsx | import {FromVDF, ToVDF, Global} from "../Frame/Globals";
import {BaseComponent, BaseProps} from "../Frame/ReactGlobals";
import ScrollableTabView from "react-native-scrollable-tab-view";
import DialogAndroid from "react-native-dialogs";
import Node from "../Packages/VTree/Node";
import GeneralUI from "./Settings/Gener... | }
export class ToolsUI extends BaseComponent<BaseProps & {}, {show: boolean}> {
ComponentDidMount() {
// fixes that first-tab's tab-view would not display
setTimeout(()=>this.setState({show: true}), 0);
}
render() {
if (!this.state.show) return <View/>;
return (
<ScrollableTabView style={{flex: 1}}>
... | random_line_split | |
Tools.tsx | import {FromVDF, ToVDF, Global} from "../Frame/Globals";
import {BaseComponent, BaseProps} from "../Frame/ReactGlobals";
import ScrollableTabView from "react-native-scrollable-tab-view";
import DialogAndroid from "react-native-dialogs";
import Node from "../Packages/VTree/Node";
import GeneralUI from "./Settings/Gener... | extends Node {
@T("FBA") @P(true, true) fba = new FBA();
@T("RVP") @P(true, true) rvp = new RVP();
@T("SPMonitor") @P(true, true) spMonitor = new SPMonitor();
@T("Monitor") @P(true, true) monitor = new Monitor();
}
export class ToolsUI extends BaseComponent<BaseProps & {}, {show: boolean}> {
ComponentDidMount() ... | Tools | identifier_name |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | <'c>() -> App<'c, 'c> {
SubCommand::with_name(SUBCOMMAND_NAME)
.about(
"Initialize a Delivery project \
(and lots more!)",
)
.args(&vec![
config_path_arg(),
no_open_arg(),
project_arg(),
local_arg(),
config_... | clap_subcommand | identifier_name |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | ,
}
}
}
impl<'n> Options for InitClapOptions<'n> {
fn merge_options_and_config(&self, config: Config) -> DeliveryResult<Config> {
let project = try!(project::project_or_from_cwd(&self.project));
let new_config = config
.set_user(&self.user)
.set_server(&self.ser... | {
None
} | conditional_block |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | config_path_arg(),
no_open_arg(),
project_arg(),
local_arg(),
config_project_arg(),
])
.args_from_usage(
"--generator=[generator] 'Local path or Git repo URL to a \
custom ChefDK build_cookbook generator (default:github... | random_line_split | |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | .args(&pipeline_arg())
.args(&project_specific_args())
.args(&vec![a2_mode_arg()])
}
| {
SubCommand::with_name(SUBCOMMAND_NAME)
.about(
"Initialize a Delivery project \
(and lots more!)",
)
.args(&vec![
config_path_arg(),
no_open_arg(),
project_arg(),
local_arg(),
config_project_arg(),
... | identifier_body |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, _
from openerp.ex... | (self, afip_ws='wsfe', company=False):
self.ensure_one()
# if not company, then we search one that uses argentinian localization
if not company:
company = self.env['res.company'].search(
[('localization', '=', 'argentina')],
limit=1)
if not com... | get_pyafipws_currency_rate | identifier_name |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, _
from openerp.ex... | elif afip_ws == "wsfe":
rate = ws.ParamGetCotizacion(self.afip_code)
else:
raise UserError(_('AFIP WS %s not implemented') % (
afip_ws))
msg = (_("Currency rate for %s: %s.\nObservations: %s") % (
self.name, rate, ".\n".join([ws.Excepcion, ws.E... | self.ensure_one()
# if not company, then we search one that uses argentinian localization
if not company:
company = self.env['res.company'].search(
[('localization', '=', 'argentina')],
limit=1)
if not company:
raise UserError(_(
... | identifier_body |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, _
from openerp.ex... | @api.multi
def action_get_pyafipws_currencies(self):
return self.get_pyafipws_currencies()
@api.model
def get_pyafipws_currencies(self, afip_ws='wsfex', company=False):
# if not company, then we search one that uses argentinian localization
if not company:
company = ... | _inherit = "res.currency"
| random_line_split |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, _
from openerp.ex... |
elif afip_ws == 'wsfe':
ret = ws.ParamGetTiposMonedas(sep=" ")
elif afip_ws == 'wsbfe':
ret = ws.GetParamMon()
else:
raise UserError(_('AFIP WS %s not implemented') % (
afip_ws))
msg = (_("Authorized Currencies on AFIP%s\n. \nObservati... | ret = ws.GetParamMon(sep=" ") | conditional_block |
reqobject.py | #!/usr/bin/python
#
# Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | def get_selected_item(self):
try:
return self.__list.get_item(self.__list.get_selected())[1]
except Exception, e:
print "Unable to get selected item: %s" % e
return None | for name, info in objlist:
self.__list.set_item(name, name, info)
| random_line_split |
reqobject.py | #!/usr/bin/python
#
# Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | (gtk.Dialog):
def __init__(self, rpcsession, station, parent=None):
gtk.Dialog.__init__(self,
title="Request remote object",
buttons=("Retrieve", gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
... | RequestRemoteObjectUI | identifier_name |
reqobject.py | #!/usr/bin/python
#
# Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | try:
return self.__list.get_item(self.__list.get_selected())[1]
except Exception, e:
print "Unable to get selected item: %s" % e
return None | identifier_body | |
reqobject.py | #!/usr/bin/python
#
# Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... |
def get_selected_item(self):
try:
return self.__list.get_item(self.__list.get_selected())[1]
except Exception, e:
print "Unable to get selected item: %s" % e
return None
| self.__list.set_item(name, name, info) | conditional_block |
vertexdomain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# vertexdomain.py
#
# Copyright 2016 notna <notna@apparat.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the ... | #
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# | random_line_split | |
metadata_basic.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
#[test]
pub fn new_predicate_named_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string], bytes, uint64))
})
})
}
#[test]
pub fn new_predicate_doc_field() {
single(&|holme... | () {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})
})
}
#[test]
pub fn predicate_roundtrip() {
si... | new_predicate_doc_all | identifier_name |
metadata_basic.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
#[test]
pub fn new_predicate_named_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string], bytes, uint64))
})
})
}
#[test]
pub fn new_predicate_doc_field() |
#[test]
pub fn new_predicate_doc_all() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})
})
}
#[test]... | {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"], bytes, uint64))
})
})
} | identifier_body |
metadata_basic.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
#[test]
pub fn new_predicate_named_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string], bytes, uint64))
})
})
}
#[test]
pub fn new_predicate_doc_field() {
single(&|holme... | })
}
#[test]
pub fn predicate_roundtrip() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})?;
le... | }) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.