language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Long marketplace_createListing(Boolean showOnProfile, MarketplaceListing attrs) throws FacebookException, IOException { T result = this.callMethod(FacebookMethod.MARKETPLACE_CREATE_LISTING, new Pair<String, CharSequence>("show_on_profile", showOnProfile ? "1" : "0"), ...
python
def save_option(self, path, section, option, value): """ Write the specified Section.Option to the config file specified by path. Replace any previous value. If the path doesn't exist, create it. Also add the option the the in-memory config. """ config = ConfigParser.Saf...
python
def placeholdit( width, height, background_color="cccccc", text_color="969696", text=None, random_background_color=False ): """ Creates a placeholder image using placehold.it Usage format: {% placeholdit [width] [height] [background_color] [text_color] [text] %} Example ...
python
def set_slug(apps, schema_editor): """ Create a slug for each Creator already in the DB. """ Creator = apps.get_model('spectator_core', 'Creator') for c in Creator.objects.all(): c.slug = generate_slug(c.pk) c.save(update_fields=['slug'])
java
public <T> KxPublisher<T> asKxPublisher(Publisher<T> p) { if ( p instanceof KxPublisher) return (KxPublisher<T>) p; return new KxPublisher<T>() { @Override public void subscribe(Subscriber<? super T> s) { p.subscribe(s); } @Ove...
java
public void decompose( DMatrixRMaj A ) { this.QR = A.copy(); int N = Math.min(A.numCols,A.numRows); gammas = new double[ A.numCols ]; DMatrixRMaj A_small = new DMatrixRMaj(A.numRows,A.numCols); DMatrixRMaj A_mod = new DMatrixRMaj(A.numRows,A.numCols); DMatrixRMaj v = ...
python
def get_upload_path(instance, filename): """Overriding to store the original filename""" if not instance.name: instance.name = filename # set original filename date = timezone.now().date() filename = '{name}.{ext}'.format(name=uuid4().hex, ext=filename.split...
java
public List<E> tokenize() { // System.out.println("tokenize called"); List<E> result = new ArrayList<E>(); while (hasNext()) { result.add(next()); } return result; }
python
def process_form(request, form_class, form_dict=None, save_kwargs=None, *a, **kw): ''' Optional: ========= You can pass kwargs to the form save function in a 'save_kwargs' dict. Example Usage: ============== success, form = process_form(request, DiscussionForm, in...
java
private void emit(DerOutputStream out) throws IOException, CertificateEncodingException { DerOutputStream tagged = new DerOutputStream(); if (forward != null) { DerOutputStream tmp = new DerOutputStream(); tmp.putDerValue(new DerValue(forward.getEncoded())); ...
python
def normalize_selectors(self, _selectors, extra_selectors=None, extra_parents=None): """ Normalizes or extends selectors in a string. An optional extra parameter that can be a list of extra selectors to be added to the final normalized selectors string. """ # Fixe tabs an...
python
def _assert_refspec(self): """Turns out we can't deal with remotes if the refspec is missing""" config = self.config_reader unset = 'placeholder' try: if config.get_value('fetch', default=unset) is unset: msg = "Remote '%s' has no refspec set.\n" ...
python
def ensure_dir_path(self, path, relative=False): """ Ensure the path is a dir path. Should end with '/' except for schemes and locators. Args: path (str): Path or URL. relative (bool): Path is relative to current root. Returns: path: dir pat...
java
public static boolean isCompatibleClientDatanodeProtocol( long clientVersion, long serverVersion) { return clientVersion == serverVersion || ( ( clientVersion == ClientDatanodeProtocol.GET_BLOCKINFO_VERSION-1 || clientVersion == ClientDatanodeProtocol.GET_BLOCKINFO_VERSION...
python
def send(self, uMsg, wParam = None, lParam = None, dwTimeout = None): """ Send a low-level window message syncronically. @type uMsg: int @param uMsg: Message code. @param wParam: The type and meaning of this parameter depends on the message. @param lParam:...
java
public static Connection getConnection(String dataSourceName, boolean startTransaction) throws SQLException { Map<String, OpenConnStats> statsMap = openConnStats.get(); OpenConnStats connStats = statsMap.get(dataSourceName); Connection conn; if (connStats == null) { ...
java
@Override public SetStackPolicyResult setStackPolicy(SetStackPolicyRequest request) { request = beforeClientExecution(request); return executeSetStackPolicy(request); }
java
public ServiceFuture<VirtualNetworkRuleInner> getAsync(String resourceGroupName, String serverName, String virtualNetworkRuleName, final ServiceCallback<VirtualNetworkRuleInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, serverName, virtualNetworkRuleName...
java
@SuppressWarnings("unchecked") @NonNull public final GenericType<? super T> getSupertype(@NonNull Class<? super T> superclass) { return new GenericType(token.getSupertype(superclass)); }
java
@Override public EbeanQueryWrapper doCreateQuery(Object[] values) { ParameterAccessor accessor = new ParametersParameterAccessor(getQueryMethod().getParameters(), values); EbeanQueryWrapper query = createEbeanQuery(this.query.getQueryString()); return createBinder(values).bindAndPrepare(qu...
python
def configure(self): """ The main configure function. Uses a schema file and an optional data file, and combines them with user prompts to write a new data file. """ # Make the lazy folder if it doesn't already exist. path = os.getcwd() + '/' + self.lazy_folder if not os.pat...
python
def create_image(self, df_dir_path, image, use_cache=False): """ create image: get atomic-reactor sdist tarball, build image and tag it :param df_path: :param image: :return: """ logger.debug("creating build image: df_dir_path = '%s', image = '%s'", df_dir_path, ...
python
def score(self, full_report=False): """ Returns a number between 0 and 1, indicating how suboptimal the tree is. The lower, the better. Roughly, this number represents the fraction of flawed Intervals in the tree. :rtype: float """ if len(self) <= 2: r...
java
public static StringBuilder get(FacesContext context, String key, int initialSize) { StringBuilder builder = (StringBuilder) context.getAttributes().get(key); if (builder == null) { builder = new StringBuilder(initialSize); context.getAttributes().put(key, builder); } ...
java
public void removeVertex(AtlasVertex vertex) { String vertexString = null; if (LOG.isDebugEnabled()) { vertexString = string(vertex); LOG.debug("Removing {}", vertexString); } graph.removeVertex(vertex); if (LOG.isDebugEnabled()) { LOG.info...
java
@Override public boolean clearKnowledgeBase() { if (!this.graphStoreManager.canBeModified()) { log.warn("The dataset cannot be modified."); return false; } log.info("Clearing knowledge base."); this.graphStoreManager.clearDataset(); // Generate Even...
python
def _selective_filter(self, data, indices): """ Selectively filter only pixels above ``filter_threshold`` in the background mesh. The same pixels are filtered in both the background and background RMS meshes. Parameters ---------- data : 2D `~numpy.ndarr...
java
protected void doGet(WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException { WebPageLayout layout=getWebPageLayout(req); ChainWriter out=getHTMLChainWriter(req, resp); try { layout.startHTML(this, req, resp, out, null); doGet(out, req, resp); layout.endHTML(thi...
java
JcrNodeType getNodeType( Name nodeTypeName ) { JcrNodeType nodeType = nodeTypes().getNodeType(nodeTypeName); if (nodeType != null) { nodeType = nodeType.with(context(), session); } return nodeType; }
java
public java.util.List<String> getDnsIpAddresses() { if (dnsIpAddresses == null) { dnsIpAddresses = new com.amazonaws.internal.SdkInternalList<String>(); } return dnsIpAddresses; }
java
public final Cursor<T> straightJoin (Connection conn, String table, String condition) { String query = "select " + listOfFields + " from " + name + " straight_join " + table + " " + condition; return new Cursor<T>(this, conn, query); }
python
def get_children(self, path, watch=None): """Returns the children of the specified node.""" _log.debug( "ZK: Getting children of {path}".format(path=path), ) return self.zk.get_children(path, watch)
java
@Override public void add(IAtomContainer that) { atoms = Arrays.copyOf(atoms, atomCount + that.getAtomCount()); bonds = Arrays.copyOf(bonds, bondCount + that.getBondCount()); for (IAtom atom : that.atoms()) atom.setFlag(CDKConstants.VISITED, false); for (IBond bond : th...
java
@Override public <C, D> Const<C, D> biMap(Function<? super A, ? extends C> lFn, Function<? super B, ? extends D> rFn) { return new Const<>(lFn.apply(a)); }
java
public Vector3d half(Vector3dc other, Vector3d dest) { return half(other.x(), other.y(), other.z(), dest); }
java
public <T> T set(Object jsonObject, Object newVal, Configuration configuration) { notNull(jsonObject, "json can not be null"); notNull(configuration, "configuration can not be null"); EvaluationContext evaluationContext = path.evaluate(jsonObject, jsonObject, configuration, true); for (P...
python
def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs): """ Return any additional field options that need to be included as a result of uniqueness constraints on the model. This is returned as a two-tuple of: ('dict of updated extra kwargs', 'mapping o...
python
def p_string_literal(self, p): """string_literal : STRING""" p[0] = self.asttypes.String(p[1]) p[0].setpos(p)
python
def cellpar_to_cell(cellpar, ab_normal=(0,0,1), a_direction=None): """Return a 3x3 cell matrix from `cellpar` = [a, b, c, alpha, beta, gamma]. The returned cell is orientated such that a and b are normal to `ab_normal` and a is parallel to the projection of `a_direction` in the a-b plane. Default ...
python
def waveguide(path, points, finish, bend_radius, number_of_points=0.01, direction=None, layer=0, datatype=0): ''' Easy waveguide creation tool with absolute positioning. path : starting `gdspy.Path...
java
public void dispatch (T object) { final Object[] items = listeners.begin(); for (int i = 0, n = listeners.size; i < n; i++) { Listener<T> listener = (Listener<T>)items[i]; listener.receive(this, object); } listeners.end(); }
java
protected static String getInstancesFolder(FileSystem fS, Configuration conf) throws IOException { return conf.get(HDFS_TMP_FOLDER_CONF, fS.equals(FileSystem.getLocal(conf)) ? DEFAULT_LOCAL_TMP_FOLDER_CONF_VALUE : DEFAULT_HDFS_TMP_FOLDER_CONF_VALUE); }
java
public void pinchToZoom(PointF startPoint1, PointF startPoint2, PointF endPoint1, PointF endPoint2) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "pinchToZoom("+startPoint1+", "+startPoint2+", "+endPoint1+", "+endPoint2+")"); } if (android.os.Build.VERSION.SDK_INT < 14){ throw new Runtime...
python
def needs_compile(self): '''Returns True if self.sourcepath is newer than self.targetpath''' try: source_mtime = os.stat(self.sourcepath).st_mtime except OSError: # no source for this template, so just return return False try: target_mtime = os.stat(s...
java
private Statement handleBasicTranslation( List<SoyPrintDirective> escapingDirectives, Expression soyMsgParts) { // optimize for simple constant translations (very common) // this becomes: renderContext.getSoyMessge(<id>).getParts().get(0).getRawText() SoyExpression text = SoyExpression.forStri...
java
private static KeyStore loadKeyStore(InputStream is, String pass) throws InitializationException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(is, pass.toCharArray()); return ks; }
java
@Override public List<FILTERTYPE> getAllFilter() { final List<FILTERTYPE> list = new ArrayList<FILTERTYPE>(); final List<Node> nodeList = model.get("filter"); for (final Node node : nodeList) { final FILTERTYPE filter = this.createNewFilterViewForModel(node); list.ad...
python
def get_current_peers( self, peer_table=None ): """ Get the current set of peers """ # get current peers current_peers = None with AtlasPeerTableLocked(peer_table) as ptbl: current_peers = ptbl.keys()[:] return current_peers
python
def decimal_to_digits(decimal, min_digits=None): """ Return the number of digits to the first nonzero decimal. Parameters ----------- decimal: float min_digits: int, minimum number of digits to return Returns ----------- digits: int, number of digits to the first nonzero decima...
python
def sync(self): """ synchronize self from Ariane server according its id (prioritary) or name :return: """ LOGGER.debug("OSInstance.sync") params = None if self.id is not None: params = {'id': self.id} elif self.name is not None: pa...
java
public void onClickOpen(CmsSitemapTreeNode node) { if (node.isOpen()) { node.setOpen(false); } else { if (!m_alreadyLoaded.containsKey(node)) { Object nodeData = node.getData(); List<CmsSitemapTreeNodeData> children = m_treeDataProvider.getChildre...
java
private static boolean canEncode(final CoreCharset charset, final char c, final CharsetEncoder fallback) { // todo add more charset tests if impacted by Android's bad perf in canEncode switch (charset) { case ascii: return c < 0x80; case utf: retur...
java
@Cmd public Reporter registerReporter(final Reporter reporter) { injector.injectMembers(reporter); reporters.add(reporter); return reporter; }
python
def _CheckIsLink(self, file_entry): """Checks the is_link find specification. Args: file_entry (FileEntry): file entry. Returns: bool: True if the file entry matches the find specification, False if not. """ if definitions.FILE_ENTRY_TYPE_LINK not in self._file_entry_types: retur...
java
public Contact updateContact(final String id, ContactRequest contactRequest) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Contact ID must be specified."); } String request = CONTACTPATH + "/" + id; return messageBirdSe...
python
def _make_cron_re(): """ Make the regular expression that matches a crontab 'cron' line. Each field has a set of allowed values, and can then be in a range, and be listed with dashes. A range can be stepped with the '/' modifier, and ranges can be in a list. A field can also be '*', or '*' divide...
java
public byte[] get(byte[] key) throws IOException { int keyLength = key.length; if (keyLength >= slots.length || keyCounts[keyLength] == 0) { return null; } long hash = (long) hashUtils.hash(key); int numSlots = slots[keyLength]; int slotSize = slotSizes[keyLength]; int indexOffse...
java
public Vector4d mul(double scalar, Vector4d dest) { dest.x = x * scalar; dest.y = y * scalar; dest.z = z * scalar; dest.w = w * scalar; return dest; }
java
public void bezierCurveTo(double xc1, double yc1, double xc2, double yc2, double x1, double y1) { this.gc.bezierCurveTo( doc2fxX(xc1), doc2fxY(yc1), doc2fxX(xc2), doc2fxY(yc2), doc2fxX(x1), doc2fxY(y1)); }
java
@Override public final Iterator<T> iterator() { synchronized (this.state) { checkState(); this.state.available = false; final Iterator<T> iterator; try { iterator = new CheckedIterator<T>(doIterator(), this); } catch (final Throwabl...
java
protected void checkFrozen() throws CmsRuntimeException { if (m_frozen) { throw new CmsRuntimeException(Messages.get().container(Messages.ERR_JOB_INFO_FROZEN_1, getJobName())); } }
java
public static void setPreferredAttributeValueForTrafficDirection(TrafficDirection direction, int index, String value) { final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class); if (prefs != null) { final StringBuilder keyName = new StringBuilder(); keyName.append("TRAFFIC_DIRECTIO...
python
def monotonicity_(n, coef, increasing=True): """ Builds a penalty matrix for P-Splines with continuous features. Penalizes violation of monotonicity in the feature function. Parameters ---------- n : int number of splines coef : array-like coefficients of the feature functio...
python
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): # NOQA """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is false then ``dict`` keys that are not basic types (``str``, ``uni...
java
public static <T> List<T> cast(List<?> list) { return list == null ? null : new CastingList<T>(list); }
python
def transform(self, Y): """Transform input data `Y` to reduced data space defined by `self.data` Takes data in the same ambient space as `self.data` and transforms it to be in the same reduced space as `self.data_nu`. Parameters ---------- Y : array-like, shape=[n_sampl...
python
def hide( input_image: Union[str, IO[bytes]], message: str, generator: Iterator[int], shift: int = 0, encoding: str = "UTF-8", auto_convert_rgb: bool = False, ): """Hide a message (string) in an image with the LSB (Least Significant Bit) technique. """ message_length = len(messag...
python
def json2table(json): """This does format a dictionary into a table. Note this expects a dictionary (not a json string!) :param json: :return: """ filter_terms = ['ResponseMetadata'] table = [] try: for k in filter(lambda k: k not in filter_terms, json.keys()): table...
java
private void abortTransactions(Set<String> transactionalIds) { for (String transactionalId : transactionalIds) { try (FlinkKafkaInternalProducer<byte[], byte[]> kafkaProducer = initTransactionalProducer(transactionalId, false)) { // it suffice to call initTransactions - this will abort any lingering transa...
java
public static <KEY extends Comparable<KEY>, VALUE> CachingTemplate<KEY, VALUE> with(Cache<KEY, VALUE> cache) { return new CachingTemplate<>(cache); }
python
def store_atomic(self, value, ptr, ordering, align): """ Store value to pointer, with optional guaranteed alignment: *ptr = name """ if not isinstance(ptr.type, types.PointerType): raise TypeError("cannot store to value of type %s (%r): not a pointer" ...
python
def request_system_arm(blink, network): """ Arm system. :param blink: Blink instance. :param network: Sync module network id. """ url = "{}/network/{}/arm".format(blink.urls.base_url, network) return http_post(blink, url)
python
def get_files(file_tokens, cwd=None): """ Given a list of parser file tokens, return a list of input objects for them. """ if not file_tokens: return [] token = file_tokens.pop() try: filename = token.filename except AttributeError: filename = '' if cwd: ...
java
public static ByteBuffer allocateDirectAligned(final int capacity, final int alignment) { if (!isPowerOfTwo(alignment)) { throw new IllegalArgumentException("Must be a power of 2: alignment=" + alignment); } final ByteBuffer buffer = ByteBuffer.allocateDirect(capacity + ...
java
public void setIdentity() { this.path = null; this.firstSegmentDirection = detectFirstSegmentDirection(null); this.curvilineTranslation = 0.; this.shiftTranslation = 0.; this.isIdentity = Boolean.TRUE; }
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enabled') and self.enabled is not None: _dict['enabled'] = self.enabled if hasattr(self, 'selector_tags') and self.selector_tags is not None: _dict['selector_t...
java
public List<JobInfo> findJobs(final Optional<String> type, final int count) { if (type.isPresent()) { return jobRepository.findLatestBy(type.get(), count); } else { return jobRepository.findLatest(count); } }
java
public void marshall(DeleteTagsRequest deleteTagsRequest, ProtocolMarshaller protocolMarshaller) { if (deleteTagsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteTagsRequest.getResourc...
python
async def _async_get_sshable_ips(self, ip_addresses): """Return list of all IP address that could be pinged.""" async def _async_ping(ip_address): try: reader, writer = await asyncio.wait_for( asyncio.open_connection(ip_address, 22), timeout=5) ...
python
def nameop_put_collision( cls, collisions, nameop ): """ Record a nameop as collided with another nameop in this block. """ # these are supposed to have been put here by nameop_set_collided history_id_key = nameop.get('__collided_history_id_key__', None) history_id = name...
python
def local(self, fun, tgt, **kwargs): ''' Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` ''' self.client_cache['local'].cmd_async(tgt, fun, **kwargs)
java
public boolean remove(K key, V value) { key = sanitizeKey(key); List<V> values = map.get(key); if (values == null) { return false; } boolean success = values.remove(value); if (values.isEmpty()) { map.remove(key); } return success; }
java
public int lookupIndex (long entry) { int ret = map.get(entry); if (ret <= 0 && !growthStopped) { numEntries++; ret = numEntries; map.put (entry, ret); } return ret - 1; // feature id should be 0-based }
python
def calculate_size(name, expected, updated): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += LONG_SIZE_IN_BYTES data_size += LONG_SIZE_IN_BYTES return data_size
java
@Pure public static List<String> splitAsList(char leftSeparator, char rightSeparator, String str) { final List<String> list = new ArrayList<>(); splitSeparatorAlgorithm( leftSeparator, rightSeparator, str, new SplitSeparatorToListAlgorithm(list)); return list; }
python
def handle(cls, value, **kwargs): """Decrypt the specified value with a master key in KMS. kmssimple field types should be in the following format: [<region>@]<base64 encrypted value> Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if n...
python
def process_edge_flow(self, source, sink, i, j, algo, q): ''' API: process_edge_flow(self, source, sink, i, j, algo, q) Description: Used by by max_flow_preflowpush() method. Processes edges along prefolow push. Input: source: Source node name of flow graph. ...
java
@Deprecated public static ObjectId massageToObjectId(Object o) { if (o == null) return null; if (o instanceof ObjectId) return (ObjectId) o; if (o instanceof String) { String s = o.toString(); if (isValid(s)) return new ObjectId(s); } return null; }
python
def select(self, *cols): """ Returns DataTable with a subset of columns in this table """ return DataTable([cols] + zip(*[self[col] for col in cols]))
python
def from_json(cls, filename): """ Creates an experimental setup from a JSON file Parameters ---------- filename : str Absolute path to JSON file Returns ------- caspo.core.setup.Setup Created object instance """ wi...
java
public static JawrCacheManager getCacheManager(JawrConfig config, String resourceType) { String cacheMgrAttributeName = CACHE_ATTR_PREFIX + resourceType.toUpperCase() + CACHE_ATTR_SUFFIX; JawrCacheManager cacheManager = (JawrCacheManager) config.getContext().getAttribute(cacheMgrAttributeName); if (cacheManager ...
python
def __geometryListToGeomTemplate(self, geometries): """ converts a list of common.Geometry objects to the geometry template value Input: geometries - list of common.Geometry objects Output: Dictionary in geometry service template ...
python
def lookupListener(self, listenID): """ (internal) Retrieve a waiting connection by its connection identifier, passing in the transport to be used to connect the waiting protocol factory to. """ if listenID in self.inboundConnections: # Make the connection? ...
java
public static <T extends Model> LazyList<T> findBySQL(String fullQuery, Object... params) { return ModelDelegate.findBySql(Model.<T>modelClass(), fullQuery, params); }
java
public synchronized ExecutorService getBatchThreadPool() { if (batchThreadPool == null) { batchThreadPool = Executors .newCachedThreadPool(ThreadUtil.getThreadFactory(BATCH_POOL_THREAD_NAME_PATTERN, true)); } return batchThreadPool; }
python
def setup_signing(self, secret_key, sign_outgoing=True, allow_unsigned_callback=None, initial_timestamp=None, link_id=None): '''setup for MAVLink2 signing''' self.mav.signing.secret_key = secret_key self.mav.signing.sign_outgoing = sign_outgoing self.mav.signing.allow_unsigned_callback =...
java
public static base_responses delete(nitro_service client, String ipaddress[]) throws Exception { base_responses result = null; if (ipaddress != null && ipaddress.length > 0) { cacheforwardproxy deleteresources[] = new cacheforwardproxy[ipaddress.length]; for (int i=0;i<ipaddress.length;i++){ deleteresourc...
java
@Override public List<CPAttachmentFileEntry> getCPAttachmentFileEntriesByUuidAndCompanyId( String uuid, long companyId) { return cpAttachmentFileEntryPersistence.findByUuid_C(uuid, companyId); }
python
def add_patch(self, pset, augref): """Add patch corresponding to `augref` to `pset`. `augref` must be either 'augment' or 'refine' statement. """ try: path = [ self.add_prefix(c, augref) for c in augref.arg.split("/") if c ] except KeyError: ...
python
def _get_field_schema(self): """ Get a list of all of the default fields for this query type. If data is available in the monitor type, a list of field definitions will be returned ahead of the actual data, providing insight into the available fields. If no data is available in a...