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
plot_object.py
check_integrity class Viewable(MetaHasProps): """ Any plot object (Data Model) which has its own View Model in the persistence layer. One thing to keep in mind is that a Viewable should have a single unique representation in the persistence layer, but it might have multiple concurrent client-side...
return objs def references(self): """Returns all ``PlotObjects`` that this object has references to. """ return set(self.collect_plot_objects(self)) #--------------------------------------------------------------------- # View Model connection methods # # Whereas a rich cli...
elif isinstance(obj, dict): for key, value in iteritems(obj): descend(key); descend(value) descend(input_objs)
random_line_split
plot_object.py
check_integrity class Viewable(MetaHasProps): """ Any plot object (Data Model) which has its own View Model in the persistence layer. One thing to keep in mind is that a Viewable should have a single unique representation in the persistence layer, but it might have multiple concurrent client-side...
(self): pass def select(self, selector): ''' Query this object and all of its references for objects that match the given selector. Args: selector (JSON-like) : Returns: seq[PlotObject] ''' return find(self.references(), selector) ...
setup_events
identifier_name
plot_object.py
check_integrity class Viewable(MetaHasProps): """ Any plot object (Data Model) which has its own View Model in the persistence layer. One thing to keep in mind is that a Viewable should have a single unique representation in the persistence layer, but it might have multiple concurrent client-side...
else: raise KeyError("View model name '%s' not found" % view_model_name) @add_metaclass(Viewable) class PlotObject(HasProps): """ Base class for all plot-related objects """ session = Instance(".session.Session") name = String() tags = List(Any) def __init__(self, **kwargs): ...
return d[view_model_name]
conditional_block
p065.rs
//! [Problem 65](https://projecteuler.net/problem=65) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; fn
(i: u32) -> u32 { match i { 0 => 2, i if i % 3 == 2 => 2 * (i + 1) / 3, _ => 1, } } fn solve() -> String { let len = 100; let napier = (0u32..len).map(napier_seq); let (n, _d) = cont_frac::fold::<BigUint, _>(napier); n.to_string() .chars() .filter_map(|c|...
napier_seq
identifier_name
p065.rs
//! [Problem 65](https://projecteuler.net/problem=65) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; fn napier_seq(i: u32) -> u32 { match i { 0 => 2, i if i % 3 == 2 => 2 * (...
.to_string() } common::problem!("272", solve);
.sum::<u32>()
random_line_split
p065.rs
//! [Problem 65](https://projecteuler.net/problem=65) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; fn napier_seq(i: u32) -> u32 { match i { 0 => 2, i if i % 3 == 2 => 2 * (...
common::problem!("272", solve);
{ let len = 100; let napier = (0u32..len).map(napier_seq); let (n, _d) = cont_frac::fold::<BigUint, _>(napier); n.to_string() .chars() .filter_map(|c| c.to_digit(10)) .sum::<u32>() .to_string() }
identifier_body
IdealLinearPolarizer.py
import numpy as np from PyQt4.QtGui import QIntValidator, QDoubleValidator, QApplication, QSizePolicy from orangewidget import gui from orangewidget.settings import Setting from oasys.widgets import widget import orangecanvas.resources as resources import sys, os from crystalpy.util.PolarizedPhotonBunch import Polariz...
def calculate_IdealLinearPolarizer(self): if self._input_available: # TYPE=self.TYPE,THETA=self.THETA,DELTA=self.DELTA photon_bunch = self.incoming_bunch if self.TYPE == 0: mm = MuellerMatrix.initialize_as_general_linear_polarizer(theta=self.THETA*np....
self._input_available = True self.incoming_bunch = photon_bunch self.calculate_IdealLinearPolarizer()
conditional_block
IdealLinearPolarizer.py
import numpy as np from PyQt4.QtGui import QIntValidator, QDoubleValidator, QApplication, QSizePolicy from orangewidget import gui from orangewidget.settings import Setting from oasys.widgets import widget import orangecanvas.resources as resources import sys, os from crystalpy.util.PolarizedPhotonBunch import Polariz...
(self): self.resetSettings() self.calculate_IdealLinearPolarizer() return def get_doc(self): print("help pressed.") home_doc = resources.package_dirname("orangecontrib.oasyscrystalpy") + "/doc_files/" filename1 = os.path.join(home_doc,'IdealLinearPolarizer'+'.txt'...
defaults
identifier_name
IdealLinearPolarizer.py
import numpy as np from PyQt4.QtGui import QIntValidator, QDoubleValidator, QApplication, QSizePolicy from orangewidget import gui from orangewidget.settings import Setting from oasys.widgets import widget import orangecanvas.resources as resources import sys, os from crystalpy.util.PolarizedPhotonBunch import Polariz...
want_main_area = False TYPE = Setting(0) THETA = Setting(0.0) DUMP_TO_FILE = Setting(1) FILE_NAME = Setting("linear_polarizer.dat") def __init__(self): super().__init__() box0 = gui.widgetBox(self.controlArea, " ",orientation="horizontal") #widget buttons: compute, se...
name = "IdealLinearPolarizer" id = "orange.widgets.dataIdealLinearPolarizer" description = "Application to compute..." icon = "icons/IdealLinearPolarizer.png" author = "create_widget.py" maintainer_email = "srio@esrf.fr" priority = 30 category = "" keywords = ["oasyscrystalpy", "IdealLin...
identifier_body
IdealLinearPolarizer.py
import numpy as np from PyQt4.QtGui import QIntValidator, QDoubleValidator, QApplication, QSizePolicy from orangewidget import gui from orangewidget.settings import Setting from oasys.widgets import widget import orangecanvas.resources as resources import sys, os from crystalpy.util.PolarizedPhotonBunch import Polariz...
gui.button(box0, self, "Help", callback=self.get_doc) self.process_showers() box = gui.widgetBox(self.controlArea, " ",orientation="vertical") idx = -1 # widget index 0 idx += 1 box1 = gui.widgetBox(box) gui.comboBox(box1, s...
gui.button(box0, self, "Compute", callback=self.calculate_IdealLinearPolarizer) gui.button(box0, self, "Defaults", callback=self.defaults)
random_line_split
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn test(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq...
} #[cfg(not(feature="clang_4_0"))] fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) { let file = tu.get_file(f).unwrap(); assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); } test_get_skipped_ranges(tu, f); }); ...
{ assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); }
conditional_block
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn test(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq...
test_get_skipped_ranges(tu, f); }); super::with_file(&clang, "#ifndef _TEST_H_\n#define _TEST_H_\nint a = 322;\n#endif", |_, f| { assert!(f.is_include_guarded()); }); let source = r#" void f() { int a = 2 + 2; double b = 0.25 * 2.0; const c...
{ let file = tu.get_file(f).unwrap(); assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); }
identifier_body
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn
(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq!(file.get_contents(), Some("int a = 322;".into())); } #[cfg(not(feature="clan...
test
identifier_name
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn test(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq...
assert!(f.get_time() != 0); super::with_file(&clang, "int a = 322;", |_, g| assert!(f.get_id() != g.get_id())); assert_eq!(f.get_skipped_ranges(), &[]); assert!(!f.is_include_guarded()); }); let source = " #if 0 int skipped = 32; #endif int unskip...
test_get_contents(&f); }); super::with_file(&clang, "int a = 322;", |p, f| { assert_eq!(f.get_path(), p.to_path_buf());
random_line_split
typedefRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
extends Lint.RuleWalker { public visitFunctionDeclaration(node: ts.FunctionDeclaration) { this.handleCallSignature(node); super.visitFunctionDeclaration(node); } public visitFunctionExpression(node: ts.FunctionExpression) { this.handleCallSignature(node); super.visitFunctio...
TypedefWalker
identifier_name
typedefRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
private checkTypeAnnotation(option: string, location: number, typeAnnotation: ts.TypeNode, name?: ts.Node) { if (this.hasOption(option) && typeAnnotation == null) { let ns = ""; if (name...
{ const location = (node.parameters != null) ? node.parameters.end : null; // set accessors can't have a return type. if (node.kind !== ts.SyntaxKind.SetAccessor) { this.checkTypeAnnotation("call-signature", location, node.type, node.name); } }
identifier_body
typedefRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
let failure = this.createFailure(location, 1, "expected " + option + ns + " to have a typedef"); this.addFailure(failure); } } }
{ ns = `: '${(<ts.Identifier> name).text}'`; }
conditional_block
typedefRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
this.handleCallSignature(node); super.visitFunctionExpression(node); } public visitGetAccessor(node: ts.AccessorDeclaration) { this.handleCallSignature(node); super.visitGetAccessor(node); } public visitMethodDeclaration(node: ts.MethodDeclaration) { this.handle...
random_line_split
tts.py
"""Support for the cloud for text to speech service.""" from hass_nabucasa import Cloud from hass_nabucasa.voice import MAP_VOICE, VoiceError import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from .const import DOMAIN CONF_GENDER = "gender" SUPPORT_LANGUAGES = l...
async def async_get_tts_audio(self, message, language, options=None): """Load TTS from NabuCasa Cloud.""" # Process TTS try: data = await self.cloud.voice.process_tts( message, language, gender=options[CONF_GENDER] ) except VoiceError: ...
"""Return a dict include default options.""" return {CONF_GENDER: self._gender}
identifier_body
tts.py
"""Support for the cloud for text to speech service.""" from hass_nabucasa import Cloud from hass_nabucasa.voice import MAP_VOICE, VoiceError import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from .const import DOMAIN CONF_GENDER = "gender" SUPPORT_LANGUAGES = l...
else: language = config[CONF_LANG] gender = config[CONF_GENDER] return CloudProvider(cloud, language, gender) class CloudProvider(Provider): """NabuCasa Cloud speech API provider.""" def __init__(self, cloud: Cloud, language: str, gender: str) -> None: """Initialize cloud pr...
language = None gender = None
conditional_block
tts.py
"""Support for the cloud for text to speech service.""" from hass_nabucasa import Cloud from hass_nabucasa.voice import MAP_VOICE, VoiceError import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from .const import DOMAIN CONF_GENDER = "gender" SUPPORT_LANGUAGES = l...
(self, message, language, options=None): """Load TTS from NabuCasa Cloud.""" # Process TTS try: data = await self.cloud.voice.process_tts( message, language, gender=options[CONF_GENDER] ) except VoiceError: return (None, None) ...
async_get_tts_audio
identifier_name
tts.py
"""Support for the cloud for text to speech service.""" from hass_nabucasa import Cloud from hass_nabucasa.voice import MAP_VOICE, VoiceError import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from .const import DOMAIN CONF_GENDER = "gender" SUPPORT_LANGUAGES = l...
), validate_lang, ) async def async_get_engine(hass, config, discovery_info=None): """Set up Cloud speech component.""" cloud: Cloud = hass.data[DOMAIN] if discovery_info is not None: language = None gender = None else: language = config[CONF_LANG] gender = con...
PLATFORM_SCHEMA.extend( { vol.Optional(CONF_LANG): str, vol.Optional(CONF_GENDER): str, }
random_line_split
letter-data.js
jQuery.fn.resolveLetterData = function() { var letterTypes = []; letterTypes.push("Peraturan"); letterTypes.push("Pedoman"); letterTypes.push("Petunjuk Pelaksanaan"); letterTypes.push("Instruksi"); letterTypes.push("Prosedur Tetap (SOP)"); letterTypes.push("Surat Edaran"); letterTypes.push("Keputusan");...
$(document).ready(function() { $(".resolve-letter-data").resolveLetterData(); $("#search-type").change(function(){ $("select[id='search-type'] option:selected").each(function(){ updateSearchDateVisibility(this); }); }); });
{ var searchByDate = ($(e).attr("data-type") === "date"); if (searchByDate) { $(".search-date").removeClass("hidden"); $("#search-string").addClass("hidden"); } else { $(".search-date").addClass("hidden"); $("#search-string").removeClass("hidden"); } }
identifier_body
letter-data.js
jQuery.fn.resolveLetterData = function() { var letterTypes = []; letterTypes.push("Peraturan"); letterTypes.push("Pedoman"); letterTypes.push("Petunjuk Pelaksanaan"); letterTypes.push("Instruksi"); letterTypes.push("Prosedur Tetap (SOP)"); letterTypes.push("Surat Edaran"); letterTypes.push("Keputusan");...
(e) { var searchByDate = ($(e).attr("data-type") === "date"); if (searchByDate) { $(".search-date").removeClass("hidden"); $("#search-string").addClass("hidden"); } else { $(".search-date").addClass("hidden"); $("#search-string").removeClass("hidden"); } } $(document).ready(function() { $("....
updateSearchDateVisibility
identifier_name
letter-data.js
jQuery.fn.resolveLetterData = function() { var letterTypes = []; letterTypes.push("Peraturan"); letterTypes.push("Pedoman"); letterTypes.push("Petunjuk Pelaksanaan"); letterTypes.push("Instruksi"); letterTypes.push("Prosedur Tetap (SOP)"); letterTypes.push("Surat Edaran"); letterTypes.push("Keputusan");...
else if (type == "status") { $(item).text(letterStatus[value]); $(item).addClass("label label-" + letterStatusClasses[value]); } } else { $(item).text("Tidak diketahui"); } } } function updateSearchDateVisibility(e) { var searchByDate = ($(e).attr("data-type") === "date"); if ...
{ $(item).text(letterPriorities[value]); $(item).addClass("label label-" + letterPrioritiesClasses[value]); }
conditional_block
letter-data.js
jQuery.fn.resolveLetterData = function() { var letterTypes = []; letterTypes.push("Peraturan"); letterTypes.push("Pedoman"); letterTypes.push("Petunjuk Pelaksanaan"); letterTypes.push("Instruksi"); letterTypes.push("Prosedur Tetap (SOP)"); letterTypes.push("Surat Edaran"); letterTypes.push("Keputusan");...
$(item).addClass("label label-" + letterClassificationClasses[value]); } else if (type == "priority") { $(item).text(letterPriorities[value]); $(item).addClass("label label-" + letterPrioritiesClasses[value]); } else if (type == "status") { $(item).text(letterStatus[value]); ...
$(item).text(letterTypes[value]); else if (type == "classification") { $(item).text(letterClassifications[value]);
random_line_split
path.rs
use fnv; use super::Entry; #[derive(Debug, Clone)] pub struct Path { pub src: u32, pub dst: u32, pub path: Result<Vec<u32>,PathError>, } #[derive(Debug, Clone)] pub enum PathError { NoSuchPath, Terminated(u32) } impl Path { pub fn len(&self) -> Option<usize> { if let Ok(ref v) = self....
}, Err(PathError::NoSuchPath) => println!("\tNo such path exists"), Err(PathError::Terminated(i)) => println!("\tSearch expired after {} iterations", i), } println!("\tlen = {:?}", self.len()); } }
println!("\t{}:\t\"{}\"", i, entries[i].title);
random_line_split
path.rs
use fnv; use super::Entry; #[derive(Debug, Clone)] pub struct Path { pub src: u32, pub dst: u32, pub path: Result<Vec<u32>,PathError>, } #[derive(Debug, Clone)] pub enum PathError { NoSuchPath, Terminated(u32) } impl Path { pub fn len(&self) -> Option<usize> { if let Ok(ref v) = self....
else { None } } pub fn is_empty(&self) -> bool { if let Ok(ref v) = self.path { v.len() <= 1 } else { false } } pub fn print(&self, entries: &fnv::FnvHashMap<u32,Entry>) { println!("Path from {}\t(\"{}\")", self.src, entries.ge...
{ Some(v.len()-1) }
conditional_block
path.rs
use fnv; use super::Entry; #[derive(Debug, Clone)] pub struct
{ pub src: u32, pub dst: u32, pub path: Result<Vec<u32>,PathError>, } #[derive(Debug, Clone)] pub enum PathError { NoSuchPath, Terminated(u32) } impl Path { pub fn len(&self) -> Option<usize> { if let Ok(ref v) = self.path { Some(v.len()-1) } else { Non...
Path
identifier_name
demo.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { Http, XHRBackend, RequestOptions, BrowserXhr, BaseRequestOptions, ResponseOptions, BaseResponseOptions, XSRFStrategy, CookieXSRFStrategy } from '@angular/http'; import { Demo } from './demo.component';...
{}
DemoModule
identifier_name
demo.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { Http, XHRBackend, RequestOptions, BrowserXhr, BaseRequestOptions, ResponseOptions, BaseResponseOptions, XSRFStrategy, CookieXSRFStrategy } from '@angular/http'; import { Demo } from './demo.component';...
provide: RequestOptions, useClass: BaseRequestOptions }, { provide: ResponseOptions, useClass: BaseResponseOptions }, XHRBackend, { provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy() } ]; @NgModule({ declarations: [Demo], imports: [BrowserModule, W...
BrowserXhr, {
random_line_split
template.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # This is a virtual module that is entirely implemented as an action plugin and runs on the controller from __future__ import absolute_import, ...
version_added: historical options: follow: description: - Determine whether symbolic links should be followed. - When set to C(yes) symbolic links will be followed, if they exist. - When set to C(no) symbolic links will not be followed. - Previous to Ansible 2.4, this was hardcoded as C(yes). ...
DOCUMENTATION = r''' --- module: template
random_line_split
main.js
setInterval(function () { update(); }, 1000); function update() { var currentdate = new Date(); var arrTime = [currentdate.getHours(),currentdate.getMinutes(),currentdate.getSeconds()]; //arrTime = [23,59,59]; var i = 0; var d = 1; do
while(i<arrTime.length); } /** * * @param digit * @param lights */ function lightsOn(digit, lights) { if (lights) { var i = 1; do { var $el = $(".linearWatch ul:nth-child(" + digit + ") li:nth-child(" + i + ")"); $el.addClass("active"); i++; } while (i<=li...
{ lightsOn(d, Math.floor(arrTime[i]/10)); lightsOn(d+1, arrTime[i] % 10); d=d+2; i++; }
conditional_block
main.js
setInterval(function () { update(); }, 1000); function update() { var currentdate = new Date(); var arrTime = [currentdate.getHours(),currentdate.getMinutes(),currentdate.getSeconds()]; //arrTime = [23,59,59]; var i = 0; var d = 1; do{ lightsOn(d, Math.floor(arrTime[i]/10)); lightsOn(d...
(digit, lights) { if (lights) { var i = 1; do { var $el = $(".linearWatch ul:nth-child(" + digit + ") li:nth-child(" + i + ")"); $el.addClass("active"); i++; } while (i<=lights); }else{ $(".linearWatch ul:nth-child(" + digit + ") li").removeClass("active");...
lightsOn
identifier_name
main.js
setInterval(function () { update(); }, 1000); function update() { var currentdate = new Date(); var arrTime = [currentdate.getHours(),currentdate.getMinutes(),currentdate.getSeconds()]; //arrTime = [23,59,59]; var i = 0; var d = 1; do{ lightsOn(d, Math.floor(arrTime[i]/10)); lightsOn(d...
* * @param digit * @param lights */ function lightsOn(digit, lights) { if (lights) { var i = 1; do { var $el = $(".linearWatch ul:nth-child(" + digit + ") li:nth-child(" + i + ")"); $el.addClass("active"); i++; } while (i<=lights); }else{ $(".linearWat...
} while(i<arrTime.length); } /**
random_line_split
main.js
setInterval(function () { update(); }, 1000); function update() { var currentdate = new Date(); var arrTime = [currentdate.getHours(),currentdate.getMinutes(),currentdate.getSeconds()]; //arrTime = [23,59,59]; var i = 0; var d = 1; do{ lightsOn(d, Math.floor(arrTime[i]/10)); lightsOn(d...
{ if (lights) { var i = 1; do { var $el = $(".linearWatch ul:nth-child(" + digit + ") li:nth-child(" + i + ")"); $el.addClass("active"); i++; } while (i<=lights); }else{ $(".linearWatch ul:nth-child(" + digit + ") li").removeClass("active"); } }
identifier_body
rpm_md_test.py
from mock import patch, call import mock from lxml import etree from kiwi.solver.repository.rpm_md import SolverRepositoryRpmMd from kiwi.solver.repository.base import SolverRepositoryBase class TestSolverRepositoryRpmMd: def
(self): self.xml_data = etree.parse('../data/repomd.xml') self.uri = mock.Mock() self.solver = SolverRepositoryRpmMd(self.uri) @patch.object(SolverRepositoryBase, 'download_from_repository') @patch.object(SolverRepositoryBase, '_create_solvables') @patch.object(SolverRepositoryBase,...
setup
identifier_name
rpm_md_test.py
from mock import patch, call import mock from lxml import etree from kiwi.solver.repository.rpm_md import SolverRepositoryRpmMd from kiwi.solver.repository.base import SolverRepositoryBase class TestSolverRepositoryRpmMd: def setup(self): self.xml_data = etree.parse('../data/repomd.xml') self.u...
@patch.object(SolverRepositoryBase, '_get_repomd_xml') def test_timestamp(self, mock_xml): mock_xml.return_value = self.xml_data assert self.solver.timestamp() == '1478352191'
random_line_split
rpm_md_test.py
from mock import patch, call import mock from lxml import etree from kiwi.solver.repository.rpm_md import SolverRepositoryRpmMd from kiwi.solver.repository.base import SolverRepositoryBase class TestSolverRepositoryRpmMd: def setup(self):
@patch.object(SolverRepositoryBase, 'download_from_repository') @patch.object(SolverRepositoryBase, '_create_solvables') @patch.object(SolverRepositoryBase, '_create_temporary_metadata_dir') @patch.object(SolverRepositoryBase, '_get_repomd_xml') def test__setup_repository_metadata( self, m...
self.xml_data = etree.parse('../data/repomd.xml') self.uri = mock.Mock() self.solver = SolverRepositoryRpmMd(self.uri)
identifier_body
matrix.rs
} /// Swaps the content from two rows. pub fn swap_rows(&mut self, ya: usize, yb: usize) { if ya == yb { return; } for x in 0..self.n { self.swap((x,ya),(x,yb)); } } } impl <T: Zero> Matrix<T> { /// Creates a new matrix initialized to zero. pub fn
(n: usize, m: usize) -> Self { Matrix::new(n,m, |_,_| T::zero()) } } impl <T: Clone> Matrix<T> { /// Returns a new Vector, cloned from the given row. pub fn row(&self, y: usize) -> Vector<T> { Vector::new(self.n, |i| self[(i,y)].clone()) } /// Returns a new Vector, cloned from the...
zero
identifier_name
matrix.rs
/// Swaps the content from two rows. pub fn swap_rows(&mut self, ya: usize, yb: usize) { if ya == yb
for x in 0..self.n { self.swap((x,ya),(x,yb)); } } } impl <T: Zero> Matrix<T> { /// Creates a new matrix initialized to zero. pub fn zero(n: usize, m: usize) -> Self { Matrix::new(n,m, |_,_| T::zero()) } } impl <T: Clone> Matrix<T> { /// Returns a new Vector,...
{ return; }
conditional_block
matrix.rs
/// Swaps the content from two rows. pub fn swap_rows(&mut self, ya: usize, yb: usize) { if ya == yb { return; } for x in 0..self.n { self.swap((x,ya),(x,yb)); } } } impl <T: Zero> Matrix<T> { /// Creates a new matrix initialized to zero. pub fn zero(n: usize, m...
} impl <T: Clone + Num> Matrix<T> { /// Returns the square norm of a matrix: the sum of the square of all cells. pub fn square_norm(&self) -> T { self.data.iter().map(|a| a.clone() * a.clone()).fold(T::zero(), |a,b| a+b) } /// Returns the matrix determinant. /// /// Returns zero for n...
{ Matrix::scalar(n, T::one()) }
identifier_body
matrix.rs
} /// Swaps the content from two rows. pub fn swap_rows(&mut self, ya: usize, yb: usize) { if ya == yb { return; } for x in 0..self.n { self.swap((x,ya),(x,yb)); } } } impl <T: Zero> Matrix<T> { /// Creates a new matrix initialized to zero. pub fn zero(n: usiz...
let mut m = Matrix::zero(n,n); for (i,x) in vector.into_iter().enumerate() { m[(i,i)] = x; } m } /// Creates a new scalar matrix with the given value. pub fn scalar(n: usize, value: T) -> Self { Matrix::diagonal(Vector::from_copies(n, value)) } } imp...
pub fn diagonal(vector: Vector<T>) -> Self { let n = vector.dim();
random_line_split
edit.ts
import {autoinject} from 'aurelia-framework'; import {Customer} from './customer'; import {CustomerData} from './customerData'; import {Router} from 'aurelia-router'; import { default as swal } from 'sweetalert2'; @autoinject() export class Edit { dataService: CustomerData; router: Router; customer: Customer; ...
self.router.navigate("list"); }).catch(function() { swal('Oops...', 'Something went wrong!', 'error'); }); swal('Deleted!', 'Your customer has been deleted.', 'success'); }); }; areEqual(obj1: object | null, obj2: object | null): boolean { if(obj1 && !obj2) { r...
self.dataService.delete(self.customer) .then(customer => { self.original = customer;
random_line_split
edit.ts
import {autoinject} from 'aurelia-framework'; import {Customer} from './customer'; import {CustomerData} from './customerData'; import {Router} from 'aurelia-router'; import { default as swal } from 'sweetalert2'; @autoinject() export class Edit { dataService: CustomerData; router: Router; customer: Customer; ...
() { this.dataService.save(this.customer) .then(customer => { this.original = customer; this.router.navigate("list"); }); }; delete() { let self = this; swal({ title: `Are you sure you want to delete this customer?`, text: `${this.customer.firstName} ${this.cust...
save
identifier_name
edit.ts
import {autoinject} from 'aurelia-framework'; import {Customer} from './customer'; import {CustomerData} from './customerData'; import {Router} from 'aurelia-router'; import { default as swal } from 'sweetalert2'; @autoinject() export class Edit { dataService: CustomerData; router: Router; customer: Customer; ...
; get isUnchanged() { return this.areEqual(this.customer, this.original); } save() { this.dataService.save(this.customer) .then(customer => { this.original = customer; this.router.navigate("list"); }); }; delete() { let self = this; swal({ title: `Are you ...
{ return this.dataService.getById(id) .then(customer => this.customer = customer); }
identifier_body
edit.ts
import {autoinject} from 'aurelia-framework'; import {Customer} from './customer'; import {CustomerData} from './customerData'; import {Router} from 'aurelia-router'; import { default as swal } from 'sweetalert2'; @autoinject() export class Edit { dataService: CustomerData; router: Router; customer: Customer; ...
return Object.keys(obj1).every((key) => obj2.hasOwnProperty(key) && (obj1[key] === obj2[key])); } }
{ return true; }
conditional_block
validator.js
c) 2013 Spiceworks, Inc. * Made by Cina Saffary (@1000hz) in the style of Bootstrap 3 era @fat * * 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 li...
}, this)) if (!errors.length && $el.val() && $el.data('remote')) { this.defer($el, function () { $.get($el.data('remote'), [$el.attr('name'), $el.val()].join('=')) .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) }) .always(function ...
{ var error = getErrorMessage(key) !~errors.indexOf(error) && errors.push(error) }
conditional_block
validator.js
(c) 2013 Spiceworks, Inc. * Made by Cina Saffary (@1000hz) in the style of Bootstrap 3 era @fat * * 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 ...
(key) { return $el.data(key + '-error') || $el.data('error') || key == 'native' && $el[0].validationMessage || options.errors[key] } $.each(Validator.VALIDATORS, $.proxy(function (key, validator) { if (($el.data(key) || key == 'native') && !validator.call(this, $el)) { ...
getErrorMessage
identifier_name
validator.js
c) 2013 Spiceworks, Inc. * Made by Cina Saffary (@1000hz) in the style of Bootstrap 3 era @fat * * 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 li...
var old = $.fn.validator $.fn.validator = Plugin $.fn.validator.Constructor = Validator // VALIDATOR NO CONFLICT // ===================== $.fn.validator.noConflict = function ()
{ return this.each(function () { var $this = $(this) var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option) var data = $this.data('bs.validator') if (!data && option == 'destroy') return if (!data) $this.data('bs.validator', (data = new ...
identifier_body
validator.js
(c) 2013 Spiceworks, Inc. * Made by Cina Saffary (@1000hz) in the style of Bootstrap 3 era @fat * * 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 ...
} return !!this.$element.find(':input:enabled').filter(fieldErrors).length } Validator.prototype.isIncomplete = function () { function fieldIncomplete() { return this.type === 'checkbox' ? !this.checked : this.type === 'radio' ? !$('[name="' + th...
Validator.prototype.hasErrors = function () { function fieldErrors() { return !!($(this).data('bs.validator.errors') || []).length
random_line_split
image-upload-panel.component.ts
/** * Created by qhyang on 2017/9/26. */ import { Component, EventEmitter, OnInit, Input, Output } from "@angular/core"; import { FileUploader } from "ng2-file-upload"; import { Image } from "../interfaces"; @Component({ selector: "image-upload-panel", template: require("./image-upload-panel.c...
}; } remove (index: number) { this.onRemoved.emit(index); } }
{ let images: Image[] = this.images || []; this.uploader.onSuccessItem = (item, response: any) => { response = JSON.parse(response); if (response.code === 1) { images.push({ url: response.data.file.url, title: ite...
identifier_body
image-upload-panel.component.ts
/** * Created by qhyang on 2017/9/26. */ import { Component, EventEmitter, OnInit, Input, Output } from "@angular/core"; import { FileUploader } from "ng2-file-upload"; import { Image } from "../interfaces"; @Component({ selector: "image-upload-panel", template: require("./image-upload-panel.c...
() { let images: Image[] = this.images || []; this.uploader.onSuccessItem = (item, response: any) => { response = JSON.parse(response); if (response.code === 1) { images.push({ url: response.data.file.url, title: ...
ngOnInit
identifier_name
image-upload-panel.component.ts
/** * Created by qhyang on 2017/9/26. */ import { Component, EventEmitter, OnInit, Input, Output } from "@angular/core"; import { FileUploader } from "ng2-file-upload"; import { Image } from "../interfaces"; @Component({ selector: "image-upload-panel", template: require("./image-upload-panel.c...
this.onRemoved.emit(index); } }
}; } remove (index: number) {
random_line_split
image-upload-panel.component.ts
/** * Created by qhyang on 2017/9/26. */ import { Component, EventEmitter, OnInit, Input, Output } from "@angular/core"; import { FileUploader } from "ng2-file-upload"; import { Image } from "../interfaces"; @Component({ selector: "image-upload-panel", template: require("./image-upload-panel.c...
else { // TODO: add error handler } }; this.uploader.onCompleteAll = () => { this.onUploaded.emit(images); this.showBackgroundImageConfig = false; this.uploader.clearQueue(); }; } remove (index: number) { ...
{ images.push({ url: response.data.file.url, title: item.file.name }); }
conditional_block
outputFormat.spec.js
/* global expect */ describe('outputFormat', () => { describe('when given a format', () => { it('decides the output that will be used for serializing errors', () => { expect( function () { const clonedExpect = expect.clone().outputFormat('html'); clonedExpect(42, 'to equal', 24);...
{ htmlMessage: '<div style="font-family: monospace; white-space: nowrap">' + '<div><span style="color: red; font-weight: bold">expected</span>&nbsp;<span style="color: #0086b3">42</span>&nbsp;<span style="color: red; font-weight: bold">to&nbsp;equal</span>&nbsp;<span style="col...
'to throw',
random_line_split
two_sum_iii_data_structure_design.js
/** * @constructor */ var TwoSum = function() { this.dict = {}; }; /** * @param {number} input * @returns {void} */ TwoSum.prototype.add = function(input) { // no need to bigger that 2 this.dict[input] = this.dict[input] ? 2 : 1; }; /** * @param {number} val * @returns {boolean} */ TwoSum.prototype.find...
return false; }; var eq = require('assert').equal; var ts = new TwoSum(); ts.add(0); ts.find(0) eq(ts.find(0), false); ts = new TwoSum(); ts.add(0); ts.add(0); ts.find(0) eq(ts.find(0), true); ts = new TwoSum(); ts.add(1); ts.add(3); ts.add(5); eq(ts.find(1), false); eq(ts.find(4), true); eq(ts.find(7), false);...
{ var key = parseInt(keys[i]); var target = val - key; if (!dict[target]) continue; if ((target === key && dict[target] === 2) || target !== key) { return true; } }
conditional_block
two_sum_iii_data_structure_design.js
/** * @constructor */ var TwoSum = function() { this.dict = {}; }; /** * @param {number} input * @returns {void} */ TwoSum.prototype.add = function(input) { // no need to bigger that 2 this.dict[input] = this.dict[input] ? 2 : 1; }; /** * @param {number} val * @returns {boolean} */ TwoSum.prototype.find...
target !== key) { return true; } } return false; }; var eq = require('assert').equal; var ts = new TwoSum(); ts.add(0); ts.find(0) eq(ts.find(0), false); ts = new TwoSum(); ts.add(0); ts.add(0); ts.find(0) eq(ts.find(0), true); ts = new TwoSum(); ts.add(1); ts.add(3); ts.add(5); eq(ts.find(1)...
if ((target === key && dict[target] === 2) ||
random_line_split
caa.rs
use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::os::raw::{c_char, c_int, c_uchar, c_void}; use std::ptr; use std::slice; use itertools::Itertools; use crate::error::{Error, Result}; use crate::panic; /// The result of a successful CAA lookup. #[derive(Debug)] pub struct CAAResults { caa_...
(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self { CAAResults { caa_reply, phantom: PhantomData, } } /// Returns an iterator over the `CAAResult` values in this `CAAResults`. pub fn iter(&self) -> CAAResultsIter { CAAResultsIter { next: unsafe...
new
identifier_name
caa.rs
use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::os::raw::{c_char, c_int, c_uchar, c_void}; use std::ptr; use std::slice; use itertools::Itertools; use crate::error::{Error, Result}; use crate::panic; /// The result of a successful CAA lookup. #[derive(Debug)] pub struct CAAResults { caa_...
else { Err(Error::from(parse_status)) } } fn new(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self { CAAResults { caa_reply, phantom: PhantomData, } } /// Returns an iterator over the `CAAResult` values in this `CAAResults`. pub fn ite...
{ let caa_result = CAAResults::new(caa_reply); Ok(caa_result) }
conditional_block
caa.rs
use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::os::raw::{c_char, c_int, c_uchar, c_void}; use std::ptr; use std::slice; use itertools::Itertools; use crate::error::{Error, Result}; use crate::panic; /// The result of a successful CAA lookup. #[derive(Debug)] pub struct CAAResults { caa_...
/// Iterator of `CAAResult`s. #[derive(Clone, Copy)] pub struct CAAResultsIter<'a> { next: Option<&'a c_ares_sys::ares_caa_reply>, } impl<'a> Iterator for CAAResultsIter<'a> { type Item = CAAResult<'a>; fn next(&mut self) -> Option<Self::Item> { let opt_reply = self.next; self.next = opt_r...
let results = self.iter().format("}, {"); write!(fmt, "[{{{}}}]", results) } }
random_line_split
__manifest__.py
# -*- coding: utf-8 -*- # Copyright 2015 Antiun Ingeniería S.L. - Antonio Espinosa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': "Manage model export profiles",
'data': [ 'views/assets.xml', 'views/ir_exports.xml', 'views/ir_model.xml', 'views/ir_model_access.xml', 'views/res_groups.xml', ], 'qweb': [ "static/src/xml/base.xml", ], 'author': 'Tecnativa, ' 'LasLabs, ' 'Ursa Informatio...
'category': 'Personalization', 'version': '10.0.1.0.0', 'depends': [ 'web', ],
random_line_split
everflourish.js
TELLSTICK_TOGGLE: 8, //TELLSTICK_DIM: 16, TELLSTICK_LEARN: 32, //TELLSTICK_EXECUTE: 64, //TELLSTICK_UP: 128, //TELLSTICK_DOWN: 256, //TELLSTICK_STOP: 512 }; function getStringSelflearningForCode(intHouse, intCode, method) { var action = 0; switch(method) { case methods.TELLSTICK_TURNON: case 'turnon': a...
function normalizeDevice(params) { var pubs = []; var device = { //group: params.house, }; if(!params.group) { //device.unit = params.unit; } var deviceId = normalizeDeviceId(params); if(['turnon', 'turnoff', 'dim'].indexOf(params.method) > -1) { device.power = params.method == 'turnon' || (params.metho...
{ return `everflourish/${params.house}/${params.unit}`; }
identifier_body
everflourish.js
//TELLSTICK_TOGGLE: 8, //TELLSTICK_DIM: 16, TELLSTICK_LEARN: 32, //TELLSTICK_EXECUTE: 64, //TELLSTICK_UP: 128, //TELLSTICK_DOWN: 256, //TELLSTICK_STOP: 512 }; function getStringSelflearningForCode(intHouse, intCode, method) { var action = 0; switch(method) { case methods.TELLSTICK_TURNON: case 'turnon': ...
lo = 0x12; } x = lo | hi; } for(i = 0; i < 16; i++) { if(x & bit) { res = res ^ bits[i]; } bit = bit << 1; } return res; } function decodeData(allData) { var house = (allData & 0xFFFC00) >> 10; var unit = ((allData & 0x300) >> 8) + 1; var method = allData & 0xF; const methodsAvailable = { ...
if(lo>0x100) {
random_line_split
everflourish.js
//TELLSTICK_TOGGLE: 8, //TELLSTICK_DIM: 16, TELLSTICK_LEARN: 32, //TELLSTICK_EXECUTE: 64, //TELLSTICK_UP: 128, //TELLSTICK_DOWN: 256, //TELLSTICK_STOP: 512 }; function getStringSelflearningForCode(intHouse, intCode, method) { var action = 0; switch(method) { case methods.TELLSTICK_TURNON: case 'turnon': ...
return { class: 'command', protocol: 'everflourish', model: 'selflearning', house: house, unit: unit, method: methodsAvailable[method] }; } function normalizeDeviceId(params) { return `everflourish/${params.house}/${params.unit}`; } function normalizeDevice(params) { var pubs = []; var device = { ...
{ // not everflourish console.error('Could not decode Everflourish:', allData, { class: 'command', protocol: 'everflourish', model: 'selflearning', house: house, unit: unit, method: method }); return {error: 'Could not decode'}; }
conditional_block
everflourish.js
//TELLSTICK_TOGGLE: 8, //TELLSTICK_DIM: 16, TELLSTICK_LEARN: 32, //TELLSTICK_EXECUTE: 64, //TELLSTICK_UP: 128, //TELLSTICK_DOWN: 256, //TELLSTICK_STOP: 512 }; function getStringSelflearningForCode(intHouse, intCode, method) { var action = 0; switch(method) { case methods.TELLSTICK_TURNON: case 'turnon': ...
(topic, value) { // everflourish/1234/1/power/set, 1 var [protocol, house, unit, prop] = topic.split('/'); if(prop == 'set') { prop = unit; unit = null; } var params = { protocol: 'everflourish', model: 'selflearning', house: house, unit: unit }; if(prop == 'brightness') { params.method = 'dim'; ...
updateDevice
identifier_name
test_views.py
""" Logistration API View Tests """ from unittest.mock import patch from urllib.parse import urlencode import socket import ddt from django.conf import settings from django.urls import reverse from rest_framework.test import APITestCase from common.djangoapps.student.models import Registration from common.djangoapps.s...
def _third_party_login_url(self, backend_name, auth_entry, params): """ Construct the login URL to start third party authentication """ return '{url}?auth_entry={auth_entry}&{param_str}'.format( url=reverse('social:begin', kwargs={'backend': backend_name}), ...
""" Test Setup """ super().setUp() self.url = reverse('mfe_context') self.query_params = {'next': '/dashboard'} hostname = socket.gethostname() ip_address = socket.gethostbyname(hostname) self.country_code = country_code_from_ip(ip_address) # Se...
identifier_body
test_views.py
""" Logistration API View Tests """ from unittest.mock import patch from urllib.parse import urlencode import socket import ddt from django.conf import settings from django.urls import reverse from rest_framework.test import APITestCase from common.djangoapps.student.models import Registration from common.djangoapps.s...
""" Test that api returns details of currently enabled third party auth providers """ response = self.client.get(self.url, self.query_params) params = { 'next': self.query_params['next'] } assert response.status_code == 200 assert response.dat...
def test_third_party_auth_providers(self):
random_line_split
test_views.py
""" Logistration API View Tests """ from unittest.mock import patch from urllib.parse import urlencode import socket import ddt from django.conf import settings from django.urls import reverse from rest_framework.test import APITestCase from common.djangoapps.student.models import Registration from common.djangoapps.s...
(self): """ Test that if tpa_hint is provided, the context returns the third party auth provider even if it is not visible on the login page """ params = { 'next': self.query_params['next'] } tpa_hint = self.hidden_enabled_provider.provider_id ...
test_tpa_hint
identifier_name
StatementParserTest.js
/* * Copyright 2012 Amadeus s.a.s. * 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 i...
seq.$on({ scope : this, end : this._taskParseTemplateEnd }); seq.start(); }, _taskParseTemplate : function (task, args) { var cg = aria.templates.TplClassGenerator; cg.parseTemplate(args.tpl, true, { ...
{ seq.addTask({ name : "testAsyncParseTemplate" + i, fn : this._taskParseTemplate, scope : this, args : toTest[i], asynchronous : true }); }
conditional_block
StatementParserTest.js
/* * Copyright 2012 Amadeus s.a.s. * 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 i...
}, $prototype : { testAsyncParseTemplateErrors : function () { var toTest = [{ tpl : "{Template {$classpath: 'test.aria.templates.test.StmtTemplate'}}{macro main()}{/macro}{/Template}" }, { tpl : "{Template {$classpath: 'test.aria.templates.test.St...
$constructor : function () { this.$TestCase.constructor.call(this);
random_line_split
baseline.py
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
gv = objax.GradValues(loss_function, train_vars) @objax.Function.with_vars(self.vars()) def train_op(step, sx, sy, tx, ty, tu, probe=None): y_probe = eval_op(probe, 1) if probe is not None else None p = step / (FLAGS.train_mimg << 20) lr = self.lr(p) ...
c, h, w = sx.shape[-3:] xu = jn.concatenate((sx, tu)).reshape((-1, c, h, w)) logit = self.model(xu, training=True) logit_sx = jn.split(logit, (2 * sx.shape[0],))[0] logit_sx_weak, logit_sx_strong = logit_sx[::2], logit_sx[1::2] xe = 0.5 * (objax.functional.lo...
identifier_body
baseline.py
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(x: JaxArray, domain: int) -> JaxArray: return objax.functional.softmax(self.model_ema(x, training=False, domain=domain)) def loss_function(sx, sy, tu): c, h, w = sx.shape[-3:] xu = jn.concatenate((sx, tu)).reshape((-1, c, h, w)) logit = self.model(xu, training=T...
eval_op
identifier_name
baseline.py
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
self.model: objax.Module = model(colors=3, nclass=nclass, **kwargs) self.model_ema = objax.optimizer.ExponentialMovingAverageModule(self.model, momentum=0.999) if FLAGS.arch.endswith('pretrain'): # Initialize weights of EMA with pretrained model's weights. self.model_ema....
def __init__(self, nclass: int, model: Callable, **kwargs): super().__init__(nclass, kwargs)
random_line_split
baseline.py
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
else: raise ValueError(f'Augment flag value {FLAGS.augment} not supported.') module.train(FLAGS.train_mimg << 10, FLAGS.report_kimg, train, test, logdir, FLAGS.keep_ckpts) train.stop() if __name__ == '__main__': flags.DEFINE_enum('arch', 'wrn28-2', ARCHS, 'Model architecture.') flags.DEFI...
train = CTAData(source.train, target_labeled.train, target_unlabeled.train, source.nclass, FLAGS.batch, FLAGS.uratio)
conditional_block
batch.rs
use snowchains::app::{App, Modify, Opt}; use snowchains::errors::{JudgeError, JudgeErrorKind}; use snowchains::path::AbsPathBuf; use snowchains::service::ServiceName; use snowchains::terminal::{AnsiColorChoice, Term, TermImpl}; use snowchains::testsuite::SuiteFileExtension; use failure::Fallible; use if_chain::if_chai...
if let JudgeErrorKind::Build { .. } = ctx.get_context(); then {} else { return Err(err.into()) } } if_chain! { let err = app.test(&src_path, WRONG_CODE).unwrap_err(); if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err; if let JudgeErrorKind::TestFailed(2, 2...
app.test(&src_path, CODE)?; if_chain! { let err = app.test(&src_path, INVLID_CODE).unwrap_err(); if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
random_line_split
batch.rs
use snowchains::app::{App, Modify, Opt}; use snowchains::errors::{JudgeError, JudgeErrorKind}; use snowchains::path::AbsPathBuf; use snowchains::service::ServiceName; use snowchains::terminal::{AnsiColorChoice, Term, TermImpl}; use snowchains::testsuite::SuiteFileExtension; use failure::Fallible; use if_chain::if_chai...
(&mut self, timelimit: Duration) -> snowchains::Result<()> { self.run(Opt::Modify(Modify::Timelimit { service: Some(ServiceName::Atcoder), contest: Some("practice".to_owned()), color_choice: AnsiColorChoice::Never, problem: "a".to_owned(), extension: S...
modify_timelimit
identifier_name
batch.rs
use snowchains::app::{App, Modify, Opt}; use snowchains::errors::{JudgeError, JudgeErrorKind}; use snowchains::path::AbsPathBuf; use snowchains::service::ServiceName; use snowchains::terminal::{AnsiColorChoice, Term, TermImpl}; use snowchains::testsuite::SuiteFileExtension; use failure::Fallible; use if_chain::if_chai...
}
{ self.run(Opt::Modify(Modify::Timelimit { service: Some(ServiceName::Atcoder), contest: Some("practice".to_owned()), color_choice: AnsiColorChoice::Never, problem: "a".to_owned(), extension: SuiteFileExtension::Yaml, timelimit: Some(timeli...
identifier_body
server.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import logging import os import sys try: from magic import from_file as magic_from_file except ImportError: magic_from_file = None from six.moves import SimpleHTTPServer as srvmod from six.moves import socketserver class Comple...
logging.warning("Unable to find `%s` or variations.", self.original_path) def guess_type(self, path): """Guess at the mime type for the specified file. """ mimetype = srvmod.SimpleHTTPRequestHandler.guess_type(self, path) # If the default gue...
SUFFIXES = ['', '.html', '/index.html'] def do_GET(self): # Try to detect file by applying various suffixes for suffix in self.SUFFIXES: if not hasattr(self, 'original_path'): self.original_path = self.path self.path = self.original_path + suffix ...
identifier_body
server.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import logging import os import sys try: from magic import from_file as magic_from_file except ImportError: magic_from_file = None from six.moves import SimpleHTTPServer as srvmod from six.moves import socketserver class Comple...
(self): # Try to detect file by applying various suffixes for suffix in self.SUFFIXES: if not hasattr(self, 'original_path'): self.original_path = self.path self.path = self.original_path + suffix path = self.translate_path(self.path) if ...
do_GET
identifier_name
server.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import logging import os import sys try: from magic import from_file as magic_from_file except ImportError: magic_from_file = None from six.moves import SimpleHTTPServer as srvmod from six.moves import socketserver class Comple...
socketserver.TCPServer.allow_reuse_address = True try: httpd = socketserver.TCPServer( (SERVER, PORT), ComplexHTTPRequestHandler) except OSError as e: logging.error("Could not listen on port %s, server %s.", PORT, SERVER) sys.exit(getattr(e, 'exitcode', 1)) logging....
PORT = len(sys.argv) in (2, 3) and int(sys.argv[1]) or 8000 SERVER = len(sys.argv) == 3 and sys.argv[2] or ""
random_line_split
server.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import logging import os import sys try: from magic import from_file as magic_from_file except ImportError: magic_from_file = None from six.moves import SimpleHTTPServer as srvmod from six.moves import socketserver class Comple...
PORT = len(sys.argv) in (2, 3) and int(sys.argv[1]) or 8000 SERVER = len(sys.argv) == 3 and sys.argv[2] or "" socketserver.TCPServer.allow_reuse_address = True try: httpd = socketserver.TCPServer( (SERVER, PORT), ComplexHTTPRequestHandler) except OSError as e: logging.error(...
conditional_block
clone.ts
'use strict'; import { isArray, isObject } from './types'; let cloneDepth = 0; const clone = ( arg: object | Date | any[] | string | number | boolean | null ) => { cloneDepth++; if ( cloneDepth >= 100 ) { cloneDepth = 0; throw new Error( 'max clone depth of 100 reached' ); } let target: any; if ...
target = {}; const myArg = <any>arg; Object.keys( myArg ).forEach( ( field: string ) => { if ( (myArg).hasOwnProperty( field ) ) { target[ field ] = clone( myArg[ field ] ); } } ); } else { // functions, etc. not cloneable, and will pass through, though for primitives like str...
} else if ( isObject( arg ) && arg !== null ) {
random_line_split
clone.ts
'use strict'; import { isArray, isObject } from './types'; let cloneDepth = 0; const clone = ( arg: object | Date | any[] | string | number | boolean | null ) => { cloneDepth++; if ( cloneDepth >= 100 ) { cloneDepth = 0; throw new Error( 'max clone depth of 100 reached' ); } let target: any; if ...
else if ( isObject( arg ) && arg !== null ) { target = {}; const myArg = <any>arg; Object.keys( myArg ).forEach( ( field: string ) => { if ( (myArg).hasOwnProperty( field ) ) { target[ field ] = clone( myArg[ field ] ); } } ); } else { // functions, etc. not cloneable, and wi...
{ target = []; (<any[]>arg).forEach( ( value, i ) => { target[ i ] = clone( value ); } ); }
conditional_block
admin_form_part.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from djang...
def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPric...
name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create...
identifier_body
admin_form_part.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from djang...
def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) ...
self._build_fields()
conditional_block
admin_form_part.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from djang...
(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice...
_process_single_save
identifier_name
admin_form_part.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from djang...
name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_...
def get_shop_field(self, shop):
random_line_split
LoyaltyRounded.js
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "m21.41 11.58-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7zm11.77 8.27-3.92 3.92c-.2.2-.51.2-.71 0l-3.92-3.92c-.57-.58-.87-1.43-.67-2.3...
random_line_split
fields.py
of returned subclass TranslationFieldSpecific.__name__ = 'Translation%s' % baseclass.__name__ return TranslationFieldSpecific class TranslationField(object): """ The translation field functions as a proxy to the original field which is wrapped. For every field defined in the model's ``Trans...
custom fallback value, or field's default value. """ if instance is None: return self default = NONE
random_line_split
fields.py
list of supported fields can be extended by defining a tuple of field names in the projects settings.py like this:: MODELTRANSLATION_CUSTOM_FIELDS = ('MyField', 'MyOtherField',) If the class is neither a subclass of fields in ``SUPPORTED_FIELDS``, nor in ``CUSTOM_FIELDS`` an ``ImproperlyConfigure...
"won't fix": https://code.djangoproject.com/ticket/9590. """ formfield = super(TranslationField, self).formfield(*args, **kwargs) if isinstance(formfield, forms.CharField): if self.empty_value is None: from modeltranslation.forms import NullCharField ...
""" Returns proper formfield, according to empty_values setting (only for ``forms.CharField`` subclasses). There are 3 different formfields: - CharField that stores all empty values as empty strings; - NullCharField that stores all empty values as None (Null); - Nullable...
identifier_body
fields.py
if self.rel and self.related and not self.rel.is_hidden(): import copy current = self.related.get_accessor_name() self.rel = copy.copy(self.rel) # Since fields cannot share the same rel object. # self.related doesn't need to be copied, as it will be recreated in ...
return val
conditional_block
fields.py
of supported fields can be extended by defining a tuple of field names in the projects settings.py like this:: MODELTRANSLATION_CUSTOM_FIELDS = ('MyField', 'MyOtherField',) If the class is neither a subclass of fields in ``SUPPORTED_FIELDS``, nor in ``CUSTOM_FIELDS`` an ``ImproperlyConfigured`` e...
(self, other): if isinstance(other, fields.Field): return (self.creation_counter == other.creation_counter and self.language == getattr(other, 'language', None)) return super(TranslationField, self).__eq__(other) def __ne__(self, other): return not self.__eq_...
__eq__
identifier_name
__init__.py
# Copyright (c) 2017 Mark D. Hill and David A. Wood # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditio...
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUT...
# contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
random_line_split
ftree.py
'''File Tree scanning related functions and classes''' import os class DiskObjInfo(object): '''Hold inforation to identify an object on the disk''' def __init__(self, rel_path, path_on_disk): self.__name = os.path.basename(rel_path) self.__rel_path = rel_path self.__path_on_disk = path...
@property def fileobj_type(self): return self.TYPE_FLAG class DirInfo(DiskObjInfo): '''Hold basic information about a directory''' TYPE_FLAG = 'D' def __init__(self, rel_path, path_on_disk=None): if rel_path[-1] != '/': raise Exception("Dir path should end in '/'...
'''Hold basic information about a file''' TYPE_FLAG = 'F' def __init__(self, rel_path, path_on_disk=None): if rel_path[-1] == '/': raise Exception("File path should not end in '/'") # if path_on_disk is not None: # if not os.path.isfile(path_on_disk): # ...
identifier_body
ftree.py
'''File Tree scanning related functions and classes''' import os class DiskObjInfo(object): '''Hold inforation to identify an object on the disk''' def __init__(self, rel_path, path_on_disk): self.__name = os.path.basename(rel_path) self.__rel_path = rel_path self.__path_on_disk = path...
(DiskObjInfo): '''Hold basic information about a directory''' TYPE_FLAG = 'D' def __init__(self, rel_path, path_on_disk=None): if rel_path[-1] != '/': raise Exception("Dir path should end in '/'") # if path_on_disk is not None: # if not os.path.isdir(path_on_disk)...
DirInfo
identifier_name
ftree.py
'''File Tree scanning related functions and classes''' import os class DiskObjInfo(object): '''Hold inforation to identify an object on the disk''' def __init__(self, rel_path, path_on_disk): self.__name = os.path.basename(rel_path) self.__rel_path = rel_path self.__path_on_disk = path...
# if path_on_disk is not None: # if not os.path.isfile(path_on_disk): # raise Exception("Not a file: " + path_on_disk) super(FileInfo, self).__init__(rel_path, path_on_disk) @property def is_file(self): return True @property def is_dir(self): re...
if rel_path[-1] == '/': raise Exception("File path should not end in '/'")
random_line_split
ftree.py
'''File Tree scanning related functions and classes''' import os class DiskObjInfo(object): '''Hold inforation to identify an object on the disk''' def __init__(self, rel_path, path_on_disk): self.__name = os.path.basename(rel_path) self.__rel_path = rel_path self.__path_on_disk = path...
yield sub_obj
conditional_block
huffman.py
class ResizeError(Exception): pass def codelengths_from_frequencies(freqs): freqs = sorted(freqs.items(), key=lambda item: (item[1], -item[0]), reverse=True) nodes = [Node(char=key, weight=value) for (key, value) in freqs] while len(nodes) > 1: right, left = nodes.pop(), nodes.pop() ...
pos = 0 node = self.root res = bytearray() while pos < len(source): code = int(source[pos]) child = node.children[code] if child.is_leaf: res.append(child) node = self.root else: node = chil...
return self.decompress_bytes()
conditional_block
huffman.py
class ResizeError(Exception): pass def codelengths_from_frequencies(freqs): freqs = sorted(freqs.items(), key=lambda item: (item[1], -item[0]), reverse=True) nodes = [Node(char=key, weight=value) for (key, value) in freqs] while len(nodes) > 1: right, left = nodes.pop(), nodes.pop() ...
pos += 1 nodes.insert(pos, node) top = nodes[0] tree = Tree(top) tree.reduce(15) codes = tree.codes() code_items = list(codes.items()) code_items.sort(key=lambda item:(len(item[1]), item[0])) return [(car, len(value)) for car, value in code_items] def normaliz...
random_line_split