language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public boolean writeInbound(Object... msgs) { ensureOpen(); if (msgs.length == 0) { return isNotEmpty(inboundMessages); } ChannelPipeline p = pipeline(); for (Object m: msgs) { p.fireChannelRead(m); } flushInbound(false, voidPromise()); ...
java
private static void addAclHeaders(Request<? extends AmazonWebServiceRequest> request, AccessControlList acl) { List<Grant> grants = acl.getGrantsAsList(); Map<Permission, Collection<Grantee>> grantsByPermission = new HashMap<Permission, Collection<Grantee>>(); for ( Grant grant : grants ) { ...
python
def get_bank_hierarchy_design_session(self, proxy): """Gets the session designing bank hierarchies. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.BankHierarchyDesignSession) - a ``BankHierarchySession`` raise: NullArgument - ``proxy`` is ``null`` ...
java
public ReceiptTemplateBuilder addAdjustment(String name, BigDecimal amount) { Adjustment adjustment = new Adjustment(name, amount); return this.addAdjustment(adjustment); }
java
private void maybeWarnForInvalidDestructuring( NodeTraversal t, Node importNode, String importedNamespace) { checkArgument(importNode.getFirstChild().isDestructuringLhs(), importNode); ScriptDescription importedModule = rewriteState.scriptDescriptionsByGoogModuleNamespace.get(importedNamespace); ...
java
static Exclusion convertExclusionPatternIntoExclusion(String exceptionPattern) throws MojoExecutionException { Matcher matcher = COORDINATE_PATTERN.matcher(exceptionPattern); if (!matcher.matches()) { throw new MojoExecutionException(String.format("Bad artifact coordinates %s, expected forma...
python
def allow_buttons(self, message="", link=True, back=True): """ Function allows buttons """ self.info_label.set_label(message) self.allow_close_window() if link and self.link is not None: self.link.set_sensitive(True) self.link.show_all() if...
java
public JSONObject exportConfigurationAndProfile(String oldExport) { try { BasicNameValuePair[] params = { new BasicNameValuePair("oldExport", oldExport) }; String url = BASE_BACKUP_PROFILE + "/" + uriEncode(this._profileName) + "/" + this._clientId; ...
python
def _setup_versioned_lib_variables(env, **kw): """ Setup all variables required by the versioning machinery """ tool = None try: tool = kw['tool'] except KeyError: pass use_soname = False try: use_soname = kw['use_soname'] except KeyError: pass # The $_SHLIBVERSIONFLAGS define...
java
private double logL(int k, long n, double x) { if (x == 0.0) x = 0.01; if (x == 1.0) x = 0.99; return k * Math.log(x) + (n-k) * Math.log(1-x); }
java
public ItemIdValue copy(ItemIdValue object) { return dataObjectFactory.getItemIdValue(object.getId(), object.getSiteIri()); }
python
def release(major=False, minor=False, patch=True, pypi_index=None): """Overall process flow for performing a release""" relver = next_release(major, minor, patch) start_rel_branch(relver) prepare_release(relver) finish_rel_branch(relver) publish(pypi_index)
java
public void setHistoricalMetrics(java.util.Collection<HistoricalMetric> historicalMetrics) { if (historicalMetrics == null) { this.historicalMetrics = null; return; } this.historicalMetrics = new java.util.ArrayList<HistoricalMetric>(historicalMetrics); }
python
def read_creds_from_ecs_container_metadata(): """ Read credentials from ECS instance metadata (IAM role) :return: """ creds = init_creds() try: ecs_metadata_relative_uri = os.environ['AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'] credentials = requests.get('http://169.254.170.2' + ec...
java
public final boolean setPointAt(int index, Point2D<?, ?> point) { return setPointAt(index, point.getX(), point.getY(), false); }
python
def tintWith(self, red, green, blue): """tintWith(self, red, green, blue)""" if not self.colorspace or self.colorspace.n > 3: print("warning: colorspace invalid for function") return return _fitz.Pixmap_tintWith(self, red, green, blue)
java
private Attributes splitAttributes(final NamedNodeMap map) { Attr sLoc = (Attr) map.getNamedItemNS(XMLConstants .W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation"); Attr nNsLoc = (Attr) map.getNamedItemNS(XMLConst...
java
@Subscribe public void updateThrottleState(ThrottleState throttleState) { // Only run if throttling is enabled. if (!throttlingAllowed) { return; } // check if we are throttled final boolean throttled = determineIfThrottled(throttleState); if (currentlyThr...
python
def catchable_exceptions(exceptions): """Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types. """ if isinstance(exceptions, type) and issubclass(exceptions, BaseException): return True if (...
java
public void putViewState(@NonNull String viewId, @NonNull Object viewState) { if (viewId == null) { throw new NullPointerException("ViewId is null"); } if (viewState == null) { throw new NullPointerException("ViewState is null"); } PresenterHolder presenterHolder = presenterMap....
python
def str_repr(klass): """ Implements string conversion methods for the given class. The given class must implement the __str__ method. This decorat will add __repr__ and __unicode__ (for Python 2). """ if PY2: klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self._...
python
def _write_xml(xmlfile, srcs): """Save the ROI model as an XML """ root = ElementTree.Element('source_library') root.set('title', 'source_library') for src in srcs: src.write_xml(root) output_file = open(xmlfile, 'w') output_file.write(utils.prettify_xml(roo...
python
def run_driz_chip(img,chip,output_wcs,outwcs,template,paramDict,single, doWrite,build,_versions,_numctx,_nplanes,_numchips, _outsci,_outwht,_outctx,_hdrlist,wcsmap): """ Perform the drizzle operation on a single chip. This is separated out from `run_driz_img` so as to keep to...
java
public EEnum getMFCMFCScpe() { if (mfcmfcScpeEEnum == null) { mfcmfcScpeEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(49); } return mfcmfcScpeEEnum; }
python
def from_array(array): """ Deserialize a new MaskPosition from a given dictionary. :return: new MaskPosition instance. :rtype: MaskPosition """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_nam...
java
public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { if (portName == null) { return getPort(serviceEndpointInterface); } java.lang.String inputPortName = portName.getLocalPart(); if ("Networ...
java
public void writeToExcel(List<? extends Object> datas, boolean hasTitle, String path) throws IOException { writeToExcel(datas, hasTitle, path, false); }
java
@Override public CommerceWishList remove(Serializable primaryKey) throws NoSuchWishListException { Session session = null; try { session = openSession(); CommerceWishList commerceWishList = (CommerceWishList)session.get(CommerceWishListImpl.class, primaryKey); if (commerceWishList == null) { ...
java
public static Option repositories(final String... repositoryUrls) { validateNotEmptyContent(repositoryUrls, true, "Repository URLs"); final List<RepositoryOption> options = new ArrayList<RepositoryOption>(); for (String repositoryUrl : repositoryUrls) { options.add(repository(reposit...
java
public static Set<String> getIFixesThatMustBeReapplied(File installDir, Map<String, ProvisioningFeatureDefinition> features, ContentBasedLocalBundleRepository repo, CommandConsole console) { Set<String> ifixesToReApply = new HashSet<String>(); ...
java
@Override public void endVisit(PrefixExpression node) { Boolean value = getReplaceableValue(node.getOperand()); if (node.getOperator() == PrefixExpression.Operator.NOT && value != null) { node.replaceWith(new BooleanLiteral(!value, typeUtil)); } }
python
def get_string(self, betas: List[float], gammas: List[float], samples: int = 100): """ Compute the most probable string. The method assumes you have passed init_betas and init_gammas with your pre-computed angles or you have run the VQE loop to determine the angles. If you have...
python
def get_plot(self, units='THz', ymin=None, ymax=None, width=None, height=None, dpi=None, plt=None, fonts=None, dos=None, dos_aspect=3, color=None, style=None, no_base_style=False): """Get a :obj:`matplotlib.pyplot` object of the phonon band structure. Args: ...
python
def check(response, expected_status=200, url=None): """ Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), othe...
java
public void printFramesDocument(String title, ConfigurationImpl configuration, HtmlTree body) throws IOException { Content htmlDocType = configuration.isOutputHtml5() ? DocType.HTML5 : DocType.TRANSITIONAL; Content htmlComment = new Comment(configuration.getTe...
python
def element_to_dict(elem_to_parse, element_path=None, recurse=True): """ :return: an element losslessly as a dictionary. If recurse is True, the element's children are included, otherwise they are omitted. The resulting Dictionary will have the following attributes: - name: the name of the elem...
java
private void processEmbeddedField(Field field) { // First create EmbeddedField so we can maintain the path/depth of the // embedded field EmbeddedField embeddedField = new EmbeddedField(field); // Introspect the embedded field. EmbeddedMetadata embeddedMetadata = EmbeddedIntrospector.introspect(embe...
python
def remove(self, widget): """Remove a widget from the window.""" for i, (wid, _) in enumerate(self._widgets): if widget is wid: del self._widgets[i] return True raise ValueError('Widget not in list')
python
def get_pull_command(self, remote=None, revision=None): """Get the command to pull changes from a remote repository into the local repository.""" if revision: raise NotImplementedError(compact(""" Bazaar repository support doesn't include the ability to pull s...
java
public static <T> ApiFuture<T> toApiFuture(CompletableFuture<T> completableFuture) { return ApiFutureUtils.createApiFuture(Java8FutureUtils.createValueSourceFuture(completableFuture)); }
python
def plot_generation_over_load(stats, plotpath): """ Plot of generation over load """ # Generation capacity vs. peak load sns.set_context("paper", font_scale=1.1) sns.set_style("ticks") # reformat to MW gen_cap_indexes = ["Gen. Cap. of MV at v_level 4", "Gen. Cap...
java
public ListMetricsResult withMetrics(Metric... metrics) { if (this.metrics == null) { setMetrics(new com.amazonaws.internal.SdkInternalList<Metric>(metrics.length)); } for (Metric ele : metrics) { this.metrics.add(ele); } return this; }
python
def load_pickle(filename): """Load a pickle file as a dictionary""" try: if pd: return pd.read_pickle(filename), None else: with open(filename, 'rb') as fid: data = pickle.load(fid) return data, None except Exception as err: return ...
python
def convert_default(self, field, **params): """Return raw field.""" for klass, ma_field in self.TYPE_MAPPING: if isinstance(field, klass): return ma_field(**params) return fields.Raw(**params)
java
private boolean hasContentInVfsOrImport(CmsResource resource) { if (m_contentFiles.contains(resource.getResourceId())) { return true; } try { List<CmsResource> resources = getCms().readSiblings(resource, CmsResourceFilter.ALL); if (!resources.isEmpty()) { ...
python
def stacklevel(): """Fetch current stack level.""" pcapkit = f'{os.path.sep}pcapkit{os.path.sep}' tb = traceback.extract_stack() for index, tbitem in enumerate(tb): if pcapkit in tbitem[0]: break else: index = len(tb) return (index-1)
python
def post_comment(self, bugid, comment): '''http://bugzilla.readthedocs.org/en/latest/api/core/v1/comment.html#create-comments''' data = {'id': bugid, "comment": comment} return self._post('bug/{bugid}/comment'.format(bugid=bugid), json.dumps(data))
java
public static <Key, Value> Aggregation<Key, Integer, Integer> integerMin() { return new AggregationAdapter(new IntegerMinAggregation<Key, Value>()); }
java
public void sendAdvertisement(final BasicTrustGraphAdvertisement message, final TrustGraphNodeId sender, final TrustGraphNodeId toNeighbor, final int ttl) { final BasicTrustGraphAdvertisement outboundMessage = ...
java
@Override public boolean hasNext() { if (state == NOT_CACHED) { state = CACHED; nextElement = fetch(); } return state == CACHED; }
python
def can_pair_with(self, other): """ A local candidate is paired with a remote candidate if and only if the two candidates have the same component ID and have the same IP address version. """ a = ipaddress.ip_address(self.host) b = ipaddress.ip_address(other.host) ...
python
def create_lv(self, name, length, units): """ Creates a logical volume and returns the LogicalVolume instance associated with the lv_t handle:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") lv = vg.create_lv("mylv", 40, "MiB") ...
java
public static int skipSpaces (final String sIn, final int nStart) { int pos = nStart; while (pos < sIn.length () && (sIn.charAt (pos) == ' ' || sIn.charAt (pos) == '\n')) pos++; return pos < sIn.length () ? pos : -1; }
java
public void setUserDataAt(int index, Object data) { if (this.userData == null) { throw new IndexOutOfBoundsException(); } this.userData.set(index, data); }
java
public static Anima open(String url, String user, String pass) { return open(url, user, pass, QuirksDetector.forURL(url)); }
python
def _func(self, volume, params): """ BirchMurnaghan equation from PRB 70, 224107 """ e0, b0, b1, v0 = tuple(params) eta = (v0 / volume) ** (1. / 3.) return (e0 + 9. * b0 * v0 / 16. * (eta ** 2 - 1)**2 * (6 + b1 * (eta ** 2 - 1.) - 4. * eta ...
python
def upload_image(self, image_file, referer_url=None, title=None, desc=None, created_at=None, collection_id=None): """Upload an image :param image_file: File-like object of an im...
python
def get_first_child_of_type(self, klass): """! @brief Breadth-first search for a child of the given class. @param self @param klass The class type to search for. The first child at any depth that is an instance of this class or a subclass thereof will be returned. Matching children a...
python
def _set_group_type(self, v, load=False): """ Setter method for group_type, mapped from YANG variable /openflow_state/group/group_info_list/group_type (group-type) If this variable is read-only (config: false) in the source YANG file, then _set_group_type is considered as a private method. Backends ...
java
@Override public List<T> readWithFilter(ReadFilter filter) { ensureOpen(); if (filter == null) { filter = new ReadFilter(); } String sql = String.format("select PARENT_ID from %s_property where PROPERTY_NAME LIKE ? and PROPERTY_VALUE = ?", className); JsonObject ...
python
def delete_build(self, project, build_id): """DeleteBuild. Deletes a build. :param str project: Project ID or project name :param int build_id: The ID of the build. """ route_values = {} if project is not None: route_values['project'] = self._serialize...
python
def decode(self, hashid): """Restore a tuple of numbers from the passed `hashid`. :param hashid The hashid to decode >>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456') >>> hashids.decode('1d6216i30h53elk3') (1, 23, 456) """ if not hashid or not _...
python
def get_virtualenv_env_data(mgr): """Finds kernel specs from virtualenv environments env_data is a structure {name -> (resourcedir, kernel spec)} """ if not mgr.find_virtualenv_envs: return {} mgr.log.debug("Looking for virtualenv environments in %s...", mgr.virtualenv_env_dirs) # fi...
java
public static double getPvalue(int n11, int n12, int n21, int n22) { double Chisquare=Math.pow(Math.abs(n12-n21) - 0.5,2)/(n12+n21); //McNemar with Yates's correction for continuity double pvalue= scoreToPvalue(Chisquare); return pvalue; }
python
def run_apidoc(_): """This method is required by the setup method below.""" import os dirname = os.path.dirname(__file__) ignore_paths = [os.path.join(dirname, '../../aaf2/model'),] # https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py argv = [ '--force', '--no-...
python
def _process_for_uuid(cls, response_raw): """ :type response_raw: client.BunqResponseRaw :rtype: client.BunqResponse[str] """ json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) uuid = converter.deserialize( Uuid, ...
java
public Collection<HazeltaskTask<GROUP>> call() throws Exception { try { if(isShutdownNow) return this.getDistributedExecutorService().shutdownNowWithHazeltask(); else this.getDistributedExecutorService().shutdown(); } catch(IllegalStateException e)...
java
public synchronized void unset(String name) { String[] names = null; if (!isDeprecated(name)) { names = getAlternativeNames(name); if(names == null) { names = new String[]{name}; } } else { names = handleDeprecation(deprecationContext.get(), name); } for(String n: names) { getOverlay().r...
java
public void setBrokerSummaries(java.util.Collection<BrokerSummary> brokerSummaries) { if (brokerSummaries == null) { this.brokerSummaries = null; return; } this.brokerSummaries = new java.util.ArrayList<BrokerSummary>(brokerSummaries); }
python
def _get_wrapper(): """ Get a socket wrapper based on SSL config. """ if not pmxbot.config.get('use_ssl', False): return lambda x: x return importlib.import_module('ssl').wrap_socket
java
public long count(Class<? extends Execution> cls, Map<String,Object> criteria) throws PersistenceException { logger.debug("enter - count(Class,Map)"); if( logger.isDebugEnabled() ) { logger.debug("For: " + cache.getTarget().getName() + "/" + cls + "/" + criteria); } try { ...
java
public static BoundedOverlay getBoundedOverlay(TileDao tileDao, float density, TileScaling scaling) { return new GeoPackageOverlay(tileDao, density, scaling); }
java
public static boolean isValid(final String value) { if (value == null) { return true; } final String uuidPattern = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-" + "[0-9a-f]{4}-[0-9a-f]{12}$"; return Pattern.matches(uuidPattern, value); }
python
def spatialBin(self, roi): """ Calculate indices of ROI pixels corresponding to object locations. """ if hasattr(self,'pixel_roi_index') and hasattr(self,'pixel'): logger.warning('Catalog alread spatially binned') return # ADW: Not safe to set index = -1...
python
def fit1d(samples, e, remove_zeros = False, **kw): """Fits a 1D distribution with splines. Input: samples: Array Array of samples from a probability distribution e: Array Edges that define the events in the probability distribution. For example, e[0] < x <= ...
java
public int scrollToPage(int pageNumber) { Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "scrollToPage pageNumber = %d mPageCount = %d", pageNumber, mPageCount); if (mSupportScrollByPage && (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) { scrollToItem(...
java
private void loadJsonResource(JSONObject json, Properties properties, Object name) throws JSONException { Iterator<?> keys = json.keys(); while (keys.hasNext()) { Object obj = keys.next(); if (!(obj instanceof String)) { LOG.warn("Object not instance of string...
python
def sameAddr(self, ha, ha2) -> bool: """ Check whether the two arguments correspond to the same address """ if ha == ha2: return True if ha[1] != ha2[1]: return False return ha[0] in self.localips and ha2[0] in self.localips
python
def from_xmrs(cls, xmrs, predicate_modifiers=False, **kwargs): """ Instantiate an Eds from an Xmrs (lossy conversion). Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): Xmrs instance to convert from predicate_modifiers (function, bool): function that is ...
java
private CmsGalleryFolderEntry readGalleryFolderEntry(CmsResource folder, String typeName) throws CmsException { CmsObject cms = getCmsObject(); CmsGalleryFolderEntry folderEntry = new CmsGalleryFolderEntry(); folderEntry.setResourceType(typeName); folderEntry.setSitePath(cms.getSitePath...
python
def _update_limits_from_api(self): """ Query EC2's DescribeAccountAttributes API action, and update limits with the quotas returned. Updates ``self.limits``. """ self.connect() self.connect_resource() logger.info("Querying EC2 DescribeAccountAttributes for limits"...
java
public Coordinate[] getPositions() { ArrayList<Coordinate> ret = new ArrayList<Coordinate>(); for (PoseSteering ps : psa) { ret.add(ps.getPose().getPosition()); } return ret.toArray(new Coordinate[ret.size()]); }
java
@SuppressWarnings("unchecked") protected <R> void connect(final EtcdRequest<R> etcdRequest, final ConnectionState connectionState) throws IOException { if(eventLoopGroup.isShuttingDown() || eventLoopGroup.isShutdown() || eventLoopGroup.isTerminated()){ etcdRequest.getPromise().getNettyPromise().cancel(true)...
python
def clear_end_date(self): """Clears the end date. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_end_date_metadata().is_read_only() or ...
java
public void marshall(GetDocumentVersionRequest getDocumentVersionRequest, ProtocolMarshaller protocolMarshaller) { if (getDocumentVersionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getD...
java
public static Predicate not(final Predicate childPredicate) { return new Predicate() { public void init(AbstractSqlCreator creator) { childPredicate.init(creator); } public String toSql() { return "not (" + childPredicate.toSql() + ")"; ...
java
public Collector<Point, ?, Length> toPathLength() { return Collector.of( () -> new LengthCollector(this), LengthCollector::add, LengthCollector::combine, LengthCollector::pathLength ); }
java
public void setAttributes(String name, int attributes) { checkNotSealed(name, 0); findAttributeSlot(name, 0, SlotAccess.MODIFY).setAttributes(attributes); }
java
public Matrix3d lookAlong(double dirX, double dirY, double dirZ, double upX, double upY, double upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); }
java
public static FileSystem create(BlockDevice device, boolean readOnly) throws IOException { return FatFileSystem.read(device, readOnly); }
python
def get_pyof_version(module_fullname): """Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow ver...
java
@Override public DescribeDBClusterParameterGroupsResult describeDBClusterParameterGroups(DescribeDBClusterParameterGroupsRequest request) { request = beforeClientExecution(request); return executeDescribeDBClusterParameterGroups(request); }
java
@BetaApi public final Router getRouter(String router) { GetRouterHttpRequest request = GetRouterHttpRequest.newBuilder().setRouter(router).build(); return getRouter(request); }
java
protected void logInternalError(String message) { if (this.log.isLoggable(Level.FINEST) && !Strings.isNullOrEmpty(message)) { this.log.log(Level.FINEST, MessageFormat.format(Messages.SARLJvmModelInferrer_1, Messages.SARLJvmModelInferrer_0, message)); } }
java
public static ResourceList<Endpoint> list(final BandwidthClient client, final String domainId, final int page, final int size) { assert(domainId != null); assert(page >= 0); assert(size > 0); final String resourceUri = String.format(client.getUserResourceUri(BandwidthConstants.ENDPOINTS...
java
static ResponseList<Place> createPlaceList(HttpResponse res, Configuration conf) throws TwitterException { JSONObject json = null; try { json = res.asJSONObject(); return createPlaceList(json.getJSONObject("result").getJSONArray("places"), res, conf); } catch (JSONExcepti...
java
private Collection parseCollection(Element collectionElement) { Collection collection = new Collection(); collection.setId(collectionElement.getAttribute("id")); collection.setServer(collectionElement.getAttribute("server")); collection.setSecret(collectionElement.getAttribute("secret")...
java
public void export() throws IOException, SQLException, ClassNotFoundException { //check if properties is set or not if(!isValidateProperties()) { logger.error("Invalid config properties: The config properties is missing important parameters: DB_NAME, DB_USERNAME and DB_PASSWORD"); ...
java
public Observable<GetPersonalPreferencesResponseInner> getPersonalPreferencesAsync(String userName, PersonalPreferencesOperationsPayload personalPreferencesOperationsPayload) { return getPersonalPreferencesWithServiceResponseAsync(userName, personalPreferencesOperationsPayload).map(new Func1<ServiceResponse<Get...
python
def add_file(self, filename): """ Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type str or unicode """ with (open(filename, 'rb')) as f: data = f.read() # below won't handle th...