language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def create(cls, obj): """ Create a new prototype object with the argument as the source prototype. .. Note: This does not `initialize` the newly created object any more than setting its prototype. Calling the __init__ method is usually unnecessary as...
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BpsimPackage.TRUNCATED_NORMAL_DISTRIBUTION_TYPE__MAX: return getMax(); case BpsimPackage.TRUNCATED_NORMAL_DISTRIBUTION_TYPE__MEAN: return getMean(); case BpsimPackage.TRUNCATED_NORMAL_DISTRIBUT...
java
@Override public synchronized void put(Integer key, T value) { int intKey = key; while (this.data.size() <= intKey) { this.data.add(null); } if (this.data.get(intKey) != null) { throw new DatabaseException("Database already has a value for key [" + key + "]"); } this.data.set(intKey, value); }
java
public SummarizedAttackVector withVectorCounters(SummarizedCounter... vectorCounters) { if (this.vectorCounters == null) { setVectorCounters(new java.util.ArrayList<SummarizedCounter>(vectorCounters.length)); } for (SummarizedCounter ele : vectorCounters) { this.vectorCou...
java
@Override public QueryRequest<ArrayNode> query(String fql) { return this.query(fql, mapper.getTypeFactory().constructType(ArrayNode.class)); }
java
private static double getDTBondF(double[] resultsH) { double result = 0.0; double SE = resultsH[0]; double PE = resultsH[1]; double PSC = resultsH[2]; double PIC = resultsH[3]; double ETP = resultsH[4]; double COUNTR = resultsH[6]; // System.out.println(...
python
def match_nth_tag_type(self, el, child): """Match tag type for `nth` matches.""" return( (self.get_tag(child) == self.get_tag(el)) and (self.get_tag_ns(child) == self.get_tag_ns(el)) )
python
def combine_tensors_and_multiply(combination: str, tensors: List[torch.Tensor], weights: torch.nn.Parameter) -> torch.Tensor: """ Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining. This is a separate fu...
java
private List<Coordinate> sortX(List<Coordinate> coordinates) { List<Coordinate> sorted = new ArrayList<Coordinate>(coordinates); Collections.sort(sorted, new XComparator()); return sorted; }
java
void shutdown() { m_isShutdown = true; try { int waitFor = 1 - Math.min(m_inFlight.availablePermits(), -4); for (int i = 0; i < waitFor; ++i) { try { if (m_inFlight.tryAcquire(1, TimeUnit.SECONDS)) { m_inFlight.release()...
java
public void buildFieldDetails(XMLNode node, Content memberDetailsTree) throws Exception { configuration.getBuilderFactory(). getFieldBuilder(writer).buildChildren(node, memberDetailsTree); }
java
public static <R, C, V> ImmutableTable<R, C, V> copyOf(Iterable<Table.Cell<R, C, V>> cells) { final ImmutableTable.Builder<R, C, V> ret = ImmutableTable.builder(); for (final Table.Cell<R, C, V> cell : cells) { ret.put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } return ret.build()...
python
def _ack_coord_handle( coord, coord_handle, queue_mapper, msg_tracker, timing_state, tile_proc_logger, stats_handler): """share code for acknowledging a coordinate""" # returns tuple of (handle, error), either of which can be None track_result = msg_tracker.done(coord_handle) queue_han...
java
public static String toRGB(Color color) { if(color != null) { return "rgb(" + Integer.toString(color.getRed()) + "," + Integer.toString(color.getGreen()) + "," + Integer.toString(color.getBlue()) + ")"; } return null; }
java
@Override public DeleteBatchPredictionResult deleteBatchPrediction(DeleteBatchPredictionRequest request) { request = beforeClientExecution(request); return executeDeleteBatchPrediction(request); }
java
public void merge(GridHubConfiguration other) { if (other == null) { return; } super.merge(other); if (isMergeAble(CapabilityMatcher.class, other.capabilityMatcher, capabilityMatcher)) { capabilityMatcher = other.capabilityMatcher; } if (isMergeAble(Integer.class, other.newSessionWa...
python
def confirm_phone_number(self, sms_code): """Confirm phone number with the recieved SMS code :param sms_code: sms code :type sms_code: :class:`str` :return: success (returns ``False`` on request fail/timeout) :rtype: :class:`bool` """ sess = self._get_web_sessio...
python
def get_model(self, sm_id): """ Extract a CompositeSourceModel instance containing the single model of index `sm_id`. """ sm = self.source_models[sm_id] if self.source_model_lt.num_samples: self.source_model_lt.num_samples = sm.samples new = self.__cla...
python
def create(self, dataset_id): """ Create a dataset in Google BigQuery Parameters ---------- dataset : str Name of dataset to be written """ from google.cloud.bigquery import Dataset if self.exists(dataset_id): raise DatasetCreationError( ...
java
protected boolean isStartViewAvailableOnRoot() { if (!m_startview.isEnabled()) { return false; } return !m_startview.getValue().equals(CmsPageEditorConfiguration.APP_ID) & !m_startview.getValue().equals(CmsSitemapEditorConfiguration.APP_ID); }
python
def RGBA(self, val): """Set the color using an Nx4 array of RGBA uint8 values""" # need to convert to normalized float val = np.atleast_1d(val).astype(np.float32) / 255 self.rgba = val
python
def set_bucket_props(self, bucket, props): """ Set the properties on the bucket object given """ bucket_type = self._get_bucket_type(bucket.bucket_type) url = self.bucket_properties_path(bucket.name, bucket_type=bucket_type) heade...
python
def annual_cooling_design_day_004(self): """A design day object representing the annual 0.4% cooling design day.""" if bool(self._summer_des_day_dict) is True: tau = None month_num = int(self._summer_des_day_dict['Month']) if self._monthly_tau_beam != [] and self._mon...
java
private CmsModule getModuleForFileName(String fileName) { String moduleName = fileName; if (fileName.endsWith(SUFFIX)) { moduleName = fileName.substring(0, fileName.length() - SUFFIX.length()); } CmsModule result = OpenCms.getModuleManager().getModule(moduleName); re...
java
private PropertyAdapter createLocalDMAdapter(InetSocketAddress local, InetSocketAddress host, Map options) throws KNXException { return new KnIPDeviceMgmtAdapter(local, host, options.containsKey("nat"), null, false); }
python
def writefile(filename, data, binary=False): """ Write the provided data to the file. `filename` Filename to write. `data` Data buffer to write. `binary` Set to ``True`` to indicate a binary file. Returns boolean. """ try: fla...
java
private boolean checkUniqueMasterCitizenNumber(final String ptaxNumber) { final int checkSum = ptaxNumber.charAt(12) - '0'; final int sum = ((ptaxNumber.charAt(0) - '0' + ptaxNumber.charAt(6) - '0') * 7 // + (ptaxNumber.charAt(1) - '0' + ptaxNumber.charAt(7) - '0') * 6 // + (ptaxNumber.charA...
python
def atlas_peer_update_health( peer_hostport, received_response, peer_table=None ): """ Mark the given peer as alive at this time. Update times at which we contacted it, and update its health score. Use the global health table by default, or use the given health info if set. """ with A...
java
public static String joinStrings(List<String> strings, boolean fixCase, char withChar) { if (strings == null || strings.size() == 0) { return ""; } StringBuilder result = null; for (String s : strings) { if (fixCase) { s = fixCase(s); }...
python
def OnEnterSelectionMode(self, event): """Event handler for entering selection mode, disables cell edits""" self.grid.sel_mode_cursor = list(self.grid.actions.cursor) self.grid.EnableDragGridSize(False) self.grid.EnableEditing(False)
java
public static boolean isDefined(@NonNull Class<? extends EnumValue> enumClass, @NonNull String name) { return GLOBAL_REPOSITORY.containsKey(toKey(enumClass, name)); }
java
private OnClickListener createRemovePreferenceHeaderClickListener() { return new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { int position = spinner.getSelectedItemPosition(); listener.onRemovePreferen...
python
def do_repo_report(repos, report='full', output=sys.stdout, *args, **kwargs): """ Do a repository report: call the report function for each Repository Args: repos (iterable): iterable of Repository instances report (string): report name output (writeable): output stream to print to ...
python
def format_seq(self, outstream=None, linewidth=70): """ Print a sequence in a readable format. :param outstream: if `None`, formatted sequence is returned as a string; otherwise, it is treated as a file-like object and the formatted sequence i...
java
public Quaternionf normalize(Quaternionf dest) { float invNorm = (float) (1.0 / Math.sqrt(x * x + y * y + z * z + w * w)); dest.x = x * invNorm; dest.y = y * invNorm; dest.z = z * invNorm; dest.w = w * invNorm; return dest; }
python
def _on_write(self, sender, *args, **kwargs): """ Internal handler for writing to the device. """ self.on_write(data=kwargs.get('data', None))
java
public Vector3f div(Vector3fc v, Vector3f dest) { dest.x = x / v.x(); dest.y = y / v.y(); dest.z = z / v.z(); return dest; }
python
def increment(version): """Return an incremented version string.""" release_version = os.environ.get("RELEASE_VERSION", None) if release_version is not None: return release_version if isinstance(version, LegacyVersion): msg = """{0} is considered a legacy version ...
java
@Override protected void adapt(LogLevel logLevel, String message, Class clazz) { Logger logger = Logger.getLogger(clazz); Level level = convertToLog4jLevel(logLevel); logger.log(DebugLogTee.class.getName(), level, message, null); }
python
def model(model_names): """ Creates the example directory structure necessary for a model service. """ # for each model name we need to create for model_name in model_names: # the template context context = { 'name': model_name, } # render the model t...
java
@Override public String getReverseRouteFor(Class<? extends Controller> clazz, String method, Map<String, Object> params) { return getReverseRouteFor(clazz.getName(), method, params); }
python
def get_document_field(instance): """ Returns which field the search index has marked as it's `document=True` field. """ for name, field in instance.searchindex.fields.items(): if field.document is True: return name
java
private Ref scope(String idStr) { if (!limited && idStr.equals("var")) { String name = identifier(false); if (name != null) { cfml.removeSpace(); return new Variable(new lucee.runtime.interpreter.ref.var.Scope(ScopeSupport.SCOPE_VAR), name, limited); } } int scope = limited ? Scope.SCOPE_UNDEFINED...
java
public static CompilationFailedException create(final IMessage[] errors) { final StringBuilder sb = new StringBuilder(); sb.append("AJC compiler errors:").append(LINE_SEPARATOR); for (final IMessage error : errors) { sb.append(error.toString()).append(LINE_SEPARATOR); } ...
python
def _get_coordinator_for_group(self, consumer_group): """Returns the coordinator (broker) for a consumer group Returns the broker for a given consumer group or Raises ConsumerCoordinatorNotAvailableError """ if self.consumer_group_to_brokers.get(consumer_group) is None: ...
java
public Postcard withInt(@Nullable String key, int value) { mBundle.putInt(key, value); return this; }
python
def search( self, base=False, trim=False, objects=False, **kwargs ): """ Returns matching entries for search in ldap structured as [(dn, {attributes})] UNLESS searching by dn, in which case the first match is returned """ scope = pyldap.SCOPE_SUBTREE i...
java
private void addHeaderCode(Node script) { script.addChildToFront(createConditionalObjectDecl(JS_INSTRUMENTATION_OBJECT_NAME, script)); // Make subsequent usages of "window" and "window.top" work in a Web Worker context. script.addChildToFront( compiler.parseSyntheticCode( "if (!self.win...
java
public Matrix4d frustumAabb(Vector3d min, Vector3d max) { double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double minZ = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; double maxZ = ...
python
def rollback(self, number=0): """ Will rollback the configuration to a previous state. Can be called also when :param number: How many steps back in the configuration history must look back. :raise pyPluribus.exceptions.RollbackError: In case the configuration cannot be rolled b...
java
private Process launchBundleAudit(File folder) throws AnalysisException { if (!folder.isDirectory()) { throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath())); } final List<String> args = new ArrayList<>(); final String bundleA...
java
public void serialize(XMLExtendedStreamWriter writer, GlobalConfiguration globalConfiguration, Map<String, Configuration> configurations) throws XMLStreamException { writer.writeStartDocument(); writer.writeStartElement("infinispan"); Serializer serializer = new Serializer(); serializer.serializ...
python
def com_google_fonts_check_name_typographicsubfamilyname(ttFont, style_with_spaces): """ Check name table: TYPOGRAPHIC_SUBFAMILY_NAME entries. """ from fontbakery.utils import name_entry_id failed = False if style_with_spaces in ['Regular', 'Italic', 'Bold'...
python
def compiled_init_func(self): """Returns compiled init function""" def get_column_assignment(column_name): return ALCHEMY_TEMPLATES.col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): return ALCHEMY_TEMPLATES.func_arg.safe_substitute(ar...
python
def close(self, force=False): """ close opened file :param force: force closing of externally opened file or buffer """ if self.__write: self.write = self.__write_adhoc self.__write = False if not self._is_buffer or force: self._file....
python
def _read_utf(cls, data, pos, kind=None): """ :param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?). Used to construct more informative exception messages when a decoding er...
python
def set_default_args(self, default_args): """Set default args for commands in collection. Default args are used when the corresponding args aren't passed on the command line or in a direct call. """ for name, args in default_args.items(): command = self[name] ...
java
public static <T> void writeWorkBook(File file, int excelType, List<T> beans) throws WriteExcelException { WriteExcelUtils.writeWorkBook(file, excelType, beans, null); }
python
def infer_argument(self, funcnode, name, context): """infer a function argument value according to the call context Arguments: funcnode: The function being called. name: The name of the argument whose value is being inferred. context: Inference context object ...
java
public static Set<Method> getMethods(Class<?> clazz, Filter<Method>filter) { Set<Method> methods = new HashSet<Method>(); Class<?> cursor = clazz; while(cursor != null && cursor != Object.class) { // get all methods and apply filters methods.addAll(Filter.apply(filter, cursor.getDeclaredMethods())); /...
python
def multi_lpop(self, queue, number, transaction=False): ''' Pops multiple elements from a list ''' try: self._multi_lpop_pipeline(self, queue, number) except: raise
python
def copy(self, memo=None, which=None): """ Returns a (deep) copy of the current parameter handle. All connections to parents of the copy will be cut. :param dict memo: memo for deepcopy :param Parameterized which: parameterized object which started the copy process [default: se...
python
def run_validators(self, value): """ Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: if hasattr(validator, 'set_context'): va...
python
def Minus(self, other): """ Returns a new point which is the pointwise subtraction of other from self. """ return Point(self.x - other.x, self.y - other.y, self.z - other.z)
java
@Nonnull public static <T1, T2, T3> LToIntTriFunction<T1, T2, T3> toIntTriFunctionFrom(Consumer<LToIntTriFunctionBuilder<T1, T2, T3>> buildingFunction) { LToIntTriFunctionBuilder builder = new LToIntTriFunctionBuilder(); buildingFunction.accept(builder); return builder.build(); }
python
def human_size(size_bytes, precision=0): """ Format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc """ if size_bytes == ...
python
def t_measures(dirname, time_func, measure_func): """Calculate a measure over time for a single output directory, and its uncertainty. Parameters ---------- dirname: str Path to a model output directory. time_func: function Function which takes a :class:`Model` instance as a sin...
java
public SIBusMessage peek() throws SISessionUnavailableException, SIResourceException, SIIncorrectCallException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "peek"); checkValidState("peek"); _localConsumerPoint.checkNotClosed(); SIBusMessage ...
java
@Override public void report() { for (Map.Entry<String, Map<String, BugInstance>> thisEntry : possibleBugs.entrySet()) { Map<String, BugInstance> equalsClassesMap = thisEntry.getValue(); for (Map.Entry<String, BugInstance> equalsEntry : equalsClassesMap.entrySet()) { ...
python
def update_project(self, project_key, **kwargs): """Update an existing project :param project_key: Username and unique identifier of the creator of a project in the form of owner/id. :type project_key: str :param title: Project title :type title: str :param o...
java
private static List<ProxyAction> createProxyActions(final Slice<Action> actionBeans) { final List<ProxyAction> proxyActions = new ArrayList<>(); for (final Action action : actionBeans) { final ProxyAction proxyAction = new ProxyAction(); final String dsNameVersion = action.getDis...
python
def triggers(self): """Get a camera's triggers.""" capabilities = self.capabilities if not capabilities: return None for capability in capabilities: if not isinstance(capability, dict): continue triggers = capability.get("Triggers") ...
java
@Override public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder, @NonNull List<Object> payloads) { return !payloads.isEmpty() || super.canReuseUpdatedViewHolder(viewHolder, payloads); }
java
public OvhUser identity_user_user_GET(String user) throws IOException { String qPath = "/me/identity/user/{user}"; StringBuilder sb = path(qPath, user); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhUser.class); }
python
def project_inspect_template_path(cls, project, inspect_template): """Return a fully-qualified project_inspect_template string.""" return google.api_core.path_template.expand( "projects/{project}/inspectTemplates/{inspect_template}", project=project, inspect_template=...
java
@Override public Object getMember(String name) { switch (name) { case "BOOLEAN": return F_BOOLEAN; // case "BYTE": // return F_BYTE; // case "SHORT": // return F_SHORT; case "INT": return F_INT; // ...
python
def set_input_shape_ngpu(self, new_input_shape): """ Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_shape: a list or tuple for the shape of the input. """ assert self.device_name, "Device name has not been set." device_name = self....
python
def available(name): ''' Return True if the named service is available. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' cmd = '{0} get {1}'.format(_cmd(), name) if __salt__['cmd.retcode'](cmd) == 2: return False return True
java
protected AjaxButton newSaveButton(final String id, final Form<?> form) { final AjaxButton saveButton = new AjaxButton(id, form) { /** * The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override protected void onSubmit(final AjaxReque...
python
def markdown_search_user(request): """ Json usernames of the users registered & actived. url(method=get): /martor/search-user/?username={username} Response: error: - `status` is status code (204) - `error` is error message. success: - `status...
java
private Context parse(Object localContext, List<String> remoteContexts, boolean parsingARemoteContext) throws JsonLdError { if (remoteContexts == null) { remoteContexts = new ArrayList<String>(); } // 1. Initialize result to the result of cloning active context. C...
python
def coerce(cls, key, value): """Convert plain dictionaries to MutableDict.""" if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) elif isinstance(value, six.string_types): # Assume JSON string ...
java
protected static boolean writeListType(Output out, Object listType) { log.trace("writeListType"); if (listType instanceof List<?>) { writeList(out, (List<?>) listType); } else { return false; } return true; }
python
def prepare(args): """ Read all seq.fa files and create a matrix and unique fasta files. The information is :param args: options parsed from command line :param con: logging messages going to console :param log: logging messages going to console and file :returns: files - matrix and fasta ...
python
def partial_path_match(path1, path2, kwarg_re=r'\{.*\}'): """Validates if path1 and path2 matches, ignoring any kwargs in the string. We need this to ensure we can match Swagger patterns like: /foo/{id} against the observed pyramid path /foo/1 :param path1: path of a url :type path...
python
def unique(transactions): """ Remove any duplicate entries. """ seen = set() # TODO: Handle comments return [x for x in transactions if not (x in seen or seen.add(x))]
python
def null_write_block(fo, block_bytes): """Write block in "null" codec.""" write_long(fo, len(block_bytes)) fo.write(block_bytes)
python
async def close_async(self): """Close the client asynchronously. This includes closing the Session and CBS authentication layer as well as the Connection. If the client was opened using an external Connection, this will be left intact. """ if self.message_handler: ...
java
@Override public void removeByG_P_A(long groupId, boolean primary, boolean active) { for (CommerceCurrency commerceCurrency : findByG_P_A(groupId, primary, active, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceCurrency); } }
java
public static Object setObjectIndex(Object obj, double dblIndex, Object value, Context cx, Scriptable scope) { Scriptable sobj = toObjectOrNull(cx, obj, scope); if (sobj == null) { throw undefWriteError(obj, ...
python
def qos_queue_scheduler_strict_priority_dwrr_traffic_class1(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") queue = ET.SubElement(qos, "queue") scheduler = ET.SubElement...
java
protected final void setMeasuredDimension(View view, int width, int height) { final ViewProxy proxy = (ViewProxy) view; proxy.invokeSetMeasuredDimension(width, height); }
python
def check_args(args): """ Parse arguments and check if the arguments are valid """ if not os.path.exists(args.fd): print("Not a valid path", args.fd, file=ERROR_LOG) return [], [], False if args.fl is not None: # we already ensure the file can be opened and opened the file ...
python
def download(self, name: str, force: bool = False ) -> bool: """ Attempts to download a given Docker image. If `force=True`, then any previously installed version of the image (described by the instructions) will be replaced by the image...
python
def _get_flaky_attributes(cls, test_item): """ Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` ...
python
def format_date(self, value, format_): """ Format the date using Babel """ date_ = make_date(value) return dates.format_date(date_, format_, locale=self.lang)
python
def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names """ if not feature_names is None: # validate feature name ...
python
def update(self, friendly_name=values.unset, unique_name=values.unset): """ Update the FieldTypeInstance :param unicode friendly_name: A string to describe the resource :param unicode unique_name: An application-defined string that uniquely identifies the resource :returns: Upd...
python
def parse(self, p_todo): """ Returns fully parsed string from 'format_string' attribute with all placeholders properly substituted by content obtained from p_todo. It uses preprocessed form of 'format_string' (result of ListFormatParser._preprocess_format) stored in 'format_list...
python
def nLLevalAllY(ldelta, UY, UX, S): """ nLLevalAllY(double ldelta, MatrixXd const & UY, MatrixXd const & UX, VectorXd const & S) Parameters ---------- ldelta: double UY: MatrixXd const & UX: MatrixXd const & S: VectorXd const & """ return _core.nLLevalAllY(ldelta, UY, UX, S)