language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public final String entryRuleOpSingleAssign() throws RecognitionException { String current = null; AntlrDatatypeRuleToken iv_ruleOpSingleAssign = null; try { // InternalPureXbase.g:906:54: (iv_ruleOpSingleAssign= ruleOpSingleAssign EOF ) // InternalPureXbase.g:907:2: i...
java
protected static int removeTreeStructure(BinaryTree curStruc) { BinaryTree equalStruc = curStruc.getEqual(); BinaryTree notEqualStruc = curStruc.getNotEqual(); curStruc = null; if (equalStruc != null) { removeTreeStructure(equalStruc); } if (notEqualStruc !...
java
@MemberOrder(name="sector", sequence = "1") public ExampleTaggableEntity newSector( @ParameterLayout(named="Tag") @Parameter(optionality = Optionality.OPTIONAL) final String sector) { setSector(sector); return this; }
java
@Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { internalStmt.setBigDecimal(parameterIndex, x); }
python
def _infer_sequence_helper(node, context=None): """Infer all values based on _BaseContainer.elts""" values = [] for elt in node.elts: if isinstance(elt, nodes.Starred): starred = helpers.safe_infer(elt.value, context) if not starred: raise exceptions.Inferenc...
python
def create_floatingip(self, context, floatingip): """Create floating IP. :param context: Neutron request context :param floatingip: data for the floating IP being created :returns: A floating IP object on success As the l3 router plugin asynchronously creates floating IPs ...
java
@Nonnull public static String getWithLeading (@Nullable final String sSrc, @Nonnegative final int nMinLen, final char cFront) { return _getWithLeadingOrTrailing (sSrc, nMinLen, cFront, true); }
python
def permissions_for(self, user=None): """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to tru...
java
public ConsumedCapacity withGlobalSecondaryIndexes(java.util.Map<String, Capacity> globalSecondaryIndexes) { setGlobalSecondaryIndexes(globalSecondaryIndexes); return this; }
python
def report(self): """Dump the grammar tables to standard output, for debugging.""" from pprint import pprint print "s2n" pprint(self.symbol2number) print "n2s" pprint(self.number2symbol) print "states" pprint(self.states) print "dfas" pprin...
python
def setBusy(self, busy): ''' Called by the driver to indicate it is busy. @param busy: True when busy, false when idle @type busy: bool ''' self._busy = busy if not self._busy: self._pump()
python
def __dump_stack(self): """Dump the shell stack in a human friendly way. An example output is: 0 PlayBoy 1 └── foo-prompt: foo@[] 2 └── karPROMPT: kar@[] 3 └── DEBUG: debug@['shell'] """ maxdepth = l...
java
public Observable<ServiceResponse<List<String>>> createVideoReviewsWithServiceResponseAsync(String teamName, String contentType, List<CreateVideoReviewsBodyItem> createVideoReviewsBody, CreateVideoReviewsOptionalParameter createVideoReviewsOptionalParameter) { if (this.client.baseUrl() == null) { th...
java
@Override public Retina identifyRetinaByText(String text) throws ApiException { if (isEmpty(text)) { throw new IllegalArgumentException(NULL_TEXT_MSG); } return this.api.getLanguage(text); }
java
public void clickOnText(String text) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickOnText(\""+text+"\")"); } clicker.clickOnText(text, false, 1, true, 0); }
python
def extend(self, base, key, value=None): """ Adds a new definition to this enumerated type, extending the given base type. This will create a new key for the type and register it as a new viable option from the system, however, it will also register its base information so you c...
java
@Override @GET @Path("/events/count") public int countEvents(@QueryParam("earliest") String earliest) throws NotAuthorizedException { accessControlUtils.checkAuthorization(Action.EXECUTE_REPORT, requestContext); SearchCriteria criteria = new SearchCriteria().setEarliest(earliest); return appSensorServer....
python
def query_extensions(self, extension_query, account_token=None, account_token_header=None): """QueryExtensions. [Preview API] :param :class:`<ExtensionQuery> <azure.devops.v5_1.gallery.models.ExtensionQuery>` extension_query: :param str account_token: :param String account_token_...
java
public void update(Company company) { if (company.getId() <= 0 || company.getId() <= 0) { throw new RuntimeException("Company id invliad"); } if (!companyMap.containsKey(company.getId())) { throw new RuntimeException("Company id not exist"); } companyMap.put(company.getId(), company); }
java
@Override protected final int getSurrogateOffset(char lead, char trail) { if (m_dataManipulate_ == null) { throw new NullPointerException( "The field DataManipulate in this Trie is null"); } // get fold position for the next trail surrogate ...
python
def addOutputPort(self, node: LNode, name: str, out: Optional[Union[RtlSignalBase, LPort]], side=PortSide.EAST): """ Add and connect output port on subnode """ oPort = node.addPort(name, PortType.OUTPUT, side) if out is not None: ...
java
public Observable<Void> beginResizeAsync(String resourceGroupName, String clusterName) { return beginResizeWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { ...
python
def get_entities_by_components(self, *components): ''' Get entity by list of components All members of components must be of type Component ''' return list(filter(lambda entity: set(components) <= set(map(type, entity.get_comp...
python
def get_sec_project_activity(self): """ Generate the "project activity" section of the report. """ logger.debug("Calculating Project Activity metrics.") data_path = os.path.join(self.data_dir, "activity") if not os.path.exists(data_path): os.makedirs(data_pa...
python
def convertnumbers(table, strict=False, **kwargs): """ Convenience function to convert all field values to numbers where possible. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar', 'baz', 'quux'], ... ['1', '3.0', '9+3j', 'aaa'], ... ['2', '1.3',...
java
public void sendTriState(String codeWord) { if (transmitterPin != null) { for (int nRepeat = 0; nRepeat < repeatTransmit; nRepeat++) { for (int i = 0; i < codeWord.length(); ++i) { switch (codeWord.charAt(i)) { case '0': ...
java
public boolean supportsConvert(int fromType, int toType) throws SQLException { //#ifdef JAVA6 switch (fromType) { case java.sql.Types.NCHAR : { fromType = java.sql.Types.CHAR; break; } case java.sql.Types.N...
python
def do_ls(client, args): """List directory""" for item in client.get_folder_contents_iter(args.uri): # privacy flag if item['privacy'] == 'public': item['pf'] = '@' else: item['pf'] = '-' if isinstance(item, Folder): # type flag i...
java
protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) { Transaction tx = new Transaction(wallet.getParams()); if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) { tx.addOutput(getTotalValue().subtract(valueToMe), LegacyAddress.fromKey(wallet.getParams(), get...
java
public DynamicReport build() { if (built) { throw new DJBuilderException("DynamicReport already built. Cannot use more than once."); } else { built = true; } report.setOptions(options); if (!globalVariablesGroup.getFooterVariables().isEmpty() || !globalV...
java
public String getNamespaceURI(String prefix) throws NamespaceException, RepositoryException { String uri = null; // look in session first if (namespaces.size() > 0) { uri = namespaces.get(prefix); if (uri != null) { return uri; } } ...
python
def import_from_dict(session, data, sync=[]): """Imports databases and druid clusters from dictionary""" if isinstance(data, dict): logging.info('Importing %d %s', len(data.get(DATABASES_KEY, [])), DATABASES_KEY) for database in data.get(DATABASES_KEY, [...
python
def allocate_buffers(self): "Create the ragged array that will be filled when we ask for items." if self.ite_len is None: len(self) self.idx = LanguageModelPreLoader.CircularIndex(len(self.dataset.x.items), not self.backwards) self.batch = np.zeros((self.bs, self.bptt+1), dtype=np.int6...
java
public void show(final String repository, final String workspace, final String path, final boolean changeHistory) { this.repository = repository; this.refreshWorkspacesAndReloadNode(null, path, changeHistory); }
java
private boolean isValidCommandMethod(Object service, String commandName) { try { service.getClass().getMethod(commandName, PrintWriter.class, String[].class); return true; } catch (NoSuchMethodException e) { return false; } }
python
def reset(module, serd=None): ''' Reset module or sub-component module: string module to unload serd : string serd sub module CLI Example: .. code-block:: bash salt '*' fmadm.reset software-response ''' ret = {} fmadm = _check_fmadm() cmd = '{cmd} rese...
python
def count_end(teststr, testchar): """Count instances of testchar at end of teststr.""" count = 0 x = len(teststr) - 1 while x >= 0 and teststr[x] == testchar: count += 1 x -= 1 return count
java
@SubscribeEvent public void onDataSave(ChunkDataEvent.Save event) { Set<BlockPos> coords = chunks(event.getChunk()).get(event.getChunk()); if (!coords.isEmpty()) writeLongArray(event.getData(), coords); }
python
def dict_head(d, N=5): """Return the head of a dictionary. It will be random! Default is to return the first 5 key/value pairs in a dictionary. Args: d: Dictionary to get head. N: Number of elements to display. Returns: dict: the first N items of the dictionary. """ r...
java
public void setValue(byte[] newValue) throws Exception { Preconditions.checkState(state.get() == State.STARTED, "not started"); Stat result = client.setData().forPath(path, newValue); updateValue(result.getVersion(), Arrays.copyOf(newValue, newValue.length)); }
python
def release(cls, entity, unit_of_work): """ Releases the given entity from management under the given Unit Of Work. :raises ValueError: If `entity` is not managed at all or is not managed by the given Unit Of Work. """ if not hasattr(entity, '__everest__'): ...
java
public void setExpanded(SpatialEntry entry1, SpatialEntry entry2) { IntSet exp1 = expanded.get(getPageID(entry1)); if(exp1 == null) { exp1 = new IntOpenHashSet(); expanded.put(getPageID(entry1), exp1); } exp1.add(getPageID(entry2)); }
java
public static BigFloat asinh(BigFloat x) { return x.context.valueOf(BigDecimalMath.asinh(x.value, x.context.mathContext)); }
python
def extract(cls, keystr): """ for #{key} returns key """ regex = r'#{\s*(%s)\s*}' % cls.ALLOWED_KEY return re.match(regex, keystr).group(1)
python
def get_work_result(self, function_arn, invocation_id): """ Retrieve the result of the work processed by :code:`function_arn` with specified :code:`invocation_id`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: st...
java
public Object enterContextScope(HttpRequest request, HttpResponse response) { // Make sure servlet wrappers exist for request/response objects ServletHttpRequest srequest = (ServletHttpRequest) request.getWrapper(); ServletHttpResponse sresponse = (ServletHttpResponse) response.getWrapper();...
java
protected void verifySadRequest(SignatureActivationDataContext sadRequest, ProfileRequestContext<?, ?> context) throws ExternalAutenticationErrorCodeException { final AuthnRequest authnRequest = this.getAuthnRequest(context); if (authnRequest == null) { log.error("No AuthnRequest available [{}]", t...
python
def get_exec_create_kwargs(self, action, container_name, exec_cmd, exec_user, kwargs=None): """ Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name:...
python
def bandstructure_flow(workdir, scf_input, nscf_input, dos_inputs=None, manager=None, flow_class=Flow, allocate=True): """ Build a :class:`Flow` for band structure calculations. Args: workdir: Working directory. scf_input: Input for the GS SCF run. nscf_input: Input for the NSCF run...
java
public static double cdf(double x, double location, double shape) { return FastMath.atan2(x - location, shape) / Math.PI + .5; }
java
public void bootstrap() throws Exception { final HostRunningModeControl runningModeControl = environment.getRunningModeControl(); final ControlledProcessState processState = new ControlledProcessState(true); shutdownHook.setControlledProcessState(processState); ServiceTarget target = ser...
python
def datetime_value_renderer(value, **options): """Render datetime value with django formats, default is SHORT_DATETIME_FORMAT""" datetime_format = options.get('datetime_format', 'SHORT_DATETIME_FORMAT') return formats.date_format(timezone.localtime(value), datetime_format)
java
public void create(final Node node) { Assert.assertNotNull(node); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { NodeDO nodeDo = modelToDo(node); ...
java
public void addSource(String source) { if(this.sources == null) this.sources = new ArrayList<String>(); this.sources.add(source); }
python
def value_name(cls, value): """ Returns the label from a value if label exists otherwise returns the value since method does a reverse look up it is slow """ for k, v in list(cls.__dict__.items()): if v == value: return k return value
java
protected synchronized void writePages(OggPage[] pages) throws IOException { for(OggPage page : pages) { page.writeHeader( out ); out.write( page.getData() ); } out.flush(); }
python
def master_address(self, name): """Returns a (host, port) pair for the given ``name``.""" fut = self.execute(b'get-master-addr-by-name', name, encoding='utf-8') return wait_convert(fut, parse_address)
python
def stop(self): """Stop listening and close stream""" if self.thread: self.running = False if isinstance(self.stream, ReadWriteStream): self.stream.write(b'\0' * self.chunk_size) self.thread.join() self.thread = None self.engine.st...
java
public WexOrderInfoResult getBTCEOrderInfo(Long orderId) throws IOException { WexOrderInfoReturn btceOrderInfo = btce.OrderInfo(apiKey, signatureCreator, exchange.getNonceFactory(), orderId); checkResult(btceOrderInfo); return btceOrderInfo.getReturnValue().values().iterator().next(); }
java
public void clear() { valueBoxBase.setText(""); clearStatusText(); if (getPlaceholder() == null || getPlaceholder().isEmpty()) { label.removeStyleName(CssName.ACTIVE); } }
python
def get_group_metadata(self): """Gets the metadata for a group. return: (osid.Metadata) - metadata for the group *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metada...
java
public static String formatDate(String dateValue, FastDateFormat sdf) { try { return FDF_OUT_DAY.format(sdf.parse(dateValue)); } catch (ParseException ex) { LOG.debug(String.format("Fehler beim Parsen des Datums %s: %s", dateValue, ex.getMessage())); } re...
java
private static Node replaceReturnWithBreak(Node current, Node parent, String resultName, String labelName) { if (current.isFunction() || current.isExprResult()) { // Don't recurse into functions definitions, and expressions can't // contain RETURN nodes. return current; } i...
python
def _compute_magnitude_distance_term(self, C, rjb, mag): """ Returns the magntude dependent distance term """ rval = np.sqrt(rjb ** 2. + C["h"] ** 2.) return (C["b4"] + C["b5"] * (mag - 4.5)) * np.log(rval)
python
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." User = orm[user_orm_label] try: user = User.objects.all()[0] for article in orm.Article.objects.all(): ...
java
public Epic createEpic(String name, Map<String, Object> attributes) { return getInstance().create().epic(name, this, attributes); }
python
def objective_to_model(self, x_objective): ''' This function serves as interface between objective input vectors and model input vectors''' x_model = [] for k in range(self.objective_dimensionality): variable = self.space_expanded[k] new_entry = variable.objecti...
java
public Observable<DatabaseAccountInner> getByResourceGroupAsync(String resourceGroupName, String accountName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<DatabaseAccountInner>, DatabaseAccountInner>() { @Override publi...
java
private void modifyButtonsBasedOnScrollableContent(boolean scrollable) { if (getView() == null) { return; } View vButtonDivider = getView().findViewById(R.id.sdl_button_divider); View vButtonsBottomSpace = getView().findViewById(R.id.sdl_buttons_bottom_space); View vD...
python
def fetch(self, url, open_graph=None, twitter_card=None, touch_icon=None, favicon=None, all_images=None, parser=None, handle_file_content=None, canonical=None): """Retrieves content from the specified url, parses it, and returns a beautifully crafted dictionary of important i...
java
public DescribeVpnConnectionsResult withVpnConnections(VpnConnection... vpnConnections) { if (this.vpnConnections == null) { setVpnConnections(new com.amazonaws.internal.SdkInternalList<VpnConnection>(vpnConnections.length)); } for (VpnConnection ele : vpnConnections) { t...
java
protected List<String> getAllColumns(String tableName) { List<String> columns = new ArrayList<String>(); try { // Lower-case table names are required for PostgreSQL; we might need to // alter this if we use another comparison database (besides HSQL) someday ResultSet ...
java
private boolean appendTaskToBomFile(File buildGradleTmp) { FileReader fileReader; BufferedReader bufferedReader = null; InputStream inputStream = null; boolean hasDependencies = false; try { // appending the task only if the build.gradle file has 'dependencies {' node...
python
def _is_variable_extends(extend_node): """ Check whether an ``{% extends variable %}`` is used in the template. :type extend_node: ExtendsNode """ if django.VERSION < (1, 4): return extend_node.parent_name_expr # Django 1.3 else: # The FilterExpression.var can be either a strin...
java
public void propertyUnique(P key, String value) { GraphTraversal<Vertex, Vertex> traversal = tx().getTinkerTraversal().V().has(key.name(), value); if (traversal.hasNext()) { Vertex vertex = traversal.next(); if (!vertex.equals(element()) || traversal.hasNext()) { ...
java
public boolean remove(String classname) { String pkgname; HashSet<String> names; classname = ClassPathTraversal.cleanUp(classname); pkgname = ClassPathTraversal.extractPackage(classname); names = m_NameCache.get(pkgname); if (names != null) return names.remove(classname); else ...
java
private static List<HtmlColumn> buildCache(UIComponent table) { if (table instanceof UIData) { final int childCount = table.getChildCount(); if (childCount > 0) { final List<HtmlColumn> results = new ArrayList<>(childCount); for (UIComponent kid : table.ge...
java
public void update(Data... records) throws IOException { // ############ reorder data IntObjectOpenHashMap<ArrayList<Data>> bucketDataMapping = new IntObjectOpenHashMap<ArrayList<Data>>(); int bucketId; for (Data d : records) { bucketId = hashFunction.getBucketId(d.getKe...
java
private static RLPList decodeRLPList(ByteBuffer bb) { byte firstByte = bb.get(); int firstByteUnsigned = firstByte & 0xFF; long payloadSize=-1; if ((firstByteUnsigned>=0xc0) && (firstByteUnsigned<=0xf7)) { // length of the list in bytes int offsetSmallList = 0xc0 & 0xff; payloadSize=(long)(firstByteUnsigned)...
python
def _set_rmon(self, v, load=False): """ Setter method for rmon, mapped from YANG variable /interface/hundredgigabitethernet/rmon (container) If this variable is read-only (config: false) in the source YANG file, then _set_rmon is considered as a private method. Backends looking to populate this vari...
java
public List<GroovyRowResult> executeInsert(String sql, String[] keyColumnNames) throws SQLException { Connection connection = createConnection(); Statement statement = null; try { statement = getStatement(connection, sql); this.updateCount = statement.executeUpdate(sql, k...
python
def _get_minimal_core_reservations(core_resource, cores, chip=None): """Yield a minimal set of :py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint` objects which reserve the specified set of cores. Parameters ---------- core_resource : resource type The type of resourc...
python
def replace_placeholders(self, value): """Replaces placeholders that can be used e.g. in filepaths. Supported placeholders: * {project_runtime_dir} * {project_name} * {runtime_dir} :param str|unicode|list[str|unicode]|None value: :rtype: None|str|uni...
python
def debug_setup(logger=None, level=None, log2file=None, log_file=None, log_format=None, log_dir=None, log2stdout=None, truncate=False): ''' Local object instance logger setup. Verbosity levels are determined as such:: if level in [-1, False]: logger.setL...
java
@Override protected void registered(RequestServer.API_VERSION ver) { super.registered(ver); for (Argument arg : _arguments) { if ( arg._name.equals("activation") || arg._name.equals("initial_weight_distribution") || arg._name.equals("expert_mode") || arg._name.equals("adaptive_rate") ...
java
Name fieldName(Symbol sym) { if (scramble && (sym.flags() & PRIVATE) != 0 || scrambleAll && (sym.flags() & (PROTECTED | PUBLIC)) == 0) return names.fromString("_$" + sym.name.getIndex()); else return sym.name; }
java
private void parseExternalsConfig(final Node node, final ConfigSettings config) { String name, value; Node nnode; NodeList list = node.getChildNodes(); int length = list.getLength(); for (int i = 0; i < length; i++) { nnode = list.item(i); name = nnode.getNodeName().toUpperCase(); if (name.equ...
java
protected void checkFormPropertyUsingReservedWord(ActionRuntime runtime, VirtualForm virtualForm, final String propertyName) { if (isSuppressFormPropertyUsingReservedWordCheck()) { return; } if (reservedWordSet.contains(propertyName)) { throwThymeleafFormPropertyUsingRese...
python
def verify(self, assoc_handle, message): """Verify that the signature for some data is valid. @param assoc_handle: The handle of the association used to sign the data. @type assoc_handle: str @param message: The signed message to verify @type message: openid.message...
java
@Nullable public List<ExprRootNode> getAndRemoveGenderExprs() { List<ExprRootNode> genderExprs = this.genderExprs; this.genderExprs = null; return genderExprs; }
python
def interface_direct_class(data_class): """help to direct to the correct interface interacting with DB by class name only""" if data_class in ASSET: interface = AssetsInterface() elif data_class in PARTY: interface = PartiesInterface() elif data_class in BOOK: interface = BooksIn...
java
public void mergeDuplicate() { for(int i = 0; i < labels.size(); i++) for(int j = i + 1; j < labels.size(); j++){ T tagi = labels.get(i); T tagj = labels.get(j); if(tagi.equals(tagj)){ scores.set(i, scores.get(i) + scores.get(j)); labels.remove(j); scores.remove(j); j--; ...
java
public PutField putFields() throws IOException { if (currentObject == null) { throw new NotActiveException(); } if (currentPutField == null) { computePutField(); } return currentPutField; }
python
def send_comment_posted(comment, request): """ Send the email to staff that an comment was posted. While the django_comments module has email support, it doesn't pass the 'request' to the context. This also changes the subject to show the page title. """ recipient_list = [manager_tuple[1] f...
java
@SuppressWarnings("unchecked") public HashMap<String, HashMap<String, String>> getMetaData() { HashMap<String, HashMap<String, String>> result = new HashMap<String, HashMap<String, String>>(); for (MetaRecord mr : meta) { result.put((String) mr.get(FieldName.META_FILENAME), ...
java
public static int cusolverDnSsytrf_bufferSize( cusolverDnHandle handle, int n, Pointer A, int lda, int[] lwork) { return checkResult(cusolverDnSsytrf_bufferSizeNative(handle, n, A, lda, lwork)); }
java
public <R> AnimaQuery<T> like(TypeFunction<T, R> function, Object value) { String columnName = AnimaUtils.getLambdaColumnName(function); return this.like(columnName, value); }
java
public void marshall(LogPublishingOption logPublishingOption, ProtocolMarshaller protocolMarshaller) { if (logPublishingOption == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(logPublishingOption.ge...
java
@Override public boolean moveToNext() { clearCombinedRowsInfo(); if (nextRowPointer == null) { currentTimeAndDimsPointer = null; return false; } // This line implicitly uses the property of RowIterator.getPointer() (see [*] below), that it's still valid after // RowPointer.moveToNext...
python
def eval(self, packet): """Returns the result of evaluating this PacketExpression in the context of the given Packet. """ try: context = createPacketContext(packet) result = eval(self._code, packet._defn.globals, context) except ZeroDivisionError: ...