language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public ServiceFuture<ProjectInner> createOrUpdateAsync(String groupName, String serviceName, String projectName, ProjectInner parameters, final ServiceCallback<ProjectInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(groupName, serviceName, projectName, parameters), serviceCallback); }
python
def inFootprint(footprint,ra,dec): """ Check if set of ra,dec combinations are in footprint. Careful, input files must be in celestial coordinates. filename : Either healpix map or mangle polygon file ra,dec : Celestial coordinates Returns: inside : boolean array of coordinates in footprint """ if footprint is None: return np.ones(len(ra),dtype=bool) try: if isinstance(footprint,str) and os.path.exists(footprint): filename = footprint #footprint = hp.read_map(filename,verbose=False) #footprint = fitsio.read(filename)['I'].ravel() footprint = read_map(filename) nside = hp.npix2nside(len(footprint)) pix = ang2pix(nside,ra,dec) inside = (footprint[pix] > 0) except IOError: logger.warning("Failed to load healpix footprint; trying to use mangle...") inside = inMangle(filename,ra,dec) return inside
java
public static int toIntegerWithDefault(Object value, int defaultValue) { Integer result = toNullableInteger(value); return result != null ? (int) result : defaultValue; }
python
def solve_and_plot_series(self, x0, params, varied_data, varied_idx, solver=None, plot_kwargs=None, plot_residuals_kwargs=None, **kwargs): """ Solve and plot for a series of a varied parameter. Convenience method, see :meth:`solve_series`, :meth:`plot_series` & :meth:`plot_series_residuals_internal` for more information. """ sol, nfo = self.solve_series( x0, params, varied_data, varied_idx, solver=solver, **kwargs) ax_sol = self.plot_series(sol, varied_data, varied_idx, info=nfo, **(plot_kwargs or {})) extra = dict(ax_sol=ax_sol, info=nfo) if plot_residuals_kwargs: extra['ax_resid'] = self.plot_series_residuals_internal( varied_data, varied_idx, info=nfo, **(plot_residuals_kwargs or {}) ) return sol, extra
java
private void addFileStreamEntries(String kind) { Obligation obligation = database.getFactory().addObligation("java.io." + kind); database.addEntry(new MatchMethodEntry(new SubtypeTypeMatcher(BCELUtil.getObjectTypeInstance(Values.DOTTED_JAVA_IO_FILE + kind)), new ExactStringMatcher("<init>"), new RegexStringMatcher(".*"), false, ObligationPolicyDatabaseActionType.ADD, ObligationPolicyDatabaseEntryType.STRONG, obligation)); database.addEntry(new MatchMethodEntry(new SubtypeTypeMatcher(BCELUtil.getObjectTypeInstance("java.io." + kind)), new ExactStringMatcher("close"), new ExactStringMatcher("()V"), false, ObligationPolicyDatabaseActionType.DEL, ObligationPolicyDatabaseEntryType.STRONG, obligation)); }
python
def overwrite(self, text, size=None): """ Overwrites the current line. It will not add a new line so use line('') if necessary. """ self._io.overwrite(text, size=size)
python
def add_dimension(self, name, data=None): """Add a named dimension to this entity.""" self.dimensions.add(name) if data is None: valobj = self.__dimtype__() else: valobj = make_object(self.__dimtype__, data) self._data[name] = valobj setattr(self, name, valobj) return valobj
java
public static String asUTF8String(InputStream in) { // Precondition check Validate.notNull(in, "Stream must be specified"); StringBuilder buffer = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(in, CHARSET_UTF8)); while ((line = reader.readLine()) != null) { buffer.append(line).append(Character.LINE_SEPARATOR); } } catch (IOException ioe) { throw new RuntimeException("Error in obtaining string from " + in, ioe); } finally { try { in.close(); } catch (IOException ignore) { if (log.isLoggable(Level.FINER)) { log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring"); } } } return buffer.toString(); }
java
public static String[] getMonths(Locale locale) { if (locale == null) { locale = Locale.US; } DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale); return dfs.getMonths(); }
python
def play(self): """ Play Conway's Game of Life. """ # Write the initial configuration to file. self.t = 1 # Current time level while self.t <= self.T: # Evolve! # print( "At time level %d" % t) # Loop over each cell of the grid and apply Conway's rules. for i in range(self.N): for j in range(self.N): live = self.live_neighbours(i, j) if (self.old_grid[i][j] == 1 and live < 2): self.new_grid[i][j] = 0 # Dead from starvation. elif (self.old_grid[i][j] == 1 and (live == 2 or live == 3)): self.new_grid[i][j] = 1 # Continue living. elif (self.old_grid[i][j] == 1 and live > 3): self.new_grid[i][j] = 0 # Dead from overcrowding. elif (self.old_grid[i][j] == 0 and live == 3): self.new_grid[i][j] = 1 # Alive from reproduction. # Output the new configuration. # The new configuration becomes the old configuration for the next generation. self.old_grid = self.new_grid.copy() self.draw_board() # Move on to the next time level self.t += 1
java
public DestinationHandler getDestination(SIBUuid12 destinationUuid, boolean includeInvisible) throws SITemporaryDestinationNotFoundException, SINotPossibleInCurrentConfigurationException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getDestination", destinationUuid); // Get the destination, include invisible dests DestinationHandler destinationHandler = getDestinationInternal(destinationUuid, includeInvisible); checkDestinationHandlerExists( destinationHandler != null, destinationUuid.toString(), messageProcessor.getMessagingEngineName()); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getDestination", destinationHandler); return destinationHandler; }
java
public void deselectButton() { if (m_selectedButton != null) { if (m_selectedButton.isChecked()) { m_selectedButton.setChecked(false); } m_selectedButton = null; ValueChangeEvent.fire(this, null); } }
python
def ConsoleLogHandler(loggerRef='', handler=None, level=logging.DEBUG, color=None): """Add a handler to stderr with our custom formatter to a logger.""" if isinstance(loggerRef, logging.Logger): pass elif isinstance(loggerRef, str): # check for root if not loggerRef: loggerRef = _log # check for a valid logger name elif loggerRef not in logging.Logger.manager.loggerDict: raise RuntimeError("not a valid logger name: %r" % (loggerRef,)) # get the logger loggerRef = logging.getLogger(loggerRef) else: raise RuntimeError("not a valid logger reference: %r" % (loggerRef,)) # see if this (or its parent) is a module level logger if hasattr(loggerRef, 'globs'): loggerRef.globs['_debug'] += 1 elif hasattr(loggerRef.parent, 'globs'): loggerRef.parent.globs['_debug'] += 1 # make a handler if one wasn't provided if not handler: handler = logging.StreamHandler() handler.setLevel(level) # use our formatter handler.setFormatter(LoggingFormatter(color)) # add it to the logger loggerRef.addHandler(handler) # make sure the logger has at least this level loggerRef.setLevel(level)
python
def redirect_n_times(n): """302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. """ assert n > 0 absolute = request.args.get("absolute", "false").lower() == "true" if n == 1: return redirect(url_for("view_get", _external=absolute)) if absolute: return _redirect("absolute", n, True) else: return _redirect("relative", n, False)
java
private String getSubstringByte(final Object obj, final int capacity) throws CharacterCodingException, UnsupportedEncodingException { String str = obj == null ? "null" : obj.toString(); if (capacity < 1) { return str; } CharsetEncoder ce = Charset.forName(ENCODING_SHIFT_JIS).newEncoder() .onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).reset(); if (capacity >= ce.maxBytesPerChar() * str.length()) { return str; } CharBuffer cb = CharBuffer.wrap(new char[Math.min(str.length(), capacity)]); str.getChars(0, Math.min(str.length(), cb.length()), cb.array(), 0); if (capacity >= ce.maxBytesPerChar() * cb.limit()) { return cb.toString(); } ByteBuffer out = ByteBuffer.allocate(capacity); ce.reset(); CoderResult cr = null; if (cb.hasRemaining()) { cr = ce.encode(cb, out, true); } else { cr = CoderResult.UNDERFLOW; } if (cr.isUnderflow()) { cr = ce.flush(out); } return cb.flip().toString(); }
python
def get_selected_buffer(self): """returns currently selected :class:`Buffer` element from list""" linewidget, _ = self.bufferlist.get_focus() bufferlinewidget = linewidget.get_focus().original_widget return bufferlinewidget.get_buffer()
java
public static Type extractTypeArgument(Type t, int index) throws InvalidTypesException { if (t instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) t).getActualTypeArguments(); if (index < 0 || index >= actualTypeArguments.length) { throw new InvalidTypesException("Cannot extract the type argument with index " + index + " because the type has only " + actualTypeArguments.length + " type arguments."); } else { return actualTypeArguments[index]; } } else { throw new InvalidTypesException("The given type " + t + " is not a parameterized type."); } }
java
public static String urlEncode(String s) { try { return URLEncoder.encode(s, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("get a jdk that actually supports utf-8", e); } }
python
def metrics(self, opttype, strike, expiry): """ Basic metrics for a specific option. Parameters ---------- opttype : str ('call' or 'put') strike : numeric Strike price. expiry : date-like Expiration date. Can be a :class:`datetime.datetime` or a string that :mod:`pandas` can interpret as such, e.g. '2015-01-01'. Returns ------- out : :class:`pandas.DataFrame` """ _optrow = _relevant_rows(self.data, (strike, expiry, opttype,), "No key for {} strike {} {}".format(expiry, strike, opttype)) _index = ['Opt_Price', 'Time_Val', 'Last', 'Bid', 'Ask', 'Vol', 'Open_Int', 'Underlying_Price', 'Quote_Time'] _out = pd.DataFrame(index=_index, columns=['Value']) _out.loc['Opt_Price', 'Value'] = _opt_price = _getprice(_optrow) for _name in _index[2:]: _out.loc[_name, 'Value'] = _optrow.loc[:, _name].values[0] _eq_price = _out.loc['Underlying_Price', 'Value'] if opttype == 'put': _out.loc['Time_Val'] = _get_put_time_val(_opt_price, strike, _eq_price) else: _out.loc['Time_Val'] = _get_call_time_val(_opt_price, strike, _eq_price) return _out
python
def get_min_isr(zk, topic): """Return the min-isr for topic, or None if not specified""" ISR_CONF_NAME = 'min.insync.replicas' try: config = zk.get_topic_config(topic) except NoNodeError: return None if ISR_CONF_NAME in config['config']: return int(config['config'][ISR_CONF_NAME]) else: return None
java
Table ENABLED_ROLES() { Table t = sysTables[ENABLED_ROLES]; if (t == null) { t = createBlankTable(sysTableHsqlNames[ENABLED_ROLES]); addColumn(t, "ROLE_NAME", SQL_IDENTIFIER); // true PK HsqlName name = HsqlNameManager.newInfoSchemaObjectName( sysTableHsqlNames[ENABLED_ROLES].name, false, SchemaObject.INDEX); t.createPrimaryKey(name, new int[]{ 0 }, true); return t; } PersistentStore store = database.persistentStoreCollection.getStore(t); // Intermediate holders Iterator grantees; Grantee grantee; Object[] row; // initialization grantees = session.getGrantee().getAllRoles().iterator(); while (grantees.hasNext()) { grantee = (Grantee) grantees.next(); row = t.getEmptyRowData(); row[0] = grantee.getNameString(); t.insertSys(store, row); } return t; }
python
def print_statement_coverage(self): """Display how many of the direct statements have been converted. Also prints how many are considered 'degenerate' and not converted.""" if not self.all_direct_stmts: self.get_all_direct_statements() if not self.degenerate_stmts: self.get_degenerate_statements() if not self.all_indirect_stmts: self.get_all_indirect_statements() logger.info('') logger.info("Total indirect statements: %d" % len(self.all_indirect_stmts)) logger.info("Converted indirect statements: %d" % len(self.converted_indirect_stmts)) logger.info(">> Unhandled indirect statements: %d" % (len(self.all_indirect_stmts) - len(self.converted_indirect_stmts))) logger.info('') logger.info("Total direct statements: %d" % len(self.all_direct_stmts)) logger.info("Converted direct statements: %d" % len(self.converted_direct_stmts)) logger.info("Degenerate direct statements: %d" % len(self.degenerate_stmts)) logger.info(">> Unhandled direct statements: %d" % (len(self.all_direct_stmts) - len(self.converted_direct_stmts) - len(self.degenerate_stmts))) logger.info('') logger.info("--- Unhandled direct statements ---------") for stmt in self.all_direct_stmts: if not (stmt in self.converted_direct_stmts or stmt in self.degenerate_stmts): logger.info(stmt) logger.info('') logger.info("--- Unhandled indirect statements ---------") for stmt in self.all_indirect_stmts: if not (stmt in self.converted_indirect_stmts or stmt in self.degenerate_stmts): logger.info(stmt)
python
def is_backup_class(cls): """Return true if given class supports back up. Currently this means a gludb.data.Storable-derived class that has a mapping as defined in gludb.config""" return True if ( isclass(cls) and issubclass(cls, Storable) and get_mapping(cls, no_mapping_ok=True) ) else False
java
public static Method getAccessibleMethod(Class<?> clazz, Method method) { // Make sure we have a method to check if (method == null) { return null; } // If the requested method is not public we cannot call it if (!Modifier.isPublic(method.getModifiers())) { return null; } if (clazz == null) { clazz = method.getDeclaringClass(); } else if (!method.getDeclaringClass().isAssignableFrom(clazz)) { throw new IllegalArgumentException(clazz.getName() + " is not assignable from " + method.getDeclaringClass().getName()); } // If the class is public, we are done if (Modifier.isPublic(clazz.getModifiers())) { return method; } String methodName = method.getName(); Class<?>[] paramTypes = method.getParameterTypes(); // Check the implemented interfaces and sub interfaces method = getAccessibleMethodFromInterfaceNest(clazz, methodName, paramTypes); // Check the superclass chain if (method == null) { method = getAccessibleMethodFromSuperclass(clazz, methodName, paramTypes); } return method; }
python
def merged_cell_ranges(self): """Generates the sequence of merged cell ranges in the format: ((col_low, row_low), (col_hi, row_hi)) """ for rlo, rhi, clo, chi in self.raw_sheet.merged_cells: yield ((clo, rlo), (chi, rhi))
python
def _delete_masked_points(*arrs): """Delete masked points from arrays. Takes arrays and removes masked points to help with calculations and plotting. Parameters ---------- arrs : one or more array-like source arrays Returns ------- arrs : one or more array-like arrays with masked elements removed """ if any(hasattr(a, 'mask') for a in arrs): keep = ~functools.reduce(np.logical_or, (np.ma.getmaskarray(a) for a in arrs)) return tuple(ma.asarray(a[keep]) for a in arrs) else: return arrs
python
def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret
python
def Request(self): """Create the Approval object and notify the Approval Granter.""" approval_id = "approval:%X" % random.UInt32() approval_urn = self.BuildApprovalUrn(approval_id) email_msg_id = email.utils.make_msgid() with aff4.FACTORY.Create( approval_urn, self.approval_type, mode="w", token=self.token) as approval_request: approval_request.Set(approval_request.Schema.SUBJECT(self.subject_urn)) approval_request.Set( approval_request.Schema.REQUESTOR(self.token.username)) approval_request.Set(approval_request.Schema.REASON(self.reason)) approval_request.Set(approval_request.Schema.EMAIL_MSG_ID(email_msg_id)) cc_addresses = (self.email_cc_address, config.CONFIG.Get("Email.approval_cc_address")) email_cc = ",".join(filter(None, cc_addresses)) # When we reply with the approval we want to cc all the people to whom the # original approval was sent, to avoid people approving stuff that was # already approved. if email_cc: reply_cc = ",".join((self.approver, email_cc)) else: reply_cc = self.approver approval_request.Set(approval_request.Schema.EMAIL_CC(reply_cc)) approval_request.Set( approval_request.Schema.NOTIFIED_USERS(self.approver)) # We add ourselves as an approver as well (The requirement is that we have # 2 approvers, so the requester is automatically an approver). approval_request.AddAttribute( approval_request.Schema.APPROVER(self.token.username)) approval_link_urns = self.BuildApprovalSymlinksUrns(approval_id) for link_urn in approval_link_urns: with aff4.FACTORY.Create( link_urn, aff4.AFF4Symlink, mode="w", token=self.token) as link: link.Set(link.Schema.SYMLINK_TARGET(approval_urn)) return approval_urn
python
def _set_key(self): ''' sets the final key to be used currently ''' if self.roll: self.date = time.strftime(self.date_format, time.gmtime(self.start_time)) self.final_key = '{}:{}'.format(self.key, self.date) else: self.final_key = self.key
python
def depth(self, *args): """ Get/set the depth """ if len(args): self._depth = args[0] else: return self._depth
python
def commit(self): """ Delete the rest of the line. """ # Get the text cursor for the current document and unselect everything. tc = self.qteWidget.textCursor() tc.clearSelection() # If this is the first ever call to this undo/redo element then # backup the current cursor position and the selected text (may be # none). This information will be required for the redo operation # to position the cursor (and selected text) where it was at the # very first call. if self.cursorPos0 is None: self.cursorPos0 = tc.position() # Ensure nothing is selected. tc.setPosition(self.cursorPos0, QtGui.QTextCursor.MoveAnchor) # Mark the rest of the line, store its content in this very object # and the global kill-list, and remove it. tc.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) self.cursorPos1 = tc.selectionEnd() self.killedText = tc.selection().toHtml() data = qtmacs.kill_list.KillListElement( tc.selection().toPlainText(), tc.selection().toHtml(), 'QtmacsTextEdit-Html') qte_global.kill_list.append(data) tc.removeSelectedText() # Apply the changes. self.qteWidget.setTextCursor(tc)
java
private void initializePreferenceScreenElevation(final SharedPreferences sharedPreferences) { String key = getString(R.string.preference_screen_elevation_preference_key); String defaultValue = getString(R.string.preference_screen_elevation_preference_default_value); int elevation = Integer.valueOf(sharedPreferences.getString(key, defaultValue)); setCardViewElevation(elevation); }
python
def get_version(self, paths=None, default="unknown"): """Get version number of installed module, 'None', or 'default' Search 'paths' for module. If not found, return 'None'. If found, return the extracted version attribute, or 'default' if no version attribute was specified, or the value cannot be determined without importing the module. The version is formatted according to the requirement's version format (if any), unless it is 'None' or the supplied 'default'. """ if self.attribute is None: try: f, p, i = find_module(self.module, paths) if f: f.close() return default except ImportError: return None v = get_module_constant(self.module, self.attribute, default, paths) if v is not None and v is not default and self.format is not None: return self.format(v) return v
java
public static ExecutorService newSingleThreadDaemonExecutor() { return Executors.newSingleThreadExecutor(r -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; }); }
java
public static Range sum(Range range1, Range range2) { if (range1.getMinimum().doubleValue() <= range2.getMinimum().doubleValue()) { if (range1.getMaximum().doubleValue() >= range2.getMaximum().doubleValue()) { return range1; } else { return range(range1.getMinimum().doubleValue(), range2.getMaximum().doubleValue()); } } else { if (range1.getMaximum().doubleValue() >= range2.getMaximum().doubleValue()) { return range(range2.getMinimum().doubleValue(), range1.getMaximum().doubleValue()); } else { return range2; } } }
python
def _add_session(self, session, start_info, groups_by_name): """Adds a new Session protobuffer to the 'groups_by_name' dictionary. Called by _build_session_groups when we encounter a new session. Creates the Session protobuffer and adds it to the relevant group in the 'groups_by_name' dict. Creates the session group if this is the first time we encounter it. Args: session: api_pb2.Session. The session to add. start_info: The SessionStartInfo protobuffer associated with the session. groups_by_name: A str to SessionGroup protobuffer dict. Representing the session groups and sessions found so far. """ # If the group_name is empty, this session's group contains only # this session. Use the session name for the group name since session # names are unique. group_name = start_info.group_name or session.name if group_name in groups_by_name: groups_by_name[group_name].sessions.extend([session]) else: # Create the group and add the session as the first one. group = api_pb2.SessionGroup( name=group_name, sessions=[session], monitor_url=start_info.monitor_url) # Copy hparams from the first session (all sessions should have the same # hyperparameter values) into result. # There doesn't seem to be a way to initialize a protobuffer map in the # constructor. for (key, value) in six.iteritems(start_info.hparams): group.hparams[key].CopyFrom(value) groups_by_name[group_name] = group
python
def run(name, params, delay): ''' Run the job <name> Jobs args and kwargs are given as parameters without dashes. Ex: udata job run my-job arg1 arg2 key1=value key2=value udata job run my-job -- arg1 arg2 key1=value key2=value ''' args = [p for p in params if '=' not in p] kwargs = dict(p.split('=') for p in params if '=' in p) if name not in celery.tasks: exit_with_error('Job %s not found', name) job = celery.tasks[name] label = job_label(name, args, kwargs) if delay: log.info('Sending job %s', label) job.delay(*args, **kwargs) log.info('Job sended to workers') else: log.info('Running job %s', label) job.run(*args, **kwargs) log.info('Job %s done', name)
java
public static CmsImportExportUserDialog getExportUserDialogForOU( String ou, Window window, boolean allowTechnicalFieldsExport) { CmsImportExportUserDialog res = new CmsImportExportUserDialog(ou, null, window, allowTechnicalFieldsExport); return res; }
java
public Matrix4x3f m02(float m02) { this.m02 = m02; properties &= ~PROPERTY_ORTHONORMAL; if (m02 != 0.0f) properties &= ~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION); return this; }
python
def build_fasttext_cc_embedding_obj(embedding_type): """FastText pre-trained word vectors for 157 languages, with 300 dimensions, trained on Common Crawl and Wikipedia. Released in 2018, it succeesed the 2017 FastText Wikipedia embeddings. It's recommended to use the same tokenizer for your data that was used to construct the embeddings. This information and more can be find on their Website: https://fasttext.cc/docs/en/crawl-vectors.html. Args: embedding_type: A string in the format `fastext.cc.$LANG_CODE`. e.g. `fasttext.cc.de` or `fasttext.cc.es` Returns: Object with the URL and filename used later on for downloading the file. """ lang = embedding_type.split('.')[2] return { 'file': 'cc.{}.300.vec.gz'.format(lang), 'url': 'https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.{}.300.vec.gz'.format(lang), 'extract': False }
java
public void beginScanForUpdates(String deviceName, String resourceGroupName) { beginScanForUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).toBlocking().single().body(); }
java
private static CmsRectangle transformRegionBack(I_CmsTransform transform, CmsRectangle region) { CmsPoint topLeft = region.getTopLeft(); CmsPoint bottomRight = region.getBottomRight(); return CmsRectangle.fromPoints(transform.transformBack(topLeft), transform.transformBack(bottomRight)); }
python
def native(self): """ The native Python datatype representation of this value :return: An integer or None """ if self.contents is None: return None if self._native is None: self._native = int_from_bytes(self._merge_chunks()) return self._native
python
def _draw_label(self, obj, count): """Helper method to draw on the current label. Not intended for external use. """ # Start a drawing for the whole label. label = Drawing(float(self._lw), float(self._lh)) label.add(self._clip_label) # And one for the available area (i.e., after padding). available = Drawing(float(self._dw), float(self._dh)) available.add(self._clip_drawing) # Call the drawing function. self.drawing_callable(available, float(self._dw), float(self._dh), obj) # Render the contents on the label. available.shift(float(self._lp), float(self._bp)) label.add(available) # Draw the border if requested. if self.border: label.add(self._border) # Add however many copies we need to. for i in range(count): # Find the next available label. self._next_unused_label() # Have we been told to skip this page? if self.pages_to_draw and self.page_count not in self.pages_to_draw: continue # Add the label to the page. ReportLab stores the added drawing by # reference so we have to copy it N times. thislabel = copy(label) thislabel.shift(*self._calculate_edges()) self._current_page.add(thislabel)
java
private static void printUsage(String cmd) { String prefix = "Usage: java " + FairSchedulerShell.class.getSimpleName(); if ("-getfsmaxslots".equalsIgnoreCase(cmd)) { System.err.println(prefix + " [-getfsmaxslots trackerName1, trackerName2 ... ]"); } else if ("-setfsmaxslots".equalsIgnoreCase(cmd)) { System.err.println(prefix + " [-setfsmaxslots trackerName #maps #reduces trackerName2 #maps #reduces ... ]"); } else { System.err.println(prefix); System.err.println(" [-setfsmaxslots trackerName #maps #reduces trackerName2 #maps #reduces ... ]"); System.err.println(" [-getfsmaxslots trackerName1, trackerName2 ... ]"); System.err.println(" [-resetfsmaxslots]"); System.err.println(" [-help [cmd]]"); System.err.println(); ToolRunner.printGenericCommandUsage(System.err); } }
python
def set_basefilemtime(self): """Set attributes mtimestamp and mtimefs. If the global list ORIGINEXTENSIONS include any items, try and look for files (in the directory where self.filename is sitting) with the same base name as the loaded file, but with an extension specified in ORIGINEXTENSIONS. mtimestamp is a timestamp and mtimefs is the file (name) with that timestamp. ORIGINEXTENSIONS is empty on delivery. Which means that the attributes discussed will be based on the file that was loaded, (unless ORIGINEXTENSIONS is populated before this call). This is supposed to be a convenience in cases the data file loaded is some sort of "exported" file format, and the original file creation time is of interest. .. note:: If the provided functions in this module is used to get a pack, this method does not have to be called. It is called by those functions. """ dirpath = os.path.split(self.filename)[0] name = os.path.basename(self.fs).split('.')[0] for ext in ORIGINEXTENSIONS: # This should be some user configuration. res = glob.glob(dirpath + '/' + name + '.' + ext) if res: # Assume first match is valid. # If some shell patterns will be used later self.mtimefs = os.path.normpath(res[0]) # Time stamp string: self.mtimestamp = time.ctime(os.path.getmtime(self.mtimefs)) break else: self.mtimefs = self.filename self.mtimestamp = time.ctime(os.path.getmtime(self.mtimefs))
java
protected void performActions(List<HttpMessage> httpMessages) { for (HttpMessage httpMessage : httpMessages) { if (httpMessage != null) { performAction(httpMessage); } } }
python
def get_conns(cred, providers): """Collect node data asynchronously using gevent lib.""" cld_svc_map = {"aws": conn_aws, "azure": conn_az, "gcp": conn_gcp, "alicloud": conn_ali} sys.stdout.write("\rEstablishing Connections: ") sys.stdout.flush() busy_obj = busy_disp_on() conn_fn = [[cld_svc_map[x.rstrip('1234567890')], cred[x], x] for x in providers] cgroup = Group() conn_res = [] conn_res = cgroup.map(get_conn, conn_fn) cgroup.join() conn_objs = {} for item in conn_res: conn_objs.update(item) busy_disp_off(dobj=busy_obj) sys.stdout.write("\r \r") sys.stdout.write("\033[?25h") # cursor back on sys.stdout.flush() return conn_objs
python
def _namedtuplify(mapping): """ Make the dictionary into a nested series of named tuples. This is what allows accessing by attribute: settings.numerics.jitter Thank you https://gist.github.com/hangtwenty/5960435 """ if isinstance(mapping, collections.Mapping): for key, value in list(mapping.items()): mapping[key] = _namedtuplify(value) try: mapping.pop('__name__') except KeyError: pass # return collections.namedtuple('settingsa', dict(**mapping))(**mapping) return _MutableNamedTuple(mapping) return _parse(mapping)
java
public void setPGrpName(String newPGrpName) { String oldPGrpName = pGrpName; pGrpName = newPGrpName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.ENG__PGRP_NAME, oldPGrpName, pGrpName)); }
python
def sweHousesLon(jd, lat, lon, hsys): """ Returns lists with house and angle longitudes. """ hsys = SWE_HOUSESYS[hsys] hlist, ascmc = swisseph.houses(jd, lat, lon, hsys) angles = [ ascmc[0], ascmc[1], angle.norm(ascmc[0] + 180), angle.norm(ascmc[1] + 180) ] return (hlist, angles)
python
def validator(flag_name, message='Flag validation failed', flag_values=_flagvalues.FLAGS): """A function decorator for defining a flag validator. Registers the decorated function as a validator for flag_name, e.g. @flags.validator('foo') def _CheckFoo(foo): ... See register_validator() for the specification of checker function. Args: flag_name: str, name of the flag to be checked. message: str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. flag_values: flags.FlagValues, optional FlagValues instance to validate against. Returns: A function decorator that registers its function argument as a validator. Raises: AttributeError: Raised when flag_name is not registered as a valid flag name. """ def decorate(function): register_validator(flag_name, function, message=message, flag_values=flag_values) return function return decorate
java
private void commit() { m_selectionDone = true; if (!m_filesToUpload.isEmpty()) { m_okButton.disable(Messages.get().key(Messages.GUI_UPLOAD_BUTTON_OK_DISABLE_UPLOADING_0)); if (m_uploadButton instanceof UIObject) { ((UIObject)m_uploadButton).getElement().getStyle().setDisplay(Display.NONE); } showProgress(); submit(); } }
python
def md_options_to_metadata(options): """Parse markdown options and return language and metadata""" metadata = parse_md_code_options(options) if metadata: language = metadata[0][0] for lang in _JUPYTER_LANGUAGES + ['julia', 'scheme', 'c++']: if language.lower() == lang.lower(): return lang, dict(metadata[1:]) return None, dict(metadata)
java
public static Filter createFilterFromFilterSpec(Request request, String filterSpec) throws FilterFactory.FilterNotCreatedException { Description topLevelDescription = request.getRunner().getDescription(); String[] tuple; if (filterSpec.contains("=")) { tuple = filterSpec.split("=", 2); } else { tuple = new String[]{ filterSpec, "" }; } return createFilter(tuple[0], new FilterFactoryParams(topLevelDescription, tuple[1])); }
python
def CreateKey(self, private_key=None): """ Create a KeyPair Args: private_key (iterable_of_ints): (optional) 32 byte private key Returns: KeyPair: a KeyPair instance """ if private_key is None: private_key = bytes(Random.get_random_bytes(32)) key = KeyPair(priv_key=private_key) self._keys[key.PublicKeyHash.ToBytes()] = key return key
python
def change_ssh_pwd(self, pwd=None, comment=None): """ Executes a change SSH password operation on the specified node :param str pwd: changed password value :param str comment: optional comment for audit log :raises NodeCommandFailed: cannot change ssh password :return: None """ self.make_request( NodeCommandFailed, method='update', resource='change_ssh_pwd', params={'comment': comment}, json={'value': pwd})
java
public static String sha384Hex(String data, Charset charset) throws NoSuchAlgorithmException { return sha384Hex(data.getBytes(charset)); }
python
def filter_network_type(query): """Filter unsupported segment types""" segment_model = segment_models.NetworkSegment query = (query .filter( segment_model.network_type.in_( utils.SUPPORTED_NETWORK_TYPES))) return query
python
def get_provider(self, provider_name='default'): """Fetch provider with the name specified in Configuration file""" try: if self._providers is None: self._providers = self._initialize_providers() return self._providers[provider_name] except KeyError: raise AssertionError(f'No Provider registered with name {provider_name}')
python
def redirect_url(self, redirect_url): """ Sets the redirect_url of this CreateCheckoutRequest. The URL to redirect to after checkout is completed with `checkoutId`, Square's `orderId`, `transactionId`, and `referenceId` appended as URL parameters. For example, if the provided redirect_url is `http://www.example.com/order-complete`, a successful transaction redirects the customer to: `http://www.example.com/order-complete?checkoutId=xxxxxx&orderId=xxxxxx&referenceId=xxxxxx&transactionId=xxxxxx` If you do not provide a redirect URL, Square Checkout will display an order confirmation page on your behalf; however Square strongly recommends that you provide a redirect URL so you can verify the transaction results and finalize the order through your existing/normal confirmation workflow. Default: none; only exists if explicitly set. :param redirect_url: The redirect_url of this CreateCheckoutRequest. :type: str """ if redirect_url is None: raise ValueError("Invalid value for `redirect_url`, must not be `None`") if len(redirect_url) > 800: raise ValueError("Invalid value for `redirect_url`, length must be less than `800`") self._redirect_url = redirect_url
python
def _fetch_page_async(self, page_size, **q_options): """Internal version of fetch_page_async().""" q_options.setdefault('batch_size', page_size) q_options.setdefault('produce_cursors', True) it = self.iter(limit=page_size + 1, **q_options) results = [] while (yield it.has_next_async()): results.append(it.next()) if len(results) >= page_size: break try: cursor = it.cursor_after() except datastore_errors.BadArgumentError: cursor = None raise tasklets.Return(results, cursor, it.probably_has_next())
python
def unmanaged_cpcs(self): """ :class:`~zhmcclient.UnmanagedCpcManager`: Access to the unmanaged :term:`CPCs <CPC>` in this Console. """ # We do here some lazy loading. if not self._unmanaged_cpcs: self._unmanaged_cpcs = UnmanagedCpcManager(self) return self._unmanaged_cpcs
java
public void addScreenControls(Container parent) { FieldList record = this.getFieldList(); FieldTable table = record.getTable(); try { int iRowCount = 0; int iColumnCount = 0; table.close(); while (table.hasNext()) { table.next(); GridBagConstraints gbConstraints = this.getGBConstraints(); gbConstraints.gridx = iRowCount; gbConstraints.gridy = iColumnCount; gbConstraints.anchor = GridBagConstraints.NORTHWEST; JComponent button = this.makeMenuButton(record); GridBagLayout gridbag = (GridBagLayout)this.getScreenLayout(); gridbag.setConstraints(button, gbConstraints); parent.add(button); iRowCount++; if (iRowCount == 3) { iRowCount = 0; iColumnCount++; } } } catch (Exception ex) { ex.printStackTrace(); } }
java
@Override public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { final FileInfo fi = job.getFileInfo(f -> f.isInput).iterator().next(); if (!ATTR_FORMAT_VALUE_DITAMAP.equals(fi.format)) { return null; } final File inputFile = new File(job.tempDirURI.resolve(fi.uri)); final File styleFile = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_STYLE)); Document doc; InputStream in = null; try { doc = XMLUtils.getDocumentBuilder().newDocument(); final TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setURIResolver(CatalogUtils.getCatalogResolver()); final Transformer transformer = withLogger(transformerFactory.newTransformer(new StreamSource(styleFile)), logger); transformer.setURIResolver(CatalogUtils.getCatalogResolver()); if (input.getAttribute("include.rellinks") != null) { transformer.setParameter("include.rellinks", input.getAttribute("include.rellinks")); } transformer.setParameter("INPUTMAP", job.getInputMap()); in = new BufferedInputStream(new FileInputStream(inputFile)); final Source source = new StreamSource(in); source.setSystemId(inputFile.toURI().toString()); final DOMResult result = new DOMResult(doc); transformer.transform(source, result); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { throw new DITAOTException("Failed to read links from " + inputFile + ": " + e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) { logger.error("Failed to close input stream: " + e.getMessage(), e); } } } final Map<File, Map<String, Element>> mapSet = getMapping(doc); if (!mapSet.isEmpty()) { final DitaLinksWriter linkInserter = new DitaLinksWriter(); linkInserter.setLogger(logger); linkInserter.setJob(job); for (final Map.Entry<File, Map<String, Element>> entry: mapSet.entrySet()) { final URI uri = inputFile.toURI().resolve(toURI(entry.getKey().getPath())); logger.info("Processing " + uri); linkInserter.setLinks(entry.getValue()); linkInserter.setCurrentFile(uri); try { linkInserter.write(new File(uri)); } catch (final DITAOTException e) { logger.error("Failed to insert links: " + e.getMessage(), e); } } } return null; }
python
def _set_domain_name(self, v, load=False): """ Setter method for domain_name, mapped from YANG variable /protocol/cfm/domain_name (list) If this variable is read-only (config: false) in the source YANG file, then _set_domain_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_domain_name() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("domain_name",domain_name.domain_name, yang_name="domain-name", rest_name="domain-name", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='domain-name', extensions={u'tailf-common': {u'info': u'Configure Maintanance Domain', u'cli-run-template-enter': u'$(.?:)', u'cli-full-no': None, u'cli-suppress-list-no': None, u'cli-sequence-commands': None, u'callpoint': u'setDot1agDomain', u'cli-mode-name': u'config-cfm-md-$(domain-name)'}}), is_container='list', yang_name="domain-name", rest_name="domain-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure Maintanance Domain', u'cli-run-template-enter': u'$(.?:)', u'cli-full-no': None, u'cli-suppress-list-no': None, u'cli-sequence-commands': None, u'callpoint': u'setDot1agDomain', u'cli-mode-name': u'config-cfm-md-$(domain-name)'}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """domain_name must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("domain_name",domain_name.domain_name, yang_name="domain-name", rest_name="domain-name", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='domain-name', extensions={u'tailf-common': {u'info': u'Configure Maintanance Domain', u'cli-run-template-enter': u'$(.?:)', u'cli-full-no': None, u'cli-suppress-list-no': None, u'cli-sequence-commands': None, u'callpoint': u'setDot1agDomain', u'cli-mode-name': u'config-cfm-md-$(domain-name)'}}), is_container='list', yang_name="domain-name", rest_name="domain-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure Maintanance Domain', u'cli-run-template-enter': u'$(.?:)', u'cli-full-no': None, u'cli-suppress-list-no': None, u'cli-sequence-commands': None, u'callpoint': u'setDot1agDomain', u'cli-mode-name': u'config-cfm-md-$(domain-name)'}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='list', is_config=True)""", }) self.__domain_name = t if hasattr(self, '_set'): self._set()
python
def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A DefaultValueParameter from the current state of widget :rtype: DefaultValueParameter """ # Set value for each key for key, value in list(self._parameter.options.items()): if value.get('type') == STATIC: continue elif value.get('type') == SINGLE_DYNAMIC: new_value = self.spin_boxes.get(key).value() self._parameter.set_value_for_key(key, new_value) elif value.get('type') == MULTIPLE_DYNAMIC: # Need to iterate through all items items = [] for index in range(self.list_widget.count()): items.append(self.list_widget.item(index)) new_value = [i.text() for i in items] self._parameter.set_value_for_key(key, new_value) # Get selected radio button radio_button_checked_id = self.input_button_group.checkedId() # No radio button checked, then default value = None if radio_button_checked_id == -1: self._parameter.selected = None else: self._parameter.selected = list(self._parameter.options.keys())[ radio_button_checked_id] return self._parameter
java
@Override public void toXML(final StringBuilder builder, final ConfigVerification errors) { boolean sevenzip = controller.is7ZipEnabled(); if (sevenzip) { String cmd; builder.append("\t<externals>\r\n"); if (sevenzip) { cmd = sevenZipPathField.getText(); if (cmd.length() == 0) { errors.add(new ConfigItem(ConfigItemTypes.ERROR, ConfigErrorKeys.PATH_NOT_SET, "The path to the 7Zip executable" + " is missing.")); } builder.append("\t\t<sevenzip>\"" + cmd + "\"</sevenzip>\r\n"); } builder.append("\t</externals>\r\n"); } }
java
public String getUrl(String domain, String region) { if (url != null) { return url; } return urlFromUri(domain, region, uri); }
python
def analyzed_projects(raw_df): """ Return all projects that was analyzed. """ df = raw_df[['PRONAC', 'proponenteCgcCpf']] analyzed_projects = df.groupby('proponenteCgcCpf')[ 'PRONAC' ].agg(['unique', 'nunique']) analyzed_projects.columns = ['pronac_list', 'num_pronacs'] return analyzed_projects
java
private void fillWestFlowPanel() { checkShowDrag.setValue(graphicsService.isShowOriginalObjectWhileDragging()); checkShowDrag.setValue(graphicsService.isShowOriginalObjectWhileDragging()); checkShowDrag.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { graphicsService.setShowOriginalObjectWhileDragging(checkShowDrag.getValue()); } }); captionPanelBaseCreateButtons.setContentWidget(createBaseButtonGroupWidget.asWidget()); createBaseButtonGroupWidget.asWidget().setStyleName("graphicsExample-leftPanel-createButtonsPanel"); captionPanelCombinedCreateButtons.setContentWidget(createUpdateableGroupButtonGroupWidget.asWidget()); createUpdateableGroupButtonGroupWidget.asWidget().setStyleName("graphicsExample-leftPanel-createButtonsPanel"); Window.addResizeHandler(new ResizeHandler() { @Override public void onResize(ResizeEvent resizeEvent) { updateWestSectionToWindowHeight(); } }); updateWestSectionToWindowHeight(); }
python
def __bounce(self, **kwargs): """ Bounce off of the shoreline. NOTE: This does not work, but left here for future implementation feature = Linestring of two points, being the line segment the particle hit. angle = decimal degrees from 0 (x-axis), couter-clockwise (math style) """ start_point = kwargs.pop('start_point') hit_point = kwargs.pop('hit_point') end_point = kwargs.pop('end_point') feature = kwargs.pop('feature') distance = kwargs.pop('distance') angle = kwargs.pop('angle') # Figure out the angle of the shoreline here (beta) points_in_shore = map(lambda x: Point(x), list(feature.coords)) points_in_shore = sorted(points_in_shore, key=lambda x: x.x) # The point on the left (least longitude is always the first Point) first_shore = points_in_shore[0] last_shore = points_in_shore[-1] shoreline_x = abs(abs(first_shore.x) - abs(last_shore.x)) shoreline_y = abs(abs(first_shore.y) - abs(last_shore.y)) beta = math.degrees(math.atan(shoreline_x / shoreline_y)) theta = 90 - angle - beta bounce_azimuth = AsaMath.math_angle_to_azimuth(angle=2 * theta + angle) print "Beta: " + str(beta) print "Incoming Angle: " + str(angle) print "ShorelineAngle: " + str(theta + angle) print "Bounce Azimuth: " + str(bounce_azimuth) print "Bounce Angle: " + str(AsaMath.azimuth_to_math_angle(azimuth=bounce_azimuth)) after_distance = distance - AsaGreatCircle.great_distance(start_point=start_point, end_point=hit_point)['distance'] new_point = AsaGreatCircle.great_circle(distance=after_distance, azimuth=bounce_azimuth, start_point=hit_point) return Location4D(latitude=new_point['latitude'], longitude=new_point['longitude'], depth=start_point.depth)
java
@Override public void writeObject(Object value) throws JMSException { if (value == null) { throw new NullPointerException("Cannot write null value of object"); } if (value instanceof Boolean) { writeBoolean((Boolean) value); } else if (value instanceof Character) { writeChar((Character) value); } else if (value instanceof Byte) { writeByte((Byte) value); } else if (value instanceof Short) { writeShort((Short) value); } else if (value instanceof Integer) { writeInt((Integer) value); } else if (value instanceof Long) { writeLong((Long) value); } else if (value instanceof Float) { writeFloat((Float) value); } else if (value instanceof Double) { writeDouble((Double) value); } else if (value instanceof String) { writeUTF(value.toString()); } else if (value instanceof byte[]) { writeBytes((byte[]) value); }
java
public BigInteger incrementAndGet() { for (;;) { BigInteger current = get(); BigInteger next = current.add(BigInteger.ONE); if (compareAndSet(current, next)) return next; } }
java
public static <T extends NamedElement> ElementMatcher.Junction<T> nameMatches(String regex) { return new NameMatcher<T>(new StringMatcher(regex, StringMatcher.Mode.MATCHES)); }
python
def raw_field_definition_proxy_post_save(sender, instance, raw, **kwargs): """ When proxy field definitions are loaded from a fixture they're not passing through the `field_definition_post_save` signal. Make sure they are. """ if raw: model_class = instance.content_type.model_class() opts = model_class._meta if opts.proxy and opts.concrete_model is sender: field_definition_post_save( sender=model_class, instance=instance.type_cast(), raw=raw, **kwargs )
java
public boolean isMatch(String strMatch) { if (m_setMatches.contains(strMatch)) return true; if (m_parent instanceof XslImportScanListener) return ((XslImportScanListener)m_parent).isMatch(strMatch); return false; }
java
public static void showPublishDialog( CmsPublishData result, CloseHandler<PopupPanel> handler, Runnable refreshAction, I_CmsContentEditorHandler editorHandler) { CmsPublishDialog publishDialog = new CmsPublishDialog(result, refreshAction, editorHandler); if (handler != null) { publishDialog.addCloseHandler(handler); } publishDialog.centerHorizontally(50); // replace current notification widget by overlay publishDialog.catchNotifications(); }
python
def _submit(self): '''submit the question to the board. When we get here we should have (under self.data) {'record_environment': [('DISPLAY', ':0')], 'user_prompt_board': 'http://127.0.0.1', 'user_prompt_issue': 'I want to know why dinosaurs are so great!', 'user_prompt_title': 'Why are dinosaurs so great?'} self.token should be propogated with the personal access token ''' body = self.data['user_prompt_issue'] title = self.data['user_prompt_title'] board = self.data['user_prompt_board'] username = self.data['user_prompt_username'] category = self.data['user_prompt_category'] # Step 1: Token if self.token == None: self.token = self.request_token(board) self._get_and_update_setting('HELPME_DISCOURSE_TOKEN', self.token) # Step 1: Environment envars = self.data.get('record_environment') body = body + envars_to_markdown(envars) # Step 2: Asciinema asciinema = self.data.get('record_asciinema') if asciinema not in [None, '']: url = upload_asciinema(asciinema) # If the upload is successful, add a link to it. if url is not None: body += "\n[View Asciinema Recording](%s)" % url # Add other metadata about client body += "\n\ngenerated by [HelpMe](https://vsoch.github.io/helpme/)" body += "\nHelpMe Discourse Id: %s" %(self.run_id) # Submit the issue post = self.create_post(title, body, board, category, username) return post
python
def validate(cls, data, name, **kwargs): """Validate that a piece of data meets certain conditions""" required = kwargs.get('required', False) if required and data is None: raise ValidationError("required", name, True) elif data is None: return elif kwargs.get('readonly'): return try: for key, value in kwargs.items(): validator = cls.validation.get(key, lambda x, y: False) if validator(data, value): raise ValidationError(key, name, value) except TypeError: raise ValidationError("unknown", name, "unknown") else: return data
python
def set_search_url(self, url): """ Reads given query string and stores key-value tuples :param url: A string containing a valid URL to parse arguments from """ if url[0] == '?': url = url[1:] self.arguments = {} for key, value in parse_qs(url).items(): self.arguments.update({key: unquote(value[0])})
java
public void marshall(SubDomainSetting subDomainSetting, ProtocolMarshaller protocolMarshaller) { if (subDomainSetting == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(subDomainSetting.getPrefix(), PREFIX_BINDING); protocolMarshaller.marshall(subDomainSetting.getBranchName(), BRANCHNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
@Override public void sawOpcode(final int seen) { Object hashCodedStringRef = null; try { stack.precomputation(this); switch (seen) { case Const.INVOKEVIRTUAL: if (Values.SLASHED_JAVA_LANG_STRING.equals(getClassConstantOperand())) { String calledMethodName = getNameConstantOperand(); String calledMethodSig = getSigConstantOperand(); if (("equals".equals(calledMethodName) && SignatureBuilder.SIG_OBJECT_TO_BOOLEAN.equals(calledMethodSig)) || ("compareTo".equals(calledMethodName) && SignatureBuilder.SIG_STRING_TO_INT.equals(calledMethodSig)) || ("equalsIgnoreCase".equals(calledMethodName) && SignatureBuilder.SIG_STRING_TO_BOOLEAN.equals(calledMethodSig))) { if (stack.getStackDepth() > 0) { OpcodeStack.Item itm = stack.getStackItem(0); Object constant = itm.getConstant(); if ((constant != null) && constant.getClass().equals(String.class) && !lookupSwitchOnString()) { bugReporter.reportBug(new BugInstance(this, "LSC_LITERAL_STRING_COMPARISON", HIGH_PRIORITY) // very // confident .addClass(this).addMethod(this).addSourceLine(this)); } } } else if (Values.HASHCODE.equals(calledMethodName) && (stack.getStackDepth() > 0)) { OpcodeStack.Item item = stack.getStackItem(0); int reg = item.getRegisterNumber(); if (reg >= 0) { hashCodedStringRef = String.valueOf(reg); } else { XField xf = item.getXField(); if (xf != null) { hashCodedStringRef = xf.getName(); } else { XMethod xm = item.getReturnValueOf(); if (xm != null) { hashCodedStringRef = xm.toString(); } } } } } break; case Const.TABLESWITCH: case Const.LOOKUPSWITCH: if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); String stringRef = (String) item.getUserValue(); if (stringRef != null) { int[] offsets = getSwitchOffsets(); BitSet bs = new BitSet(); int pc = getPC(); for (int offset : offsets) { bs.set(pc + offset); } bs.set(pc + getDefaultSwitchOffset()); lookupSwitches.add(new LookupDetails(stringRef, bs)); } } break; default: break; } } finally { stack.sawOpcode(this, seen); if ((hashCodedStringRef != null) && (stack.getStackDepth() > 0)) { OpcodeStack.Item item = stack.getStackItem(0); item.setUserValue(hashCodedStringRef); } if (!lookupSwitches.isEmpty()) { int innerMostSwitch = lookupSwitches.size() - 1; LookupDetails details = lookupSwitches.get(innerMostSwitch); if (details.getSwitchTargets().get(getPC()) && (stack.getStackDepth() > 0)) { OpcodeStack.Item item = stack.getStackItem(0); item.setUserValue(details.getStringReference()); } // previousSetBit is a jdk1.7 api - gonna cheat cause findbugs // runs on 1.7 if (getPC() >= details.getSwitchTargets().previousSetBit(Integer.MAX_VALUE)) { lookupSwitches.remove(innerMostSwitch); } } } }
java
static void writeField(DataOutputView out, Field field) throws IOException { Class<?> declaringClass = field.getDeclaringClass(); out.writeUTF(declaringClass.getName()); out.writeUTF(field.getName()); }
python
def sample(self, data, sample_size=15000, blocked_proportion=0.5, original_length=None): '''Draw a sample of record pairs from the dataset (a mix of random pairs & pairs of similar records) and initialize active learning with this sample Arguments: data -- Dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names sample_size -- Size of the sample to draw blocked_proportion -- Proportion of the sample that will be blocked original_length -- Length of original data, should be set if `data` is a sample of full data ''' self._checkData(data) self.active_learner = self.ActiveLearner(self.data_model) self.active_learner.sample_combo(data, blocked_proportion, sample_size, original_length)
java
private static PeriodFormatter toFormatter(List<Object> elementPairs, boolean notPrinter, boolean notParser) { if (notPrinter && notParser) { throw new IllegalStateException("Builder has created neither a printer nor a parser"); } int size = elementPairs.size(); if (size >= 2 && elementPairs.get(0) instanceof Separator) { Separator sep = (Separator) elementPairs.get(0); if (sep.iAfterParser == null && sep.iAfterPrinter == null) { PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser); sep = sep.finish(f.getPrinter(), f.getParser()); return new PeriodFormatter(sep, sep); } } Object[] comp = createComposite(elementPairs); if (notPrinter) { return new PeriodFormatter(null, (PeriodParser) comp[1]); } else if (notParser) { return new PeriodFormatter((PeriodPrinter) comp[0], null); } else { return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]); } }
python
def keysym_definitions(): """Yields all keysym definitions parsed as tuples. """ for keysym_line in keysym_lines(): # As described in the input text, the format of a line is: # 0x20 U0020 . # space /* optional comment */ keysym_number, codepoint, status, _, name_part = [ p.strip() for p in keysym_line.split(None, 4)] name = name_part.split()[0] yield (int(keysym_number, 16), codepoint[1:], status, name)
python
def _CreateDictReader(self, line_reader): """Iterates over the log lines and provide a reader for the values. Args: line_reader (iter): yields each line in the log file. Yields: dict[str, str]: column values keyed by column header. """ for line in line_reader: if isinstance(line, py2to3.BYTES_TYPE): try: line = codecs.decode(line, self._encoding) except UnicodeDecodeError as exception: raise errors.UnableToParseFile( 'Unable decode line with error: {0!s}'.format(exception)) stripped_line = line.strip() values = stripped_line.split(self.DELIMITER) number_of_values = len(values) number_of_columns = len(self.COLUMNS) if number_of_values < self.MIN_COLUMNS: raise errors.UnableToParseFile( 'Expected at least {0:d} values, found {1:d}'.format( self.MIN_COLUMNS, number_of_values)) if number_of_values > number_of_columns: raise errors.UnableToParseFile( 'Expected at most {0:d} values, found {1:d}'.format( number_of_columns, number_of_values)) yield dict(zip(self.COLUMNS, values))
python
def resources(self): """Vault resources within context""" res = [] for resource in self._resources: res = res + resource.resources() return res
java
public ContainerOverrides withResourceRequirements(ResourceRequirement... resourceRequirements) { if (this.resourceRequirements == null) { setResourceRequirements(new java.util.ArrayList<ResourceRequirement>(resourceRequirements.length)); } for (ResourceRequirement ele : resourceRequirements) { this.resourceRequirements.add(ele); } return this; }
python
def _gather(self, func): """ Removes the experiment's path (prefix) from the names of the gathered items. This means that, for example, 'experiment.print_config' becomes 'print_config'. """ for ingredient, _ in self.traverse_ingredients(): for name, item in func(ingredient): if ingredient == self: name = name[len(self.path) + 1:] yield name, item
python
def _build_list_item(self, item_value, id_=None): """Return a dict with ID and $type for API representation of value Uses id_ param if provided, defaults to new random ID """ return { '$type': self._type_map[self.input_type]['list_item_type'], 'id': id_ or SID.generate(), 'value': item_value }
python
def read_byte(self, base, offset=0): """ Return the int value of the byte at the file position defined by self._base_offset + *base* + *offset*. If *base* is None, the byte is read from the current position in the stream. """ fmt = 'B' return self._read_int(fmt, base, offset)
java
public static UserMappingTable create(String tableName, List<UserCustomColumn> additionalColumns) { List<UserCustomColumn> columns = new ArrayList<>(); columns.addAll(createRequiredColumns()); if (additionalColumns != null) { columns.addAll(additionalColumns); } return new UserMappingTable(tableName, columns); }
java
@Override public final Float evalFloatResult( final String pQuery, final String pColumnName) throws Exception { Float result = null; IRecordSet<RS> recordSet = null; try { recordSet = retrieveRecords(pQuery); if (recordSet.moveToFirst()) { result = recordSet.getFloat(pColumnName); } } finally { if (recordSet != null) { recordSet.close(); } } return result; }
java
private I_CmsStringModel createStringModel(final CmsUUID id, final String propName, final boolean isStructure) { final CmsClientProperty property = m_properties.get(propName); return new I_CmsStringModel() { private boolean m_active; private EventBus m_eventBus = new SimpleEventBus(); public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) { return m_eventBus.addHandler(ValueChangeEvent.getType(), handler); } /** * @see com.google.gwt.event.shared.HasHandlers#fireEvent(com.google.gwt.event.shared.GwtEvent) */ public void fireEvent(GwtEvent<?> event) { m_eventBus.fireEvent(event); } public String getId() { return Joiner.on("/").join(id.toString(), propName, isStructure ? "S" : "R"); } public String getValue() { if (isStructure) { return property.getStructureValue(); } else { return property.getResourceValue(); } } public void setValue(String value, boolean notify) { if (!m_active) { m_active = true; try { String oldValue = getValue(); boolean changed = !Objects.equal(value, oldValue); if (isStructure) { property.setStructureValue(value); } else { property.setResourceValue(value); } if (notify && changed) { ValueChangeEvent.fire(this, value); } } finally { m_active = false; } } } }; }
java
public static String formatDate(final Date date, final String pattren) { final SimpleDateFormat formatter = new SimpleDateFormat(pattren, new Locale("en", "US")); if (date == null) { return ""; } return formatter.format(date); }
python
def schedule_job(date, callable_name, content_object=None, expires='7d', args=(), kwargs={}): """Schedule a job. `date` may be a datetime.datetime or a datetime.timedelta. The callable to be executed may be specified in two ways: - set `callable_name` to an identifier ('mypackage.myapp.some_function'). - specify an instance of a model as content_object and set `callable_name` to a method name ('do_job') The scheduler will not attempt to run the job if its expiration date has passed. """ # TODO: allow to pass in a real callable, but check that it's a global assert callable_name and isinstance(callable_name, basestring), callable_name if isinstance(date, basestring): date = parse_timedelta(date) if isinstance(date, datetime.timedelta): date = datetime.datetime.now() + date job = ScheduledJob(callable_name=callable_name, time_slot_start=date) if expires: if isinstance(expires, basestring): expires = parse_timedelta(expires) if isinstance(expires, datetime.timedelta): expires = date + expires job.time_slot_end = expires if content_object: job.content_object = content_object job.args = args job.kwargs = kwargs job.save() return job
python
def parse(self, type_str): """ Parses a type string into an appropriate instance of :class:`~eth_abi.grammar.ABIType`. If a type string cannot be parsed, throws :class:`~eth_abi.exceptions.ParseError`. :param type_str: The type string to be parsed. :returns: An instance of :class:`~eth_abi.grammar.ABIType` containing information about the parsed type string. """ if not isinstance(type_str, str): raise TypeError('Can only parse string values: got {}'.format(type(type_str))) try: return super().parse(type_str) except parsimonious.ParseError as e: raise ParseError(e.text, e.pos, e.expr)
java
public void addAutofilter(final Table table, final int r1, final int c1, final int r2, final int c2) { if (this.autofilters == null) this.autofilters = new ArrayList<String>(); this.autofilters.add(this.positionUtil.toRangeAddress(table, r1, c1, r2, c2)); }