file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
gulpfile.js | var gulp = require('gulp'),
argv = require('yargs').argv,
cache = require('gulp-cache'),
concat = require('gulp-concat'),
del = require('del'),
gulpif = require('gulp-if'),
gutil = require('gulp-util')
notify = require('gulp-notify'),
plumber = require('gulp-plumber'),
q = require('q... |
called = true;
})
.on('restart', function onRestart() {
// Also reload the browsers after a slight delay
setTimeout(function reload() {
browserSync.reload({
stream: false
});
}, 500);
});
});
/**
* Task to start the backend servers.
* Depends on: backend-mongo, backend-ser... | {
cb();
} | conditional_block |
gulpfile.js | var gulp = require('gulp'),
argv = require('yargs').argv,
cache = require('gulp-cache'),
concat = require('gulp-concat'),
del = require('del'),
gulpif = require('gulp-if'),
gutil = require('gulp-util')
notify = require('gulp-notify'),
plumber = require('gulp-plumber'),
q = require('q... | server: {
baseDir: settings.dist
},
ghostMode: {
clicks: true,
location: true,
forms: true,
scroll: true
},
open: "external",
injectChanges: true, // inject CSS changes (false force a reload)
browser: ["google chrome"],
scrollPro... | gulp.watch([settings.dist + '**']).on('change', function(){browserSync.reload({});notify({ message: 'Reload browser' });});
return browserSync({ | random_line_split |
gulpfile.js | var gulp = require('gulp'),
argv = require('yargs').argv,
cache = require('gulp-cache'),
concat = require('gulp-concat'),
del = require('del'),
gulpif = require('gulp-if'),
gutil = require('gulp-util')
notify = require('gulp-notify'),
plumber = require('gulp-plumber'),
q = require('q... | {
// TODO log error with gutil
notify.onError(function (error) {
return error.message;
});
this.emit('end');
} | identifier_body | |
transaction.rs | //! The `transaction` module provides functionality for creating log transactions.
use bincode::serialize;
use hash::{Hash, Hasher};
use serde::Serialize;
use sha2::Sha512;
use signature::{Keypair, KeypairUtil, Signature};
use solana_sdk::pubkey::Pubkey;
use std::mem::size_of;
pub const SIGNED_DATA_OFFSET: usize = si... | <T: Serialize>(
from_keypair: &Keypair,
transaction_keys: &[Pubkey],
program_id: Pubkey,
userdata: &T,
last_id: Hash,
fee: u64,
) -> Self {
let program_ids = vec![program_id];
let accounts = (0..=transaction_keys.len() as u8).collect();
let ins... | new | identifier_name |
transaction.rs | //! The `transaction` module provides functionality for creating log transactions.
use bincode::serialize;
use hash::{Hash, Hasher};
use serde::Serialize;
use sha2::Sha512;
use signature::{Keypair, KeypairUtil, Signature};
use solana_sdk::pubkey::Pubkey;
use std::mem::size_of;
pub const SIGNED_DATA_OFFSET: usize = si... | data.extend_from_slice(&fee_data);
let program_ids = serialize(&self.program_ids).expect("serialize program_ids");
data.extend_from_slice(&program_ids);
let instructions = serialize(&self.instructions).expect("serialize instructions");
data.extend_from_slice(&instructions);
... | data.extend_from_slice(&last_id_data);
let fee_data = serialize(&self.fee).expect("serialize fee"); | random_line_split |
transaction.rs | //! The `transaction` module provides functionality for creating log transactions.
use bincode::serialize;
use hash::{Hash, Hasher};
use serde::Serialize;
use sha2::Sha512;
use signature::{Keypair, KeypairUtil, Signature};
use solana_sdk::pubkey::Pubkey;
use std::mem::size_of;
pub const SIGNED_DATA_OFFSET: usize = si... |
}
/// An atomic transaction
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct Transaction {
/// A digital signature of `account_keys`, `program_ids`, `last_id`, `fee` and `instructions`, signed by `Pubkey`.
pub signature: Signature,
/// The `Pubkeys` that are executing this transa... | {
let userdata = serialize(userdata).unwrap();
Instruction {
program_ids_index,
userdata,
accounts,
}
} | identifier_body |
getqf.py | #!/usr/bin/env python
import pandas as pd
import urllib2
import re
import datetime
from bs4 import BeautifulSoup
from gevent.pool import Pool
def load_files(symbolfilepaths, csvdelim = ","):
"""
Takes a list of symbol file paths to respective csv files, and loads their content into a \
dictionary of file-paths to... |
def add_labels(data_lists, table_labels):
"""
Takes a dictionary with symbols for keys mapped to a list of statistic values.\
Returns a dictionary with symbols for keys mapped to a dictionary with the statistic label \
for keys, and the associated figure for the value. The new dictionary is returned
"""... | symbol = param[0]
data_lists = param[1]
index = param[2]
url = "http://finance.yahoo.com/q/ks?s={}+Key+Statistics".format(symbol)
try:
resp = urllib2.urlopen(url, timeout = 10)
if resp.getcode() == 200:
htmltext = BeautifulSoup(resp.read())
data_table_pattern = "... | identifier_body |
getqf.py | #!/usr/bin/env python
import pandas as pd
import urllib2
import re
import datetime
from bs4 import BeautifulSoup
from gevent.pool import Pool
def | (symbolfilepaths, csvdelim = ","):
"""
Takes a list of symbol file paths to respective csv files, and loads their content into a \
dictionary of file-paths to lists containing the content of the csv. The delimeter of the csv files \
defaults to a ','.
"""
index_lists = {}
for file in symbolfilepaths:
... | load_files | identifier_name |
getqf.py | #!/usr/bin/env python
import pandas as pd
import urllib2
import re
import datetime
from bs4 import BeautifulSoup
from gevent.pool import Pool
def load_files(symbolfilepaths, csvdelim = ","):
"""
Takes a list of symbol file paths to respective csv files, and loads their content into a \
dictionary of file-paths to... |
## End data grab ##
##Take dict of indexes to company symbols to lists of values and return a dataframe of stats ##
float_dict = {}
for index, companydict in qfindexdict.iteritems():
float_dict[index] = remove_number_symbols(companydict)
## End int conversion ##
# Gather stats by index... | if index == 'tsxvct' or index == 'tsxvog':
qfindexdict[index] = get_data(symbollist, index, '.V')
elif index == 'tsxct' or index == 'tsxog':
qfindexdict[index] = get_data(symbollist, index, '.TO')
else:
qfindexdict[index] = get_data(symbollist, index) | conditional_block |
getqf.py | #!/usr/bin/env python
import pandas as pd
import urllib2
import re
import datetime
from bs4 import BeautifulSoup
from gevent.pool import Pool
def load_files(symbolfilepaths, csvdelim = ","):
"""
Takes a list of symbol file paths to respective csv files, and loads their content into a \
dictionary of file-paths to... | # testindexlist = load_files(testlist)
# ##end here##
##Get the data and store it in a dict of indexes to company symbols to lists of values ##
qfindexdict = {}
for index, symbollist in indexlist.iteritems():
if index == 'tsxvct' or index == 'tsxvog':
qfindexdict[index] = get_da... | # # ##test grab##
# testlist = ['dataFiles/nsdqct.csv'] | random_line_split |
main.rs | extern crate getopts;
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate hyper_tls;
extern crate pretty_env_logger;
extern crate ftp;
use std::io::Read;
use getopts::Options;
use std::str;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::stdin;
use std::env;
use ... | match file.write_all(&x) {
Err(why) => {
panic!("couldn't write to {}: {}", display,
why.description())
},
Ok(_) => (),
}
}
println!("successfully wrote to {}", display);
}
fn extract_file_name_if_empty_string(fullpath:... |
for x in &finally { | random_line_split |
main.rs | extern crate getopts;
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate hyper_tls;
extern crate pretty_env_logger;
extern crate ftp;
use std::io::Read;
use getopts::Options;
use std::str;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::stdin;
use std::env;
use ... |
// Download a single file form FTP server
// fn ftps_download_single_file(input: std::string::String, destination: &str){
// }
// Download a single file form FTP server
fn ftp_download_single_file(input: std::string::String, destination: &str){
let (host, directory, file) = parse_data_from_ftp_fullpath(input.c... | {
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
pretty_env_logger::init().unwrap();
// Using args() instead of args_os(), cause they never panic
let commandline_args: Vec<_> = env::args().collect();
let program = commandline_args[0].clone();
// Use the getopts package Options str... | identifier_body |
main.rs | extern crate getopts;
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate hyper_tls;
extern crate pretty_env_logger;
extern crate ftp;
use std::io::Read;
use getopts::Options;
use std::str;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::stdin;
use std::env;
use ... | (url: hyper::Uri, destination: &str){
let mut core = tokio_core::reactor::Core::new().unwrap();
let client = Client::configure().connector(::hyper_tls::HttpsConnector::new(4, &core.handle()).unwrap()).build(&core.handle());
let work = client.get(url);
let reponse = core.run(work).unwrap();
let buf2 =... | https_download_single_file | identifier_name |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... | (
self,
) -> (
UpdateWebhookMessageErrorType,
Option<Box<dyn Error + Send + Sync>>,
) {
(self.kind, self.source)
}
}
impl Display for UpdateWebhookMessageError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match &self.kind {
UpdateWebhookMessa... | into_parts | identifier_name |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... |
// `self` needs to be consumed and the client returned due to parameters
// being consumed in request construction.
fn request(&mut self) -> Result<Request, HttpError> {
let mut request = Request::builder(&Route::UpdateWebhookMessage {
message_id: self.message_id.0,
token: ... | {
self.fields.payload_json = Some(payload_json);
self
} | identifier_body |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... | /// of the original message is unaffected and only the embed(s) are
/// modified.
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_embed_builder::EmbedBuilder;
/// use twilight_model::id::{MessageId, WebhookId};
///
/// # #[tokio::main] async fn main() -> Result<()... | /// Create an embed and update the message with the new embed. The content | random_line_split |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... |
self.fields.components = Some(NullableField(components));
Ok(self)
}
/// Set the content of the message.
///
/// Pass `None` if you want to remove the message content.
///
/// Note that if there is are no embeds then you will not be able to remove
/// the content of the m... | {
validate_inner::components(components).map_err(|source| {
let (kind, inner_source) = source.into_parts();
match kind {
ComponentValidationErrorType::ComponentCount { count } => {
UpdateWebhookMessageError {
... | conditional_block |
131. Custom Exceptions - Coding.py | # %%
'''
### Custom Exceptions
'''
# %%
'''
We can create our own exception types, by simply inheriting from `Exception`. (Usually, we want to inherit from
`Exception`, not `BaseException` since `BaseException` includes exceptions such as `SystemExit`, `KeyboardInterrupt`
and a few others - our custom exceptions mos... |
class DBConnectionError(DBException):
"""Indicates an error connecting to database"""
http_status = HTTPStatus.INTERNAL_SERVER_ERROR
internal_err_msg = "DB connection error."
user_err_msg = "We are sorry. An unexpected error occurred on our end."
class ClientException(APIException):
"""In... | """General database exception"""
http_status = HTTPStatus.INTERNAL_SERVER_ERROR
internal_err_msg = "Database exception."
user_err_msg = "We are sorry. An unexpected error occurred on our end." | identifier_body |
131. Custom Exceptions - Coding.py | # %%
'''
### Custom Exceptions
'''
# %%
'''
We can create our own exception types, by simply inheriting from `Exception`. (Usually, we want to inherit from
`Exception`, not `BaseException` since `BaseException` includes exceptions such as `SystemExit`, `KeyboardInterrupt`
and a few others - our custom exceptions mos... |
# %%
try:
set_age(-10)
except NegativeIntegerError as ex:
print(repr(ex))
# %%
'''
But the problem is that this is also a `ValueError`, and our users may want to trap it as a `ValueError` for some
reason, not a `NegativeIntegerError` (or `AppException` as is possible here).
'''
# %%
'''
The beauty of multi... | raise NegativeIntegerError('age cannot be negative') | conditional_block |
131. Custom Exceptions - Coding.py | # %%
'''
### Custom Exceptions
'''
# %%
'''
We can create our own exception types, by simply inheriting from `Exception`. (Usually, we want to inherit from
`Exception`, not `BaseException` since `BaseException` includes exceptions such as `SystemExit`, `KeyboardInterrupt`
and a few others - our custom exceptions mos... | """Base API exception"""
http_status = HTTPStatus.INTERNAL_SERVER_ERROR
internal_err_msg = 'API exception occurred.'
user_err_msg = "We are sorry. An unexpected error occurred on our end."
def __init__(self, *args, user_err_msg = None):
if args:
self.internal_err_msg = ... | random_line_split | |
131. Custom Exceptions - Coding.py | # %%
'''
### Custom Exceptions
'''
# %%
'''
We can create our own exception types, by simply inheriting from `Exception`. (Usually, we want to inherit from
`Exception`, not `BaseException` since `BaseException` includes exceptions such as `SystemExit`, `KeyboardInterrupt`
and a few others - our custom exceptions mos... | (HTTPException):
"""Indicates the url is invalid (dns lookup fails)"""
class TimeoutException(HTTPException):
"""Indicates a general timeout exception in http connectivity"""
class PingTimeoutException(TimeoutException):
"""Ping time out"""
class LoadTimeoutException(TimeoutException):
""... | InvalidUrlException | identifier_name |
mode.rs | use std::{io,process,str,thread,time};
use std::io::Error;
use std::result::Result;
use regex::Regex;
use serde::{Serialize,Deserialize};
use crate::{fileio,util};
#[derive(Debug)]
pub struct InputMode {
width:String,
height:String,
rate:String,
name:String,
display:String,
}
impl InputMode {
... | .arg(&mode.name)
.arg(&mode.clock)
.arg(&mode.h_disp)
.arg(&mode.h_sync_start)
.arg(&mode.h_sync_end)
.arg(&mode.h_total)
.arg(&mode.v_disp)
.arg(&mode.v_sync_start)
.arg(&mode.v_sync_end)
.arg(&mode.v_total)
.arg(&mode.flags);
... | cmd.arg("--newmode") | random_line_split |
mode.rs | use std::{io,process,str,thread,time};
use std::io::Error;
use std::result::Result;
use regex::Regex;
use serde::{Serialize,Deserialize};
use crate::{fileio,util};
#[derive(Debug)]
pub struct InputMode {
width:String,
height:String,
rate:String,
name:String,
display:String,
}
impl InputMode {
... | {
let mut cmd = process::Command::new("xrandr");
cmd.arg("--newmode")
.arg(&mode.name)
.arg(&mode.clock)
.arg(&mode.h_disp)
.arg(&mode.h_sync_start)
.arg(&mode.h_sync_end)
.arg(&mode.h_total)
.arg(&mode.v_disp)
.arg(&mode.v_sync_start)
.arg... | identifier_body | |
mode.rs | use std::{io,process,str,thread,time};
use std::io::Error;
use std::result::Result;
use regex::Regex;
use serde::{Serialize,Deserialize};
use crate::{fileio,util};
#[derive(Debug)]
pub struct InputMode {
width:String,
height:String,
rate:String,
name:String,
display:String,
}
impl InputMode {
... | (w: Option<&str>, h: Option<&str>, r: Option<&str>, d: Option<&str>, n: Option<&str>, t: Option<&str>, f: Option<&str>, test: bool, save: bool, verbose: bool) -> Result<(),Error> {
let current_modes = get_current_modes(verbose)?;
// Use first current display mode for parameters not supplied
// and as the fa... | add_mode | identifier_name |
model.py | from typing import Union
import numpy as np
from scipy import signal
from .._base_layer import Layer
from .._register import add_to_viewer
from ..._vispy.scene.visuals import Mesh
from ...util.event import Event
from ...util import segment_normal
from vispy.color import get_color_names
from .view import QtVectorsLay... |
else:
self.name = name
self._qt_properties = QtVectorsLayer(self)
# ====================== Property getter and setters =====================
@property
def _original_data(self) -> np.ndarray:
return self._raw_data
@_original_data.setter
def _original_data(self,... | self.name = 'vectors' | conditional_block |
model.py | from typing import Union
import numpy as np
from scipy import signal
from .._base_layer import Layer
from .._register import add_to_viewer
from ..._vispy.scene.visuals import Mesh
from ...util.event import Event
from ...util import segment_normal
from vispy.color import get_color_names
from .view import QtVectorsLay... |
self.events.averaging()
self._update_avg()
self.refresh()
def _update_avg(self):
"""Method for calculating average
Implemented ONLY for image-like vector data
"""
if self._data_type == 'coords':
# default averaging is supported only for 'matrix'... | Parameters
----------
value : int that defines (int, int) kernel
"""
self._averaging = value | random_line_split |
model.py | from typing import Union
import numpy as np
from scipy import signal
from .._base_layer import Layer
from .._register import add_to_viewer
from ..._vispy.scene.visuals import Mesh
from ...util.event import Event
from ...util import segment_normal
from vispy.color import get_color_names
from .view import QtVectorsLay... | (self):
"""Method for calculating average
Implemented ONLY for image-like vector data
"""
if self._data_type == 'coords':
# default averaging is supported only for 'matrix' dataTypes
return
elif self._data_type == 'image':
x, y = self._averagi... | _update_avg | identifier_name |
model.py | from typing import Union
import numpy as np
from scipy import signal
from .._base_layer import Layer
from .._register import add_to_viewer
from ..._vispy.scene.visuals import Mesh
from ...util.event import Event
from ...util import segment_normal
from vispy.color import get_color_names
from .view import QtVectorsLay... |
def _convert_coords_to_coordinates(self, vect) -> np.ndarray:
"""To convert a list of coordinates of shape
(y-center, x-center, y-proj, x-proj) into a list of coordinates
Input coordinate of (N,4) becomes two output coordinates of (N,2)
Parameters
----------
vect :... | """To convert an image-like array with elements (y-proj, x-proj) into a
position list of coordinates
Every pixel position (n, m) results in two output coordinates of (N,2)
Parameters
----------
vect : np.ndarray of shape (N, M, 2)
"""
xdim = vect.shape[0]
... | identifier_body |
draw_trans_pixel_cihea.py | #!/usr/bin/env python
#from shapely.geometry.polygon import Polygon
import os
import sys
import warnings
from datetime import datetime
import numpy as np
from scipy.interpolate import griddata
import shapefile
import shapely
try:
import gdal
except Exception:
from osgeo import gdal
try:
import osr
except Ex... | (longitude,latitude):
utm_zone = (int(1+(longitude.mean()+180.0)/6.0))
is_northern = (1 if latitude.mean() > 0 else 0)
utm_coordinate_system = osr.SpatialReference()
utm_coordinate_system.SetWellKnownGeogCS('WGS84') # Set geographic coordinate system to handle lat/lon
utm_coordinate_system.SetUTM(ut... | transform_wgs84_to_utm | identifier_name |
draw_trans_pixel_cihea.py | #!/usr/bin/env python
#from shapely.geometry.polygon import Polygon
import os
import sys
import warnings
from datetime import datetime
import numpy as np
from scipy.interpolate import griddata
import shapefile
import shapely
try:
import gdal
except Exception:
from osgeo import gdal
try:
import osr
except Ex... |
if opts.add_tmax:
if not tmax in values:
if ds > 1.0:
values.append(tmax)
labels.append(dmax.strftime('%Y-%m'))
else:
values.append(tmax)
labels.append(dmax.strftime('%m/%d'))
torg = date2num(datetime(dmin.year,1,1))
twid = 365.0*2.0
newcolors = mymap... | if not tmin in values:
if ds > 1.0:
values.append(tmin)
labels.append(dmin.strftime('%Y-%m'))
else:
values.append(tmin)
labels.append(dmin.strftime('%m/%d')) | conditional_block |
draw_trans_pixel_cihea.py | #!/usr/bin/env python
#from shapely.geometry.polygon import Polygon
import os
import sys
import warnings
from datetime import datetime
import numpy as np
from scipy.interpolate import griddata
import shapefile
import shapely
try:
import gdal
except Exception:
from osgeo import gdal
try:
import osr
except Ex... |
if opts.batch:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap,LinearSegmentedColormap,to_rgba
from matplotlib.dates import date2num,num2date
from matplotlib.path import Path
def transform_wgs84_to_utm(longitude,la... | if not opts.debug:
warnings.simplefilter('ignore') | random_line_split |
draw_trans_pixel_cihea.py | #!/usr/bin/env python
#from shapely.geometry.polygon import Polygon
import os
import sys
import warnings
from datetime import datetime
import numpy as np
from scipy.interpolate import griddata
import shapefile
import shapely
try:
import gdal
except Exception:
from osgeo import gdal
try:
import osr
except Ex... |
if opts.add_coords:
center_x = 107.268
center_y = -6.839
lon = np.arange(107+10/60,107+23/60,2.0/60.0)
lat = np.arange(-6-56/60,-6.756,2.0/60.0)
xg,yg = np.meshgrid(lon,lat)
x,y,z = transform_wgs84_to_utm(xg,yg)
ind_x = np.argmin(np.abs(lon-center_x))
ind_y = np.argmin(np.abs(lat-cente... | utm_zone = (int(1+(longitude.mean()+180.0)/6.0))
is_northern = (1 if latitude.mean() > 0 else 0)
utm_coordinate_system = osr.SpatialReference()
utm_coordinate_system.SetWellKnownGeogCS('WGS84') # Set geographic coordinate system to handle lat/lon
utm_coordinate_system.SetUTM(utm_zone,is_northern)
wg... | identifier_body |
base.py | import abc
import logging
import platform
import sys
from threading import RLock
from typing import Any, Callable, Dict, Optional, Union
from ..config import Config
from ..exceptions import WatchdogError
__all__ = ['WatchdogError', 'Watchdog']
logger = logging.getLogger(__name__)
MODE_REQUIRED = 'required' # Wi... | (self: 'Watchdog', *args: Any, **kwargs: Any) -> Any:
with self.lock:
return func(self, *args, **kwargs)
return wrapped
class WatchdogConfig(object):
"""Helper to contain a snapshot of configuration"""
def __init__(self, config: Config) -> None:
watchdog_config = config.get("wa... | wrapped | identifier_name |
base.py | import abc
import logging
import platform
import sys
from threading import RLock
from typing import Any, Callable, Dict, Optional, Union
from ..config import Config
from ..exceptions import WatchdogError
__all__ = ['WatchdogError', 'Watchdog']
logger = logging.getLogger(__name__)
MODE_REQUIRED = 'required' # Wi... |
return True
def _set_timeout(self) -> Optional[int]:
if self.impl.has_set_timeout():
self.impl.set_timeout(self.config.timeout)
# Safety checks for watchdog implementations that don't support configurable timeouts
actual_timeout = self.impl.get_timeout()
if se... | logger.error("Configuration requires watchdog, but watchdog could not be activated")
return False | conditional_block |
base.py | import abc
import logging
import platform
import sys
from threading import RLock
from typing import Any, Callable, Dict, Optional, Union
from ..config import Config
from ..exceptions import WatchdogError
__all__ = ['WatchdogError', 'Watchdog']
logger = logging.getLogger(__name__)
MODE_REQUIRED = 'required' # Wi... | # Safety checks for watchdog implementations that don't support configurable timeouts
actual_timeout = self.impl.get_timeout()
if self.impl.is_running and actual_timeout < self.config.loop_wait:
logger.error('loop_wait of {0} seconds is too long for watchdog {1} second timeout'
... | self.impl.set_timeout(self.config.timeout)
| random_line_split |
base.py | import abc
import logging
import platform
import sys
from threading import RLock
from typing import Any, Callable, Dict, Optional, Union
from ..config import Config
from ..exceptions import WatchdogError
__all__ = ['WatchdogError', 'Watchdog']
logger = logging.getLogger(__name__)
MODE_REQUIRED = 'required' # Wi... |
def has_set_timeout(self) -> bool:
"""Returns True if setting a timeout is supported."""
return False
def set_timeout(self, timeout: int) -> None:
"""Set the watchdog timer timeout.
:param timeout: watchdog timeout in seconds"""
raise WatchdogError("Setting timeout is... | """Returns the current keepalive timeout in effect.""" | identifier_body |
db_viewer.go | package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/aybabtme/dskvs"
"log"
"regexp"
"strconv"
"time"
)
/*
This code is fucking ugly. Like really fucking ugly. It's just the fastest piece of shit I needed to get a working data set.
*/
const (
... | Credit: credit,
Name: name,
Description: descr,
Dependency: depend,
Equivalence: equiv,
LastUpdated: time.Now(),
}
log.Printf("Read course: %v", c)
courses = append(courses, c)
})
return courses, nil
} | random_line_split | |
db_viewer.go | package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/aybabtme/dskvs"
"log"
"regexp"
"strconv"
"time"
)
/*
This code is fucking ugly. Like really fucking ugly. It's just the fastest piece of shit I needed to get a working data set.
*/
const (
... | () []string {
t0 := time.Now()
doc, err := goquery.NewDocument(DEGREE_URL)
if err != nil {
log.Printf("Error getting degree list %s: %v", DEGREE_URL[:10], err)
return nil
}
log.Printf("readDegreeUrlList Reading <%s> done in %s\n",
DEGREE_URL, time.Since(t0))
var degrees []string
doc.Find("a[href]").Each(... | readDegreeUrlList | identifier_name |
db_viewer.go | package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/aybabtme/dskvs"
"log"
"regexp"
"strconv"
"time"
)
/*
This code is fucking ugly. Like really fucking ugly. It's just the fastest piece of shit I needed to get a working data set.
*/
const (
... |
var degrees []Degree
for _, b := range results {
d := Degree{}
if err := json.Unmarshal(b, &d); err != nil {
log.Printf("Couldn't unmarshal degrees from store, %v", err)
continue
}
degrees = append(degrees, d)
}
return degrees
}
func doDegreeBackfill(s *dskvs.Store) {
degreeChan := make(chan Degree... | {
log.Printf("Couldn't query back saved degrees, %v", err)
return nil
} | conditional_block |
db_viewer.go | package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/aybabtme/dskvs"
"log"
"regexp"
"strconv"
"time"
)
/*
This code is fucking ugly. Like really fucking ugly. It's just the fastest piece of shit I needed to get a working data set.
*/
const (
... |
func readTopicPage(s *dskvs.Store, topicChan chan Topic) {
t0 := time.Now()
doc, err := goquery.NewDocument(TOPIC_URL)
if err != nil {
log.Printf("Error getting topic doc %s, %v", TOPIC_URL, err)
return
}
log.Printf("readTopicPage Reading <%s> done in %s\n",
TOPIC_URL, time.Since(t0))
doc.Find(S_T_PAI... | {
deg := Degree{Url: DEGREE_URL + degreePage, LastUpdated: time.Now()}
t0 := time.Now()
doc, err := goquery.NewDocument(deg.Url)
if err != nil {
log.Printf("Error getting degree doc %s, %v", degreePage, err)
return deg, err
}
log.Printf("readDegreePage Reading <%s> done in %s\n",
deg.Url, time.Since(t0))... | identifier_body |
ic4164.rs | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
pub mod constants {
/// Pin assignment for address pin A0.
pub const A0: usize = 5;
/// Pin assignment for address pin A1.
pub const A1: usize = 7;
/// Pin assignme... | else {
self.col = Some(pins_to_value(&self.addr_pins) as u8);
if high!(self.pins[WE]) {
self.read();
} else {
self.data = Some(if high!(self.pins[D]) { 1 } else { 0 });
self.write();
... | {
float!(self.pins[Q]);
self.col = None;
self.data = None;
} | conditional_block |
ic4164.rs | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
pub mod constants {
/// Pin assignment for address pin A0.
pub const A0: usize = 5;
/// Pin assignment for address pin A1.
pub const A1: usize = 7;
/// Pin assignme... | // 1 is written to address 0x0000 at this point
set!(tr[CAS]);
set!(tr[RAS]);
set!(tr[WE]);
clear!(tr[RAS]);
clear!(tr[CAS]);
let value = high!(tr[Q]);
set!(tr[CAS]);
set!(tr[RAS]);
assert!(value, "Value 1 not written to address 0x0000");... | clear!(tr[WE]); | random_line_split |
ic4164.rs | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
pub mod constants {
/// Pin assignment for address pin A0.
pub const A0: usize = 5;
/// Pin assignment for address pin A1.
pub const A1: usize = 7;
/// Pin assignme... | () {
let (_, tr, _) = before_each();
// Write is happening at 0x0000, so we don't need to set addresses at all
set!(tr[D]);
clear!(tr[WE]);
clear!(tr[RAS]);
clear!(tr[CAS]);
// 1 is written to address 0x0000 at this point
set!(tr[CAS]);
set!(tr[RA... | read_write_one_bit | identifier_name |
ic4164.rs | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
pub mod constants {
/// Pin assignment for address pin A0.
pub const A0: usize = 5;
/// Pin assignment for address pin A1.
pub const A1: usize = 7;
/// Pin assignme... |
fn bit_value(row: usize, col: usize) -> usize {
let bit = col & 0b0001_1111;
(row >> bit) & 1
}
// Regular read and write of each of the chip's 65,536 memory locations.
#[test]
fn read_write_full() {
let (_, tr, addr_tr) = before_each();
// Write all 65,536 locati... | {
let (_, tr, _) = before_each();
// Write is happening at 0x0000, so we don't need to set addresses at all
set!(tr[D]);
clear!(tr[RAS]);
clear!(tr[CAS]);
// in read mode, Q should be 0 because no data has been written to 0x0000 yet
assert!(
low!(tr[Q... | identifier_body |
main_demo.py | import os
from PyQt5.QtWidgets import QApplication ,QMainWindow,QMessageBox,QFileDialog,QLabel
from PyQt5.QtCore import QBasicTimer,pyqtSignal,Qt,QSize,QThread
from PyQt5.QtGui import *
from untitled import Ui_Dialog
from face_ui import Ui_MainWindow
import sys
from os import listdir,getcwd # 地址 用于打开位置
from re... | #self.sources = 'rtsp://admin:5417010101xx@59.70.132.250/Streaming/Channels/1'
#self.source = 'shishi-nini.mp4'
self.source = conf.get('image_config', 'capture_source')
if self.source == '0':
self.source = 0
else :
self.source = str(self.source)
... | infor_sql.update_infor()
self.close()
def show_camera(self): #展示摄像头画面并进行人脸识别的功能
| identifier_body |
main_demo.py | import os
from PyQt5.QtWidgets import QApplication ,QMainWindow,QMessageBox,QFileDialog,QLabel
from PyQt5.QtCore import QBasicTimer,pyqtSignal,Qt,QSize,QThread
from PyQt5.QtGui import *
from untitled import Ui_Dialog
from face_ui import Ui_MainWindow
import sys
from os import listdir,getcwd # 地址 用于打开位置
from re... | self.conf.set(search_name,'性别',sex2)
button2=1
if mor_infor2!='':
self.conf.set(search_name,'更多信息',mor_infor2)
button2=1
if mor_infor2 =='删除':
self.conf.remove_section(search_name)
button2=1
if button2==1:
... | print('更改余额',search_name,age2)
self.conf.set(search_name,'余额',age2)
button2=1
if sex2!='' and (sex2=='男' or sex2=='女'):
| random_line_split |
main_demo.py | import os
from PyQt5.QtWidgets import QApplication ,QMainWindow,QMessageBox,QFileDialog,QLabel
from PyQt5.QtCore import QBasicTimer,pyqtSignal,Qt,QSize,QThread
from PyQt5.QtGui import *
from untitled import Ui_Dialog
from face_ui import Ui_MainWindow
import sys
from os import listdir,getcwd # 地址 用于打开位置
from re... | git(age2)== True:
print('更改余额',search_name,age2)
self.conf.set(search_name,'余额',age2)
button2=1
if sex2!='' and (sex2=='男' or sex2=='女'):
self.conf.set(search_name,'性别',sex2)
button2=1
if mor_infor2!='':
self.conf.set(search... | and str.isdi | identifier_name |
main_demo.py | import os
from PyQt5.QtWidgets import QApplication ,QMainWindow,QMessageBox,QFileDialog,QLabel
from PyQt5.QtCore import QBasicTimer,pyqtSignal,Qt,QSize,QThread
from PyQt5.QtGui import *
from untitled import Ui_Dialog
from face_ui import Ui_MainWindow
import sys
from os import listdir,getcwd # 地址 用于打开位置
from re... | lf.conf.get(search_name,'性别'))
self.lineEdit_20.setPlaceholderText(self.conf.get(search_name,'更多信息'))
else:
QMessageBox.about(self,'warning','找不到'+search_name+'的信息')
def new_register(self):
button=0 #当都输入正确的时候写入 配置文件
name=self.lineEdit_15.text()
... | ame,'余额'))
self.lineEdit_18.setPlaceholderText(se | conditional_block |
field.py | #
# ff7.field - Final Fantasy VII field map and script handling
#
# Copyright (C) 2014 Christian Bauer <www.cebix.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appea... |
# Read the string offset table
offset = stringTableOffset
offset += 2 # the first two bytes are supposed to indicate the number of strings, but this is totally unreliable
firstOffset = struct.unpack_from("<H", data, offset)[0]
numStrings = firstOffset / 2 - 1 # determine the ... | if self.scriptCode[codeOffset] == Op.RET and self.scriptCode[codeOffset + 1] == Op.RET:
entry = codeOffset + self.scriptBaseAddress + 2
if entry not in self.scriptEntryAddresses:
self.actorScripts[i].append(entry)
s... | conditional_block |
field.py | #
# ff7.field - Final Fantasy VII field map and script handling
#
# Copyright (C) 2014 Christian Bauer <www.cebix.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appea... |
paths = []
for addr in succ:
if addr not in path:
paths += findPaths(graph, addr, path)
if paths:
return paths
else:
return [path] # cycle reached
# Remove instructions from the blocks of a code flow graph, only keeping those
# in the specified list. The passed-i... | random_line_split | |
field.py | #
# ff7.field - Final Fantasy VII field map and script handling
#
# Copyright (C) 2014 Christian Bauer <www.cebix.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appea... | (self, event):
data = event.getData()
# Align section size to multiple of four
if len(data) % 4:
data += '\0' * (4 - len(data) % 4)
self.sections[Section.EVENT] = data
# Write the map to a file object, truncating the file.
def writeToFile(self, fileobj):
ma... | setEventSection | identifier_name |
field.py | #
# ff7.field - Final Fantasy VII field map and script handling
#
# Copyright (C) 2014 Christian Bauer <www.cebix.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appea... |
# Write the map to a file object, truncating the file.
def writeToFile(self, fileobj):
mapData = ""
# Create the pointer table
pointer = self.basePointer
for data in self.sections:
mapData += struct.pack("<L", pointer)
pointer += len(data)
# Ap... | data = event.getData()
# Align section size to multiple of four
if len(data) % 4:
data += '\0' * (4 - len(data) % 4)
self.sections[Section.EVENT] = data | identifier_body |
trainer.py | import itertools
import os
import numpy as np
import torch
from ignite.contrib.handlers.tensorboard_logger import OptimizerParamsHandler, OutputHandler, TensorboardLogger
from ignite.contrib.handlers.tqdm_logger import ProgressBar
from ignite.engine import Engine, Events
from ignite.handlers import Checkpoint, DiskSav... |
else:
return 'cpu'
def prepare_batch(batch, device=None, non_blocking=False):
"""
Move the batch to the provided device.
:param batch: The batch to prepare.
:param device: The device to move to (e.g. cpu or gpu).
:param non_blocking: Bool. Whether it should be blocking or not.
:return: The prepared batch.
... | return 'cuda:{}'.format(torch.cuda.current_device()) | conditional_block |
trainer.py | import itertools
import os
import numpy as np
import torch
from ignite.contrib.handlers.tensorboard_logger import OptimizerParamsHandler, OutputHandler, TensorboardLogger
from ignite.contrib.handlers.tqdm_logger import ProgressBar
from ignite.engine import Engine, Events
from ignite.handlers import Checkpoint, DiskSav... | (model_type, lr, lr_decay_step, epochs, dilation, validate, batch_size, log_dir, data_dir, csv_file, use_adam,
checkpoint_dir, resume_checkpoint):
"""
Train the model with the given parameters.
:param model_type: The type of the model to train.
:param lr: Float or Array[Float]. The learning rate.
:param ... | train | identifier_name |
trainer.py | import itertools
import os
import numpy as np
import torch
from ignite.contrib.handlers.tensorboard_logger import OptimizerParamsHandler, OutputHandler, TensorboardLogger
from ignite.contrib.handlers.tqdm_logger import ProgressBar
from ignite.engine import Engine, Events
from ignite.handlers import Checkpoint, DiskSav... | avg_fps = list(range(1, 26))
avg_fps.append(0.5)
avg_fps.sort()
tags = ['froc_{}fp'.format(fp) for fp in avg_fps]
for avg_fp, tag in zip(avg_fps, tags):
FROC([avg_fp], iou_threshold=0.5).attach(self, tag)
# tqdm
ProgressBar(persist=True).attach(self)
# Tensorboard logging
tb_logger.attach(self,
... | # FROC | random_line_split |
trainer.py | import itertools
import os
import numpy as np
import torch
from ignite.contrib.handlers.tensorboard_logger import OptimizerParamsHandler, OutputHandler, TensorboardLogger
from ignite.contrib.handlers.tqdm_logger import ProgressBar
from ignite.engine import Engine, Events
from ignite.handlers import Checkpoint, DiskSav... |
def get_device(model):
"""
Extract the device to run on from the model.
:param model: The model to train.
:return: String. The name of the device.
"""
if next(model.parameters()).is_cuda:
return 'cuda:{}'.format(torch.cuda.current_device())
else:
return 'cpu'
def prepare_batch(batch, device=None, non_bl... | """
Scan the system for available GPUs' and return the one with the most memory available.
NOTE: Only available for linux systems!
:return: Integer. The index of the GPU.
"""
os.system('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >tmp')
if os.path.exists('tmp'):
memory_available = [int(x.split()[2]) for x i... | identifier_body |
vet.go | // Package vet is an API for gomodvet (a simple prototype of a potential future 'go mod vet' or similar).
//
// See the README at https://github.com/thepudds/gomodvet for more details.
package vet
import (
"fmt"
"os/exec"
"regexp"
"sort"
"strings"
"github.com/rogpeppe/go-internal/semver"
"github.c... |
return flagged, nil
}
// MultipleMajor reports if the current module has any dependencies with multiple major versions.
// For example, if the current module is 'foo', it reports if there is a 'bar' and 'bar/v3' as dependencies of 'foo'.
// It returns true if multiple major versions are found.
// Note that th... | {
if verbose {
fmt.Printf("gomodvet: upgrades: module %s: %+v\n", mod.Path, mod)
}
if mod.Update != nil {
fmt.Println("gomodvet-002: dependencies have available updates: ", mod.Path, mod.Update.Version)
flagged = true
}
} | conditional_block |
vet.go | // Package vet is an API for gomodvet (a simple prototype of a potential future 'go mod vet' or similar).
//
// See the README at https://github.com/thepudds/gomodvet for more details.
package vet
import (
"fmt"
"os/exec"
"regexp"
"sort"
"strings"
"github.com/rogpeppe/go-internal/semver"
"github.c... |
// PseudoVersion reports if the current module or any dependencies are using a prerelease semver version
// (exclusive of pseudo-versions, which are also prerelease versions according to semver spec but are reported separately).
// It returns true if so.
// Rule: gomodvet-007
func PseudoVersion(verbose bool) (b... | {
mods, err := buildlist.Resolve()
if err != nil {
return false, fmt.Errorf("prerelease: %v", err)
}
flagged := false
for _, mod := range mods {
if verbose {
fmt.Printf("gomodvet: prerelease: module %s: %+v\n", mod.Path, mod)
}
if isPrerelease(mod.Version) {
fmt.Printf("gomodvet-006: a m... | identifier_body |
vet.go | // Package vet is an API for gomodvet (a simple prototype of a potential future 'go mod vet' or similar).
//
// See the README at https://github.com/thepudds/gomodvet for more details.
package vet
import (
"fmt"
"os/exec"
"regexp"
"sort"
"strings"
"github.com/rogpeppe/go-internal/semver"
"github.c... | // ExcludedVersion reports if the current module or any dependencies are using a version excluded by a dependency.
// It returns true if so.
// Currently requires main module's go.mod being in a consistent state (e.g., after a 'go list' or 'go build'), such that
// the main module does not have a go.mod file using s... | }
}
return flagged, nil
}
| random_line_split |
vet.go | // Package vet is an API for gomodvet (a simple prototype of a potential future 'go mod vet' or similar).
//
// See the README at https://github.com/thepudds/gomodvet for more details.
package vet
import (
"fmt"
"os/exec"
"regexp"
"sort"
"strings"
"github.com/rogpeppe/go-internal/semver"
"github.c... | (version string) bool {
return semver.IsValid(version) && semver.Compare(version, "v1.0.0") < 0
}
// isV1 reports if the major version is 'v1' (e.g., 'v1.2.3')
func isV1(version string) bool {
if !semver.IsValid(version) || isBeforeV1(version) {
return false
}
return semver.Major(version) == "v1"
}
... | isBeforeV1 | identifier_name |
dldata.py | """
Parses data and returns download data.
"""
import logging
import re
import string
from os import PathLike
from os.path import join, realpath, splitext
from typing import Dict, List, Optional, Tuple
from ..models import (AnimeListSite, AnimeThemeAnime, AnimeThemeEntry,
AnimeThemeTheme, AnimeTh... | (**kwargs) -> Dict[str,str]:
"""
Generates a formatter dict used for formatting filenames.
Takes in kwargs of Dict[str,Any].
Does not keep lists, dicts and bools.
Automatically filters out` .endswith('ated_at')` for animethemes-dl.
Also adds `{video_filetype:webm,anime_filename:...}`.
"""
... | get_formatter | identifier_name |
dldata.py | """
Parses data and returns download data.
"""
import logging
import re
import string
from os import PathLike
from os.path import join, realpath, splitext
from typing import Dict, List, Optional, Tuple
from ..models import (AnimeListSite, AnimeThemeAnime, AnimeThemeEntry,
AnimeThemeTheme, AnimeTh... |
return video_path,audio_path
def pick_best_entry(theme: AnimeThemeTheme) -> Optional[Tuple[AnimeThemeEntry,AnimeThemeVideo]]:
"""
Returns the best entry and video based on OPTIONS.
Returns None if no entry/video is wanted
"""
# picking best entry
entries = []
for entry in theme['e... | audio_path = None | conditional_block |
dldata.py | """
Parses data and returns download data.
"""
import logging
import re
import string
from os import PathLike
from os.path import join, realpath, splitext
from typing import Dict, List, Optional, Tuple
from ..models import (AnimeListSite, AnimeThemeAnime, AnimeThemeEntry,
AnimeThemeTheme, AnimeTh... |
def generate_path(
anime: AnimeThemeAnime, theme: AnimeThemeTheme,
entry: AnimeThemeEntry, video: AnimeThemeVideo) -> (
Tuple[Optional[PathLike],Optional[PathLike]]):
"""
Generates a path with animethemes api returns.
Returns `(videopath|None,audiopath|None)`
"""
formatter = get_f... | """
Generates a formatter dict used for formatting filenames.
Takes in kwargs of Dict[str,Any].
Does not keep lists, dicts and bools.
Automatically filters out` .endswith('ated_at')` for animethemes-dl.
Also adds `{video_filetype:webm,anime_filename:...}`.
"""
formatter = {}
for t,d in k... | identifier_body |
dldata.py | """
Parses data and returns download data.
"""
import logging
import re
import string
from os import PathLike
from os.path import join, realpath, splitext
from typing import Dict, List, Optional, Tuple
from ..models import (AnimeListSite, AnimeThemeAnime, AnimeThemeEntry,
AnimeThemeTheme, AnimeTh... | """
for k in ('spoiler','nsfw'):
v = OPTIONS['filter'][k]
if v is not None and entry[k] ^ v:
return False
return True
def is_video_wanted(video: AnimeThemeVideo) -> bool:
"""
Determines wheter all the tags in the entry are the same as in OPTIONS
"""
for k in ('nc... | random_line_split | |
securitygroup.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... |
type SecurityGroupPolicy struct {
region *SRegion
PolicyIndex int // 安全组规则索引号。
Protocol string // 协议, 取值: TCP,UDP, ICMP。
Port string // 端口(all, 离散port, range)。
ServiceTemplate ServiceTemplateSpecification... |
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud"
) | random_line_split |
securitygroup.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... | Rules() []cloudprovider.SecurityRule {
result := []cloudprovider.SecurityRule{}
rule := cloudprovider.SecurityRule{
ExternalId: fmt.Sprintf("%d", self.PolicyIndex),
SecurityRule: secrules.SecurityRule{
Action: secrules.SecurityRuleAllow,
Protocol: secrules.PROTO_ANY,
Direction: secrules.TSecurityRule... | roupPolicy) to | identifier_name |
securitygroup.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... |
params[fmt.Sprintf("Filters.%d.Values.0", filter)] = groupId
filter++
}
if len(groupName) > 0 {
params[fmt.Sprintf("Filters.%d.Name", filter)] = "address-template-group-name"
params[fmt.Sprintf("Filters.%d.Values.0", filter)] = groupName
filter++
}
params["Offset"] = fmt.Sprintf("%d", offset)
if limit =... | ddress-template-group-id" | conditional_block |
securitygroup.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... | ressIndex := -1, -1
for _, rule := range rules {
policyIndex := 0
switch rule.Direction {
case secrules.DIR_IN:
ingressIndex++
policyIndex = ingressIndex
case secrules.DIR_OUT:
egressIndex++
policyIndex = egressIndex
default:
return fmt.Errorf("Unknown rule direction %v for secgroup %s", rule,... | roupRules(self.SecurityGroupId, rules)
}
func (self *SRegion) syncSecgroupRules(secgroupid string, rules []cloudprovider.SecurityRule) error {
err := self.deleteAllRules(secgroupid)
if err != nil {
return errors.Wrap(err, "deleteAllRules")
}
egressIndex, ing | identifier_body |
ext-all-extend.js | Ext.ns("Ext.haode");
Ext.QuickTips.init();
Ext.BLANK_IMAGE_URL = "scripts/ext-3.4/resources/images/default/s.gif";
//Ext.util.CSS.swapStyleSheet('theme', Ext.haode.contextPath + "/scripts/ext-3.4/resources/css/xtheme-access.css");
/**
* 数组去重
*/
Array.prototype.distinct = function() {
var self = this... | handler : this.movePrevious,
scope : this
}), '-', '每页', new Ext.form.ComboBox({
store : new Ext.data.ArrayStore({
fields : [ 'id', 'value' ],
data : pageSizeStore
}),
typeAhead: false,
triggerAction: 'all',
mode : 'local',
valueField : 'id',
displayField : 'value',
v... | random_line_split | |
ext-all-extend.js | Ext.ns("Ext.haode");
Ext.QuickTips.init();
Ext.BLANK_IMAGE_URL = "scripts/ext-3.4/resources/images/default/s.gif";
//Ext.util.CSS.swapStyleSheet('theme', Ext.haode.contextPath + "/scripts/ext-3.4/resources/css/xtheme-access.css");
/**
* 数组去重
*/
Array.prototype.distinct = function() {
var self = this... | Reader({
root: "rows",
totalProperty: 'totalcount'
}, [
{name: "menuId"},
{name: "name"}
])
});
ds.on("load", function(){
var totalcount = ds.getCount();
for (var i = 0; i < totalcount; i++) {
var menuId = ds.getAt(i).data.menuId;
var sArray = menuId.split(".");
var funcId =... | on=getSubFuncs&menuId=" + menuId}),
reader: new Ext.data.Json | conditional_block |
ext-all-extend.js | Ext.ns("Ext.haode");
Ext.QuickTips.init();
Ext.BLANK_IMAGE_URL = "scripts/ext-3.4/resources/images/default/s.gif";
//Ext.util.CSS.swapStyleSheet('theme', Ext.haode.contextPath + "/scripts/ext-3.4/resources/css/xtheme-access.css");
/**
* 数组去重
*/
Array.prototype.distinct = function() {
var self = this... | return;
alert('出错了: ' + error.msg);
// var msg = ['噢,出错了!!!\t\n--------------------------------------------------------\n错误信息:',
// error.msg, '\n 控制器:', error.controller, '\n 错误行:', error.line, '\n 动 作:',
// error.action, '\n'].join('');
if (error.type == 'sessiontime... | ndNodes = fn;
se.activeNode = fn.length > 0 ? fn[0].id : undefined;
return se;
}
});
Ext.Ajax.on('requestexception', function(conn, response, options){
try {
var error = Ext.decode(response.responseText);
if (!error)
| identifier_body |
ext-all-extend.js | Ext.ns("Ext.haode");
Ext.QuickTips.init();
Ext.BLANK_IMAGE_URL = "scripts/ext-3.4/resources/images/default/s.gif";
//Ext.util.CSS.swapStyleSheet('theme', Ext.haode.contextPath + "/scripts/ext-3.4/resources/css/xtheme-access.css");
/**
* 数组去重
*/
Array.prototype.distinct = function() {
var self = this... | se.foundNodes = fn;
se.activeNode = fn.length > 0 ? fn[0].id : undefined;
return se;
}
});
Ext.Ajax.on('requestexception', function(conn, response, options){
try {
var error = Ext.decode(response.responseText);
if (!error)
return;
alert('出错了: ' + error.msg);
// var msg = ['噢,出错了!!!... | key);
| identifier_name |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... | self.separation = separation;
self
}
/// This is the range available for warriors to write information
/// to core. Attempts to write outside the limits of this range
/// result in writing within the local writable range. The range
/// is centered on the current instruction. Thus... | /// warrior to the first instruction of the next warrior.
/// Separation can be set to `Random`, meaning separations will be
/// chosen randomly from those larger than the minimum separation.
pub fn separation(&mut self, separation: Separation) -> &mut Self { | random_line_split |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... | (&mut self, warriors: &[Warrior]) -> Result<&mut Self, CoreError> {
for warrior in warriors {
if warrior.len() > self.instruction_limit {
return Err(CoreError::WarriorTooLong(
warrior.len(),
self.instruction_limit,
warrior.m... | load_warriors | identifier_name |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... |
/// Each warrior can spawn multiple additional tasks. This variable sets the maximum
/// number of tasks allowed per warrior. In other words, this is the size of each warrior's task queue.
pub fn maximum_number_of_tasks(&mut self, maximum_number_of_tasks: usize) -> &mut Self {
self.maximum_number_... | {
self.instruction_limit = instruction_limit;
self
} | identifier_body |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... |
if warrior.is_empty() {
return Err(CoreError::EmptyWarrior(
warrior.metadata.name().unwrap_or("Unnamed").to_owned(),
));
};
}
self.warriors = warriors.to_vec();
Ok(self)
}
/// Use a `Logger` to log the battle... | {
return Err(CoreError::WarriorTooLong(
warrior.len(),
self.instruction_limit,
warrior.metadata.name().unwrap_or("Unnamed").to_owned(),
));
} | conditional_block |
exec_plan9.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Fork, exec, wait, etc.
package syscall
import (
"internal/itoa"
"runtime"
"sync"
"unsafe"
)
// ForkLock is not used on plan9.
var ForkLock sync.RWMute... | r1, _, _ = RawSyscall(SYS_DUP, uintptr(fd[i]), uintptr(nextfd), 0)
if int32(r1) == -1 {
goto childerror
}
fd[i] = nextfd
nextfd++
}
}
// Pass 2: dup fd[i] down onto i.
for i = 0; i < len(fd); i++ {
if fd[i] == -1 {
RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
continue
}
if fd[i] == int(... | if fd[i] >= 0 && fd[i] < int(i) {
if nextfd == pipe { // don't stomp on pipe
nextfd++
} | random_line_split |
exec_plan9.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Fork, exec, wait, etc.
package syscall
import (
"internal/itoa"
"runtime"
"sync"
"unsafe"
)
// ForkLock is not used on plan9.
var ForkLock sync.RWMute... | (ss []string) []*byte {
bb := make([]*byte, len(ss)+1)
for i := 0; i < len(ss); i++ {
bb[i] = StringBytePtr(ss[i])
}
bb[len(ss)] = nil
return bb
}
// SlicePtrFromStrings converts a slice of strings to a slice of
// pointers to NUL-terminated byte arrays. If any string contains
// a NUL byte, it returns (nil, EI... | StringSlicePtr | identifier_name |
exec_plan9.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Fork, exec, wait, etc.
package syscall
import (
"internal/itoa"
"runtime"
"sync"
"unsafe"
)
// ForkLock is not used on plan9.
var ForkLock sync.RWMute... |
// Combination of fork and exec, careful to be thread safe.
func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error) {
return startProcess(argv0, argv, attr)
}
// StartProcess wraps ForkExec for package os.
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintpt... | {
type forkRet struct {
pid int
err error
}
forkc := make(chan forkRet, 1)
go func() {
runtime.LockOSThread()
var ret forkRet
ret.pid, ret.err = forkExec(argv0, argv, attr)
// If fork fails there is nothing to wait for.
if ret.err != nil || ret.pid == 0 {
forkc <- ret
return
}
waitc := ma... | identifier_body |
exec_plan9.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Fork, exec, wait, etc.
package syscall
import (
"internal/itoa"
"runtime"
"sync"
"unsafe"
)
// ForkLock is not used on plan9.
var ForkLock sync.RWMute... |
fd, e := Create("/env/"+v[:i], O_WRONLY, 0666)
if e != nil {
return e
}
_, e = Write(fd, []byte(v[i+1:]))
if e != nil {
Close(fd)
return e
}
Close(fd)
}
}
argv0p, err := BytePtrFromString(argv0)
if err != nil {
return err
}
argvp, err := SlicePtrFromStrings(argv)
if err !=... | {
i++
} | conditional_block |
ha-state.go | package models
import (
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path"
"strconv"
"time"
"github.com/pborman/uuid"
)
// Cert is one of the self-signed root CA entries used to secure communication between
// consensus cluster ... | if c.leaf == nil {
log.Panicf("cert TLS called with nil leaf!")
}
return c.leaf
}
// GlobalHaState is the consensus state shared by all members of
// a consensus cluster.
type GlobalHaState struct {
// LoadBalanced indicates that an external service is responsible for
// routing traffic destined to VirtAddr to ... | return nil
}
// TLS converts the Cert into a TLS compatible certificate.
func (c *Cert) TLS() *tls.Certificate { | random_line_split |
ha-state.go | package models
import (
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path"
"strconv"
"time"
"github.com/pborman/uuid"
)
// Cert is one of the self-signed root CA entries used to secure communication between
// consensus cluster ... |
// GetHaState loads a serialized version of the CurrentHAState for a node from
// the directory passed in as Base. It always attempts to read from a file named
// ha-state.json
func GetHaState(base string) (*CurrentHAState, error) {
haStateFile := path.Join(base, "ha-state.json")
stateFi, err := os.OpenFile(haStat... | {
// Validate HA args.
if !cOpts.Enabled {
return nil
}
ourAddrs, err := net.InterfaceAddrs()
if err != nil {
return err
}
consensusAddr := ""
consensusPort := ""
if cOpts.ConsensusAddr != "" {
consensusAddr, consensusPort, err = net.SplitHostPort(cOpts.ConsensusAddr)
if err != nil {
return err
... | identifier_body |
ha-state.go | package models
import (
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path"
"strconv"
"time"
"github.com/pborman/uuid"
)
// Cert is one of the self-signed root CA entries used to secure communication between
// consensus cluster ... | (template *x509.Certificate, parentCert *tls.Certificate) (*tls.Certificate, error) {
var err error
var priv ed25519.PrivateKey
var public ed25519.PublicKey
public, priv, err = ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
var parent *x509.Certificate
var parentPriv ed25519.PrivateKey
if... | makeCert | identifier_name |
ha-state.go | package models
import (
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path"
"strconv"
"time"
"github.com/pborman/uuid"
)
// Cert is one of the self-signed root CA entries used to secure communication between
// consensus cluster ... |
}
if !lbAddrOk {
return fmt.Errorf("Virt address %s is present on the system, not permitted when load balanced", cOpts.VirtAddr)
}
} else {
if cOpts.VirtAddr == "" {
return fmt.Errorf("Error: HA must specify a VIP in CIDR format that DRP will move around")
}
// In HA mode with a VIP, force everythin... | {
lbAddrOk = false
break
} | conditional_block |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... | () -> usize {
glob("/sys/class/block/nbd*").unwrap().count()
}
}
impl From<String> for NbdDevInfo {
fn from(e: String) -> Self {
let instance: u32 = e.replace("/dev/nbd", "").parse().unwrap();
NbdDevInfo::create(instance).unwrap()
}
}
| num_devices | identifier_name |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... | else {
let msg = format!(
"Failed to stop nbd device {} for {}",
nbd_disk.nbd_device, nbd_disk.bdev_name
);
error!("{}", msg);
Box::new(err(Status::new(Code::Internal, msg)))
... | {
info!(
"Stopped NBD device {} with bdev {}",
nbd_disk.nbd_device, nbd_disk.bdev_name
);
NbdDevInfo::from(nbd_disk.nbd_device).put_back();
Box::new(ok(Response::new(Null {})))
... | conditional_block |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... |
}
impl fmt::Debug for NbdDevInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "nbd{} ({}:{})", self.instance, self.major, self.minor)
}
}
pub fn nbd_stage_volume(
socket: String,
msg: &NodeStageVolumeRequest,
filesystem: Fs,
mnt_opts: Vec<String>,
) -> Box<
d... | {
write!(f, "/dev/nbd{}", self.instance)
} | identifier_body |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... | }
impl From<String> for NbdDevInfo {
fn from(e: String) -> Self {
let instance: u32 = e.replace("/dev/nbd", "").parse().unwrap();
NbdDevInfo::create(instance).unwrap()
}
} | random_line_split | |
sidebar.js | var Highlighter = require('./highlighter.js');
var Storage = require('./storage.js');
var Sidebar = function Sidebar(config) {
Sidebar.config = $.extend(true, {}, config);
};
Sidebar.isInitialized = false;
Sidebar.isChromeExtension = chrome && chrome.extension;
Sidebar.prototype.toggle = function () {
... |
else if (Sidebar.hide()) { }
}
Sidebar.show = function ($sidebar) {
var $sidebar = $(Sidebar.shadowRoot.querySelector('#sidebar'));
var isShown = false;
if ($sidebar.hasClass("collapsed")) {
$sidebar.removeClass("collapsed");
isShown = true;
}
return isShown;
}
Sideb... | { } | conditional_block |
sidebar.js | var Highlighter = require('./highlighter.js');
var Storage = require('./storage.js');
var Sidebar = function Sidebar(config) {
Sidebar.config = $.extend(true, {}, config);
};
Sidebar.isInitialized = false;
Sidebar.isChromeExtension = chrome && chrome.extension;
Sidebar.prototype.toggle = function () {
... | if (selection.toString() != "") {
var anchorTag = selection.anchorNode.parentNode;
var focusTag = selection.focusNode.parentNode;
isInside =
$(anchorTag).parents("#sidebar").length ||
$(focusTag).parents("#sidebar").length;
}
return isInside;
};
/*... | random_line_split | |
basic_statements.py | """
This module contains the code the execute BASIC commands, and the class
that runs the program (Executor)
"""
from enum import Enum
from basic_dialect import UPPERCASE_INPUT
from basic_types import BasicSyntaxError, assert_syntax, is_valid_identifier
from basic_types import SymbolType, RunStatus
from basic_parsing... |
def stmt_on(executor, stmt):
var = stmt._expression
op = stmt._op
result = eval_expression(executor._symbols, var)
assert_syntax(type(result) == int or type(result) == float, "Expression not numeric in ON GOTO/GOSUB")
result = int(result) - 1 # Basic is 1-based.
# According to this: https://... | executor.do_print(prompt, end='')
result = executor.do_input()
if result is None:
print("Bad response from trekbot")
result = result.split(",")
if len(result) != len(stmt._input_vars):
print(F"Mismatched number of inputs. Expected {len(stmt._input_vars)} got {len(... | conditional_block |
basic_statements.py | """
This module contains the code the execute BASIC commands, and the class
that runs the program (Executor)
"""
from enum import Enum
from basic_dialect import UPPERCASE_INPUT
from basic_types import BasicSyntaxError, assert_syntax, is_valid_identifier
from basic_types import SymbolType, RunStatus
from basic_parsing... |
def get_exec(self):
return self._exec
class Keywords(Enum):
CLEAR = KB(stmt_clear, ParsedStatement) # Some uses of clear take arguments, which we ignore.
DEF = KB(stmt_def, ParsedStatementDef) # User defined functions
DIM = KB(stmt_dim, ParsedStatementDim)
END = KB(stmt_end, ParsedStatem... | return self._parser | identifier_body |
basic_statements.py | """
This module contains the code the execute BASIC commands, and the class
that runs the program (Executor)
"""
from enum import Enum
| from basic_parsing import ParsedStatement, ParsedStatementIf, ParsedStatementFor, ParsedStatementOnGoto
from basic_parsing import ParsedStatementLet, ParsedStatementNoArgs, ParsedStatementDef, ParsedStatementPrint
from basic_parsing import ParsedStatementGo, ParsedStatementDim
from basic_parsing import ParsedStatementI... | from basic_dialect import UPPERCASE_INPUT
from basic_types import BasicSyntaxError, assert_syntax, is_valid_identifier
from basic_types import SymbolType, RunStatus
| random_line_split |
basic_statements.py | """
This module contains the code the execute BASIC commands, and the class
that runs the program (Executor)
"""
from enum import Enum
from basic_dialect import UPPERCASE_INPUT
from basic_types import BasicSyntaxError, assert_syntax, is_valid_identifier
from basic_types import SymbolType, RunStatus
from basic_parsing... | (executor, stmt):
executor.do_return()
def stmt_width(executor, stmt):
"""
The WIDTH statement is only for compatibility with some versions of BASIC. It set the width of the screen.
Ignored.
:param executor:
:param stmt:
:return:
"""
pass
class KB:
def __init__(self, exec, p... | stmt_return | identifier_name |
ViewCreater3d.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) 2019 Bentley Systems, Incorporated. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license terms.
*--------------------------------------------------------... | },
environment:
options !== undefined &&
options.skyboxOn !== undefined &&
options.skyboxOn
? new Environment({ sky: { display: true } }).toJSON()
: undefined,
},
},
};
const viewStateProps: ViewStatePr... | backgroundMap: this._imodel.isGeoLocated,
| random_line_split |
ViewCreater3d.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) 2019 Bentley Systems, Incorporated. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license terms.
*--------------------------------------------------------... | (
options?: ViewCreator3dOptions,
modelIds?: string[]
): Promise<ViewState> {
const models = modelIds ? modelIds : await this._getAllModels();
if (models === undefined || models.length === 0)
throw new IModelError(
IModelStatus.BadModel,
"ViewCreator3d.createDefaultView: ... | createDefaultView | identifier_name |
expenv.py | # The point of this script is to help me develop on
# issues that I still need to identify since it's been
# almost two months since I felt the code.
#
# Task: Run a simple curriculum learning experiment on
# the flavor-place location task by Tse (2007): that is,
# with four starting locations, one of six signals, an... |
elif not self.centr == 'allocentric': raise Exception(self.centr)
return state_mat, True
def new_statem(self, orig_state, action, valid_move_too=False):
'''Public Method: error-proofed public method for making (S') from (S,A)
NOT currently errorproofed against egocentrism!'''
... | centr_pos = (3,3)
dx, dy = aloc[0]-centr_pos[0], aloc[1]-centr_pos[1]
state_mat = np.roll(state_mat, shift=dx, axis=0)
state_mat = np.roll(state_mat, shift=dy, axis=1) | conditional_block |
expenv.py | # The point of this script is to help me develop on
# issues that I still need to identify since it's been
# almost two months since I felt the code.
#
# Task: Run a simple curriculum learning experiment on
# the flavor-place location task by Tse (2007): that is,
# with four starting locations, one of six signals, an... |
def get_goal_loc(self,s): return self._get_loc(s,targ='goal')
# def get_allo_loc(self,s): return self._get_loc(s,targ='map') # center
def _get_loc(self, state_matrix, targ):
if targ=='agent':
return map_nparr_to_tup(np.where(state_matrix[:,:,agentLayer]==1))
if targ=='... | '''Public method: query the location of the agent. (<0,0> is NW corner.)'''
return self._get_loc(state,targ='agent') | identifier_body |
expenv.py | # The point of this script is to help me develop on
# issues that I still need to identify since it's been
# almost two months since I felt the code.
#
# Task: Run a simple curriculum learning experiment on
# the flavor-place location task by Tse (2007): that is,
# with four starting locations, one of six signals, an... | # except:
# return tuple([i+m for i in Iterable])
def addvec(Iterable, m, optn=None):
try:
m[0]
except:
if m>80:
m = DVECS[m]
else:
m = DVECS[INDICES_TO_CARDINAL_ACTIONS[m]]
return tuple([i+m for i,m in zip(Iterable,m)])
def multvec(Iterable, m, o... | #def addvec(Iterable, m, optn=None):
# try:
# return tuple([i+m for i,m in zip(Iterable,m)]) | random_line_split |
expenv.py | # The point of this script is to help me develop on
# issues that I still need to identify since it's been
# almost two months since I felt the code.
#
# Task: Run a simple curriculum learning experiment on
# the flavor-place location task by Tse (2007): that is,
# with four starting locations, one of six signals, an... | (self):
''' Public method: get a random state struct with fields: 'state',
'_startpos', 'flavor signal', '_whichgoal', 'goal loc'. The three
later fields are helper attributes for, say, curricula or presentation.
'''
return [self._view_state_copy(st) for st in self.start_sta... | get_all_starting_states | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.