language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public <T> T execute(final String query, Object connection) { Session session = factory.getConnection(); try { Statement queryStmt = new SimpleStatement(query); KunderaCoreUtils.printQuery(query, showQuery); queryStmt.setConsistencyLevel(ConsistencyLeve...
java
public static StoreException create(final Type type, final Throwable cause, final String errorMessage) { Preconditions.checkArgument(cause != null || (errorMessage != null && !errorMessage.isEmpty()), "Either cause or errorMessage should be non-empty"); StoreException exception; ...
python
def build_command(self, parameter_values, command=None): """ Build the command for this step using the given parameter values. Even if the original configuration only declared a single `command`, this function will return a list of shell commands. It is the caller's responsibil...
python
def submit_and_verify( xml_str=None, xml_file=None, xml_root=None, config=None, session=None, dry_run=None, **kwargs ): """Submits data to the Polarion Importer and checks that it was imported.""" try: config = config or configuration.get_config() xml_root = _get_xml_root(xml_root, xml_str, ...
python
def segment(self, *args): """Segment one or more datasets with this subword field. Arguments: Positional arguments: Dataset objects or other indexable mutable sequences to segment. If a Dataset object is provided, all columns corresponding to this field are u...
python
def move_complete_channel(self): """ Channels and theirs subscribers are moved completely to new channel or existing channel. """ to_channel = Channel.objects.get(self.current.task_data['target_channel_key']) chosen_channels = self.current.task_data['chosen_channels'] ...
python
def gossip_bind(self, format, *args): """ Set-up gossip discovery of other nodes. At least one node in the cluster must bind to a well-known gossip endpoint, so other nodes can connect to it. Note that gossip endpoints are completely distinct from Zyre node endpoints, and should not overlap (they can us...
python
def _array2cstr(arr): """ Serializes a numpy array to a compressed base64 string """ out = StringIO() np.save(out, arr) return b64encode(out.getvalue())
java
static MavenProject getRootModule(MavenProject module, List<MavenProject> reactor, String rulesDirectory, boolean useExecutionRootAsProjectRoot) throws MojoExecutionException { String rootModuleContextKey = ProjectResolver.class.getName() + "#rootModule"; MavenProject rootModule = (MavenProj...
java
public synchronized void stopInactivityTimer() { final boolean traceOn = TraceComponent.isAnyTracingEnabled(); if (traceOn && tc.isEntryEnabled()) Tr.entry(tc, "stopInactivityTimer"); if (_inactivityTimerActive) { _inactivityTimerActive = false; EmbeddableTi...
java
@Override public void rollback() throws IllegalStateException, SystemException { if (tc.isEntryEnabled()) Tr.entry(tc, "rollback (SPI)"); final int state = _status.getState(); // // We are only called in this method for superiors. // if (state == Transac...
python
def retry_connect(self): """Will be called when new channels in the token network are detected. If the minimum number of channels was not yet established, it will try to open new channels. If the connection manager has no funds, this is a noop. """ with self.lock: ...
java
public static String dateToIsoString(Date inputDate) { DateFormat dateStringFormat = new SimpleDateFormat("yyyy-MM-dd"); return dateStringFormat.format(inputDate); }
python
def _set_key_table(self, v, load=False): """ Setter method for key_table, mapped from YANG variable /interface/fortygigabitethernet/ip/interface_fo_ospf_conf/ospf_interface_config/md5_authentication/key_table (container) If this variable is read-only (config: false) in the source YANG file, then _set_ke...
python
def _vis_calibrate(data, chn, calib_type, pre_launch_coeffs=False, calib_coeffs=None, mask=False): """Visible channel calibration only. *calib_type* in count, reflectance, radiance """ # Calibration count to ...
python
def cost(self, logits, target): """Returns cost. Args: logits: model output. target: target. Returns: Cross-entropy loss for a sequence of logits. The loss will be averaged across time steps if time_average_cost was enabled at construction time. """ logits = tf.reshape(logi...
java
@Nonnull public static Properties loadProperties(@Nonnull String properties) throws IOException { Properties p = new Properties(); p.load(new StringReader(properties)); return p; }
java
public static Object convertExample(String value, String type) { if (value == null) { return null; } try { switch (type) { case "integer": return Integer.valueOf(value); case "number": return Float.v...
python
def getApplicationProcessId(self, pchAppKey): """Returns the process ID for an application. Return 0 if the application was not found or is not running.""" fn = self.function_table.getApplicationProcessId result = fn(pchAppKey) return result
java
@Override public Map<K, V> clearAll() { Map<K, V> result = new LinkedHashMap<K, V>(map.size()); for (Map.Entry<K, V> entry : map.entrySet()) { K key = entry.getKey(); V value = entry.getValue(); boolean removed = map.remove(key, value); if (removed)...
python
def is_stable(self,species): ''' This routine accepts input formatted like 'He-3' and checks with stable_el list if occurs in there. If it does, the routine returns True, otherwise False. Notes ----- this method is designed to work with an se instance from ...
python
def unregister_factory(self, factory_name): # type: (str) -> bool """ Unregisters the given component factory :param factory_name: Name of the factory to unregister :return: True the factory has been removed, False if the factory is unknown """ i...
python
def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. ...
python
def egg(qualifier: Union[str, Type] = '', profile: str = None): """ A function that returns a decorator (or acts like a decorator) that marks class or function as a source of `base`. If a class is decorated, it should inherit after from `base` type. If a function is decorated, it declared return t...
java
protected Dataset getDatasetOrThrowException(final Uri uri) { final Dataset dataset = mMatcher.matchDataset(uri); if (dataset == null) { throw new IllegalArgumentException("Unsupported URI: " + uri); } if (dataset instanceof ContextDataset) { ((ContextDataset)dataset).setContext(getContext()); } retur...
java
private void printKeySet() { Set<?> keys = keySet(); System.out.println("printing keyset:"); for (Object o: keys) { //System.out.println(Arrays.asList((Object[]) i.next())); System.out.println(o); } }
python
def annotate(text, gcube_token=None, lang=DEFAULT_LANG, api=DEFAULT_TAG_API, long_text=DEFAULT_LONG_TEXT): ''' Annotate a text, linking it to Wikipedia entities. :param text: the text to annotate. :param gcube_token: the authentication token provided by the D4Science infrastructure. :pa...
python
def _apply_shadow_vars(avg_grads): """ Create shadow variables on PS, and replace variables in avg_grads by these shadow variables. Args: avg_grads: list of (grad, var) tuples """ ps_var_grads = [] for grad, var in avg_grads: assert var.na...
java
protected void proddle() throws SIConnectionDroppedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "proddle"); boolean useThisThread = false; synchronized (priorityQueue) { synchronized (this) { if (idle) { useThi...
python
def geodist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0): """ Distributed version of tree_distance.geodist Parameters: two valid newick strings and a boolean """ tree_a = Tree(newick_string_a) tree_b = Tree(newick_string_b) return treedist.geodist(tr...
java
public void buildSerialFieldTagsInfo(Content serializableFieldsTree) { if(configuration.nocomment){ return; } VariableElement field = (VariableElement)currentMember; // Process Serializable Fields specified as array of // ObjectStreamFields. Print a member for each se...
python
def make_crossroad_router(source, drain=False): ''' legacy crossroad implementation. deprecated ''' sink_observer = None def on_sink_subscribe(observer): nonlocal sink_observer sink_observer = observer def dispose(): nonlocal sink_observer sink_observer ...
python
def bearing(self, format='numeric'): """Calculate bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments """ bearings...
java
public Any command_handler(final DeviceImpl device, final String command, final Any in_any) throws DevFailed { Any ret = Util.instance().get_orb().create_any(); Util.out4.println("Entering DeviceClass::command_handler() method"); int i; final String cmd_name = command.toLow...
python
def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another pack...
python
def parseEC2Json2List(jsontext, region): """ Takes a JSON and returns a list of InstanceType objects representing EC2 instance params. :param jsontext: :param region: :return: """ currentList = json.loads(jsontext) ec2InstanceList = [] for k, v in iteritems(currentList["products"]):...
python
def unicode2bytes(x, encoding='utf-8', errors='strict'): """ Convert a unicode string to C{bytes}. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 'str...
java
public KeyValue getKeyValue(String KeyURI) throws EmbeddedJmxTransException { String etcdURI = KeyURI.substring(0, KeyURI.indexOf("/", 7)); String key = KeyURI.substring(KeyURI.indexOf("/", 7)); try { return getFromEtcd(makeEtcdBaseUris(etcdURI), key); } catch (Throwable t) { throw new Em...
java
public final void equalityExpression() throws RecognitionException { int equalityExpression_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 116) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1162:5: ( instanceOfExpression ( ( '==...
python
def duplicate(self): """ create an copy of the script Returns: """ # get settings of script class_of_script = self.__class__ script_name = self.name script_instruments = self.instruments sub_scripts = self.scripts script_settings = self....
java
static int darker(int color, float factor) { return Color.argb(Color.alpha(color), Math.max((int) (Color.red(color) * factor), 0), Math.max((int) (Color.green(color) * factor), 0), Math.max((int) (Color.blue(color) * factor), 0)); }
java
public EList<Grammar> getUsedGrammars() { if (usedGrammars == null) { usedGrammars = new EObjectResolvingEList<Grammar>(Grammar.class, this, XtextPackage.GRAMMAR__USED_GRAMMARS); } return usedGrammars; }
python
def get_mapreduce_yaml(parse=parse_mapreduce_yaml): """Locates mapreduce.yaml, loads and parses its info. Args: parse: Used for testing. Returns: MapReduceYaml object. Raises: errors.BadYamlError: when contents is not a valid mapreduce.yaml file or the file is missing. """ mr_yaml_path = ...
python
def viz_json(net, dendro=True, links=False): ''' make the dictionary for the clustergram.js visualization ''' from . import calc_clust import numpy as np all_dist = calc_clust.group_cutoffs() for inst_rc in net.dat['nodes']: inst_keys = net.dat['node_info'][inst_rc] all_cats = [x for x in inst_keys...
java
public Observable<LogAnalyticsOperationResultInner> beginExportThrottledRequestsAsync(String location, ThrottledRequestsInput parameters) { return beginExportThrottledRequestsWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<LogAnalyticsOperationResultInner>, LogAnalyticsOperationResu...
python
def text_to_title(value): """when a title is required, generate one from the value""" title = None if not value: return title words = value.split(" ") keep_words = [] for word in words: if word.endswith(".") or word.endswith(":"): keep_words.append(word) i...
python
def holidays(self, year=None): """Computes holidays (non-working days) for a given year. Return a 2-item tuple, composed of the date and a label.""" if not year: year = date.today().year if year in self._holidays: return self._holidays[year] # Here we pr...
java
public TemporalDocument next() { //String fileName = filesToProcess.poll(); NameAndTime n = filesToProcess.poll(); if (n == null) return null; try { return (n.hasTimeStamp()) ? new TemporalFileDocument(n.fileName, n.timeStamp) : new TemporalFileDocument(n.fileName); // no timestamp } catch (IOExcep...
python
def _bbvi_fit(self, optimizer='RMSProp', iterations=1000, print_progress=True, start_diffuse=False, **kwargs): """ Performs Black Box Variational Inference Parameters ---------- posterior : method Hands bbvi_fit a posterior object optimizer : string ...
python
def serialize(self) -> dict: """ Serialize the message for sending to slack API Returns: serialized message """ data = {**self} if "attachments" in self: data["attachments"] = json.dumps(self["attachments"]) return data
python
def _get_key_values(self, name): """Return a dict containing key / values items for a given key, used for items like filters, page, etc. :param str name: name of the querystring parameter :return dict: a dict of key / values items """ results = {} for key, value in self...
java
@Override public void notifyChange() throws CouldNotPerformException, InterruptedException { logger.debug("Notify data change of " + this); // synchronized by manageable lock to prevent reinit between validateInitialization and publish M newData; manageLock.lockWrite(this); t...
python
def instance_norm(attrs, inputs, proto_obj): """Instance Normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'epsilon' : 'eps'}) new_attrs['eps'] = attrs.get('epsilon', 1e-5) return 'InstanceNorm', new_attrs, inputs
java
@Pure @Inline(value = "new $2($3.intValue($1))", imported = {AtomicInteger.class, PrimitiveCastExtensions.class}) public static AtomicInteger toAtomicInteger(CharSequence value) { return new AtomicInteger(intValue(value)); }
java
public ListTablesResult withTableNames(String... tableNames) { if (getTableNames() == null) setTableNames(new java.util.ArrayList<String>(tableNames.length)); for (String value : tableNames) { getTableNames().add(value); } return this; }
python
def ishermitian(A, fast_check=True, tol=1e-6, verbose=False): r"""Return True if A is Hermitian to within tol. Parameters ---------- A : {dense or sparse matrix} e.g. array, matrix, csr_matrix, ... fast_check : {bool} If True, use the heuristic < Ax, y> = < x, Ay> for rand...
java
public String getClassPath() { StringBuilder buf = new StringBuilder(); for (Entry entry : entryList) { if (buf.length() > 0) { buf.append(File.pathSeparator); } buf.append(entry.getURL()); } return buf.toString(); }
java
@Override public <T> T getProperty(Object key, Class<T> clazz) { return clazz.cast(getProperty(key)); }
python
def read_folder(folder): """ Parameters ---------- folder : string Path to a folde with *.inkml files. Returns ------- list : Objects of the type HandwrittenData """ import glob recordings = [] for filename in natsorted(glob.glob("%s/*.inkml" % folder)): ...
python
def to_utf8(value): """Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string. """ if isinstance(value, unicode): return value.encode('utf-8') assert isinstance(value, str) return value
python
def get_block(self, parent, config='running_config'): """ Scans the config and returns a block of code Args: parent (str): The parent string to search the config for and return the block config (str): A text config string to be searched. Default i...
python
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) chunk = self.mfac.value() if v < self.imin or v > self.imax or (v % chunk != 0): return False else: return True ex...
python
def _is_zero(x): """ Returns True if x is numerically 0 or an array with 0's. """ if x is None: return True if isinstance(x, numbers.Number): return x == 0.0 if isinstance(x, np.ndarray): return np.all(x == 0) return False
java
public static byte[] fromHex(final String string, final int offset, final int count) { if(offset >= string.length()) throw new IllegalArgumentException("Offset is greater than the length (" + offset + " >= " + string.length() + ").")/*by contract*/; if( (count & 0x01) != 0) throw new IllegalArgumentExce...
python
def generate_component_annotation_miriam_match(elements, component, db): """ Tabulate which MIRIAM databases the element's annotation match. If the relevant MIRIAM identifier is not in an element's annotation it is ignored. Parameters ---------- elements : list Elements of a model,...
java
@Nonnull public Section addDataSection(@Nullable SoftwareSystem softwareSystem, @Nonnull Format format, @Nonnull String content) { return addSection(softwareSystem, "Data", format, content); }
python
def _cleandoc(doc): """Remove uniform indents from ``doc`` lines that are not empty :returns: Cleaned ``doc`` """ indent_length = lambda s: len(s) - len(s.lstrip(" ")) not_empty = lambda s: s != "" lines = doc.split("\n") indent = min(map(indent_length, filter(not_empty, lines))) retu...
python
def remap_index_fn(ref_file): """minimap2 can build indexes on the fly but will also store commons ones. """ index_dir = os.path.join(os.path.dirname(ref_file), os.pardir, "minimap2") if os.path.exists(index_dir) and os.path.isdir(index_dir): return index_dir else: return os.path.dir...
python
def compress(self, condition, axis=0, out=None): """Return selected slices of an array along given axis. Parameters ---------- condition : array_like, bool Array that selects which entries to return. N.B., if len(condition) is less than the size of the given axis...
python
def ntwodgaussian_lmfit(params): """ Convert an lmfit.Parameters object into a function which calculates the model. Parameters ---------- params : lmfit.Parameters Model parameters, can have multiple components. Returns ------- model : func A function f(x,y) that will ...
python
def cost_loss(y_true, y_pred, cost_mat): #TODO: update description """Cost classification loss. This function calculates the cost of using y_pred on y_true with cost-matrix cost-mat. It differ from traditional classification evaluation measures since measures such as accuracy asing the same cost to...
java
public boolean overrides(Link other) { if (other.getStatus() == LinkStatus.ASSERTED && status != LinkStatus.ASSERTED) return false; else if (status == LinkStatus.ASSERTED && other.getStatus() != LinkStatus.ASSERTED) return true; // the two links are from equivalent sources ...
java
public static ByteArrayCache getInstance() { Application app = LCCore.getApplication(); synchronized (ByteArrayCache.class) { ByteArrayCache instance = app.getInstance(ByteArrayCache.class); if (instance != null) return instance; app.setInstance(ByteArrayCache.class, instance = new ByteArrayCache()); ...
python
def ensure_chosen_alternatives_are_in_user_alt_ids(choice_col, wide_data, availability_vars): """ Ensures that all chosen alternatives in `wide_df` are present in the `availability_vars` dict. Raises a help...
java
@SuppressWarnings("unchecked") public static <T extends Comparable<? super T>> T min(T... numberArray) { return ArrayUtil.min(numberArray); }
python
def confd_state_internal_cdb_client_subscription_priority(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal = ET.SubElement(confd_state, "internal"...
python
def parse_qs(qs, keep_blank_values=0, strict_parsing=0, keep_attr_order=True): """ Kind of like urlparse.parse_qs, except returns an ordered dict. Also avoids replicating that function's bad habit of overriding the built-in 'dict' type. Taken from below with modification: <https://bitbucket.org...
python
def prepare(self, setup_func): """This decorator wrap a function which setup a environment before running a command @manager.prepare(setup_func) def some_command(): pass """ assert inspect.isfunction(setup_func) argsspec = inspect.getargspec(setup_func...
python
def deriv(self, t, y, data=None): " Calculate [dtheta/dt, d2theta/dt2] from [theta, dtheta/dt]." theta, dtheta_dt = y return np.array([dtheta_dt, - self.g_l * gv.sin(theta)])
python
def _extract_hidden_data(dom): """ Extracts hidden input data from DOM and returns the data as dictionary. """ input_tags = dom.find_all('input', attrs={'type': 'hidden'}) data = {} for input_tag in input_tags: data[input_tag['name']] = input_tag['value'] ...
python
def from_dict(cls, d): """ Restores an object state from a dictionary, used in de-JSONification. :param d: the object dictionary :type d: dict :return: the object :rtype: object """ conf = {} for k in d["config"]: v = d["config"][k] ...
python
def to_query_parameters_dict(parameters): """Converts a dictionary of parameter values into query parameters. :type parameters: Mapping[str, Any] :param parameters: Dictionary of query parameter values. :rtype: List[google.cloud.bigquery.query._AbstractQueryParameter] :returns: A list of named que...
java
public static <T extends ImageGray<T>> InputToBinary<T> blockMean(ConfigLength regionWidth, double scale , boolean down, boolean thresholdFromLocalBlocks, Class<T> inputType) { if( BOverrideFactoryThresholdBinary.blockMean != null ) return BOverrideFactoryThresholdBinary.blockMean.handle(regionWidth, sc...
python
def change_site(self, new_name, new_location=None, new_er_data=None, new_pmag_data=None, replace_data=False): """ Update a site's name, location, er_data, and pmag_data. By default, new data will be added in to pre-existing data, overwriting existing values. If replac...
java
@Override public EClass getIfcSolarDevice() { if (ifcSolarDeviceEClass == null) { ifcSolarDeviceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(607); } return ifcSolarDeviceEClass; }
java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE", justification = "Temporary fix") private List<Long> getValidationOutputFromHive(List<String> queries) throws IOException { if (null == queries || queries.size() == 0) { log.warn("No queries specified to be...
java
public static ExecutorService newMaxQueueThreadPool(int numWorkerThreads, long waitingMillis, int maxQueue) { return new ThreadPoolExecutor(numWorkerThreads, numWorkerThreads, 0L, TimeUnit.MILLISECONDS, waitingMillis > 0 ? getWaitingLimitedBlockingQueue( ...
python
def get_deprecation_reason( node: Union[EnumValueDefinitionNode, FieldDefinitionNode] ) -> Optional[str]: """Given a field or enum value node, get deprecation reason as string.""" from ..execution import get_directive_values deprecated = get_directive_values(GraphQLDeprecatedDirective, node) return...
java
public static String wrapLinesByWords(String text, int maxLen) { StringBuffer buffer = new StringBuffer(); int lineLength = 0; for (String token : text.split(" ")) { if (lineLength + token.length() + 1 > maxLen) { buffer.append("\n"); lineLength = 0; } else if (lineLength > 0) { buffer.append(" "); ...
python
def _commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: ...
python
def setval(self, varname, value): """ Set the value of the variable with the given name. """ if varname in self: self[varname]['value'] = value else: self[varname] = Variable(self.default_type, value=value)
java
public Signature argType(int index, Class<?> type) { return new Signature(type().changeParameterType(index, type), argNames()); }
python
def _scaled_bqm(bqm, scalar, bias_range, quadratic_range, ignored_variables, ignored_interactions, ignore_offset): """Helper function of sample for scaling""" bqm_copy = bqm.copy() if scalar is None: scalar = _calc_norm_coeff(bqm_copy.linear, bqm_copy.quadratic, ...
java
public CMAEntry publish(CMAEntry entry) { assertNotNull(entry, "entry"); final String entryId = getResourceIdOrThrow(entry, "entry"); final String environmentId = entry.getEnvironmentId(); final String spaceId = getSpaceIdOrThrow(entry, "entry"); return service.publish( entry.getSystem().ge...
java
public ModuleDefinitionParameterComponent addParameter() { //3 ModuleDefinitionParameterComponent t = new ModuleDefinitionParameterComponent(); if (this.parameter == null) this.parameter = new ArrayList<ModuleDefinitionParameterComponent>(); this.parameter.add(t); return t; }
python
def _conv_general_permutations(self, dimension_numbers): """Utility for convolution dimension permutations relative to Conv HLO.""" lhs_spec, rhs_spec, out_spec = dimension_numbers lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C') charpairs = (lhs_char, rhs_char, out_char) for i, (a,...
python
def create_for_placeholder(self, placeholder, sort_order=1, language_code=None, **kwargs): """ Create a Content Item with the given parameters If the language_code is not provided, the language code of the parent will be used. This may perform an additional database query, unless ...
java
private ParseTree parseEquality(Expression expressionIn) { SourcePosition start = getTreeStartLocation(); ParseTree left = parseRelational(expressionIn); while (peekEqualityOperator()) { Token operator = nextToken(); ParseTree right = parseRelational(expressionIn); left = new BinaryOperato...
python
def uninstall_handle_input(self): """Remove the hook.""" if self.hooked is None: return ctypes.windll.user32.UnhookWindowsHookEx(self.hooked) self.hooked = None
python
def write(self): """If data exists for the entity, writes it to disk as a .JSON file with the url-encoded URI as the filename and returns True. Else, returns False.""" if (self.data): dataPath = self.client.local_dir / (urllib.parse.quote_plus(self.uri)+'.json') ...