language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def finalize(self): """finalize for PathConsumer""" super(TransposedConsumer, self).finalize() self.result = map(list, zip(*self.result))
java
public static Set<String> findAllDevices(AndroidDebugBridge adb, Integer minApiLevel) { Set<String> devices = new LinkedHashSet<>(); for (IDevice realDevice : adb.getDevices()) { if (minApiLevel == null) { devices.add(realDevice.getSerialNumber()); } else { DeviceDetails deviceDetails = DeviceDetails.createForDevice(realDevice); int apiLevel = deviceDetails.getApiLevel(); if (apiLevel == DeviceDetails.UNKNOWN_API_LEVEL || apiLevel >= minApiLevel) { devices.add(realDevice.getSerialNumber()); } } } return devices; }
java
@Override public ClassDoc asClassDoc() { return env.getClassDoc((ClassSymbol)env.types.erasure(type).tsym); }
python
def update_source_list(self): """ update ubuntu 16 source list :return: """ with cd('/etc/apt'): sudo('mv sources.list sources.list.bak') put(StringIO(bigdata_conf.ubuntu_source_list_16), 'sources.list', use_sudo=True) sudo('apt-get update -y --fix-missing')
python
def readBuffer(self, newLength): """ Read next chunk as another buffer. """ result = Buffer(self.buf, self.offset, newLength) self.skip(newLength) return result
python
def get_jokes(language='en', category='neutral'): """ Parameters ---------- category: str Choices: 'neutral', 'chuck', 'all', 'twister' lang: str Choices: 'en', 'de', 'es', 'gl', 'eu', 'it' Returns ------- jokes: list """ if language not in all_jokes: raise LanguageNotFoundError('No such language %s' % language) jokes = all_jokes[language] if category not in jokes: raise CategoryNotFoundError('No such category %s in language %s' % (category, language)) return jokes[category]
java
@Override public List<CommerceNotificationQueueEntry> findByCommerceNotificationTemplateId( long commerceNotificationTemplateId, int start, int end) { return findByCommerceNotificationTemplateId(commerceNotificationTemplateId, start, end, null); }
java
public static int readIntegerBigEndian(byte[] buffer, int offset) { int value; value = (buffer[offset] & 0xFF) << 24; value |= (buffer[offset + 1] & 0xFF) << 16; value |= (buffer[offset + 2] & 0xFF) << 8; value |= (buffer[offset + 3] & 0xFF); return value; }
java
public void setPropertyGroupDescriptions(java.util.Collection<PropertyGroup> propertyGroupDescriptions) { if (propertyGroupDescriptions == null) { this.propertyGroupDescriptions = null; return; } this.propertyGroupDescriptions = new java.util.ArrayList<PropertyGroup>(propertyGroupDescriptions); }
java
public HistoryReference getHistoryReference(int historyReferenceId) { DefaultHistoryReferencesTableEntry entry = getEntryWithHistoryId(historyReferenceId); if (entry != null) { return entry.getHistoryReference(); } return null; }
java
public final int getUint8(final int pos) { if (pos >= limit || pos < 0) throw new IllegalArgumentException("limit excceed: " + pos); return 0xff & buffer[origin + pos]; }
python
def _dirint_from_dni_ktprime(dni, kt_prime, solar_zenith, use_delta_kt_prime, temp_dew): """ Calculate DIRINT DNI from supplied DISC DNI and Kt'. Supports :py:func:`gti_dirint` """ times = dni.index delta_kt_prime = _delta_kt_prime_dirint(kt_prime, use_delta_kt_prime, times) w = _temp_dew_dirint(temp_dew, times) dirint_coeffs = _dirint_coeffs(times, kt_prime, solar_zenith, w, delta_kt_prime) dni_dirint = dni * dirint_coeffs return dni_dirint
python
def walkerWrapper(callback): """ Wraps a callback function in a wrapper that will be applied to all [sub]sections. Returns: function """ def wrapper(*args,**kwargs): #args[0] => has to be the current walked section return Section.sectionWalker(args[0],callback,*args[1:],**kwargs) return wrapper
java
public static <T> Consumer<T> pipeline(Consumer<T> first, Consumer<T> second, Consumer<T> third) { return new PipelinedConsumer<T>(Iterations.iterable(first, second, third)); }
python
def _valid_deleted_file(path): ''' Filters file path against unwanted directories and decides whether file is marked as deleted. Returns: True if file is desired deleted file, else False. Args: path: A string - path to file ''' ret = False if path.endswith(' (deleted)'): ret = True if re.compile(r"\(path inode=[0-9]+\)$").search(path): ret = True regex = re.compile("|".join(LIST_DIRS)) if regex.match(path): ret = False return ret
python
def Reinit(self, pid, auto_symfile_loading=True): """Reinitializes the object with a new pid. Since all modes might need access to this object at any time, this object needs to be long-lived. To make this clear in the API, this shorthand is supplied. Args: pid: the pid of the target process auto_symfile_loading: whether the symbol file should automatically be loaded by gdb. """ self.ShutDownGdb() self.__init__(pid, auto_symfile_loading, architecture=self.arch)
python
def discover_upnp_devices( self, st="upnp:rootdevice", timeout=2, mx=1, retries=1 ): """ sends an SSDP discovery packet to the network and collects the devices that replies to it. A dictionary is returned using the devices unique usn as key """ # prepare UDP socket to transfer the SSDP packets s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP ) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) s.settimeout(timeout) # prepare SSDP discover message msg = SSDPDiscoveryMessage(mx=mx, st=st) # try to get devices with multiple retries in case of failure devices = {} for _ in range(retries): # send SSDP discovery message s.sendto(msg.bytes, SSDP_MULTICAST_ADDR) devices = {} try: while True: # parse response and store it in dict r = SSDPResponse(s.recvfrom(65507)) devices[r.usn] = r except socket.timeout: break return devices
python
def print_plugins(self): """Print the available plugins.""" width = console_width() line = Style.BRIGHT + '=' * width + '\n' middle = int(width / 2) if self.available_providers: print(line + ' ' * middle + 'PROVIDERS') for provider in sorted(self.available_providers.values(), key=lambda x: x.identifier): provider().print() print() if self.available_checkers: print(line + ' ' * middle + 'CHECKERS') for checker in sorted(self.available_checkers.values(), key=lambda x: x.identifier): checker().print() print()
java
@SuppressWarnings("MissingPermission") static boolean getWifiConnected(Context context) { if (context != null && PackageManager.PERMISSION_GRANTED == context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE)) { ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = null; if (connManager != null) { wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } return ((wifiInfo != null) && wifiInfo.isConnected()); } return false; }
python
def _create_firefox_profile(self): """Create and configure a firefox profile :returns: firefox profile """ # Get Firefox profile profile_directory = self.config.get_optional('Firefox', 'profile') if profile_directory: self.logger.debug("Using firefox profile: %s", profile_directory) # Create Firefox profile profile = webdriver.FirefoxProfile(profile_directory=profile_directory) profile.native_events_enabled = True # Add Firefox preferences try: for pref, pref_value in dict(self.config.items('FirefoxPreferences')).items(): self.logger.debug("Added firefox preference: %s = %s", pref, pref_value) profile.set_preference(pref, self._convert_property_type(pref_value)) profile.update_preferences() except NoSectionError: pass # Add Firefox extensions try: for pref, pref_value in dict(self.config.items('FirefoxExtensions')).items(): self.logger.debug("Added firefox extension: %s = %s", pref, pref_value) profile.add_extension(pref_value) except NoSectionError: pass return profile
java
public static String get(String bundleName, String key, Object[] args) { return get(bundleName, getLocale(), key, args); }
java
public void useProject(String projectName) { removeProject(projectName); recentProjectsList.addFirst(projectName); while (recentProjectsList.size() > MAX_RECENT_FILES) { recentProjectsList.removeLast(); } }
java
boolean handleStep(ListIterator<Step<?, ?>> stepIterator, MutableInt pathCount) { Step<?, ?> step = stepIterator.next(); removeTinkerPopLabels(step); if (step instanceof GraphStep) { doFirst(stepIterator, step, pathCount); } else if (this.sqlgStep == null) { boolean keepGoing = doFirst(stepIterator, step, pathCount); stepIterator.previous(); return keepGoing; } else { if (step instanceof VertexStep || step instanceof EdgeVertexStep || step instanceof EdgeOtherVertexStep) { handleVertexStep(stepIterator, (AbstractStep<?, ?>) step, pathCount); } else if (step instanceof RepeatStep) { if (!unoptimizableRepeatStep()) { handleRepeatStep((RepeatStep<?>) step, pathCount); } else { this.currentReplacedStep.addLabel((pathCount) + BaseStrategy.PATH_LABEL_SUFFIX + BaseStrategy.SQLG_PATH_FAKE_LABEL); return false; } } else if (step instanceof OptionalStep) { if (!unoptimizableOptionalStep((OptionalStep<?>) step)) { this.optionalStepStack.clear(); handleOptionalStep(1, (OptionalStep<?>) step, this.traversal, pathCount); this.optionalStepStack.clear(); //after choose steps the optimization starts over in VertexStrategy this.reset = true; } else { return false; } } else if (step instanceof ChooseStep) { if (!unoptimizableChooseStep((ChooseStep<?, ?, ?>) step)) { this.chooseStepStack.clear(); handleChooseStep(1, (ChooseStep<?, ?, ?>) step, this.traversal, pathCount); this.chooseStepStack.clear(); //after choose steps the optimization starts over this.reset = true; } else { return false; } } else if (step instanceof OrderGlobalStep) { stepIterator.previous(); handleOrderGlobalSteps(stepIterator, pathCount); handleRangeGlobalSteps(stepIterator, pathCount); } else if (step instanceof RangeGlobalStep) { handleRangeGlobalSteps(stepIterator, pathCount); } else if (step instanceof SelectStep || (step instanceof SelectOneStep)) { handleOrderGlobalSteps(stepIterator, pathCount); handleRangeGlobalSteps(stepIterator, pathCount); //select step can not be followed by a PropertyStep if (step instanceof SelectOneStep) { SelectOneStep selectOneStep = (SelectOneStep) step; String key = (String) selectOneStep.getScopeKeys().iterator().next(); if (stepIterator.hasNext()) { Step<?, ?> next = stepIterator.next(); if (next instanceof PropertiesStep) { //get the step for the label Optional<ReplacedStep<?, ?>> labeledReplacedStep = this.sqlgStep.getReplacedSteps().stream().filter( r -> { //Take the first if (r.hasLabels()) { String label = r.getLabels().iterator().next(); String stepLabel = SqlgUtil.originalLabel(label); return stepLabel.equals(key); } else { return false; } } ).findAny(); Preconditions.checkState(labeledReplacedStep.isPresent()); ReplacedStep<?, ?> replacedStep = labeledReplacedStep.get(); handlePropertiesStep(replacedStep, next); return true; } else { stepIterator.previous(); return false; } } } // return !stepIterator.hasNext() || !(stepIterator.next() instanceof SelectOneStep); } else if (step instanceof DropStep && (!this.sqlgGraph.getSqlDialect().isMariaDb())) { Traversal.Admin<?, ?> root = TraversalHelper.getRootTraversal(this.traversal); final Optional<EventStrategy> eventStrategyOptional = root.getStrategies().getStrategy(EventStrategy.class); if (eventStrategyOptional.isPresent()) { //Do nothing, it will go via the SqlgDropStepBarrier. } else { //MariaDB does not support target and source together. //Table 'E_ab' is specified twice, both as a target for 'DELETE' and as a separate source for data //This has been fixed in 10.3.1, waiting for it to land in the repo. handleDropStep(); } return false; } else if (step instanceof DropStep && this.sqlgGraph.getSqlDialect().isMariaDb()) { return false; } else if (step instanceof PropertiesStep) { return handlePropertiesStep(this.currentReplacedStep, step); } else if (step instanceof PropertyMapStep) { return handlePropertyMapStep(step); } else { throw new IllegalStateException("Unhandled step " + step.getClass().getName()); } } return true; }
python
def get_identifier(cmd_args, endpoint=''): """ Obtain anonmyzied identifier.""" student_email = get_student_email(cmd_args, endpoint) if not student_email: return "Unknown" return hashlib.md5(student_email.encode()).hexdigest()
python
def get(self, key, lang=None): """ Returns triple related to this node. Can filter on lang :param key: Predicate of the triple :param lang: Language of the triple if applicable :rtype: Literal or BNode or URIRef """ if lang is not None: for o in self.graph.objects(self.asNode(), key): if o.language == lang: yield o else: for o in self.graph.objects(self.asNode(), key): yield o
python
def write_authorized_keys(user=None): """Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user. """ authorized_keys = list() authorized_keys_dir = '{0}/.ssh'.format(os.path.expanduser('~{0}'.format(user.name))) rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH) authorized_keys_path = '{0}/authorized_keys'.format(authorized_keys_dir) tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(user.name, rnd_chars) if not os.path.isdir(authorized_keys_dir): execute_command(shlex.split(str('{0} mkdir -p {1}'.format(sudo_check(), authorized_keys_dir)))) for key in user.public_keys: authorized_keys.append('{0}\n'.format(key.raw)) with open(tmp_authorized_keys_path, mode=text_type('w+')) as keys_file: keys_file.writelines(authorized_keys) execute_command( shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), tmp_authorized_keys_path, authorized_keys_path)))) execute_command(shlex.split(str('{0} chown -R {1} {2}'.format(sudo_check(), user.name, authorized_keys_dir)))) execute_command(shlex.split(str('{0} chmod 700 {1}'.format(sudo_check(), authorized_keys_dir)))) execute_command(shlex.split(str('{0} chmod 600 {1}'.format(sudo_check(), authorized_keys_path)))) execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_authorized_keys_path))))
python
def evaluaterforces(Pot,R,z,phi=None,t=0.,v=None): """ NAME: evaluaterforces PURPOSE: convenience function to evaluate a possible sum of potentials INPUT: Pot - a potential or list of potentials R - cylindrical Galactocentric distance (can be Quantity) z - distance above the plane (can be Quantity) phi - azimuth (optional; can be Quantity) t - time (optional; can be Quantity) v - current velocity in cylindrical coordinates (optional, but required when including dissipative forces; can be a Quantity) OUTPUT: F_r(R,z,phi,t) HISTORY: 2016-06-10 - Written - Bovy (UofT) """ isList= isinstance(Pot,list) nonAxi= _isNonAxi(Pot) if nonAxi and phi is None: raise PotentialError("The (list of) Potential instances is non-axisymmetric, but you did not provide phi") dissipative= _isDissipative(Pot) if dissipative and v is None: raise PotentialError("The (list of) Potential instances includes dissipative, but you did not provide the 3D velocity (required for dissipative forces") if isList: sum= 0. for pot in Pot: if isinstance(pot,DissipativeForce): sum+= pot.rforce(R,z,phi=phi,t=t,v=v,use_physical=False) else: sum+= pot.rforce(R,z,phi=phi,t=t,use_physical=False) return sum elif isinstance(Pot,Potential): return Pot.rforce(R,z,phi=phi,t=t,use_physical=False) elif isinstance(Pot,DissipativeForce): return Pot.rforce(R,z,phi=phi,t=t,v=v,use_physical=False) else: #pragma: no cover raise PotentialError("Input to 'evaluaterforces' is neither a Potential-instance or a list of such instances")
python
def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host
java
private @CheckForNull HashedToken searchMatch(@Nonnull String plainSecret) { byte[] hashedBytes = plainSecretToHashBytes(plainSecret); for (HashedToken token : tokenList) { if (token.match(hashedBytes)) { return token; } } return null; }
java
public static DataAttribute createDataAttribute(byte data[]) { DataAttribute attribute = new DataAttribute(); attribute.setData(data); return attribute; }
java
public void setLastPoint(double x, double y, double z) { if (this.numCoords>=3) { this.coords[this.numCoords-3] = x; this.coords[this.numCoords-2] = y; this.coords[this.numCoords-1] = z; this.graphicalBounds = null; this.logicalBounds = null; } }
python
def evaluate_unop(self, operation, right, **kwargs): """ Evaluate given unary operation with given operand. """ if not operation in self.unops: raise ValueError("Invalid unary operation '{}'".format(operation)) if right is None: return None return self.unops[operation](right)
python
def Convert(self, metadata, process, token=None): """Converts Process to ExportedProcess.""" result = ExportedProcess( metadata=metadata, pid=process.pid, ppid=process.ppid, name=process.name, exe=process.exe, cmdline=" ".join(process.cmdline), ctime=process.ctime, real_uid=process.real_uid, effective_uid=process.effective_uid, saved_uid=process.saved_uid, real_gid=process.real_gid, effective_gid=process.effective_gid, saved_gid=process.saved_gid, username=process.username, terminal=process.terminal, status=process.status, nice=process.nice, cwd=process.cwd, num_threads=process.num_threads, user_cpu_time=process.user_cpu_time, system_cpu_time=process.system_cpu_time, cpu_percent=process.cpu_percent, rss_size=process.RSS_size, vms_size=process.VMS_size, memory_percent=process.memory_percent) return [result]
python
def _process_pathway_ko(self, limit): """ This adds the kegg orthologous group (gene) to the canonical pathway. :param limit: :return: """ LOG.info("Processing KEGG pathways to kegg ortholog classes") if self.test_mode: graph = self.testgraph else: graph = self.graph line_counter = 0 raw = '/'.join((self.rawdir, self.files['pathway_ko']['file'])) with open(raw, 'r', encoding="iso-8859-1") as csvfile: filereader = csv.reader(csvfile, delimiter='\t', quotechar='\"') for row in filereader: line_counter += 1 (ko_id, pathway_id) = row if self.test_mode and pathway_id not in self.test_ids['pathway']: continue pathway_id = 'KEGG-' + pathway_id ko_id = 'KEGG-' + ko_id p = Pathway(graph) p.addGeneToPathway(ko_id, pathway_id) if not self.test_mode and limit is not None and line_counter > limit: break return
python
def reorderbydf(df2,df1): """ Reorder rows of a dataframe by other dataframe :param df2: input dataframe :param df1: template dataframe """ df3=pd.DataFrame() for idx,row in df1.iterrows(): df3=df3.append(df2.loc[idx,:]) return df3
java
@Override public ProjectFile read(InputStream stream) throws MPXJException { try { m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_calendarMap = new HashMap<Integer, ProjectCalendar>(); m_taskIdMap = new HashMap<Integer, Task>(); ProjectConfig config = m_projectFile.getProjectConfig(); config.setAutoResourceUniqueID(false); config.setAutoResourceID(false); m_projectFile.getProjectProperties().setFileApplication("ConceptDraw PROJECT"); m_projectFile.getProjectProperties().setFileType("CDP"); m_eventManager.addProjectListeners(m_projectListeners); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } Unmarshaller unmarshaller = CONTEXT.createUnmarshaller(); XMLFilter filter = new NamespaceFilter(); filter.setParent(xmlReader); UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); filter.setContentHandler(unmarshallerHandler); filter.parse(new InputSource(new InputStreamReader(stream))); Document cdp = (Document) unmarshallerHandler.getResult(); readProjectProperties(cdp); readCalendars(cdp); readResources(cdp); readTasks(cdp); readRelationships(cdp); // // Ensure that the unique ID counters are correct // config.updateUniqueCounters(); return m_projectFile; } catch (ParserConfigurationException ex) { throw new MPXJException("Failed to parse file", ex); } catch (JAXBException ex) { throw new MPXJException("Failed to parse file", ex); } catch (SAXException ex) { throw new MPXJException("Failed to parse file", ex); } catch (IOException ex) { throw new MPXJException("Failed to parse file", ex); } finally { m_projectFile = null; m_eventManager = null; m_projectListeners = null; m_calendarMap = null; m_taskIdMap = null; } }
java
public boolean returnReservedValues() throws FetchException, PersistException { synchronized (mStoredSequence) { if (mHasReservedValues) { Transaction txn = mRepository.enterTopTransaction(null); txn.setForUpdate(true); try { // Compare known StoredSequence with current persistent // one. If same, then reserved values can be returned. StoredSequence current = mStorage.prepare(); current.setName(mStoredSequence.getName()); if (current.tryLoad() && current.equals(mStoredSequence)) { mStoredSequence.setNextValue(mNextValue + mIncrement); mStoredSequence.update(); txn.commit(); mHasReservedValues = false; return true; } } finally { txn.exit(); } } } return false; }
java
public static CalendarMonth from(GregorianDate date) { PlainDate iso = PlainDate.from(date); // includes validation return CalendarMonth.of(iso.getYear(), iso.getMonth()); }
java
@InterfaceAudience.Private private void addValueEncryptionInfo(String path, String providerName, boolean escape) { if (escape) { path = path.replaceAll("~", "~0").replaceAll("/", "~1"); } if (this.encryptionPathInfo == null) { this.encryptionPathInfo = new HashMap<String, String>(); } this.encryptionPathInfo.put(path, providerName); }
java
public boolean sendMessage(WebSocketMessage<?> message) { boolean sentSuccessfully = false; if (sessions.isEmpty()) { LOG.warn("No Web Socket session exists - message cannot be sent"); } for (WebSocketSession session : sessions.values()) { if (session != null && session.isOpen()) { try { session.sendMessage(message); sentSuccessfully = true; } catch (IOException e) { LOG.error(String.format("(%s) error sending message", session.getId()), e); } } } return sentSuccessfully; }
java
public void marshall(KinesisDataStream kinesisDataStream, ProtocolMarshaller protocolMarshaller) { if (kinesisDataStream == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(kinesisDataStream.getArn(), ARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public void markAnnotation(String annotation, int lineno, int charno) { JSDocInfo.Marker marker = currentInfo.addMarker(); if (marker != null) { JSDocInfo.TrimmedStringPosition position = new JSDocInfo.TrimmedStringPosition(); position.setItem(annotation); position.setPositionInformation(lineno, charno, lineno, charno + annotation.length()); marker.setAnnotation(position); populated = true; } currentMarker = marker; }
python
async def self_check(cls): """ Check that the configuration is correct - Presence of "BERNARD_BASE_URL" in the global configuration - Presence of a "WEBVIEW_SECRET_KEY" """ async for check in super().self_check(): yield check s = cls.settings() if not hasattr(settings, 'BERNARD_BASE_URL'): yield HealthCheckFail( '00005', '"BERNARD_BASE_URL" cannot be found in the configuration. The' 'Telegram platform needs it because it uses it to ' 'automatically register its hook.' ) if not hasattr(settings, 'WEBVIEW_SECRET_KEY'): yield HealthCheckFail( '00005', '"WEBVIEW_SECRET_KEY" cannot be found in the configuration. ' 'It is required in order to be able to create secure postback ' 'URLs.' )
python
def add_extra_container(self, container, error_on_exists=False): """ Add a container as a 'extra'. These are running containers which are not necessary for running default CKAN but are useful for certain extensions :param container: The container name to add :param error_on_exists: Raise a DatacatsError if the extra container already exists. """ if container in self.extra_containers: if error_on_exists: raise DatacatsError('{} is already added as an extra container.'.format(container)) else: return self.extra_containers.append(container) cp = SafeConfigParser() cp.read(self.target + '/.datacats-environment') cp.set('datacats', 'extra_containers', ' '.join(self.extra_containers)) with open(self.target + '/.datacats-environment', 'w') as f: cp.write(f)
java
public boolean[] position(Range that){ boolean before = that.after(min); boolean after = that.before(max); boolean inside; if(before && after) inside = true; else if(!before && !after) inside = true; else if(before) inside = that.contains(max); else inside = that.contains(min); return new boolean[]{ before, inside, after }; }
python
def edit(request, translation): """ Edit a translation. @param request: Django HttpRequest object. @param translation: Translation id @return Django HttpResponse object with the view or a redirection. """ translation = get_object_or_404(FieldTranslation, id=translation) if request.method == 'POST': if "cancel" in request.POST: return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all"))) elif "save" in request.POST: form = FieldTranslationForm(request.POST, instance=translation) valid_form = form.is_valid() if valid_form: translation = form.save(commit=False) translation.context = u"Admin. Traducciones" translation.save() return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all"))) else: form = FieldTranslationForm(instance=translation) else: form = FieldTranslationForm(instance=translation) LANGUAGES = dict(lang for lang in settings.LANGUAGES) language = LANGUAGES[translation.lang] return render_to_response('modeltranslation/admin/edit_translation.html',{"translation":translation, "form":form, "lang":translation.lang, "language":language}, RequestContext(request))
python
def do_move(self, dt, buttons): """ Updates velocity and returns Rects for start/finish positions """ assert isinstance(dt, int) or isinstance(dt, float) assert isinstance(buttons, dict) newVel = self.velocity # Redirect existing vel to new direction. nv = newVel.magnitude() newVel = nv * self.impulse_dir mv = buttons['up'] if mv != 0: self.stats['battery'] -= self.battery_use['linear'] newVel += dt * mv * self.accel * self.impulse_dir else: brake = dt * self.deaccel if nv < brake: newVel *= 0 else: newVel += brake * -self.impulse_dir nv = newVel.magnitude() if nv > self.top_speed: newVel *= self.top_speed / nv return newVel
python
def wigner_d(J, alpha, beta, gamma): u"""Return the Wigner D matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.12. The simplest possible example: >>> from sympy import Integer, symbols, pprint >>> half = 1/Integer(2) >>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True) >>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True) ⎑ β…ˆβ‹…Ξ± β…ˆβ‹…Ξ³ β…ˆβ‹…Ξ± -β…ˆβ‹…Ξ³ ⎀ ⎒ ─── ─── ─── ───── βŽ₯ ⎒ 2 2 βŽ›Ξ²βŽž 2 2 βŽ›Ξ²βŽž βŽ₯ ⎒ β„― β‹…β„― β‹…cosβŽœβ”€βŽŸ β„― β‹…β„― β‹…sinβŽœβ”€βŽŸ βŽ₯ ⎒ ⎝2⎠ ⎝2⎠ βŽ₯ ⎒ βŽ₯ ⎒ -β…ˆβ‹…Ξ± β…ˆβ‹…Ξ³ -β…ˆβ‹…Ξ± -β…ˆβ‹…Ξ³ βŽ₯ ⎒ ───── ─── ───── ───── βŽ₯ ⎒ 2 2 βŽ›Ξ²βŽž 2 2 βŽ›Ξ²βŽžβŽ₯ ⎒-β„― β‹…β„― β‹…sinβŽœβ”€βŽŸ β„― β‹…β„― β‹…cosβŽœβ”€βŽŸβŽ₯ ⎣ ⎝2⎠ ⎝2⎠⎦ """ d = wigner_d_small(J, beta) M = [J-i for i in range(2*J+1)] D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma) for j, Mj in enumerate(M)] for i, Mi in enumerate(M)] return Matrix(D)
java
@Override public void disableTable(TableName tableName) throws IOException { TableName.isLegalFullyQualifiedTableName(tableName.getName()); if (!tableExists(tableName)) { throw new TableNotFoundException(tableName); } if (isTableDisabled(tableName)) { throw new TableNotEnabledException(tableName); } disabledTables.add(tableName); LOG.warn("Table " + tableName + " was disabled in memory only."); }
java
protected boolean isInside (int cross) { return (rule == WIND_NON_ZERO) ? Crossing.isInsideNonZero(cross) : Crossing.isInsideEvenOdd(cross); }
python
def put(url, data=None, **kwargs): """A wrapper for ``requests.put``. Sends a PUT request.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) _log_request('PUT', url, kwargs, data) response = requests.put(url, data, **kwargs) _log_response(response) return response
java
public java.util.List<FlowLog> getFlowLogs() { if (flowLogs == null) { flowLogs = new com.amazonaws.internal.SdkInternalList<FlowLog>(); } return flowLogs; }
python
def _setup_master(self): """ Construct a Router, Broker, and mitogen.unix listener """ self.broker = mitogen.master.Broker(install_watcher=False) self.router = mitogen.master.Router( broker=self.broker, max_message_size=4096 * 1048576, ) self._setup_responder(self.router.responder) mitogen.core.listen(self.broker, 'shutdown', self.on_broker_shutdown) mitogen.core.listen(self.broker, 'exit', self.on_broker_exit) self.listener = mitogen.unix.Listener( router=self.router, path=self.unix_listener_path, backlog=C.DEFAULT_FORKS, ) self._enable_router_debug() self._enable_stack_dumps()
python
def read_detections(fname): """ Read detections from a file to a list of Detection objects. :type fname: str :param fname: File to read from, must be a file written to by \ Detection.write. :returns: list of :class:`eqcorrscan.core.match_filter.Detection` :rtype: list .. note:: :class:`eqcorrscan.core.match_filter.Detection`'s returned do not contain Detection.event """ f = open(fname, 'r') detections = [] for index, line in enumerate(f): if index == 0: continue # Skip header if line.rstrip().split('; ')[0] == 'Template name': continue # Skip any repeated headers detection = line.rstrip().split('; ') detection[1] = UTCDateTime(detection[1]) detection[2] = int(float(detection[2])) detection[3] = ast.literal_eval(detection[3]) detection[4] = float(detection[4]) detection[5] = float(detection[5]) if len(detection) < 9: detection.extend(['Unset', float('NaN')]) else: detection[7] = float(detection[7]) detections.append(Detection( template_name=detection[0], detect_time=detection[1], no_chans=detection[2], detect_val=detection[4], threshold=detection[5], threshold_type=detection[6], threshold_input=detection[7], typeofdet=detection[8], chans=detection[3])) f.close() return detections
java
@Override public void elemAdd(MVec addend) { if (addend instanceof Tensor) { elemAdd((Tensor)addend); } else { throw new IllegalArgumentException("Addend must be of type " + this.getClass()); } }
python
def as_percent(self, percent): """ Return a string representing a percentage of this progress bar. BarSet('1234567890', wrapper=('[, ']')).as_percent(50) >>> '[12345 ]' """ if not self: return self.wrap_str() length = len(self) # Using mod 100, to provide some kind of "auto reset". 0 is 0 though. percentmod = (int(percent) % 100) or min(percent, 100) index = int((length / 100) * percentmod) try: barstr = str(self[index]) except IndexError: barstr = self[-1] return self.wrap_str(barstr)
python
async def can_run(self, ctx): """|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`.checks` attribute. Parameters ----------- ctx: :class:`.Context` The ctx of the command currently being invoked. Raises ------- :class:`CommandError` Any command error that was raised during a check call will be propagated by this function. Returns -------- :class:`bool` A boolean indicating if the command can be invoked. """ original = ctx.command ctx.command = self try: if not await ctx.bot.can_run(ctx): raise CheckFailure('The global check functions for command {0.qualified_name} failed.'.format(self)) cog = self.cog if cog is not None: local_check = Cog._get_overridden_method(cog.cog_check) if local_check is not None: ret = await discord.utils.maybe_coroutine(local_check, ctx) if not ret: return False predicates = self.checks if not predicates: # since we have no checks, then we just return True. return True return await discord.utils.async_all(predicate(ctx) for predicate in predicates) finally: ctx.command = original
java
public static File createOtherPlatformFile(File originalPlatform) { // calculate other platform sha1 for files larger than MAX_FILE_SIZE long length = originalPlatform.length(); if (length < MAX_FILE_SIZE && length < Runtime.getRuntime().freeMemory()) { try { byte[] byteArray = org.apache.commons.io.FileUtils.readFileToByteArray(originalPlatform); String fileText = new String(byteArray); File otherPlatformFile = new File(FileHandler.PATH_TO_PLATFORM_DEPENDENT_TMP_DIR, originalPlatform.getName()); if (fileText.contains(CRLF)) { org.apache.commons.io.FileUtils.write(otherPlatformFile, fileText.replaceAll(CRLF, NEW_LINE)); } else if (fileText.contains(NEW_LINE)) { org.apache.commons.io.FileUtils.write(otherPlatformFile, fileText.replaceAll(NEW_LINE, CRLF)); } if (otherPlatformFile.exists()) { return otherPlatformFile; } } catch (IOException e) { return null; } } return null; }
python
def grant_role(self, principal, role, obj=None): """Grant `role` to `user` (either globally, if `obj` is None, or on the specific `obj`).""" assert principal principal = unwrap(principal) session = object_session(obj) if obj is not None else db.session manager = self._current_user_manager(session=session) args = { "role": role, "object": obj, "anonymous": False, "user": None, "group": None, } if principal is AnonymousRole or ( hasattr(principal, "is_anonymous") and principal.is_anonymous ): args["anonymous"] = True elif isinstance(principal, User): args["user"] = principal else: args["group"] = principal query = session.query(RoleAssignment) if query.filter_by(**args).limit(1).count(): # role already granted, nothing to do return # same as above but in current, not yet flushed objects in session. We # cannot call flush() in grant_role() since this method may be called a # great number of times in the same transaction, and sqlalchemy limits # to 100 flushes before triggering a warning for ra in ( o for models in (session.new, session.dirty) for o in models if isinstance(o, RoleAssignment) ): if all(getattr(ra, attr) == val for attr, val in args.items()): return ra = RoleAssignment(**args) session.add(ra) audit = SecurityAudit(manager=manager, op=SecurityAudit.GRANT, **args) if obj is not None: audit.object_id = obj.id audit.object_type = obj.entity_type object_name = "" for attr_name in ("name", "path", "__path_before_delete"): if hasattr(obj, attr_name): object_name = getattr(obj, attr_name) audit.object_name = object_name session.add(audit) self._needs_flush() if hasattr(principal, "__roles_cache__"): del principal.__roles_cache__
python
def batched(iterable, size): """ Split an iterable into constant sized chunks Recipe from http://stackoverflow.com/a/8290514 """ length = len(iterable) for batch_start in range(0, length, size): yield iterable[batch_start:batch_start+size]
python
def write_code(self, name, code): """ Writes code to a python file called 'name', erasing the previous contents. Files are created in a directory specified by gen_dir_name (see function gen_file_path) File name is second argument of path """ file_path = self.gen_file_path(name) with open(file_path,'w') as f: f.write(code)
java
private void reflect(int v, IBond bond) { visited[v] = true; IAtom atom = container.getAtom(v); atom.setPoint2d(reflect(atom.getPoint2d(), bond)); for (int w : graph[v]) { if (!visited[w]) reflect(w, bond); } }
java
public static <C> AsmClassAccess<C> get(Class<C> clazz) { @SuppressWarnings("unchecked") AsmClassAccess<C> access = (AsmClassAccess<C>) CLASS_ACCESSES.get(clazz); if (access != null) { return access; } Class<?> enclosingType = clazz.getEnclosingClass(); final boolean isNonStaticMemberClass = determineNonStaticMemberClass(clazz, enclosingType); String clazzName = clazz.getName(); Field[] fields = ClassUtils.collectInstanceFields(clazz, false, false, true); Method[] methods = ClassUtils.collectMethods(clazz); String accessClassName = constructAccessClassName(clazzName); Class<?> accessClass = null; AccessClassLoader loader = AccessClassLoader.get(clazz); synchronized (loader) { try { accessClass = loader.loadClass(accessClassName); } catch (ClassNotFoundException ignored) { String accessClassNm = accessClassName.replace('.', '/'); String clazzNm = clazzName.replace('.', '/'); String enclosingClassNm = determineEnclosingClassNm(clazz, enclosingType, isNonStaticMemberClass); String signatureString = "L" + ASM_CLASS_ACCESS_NM + "<L" + clazzNm + ";>;L" + CLASS_ACCESS_NM + "<L" + clazzNm + ";>;"; ClassWriter cw = new ClassWriter(0); // TraceClassVisitor tcv = new TraceClassVisitor(cv, new PrintWriter(System.err)); // CheckClassAdapter cw = new CheckClassAdapter(tcv); cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, accessClassNm, signatureString, ASM_CLASS_ACCESS_NM, null); enhanceForConstructor(cw, accessClassNm, clazzNm); if (isNonStaticMemberClass) { enhanceForNewInstanceInner(cw, clazzNm, enclosingClassNm); } else { enhanceForNewInstance(cw, clazzNm); } enhanceForGetValueObject(cw, accessClassNm, clazzNm, fields); enhanceForPutValueObject(cw, accessClassNm, clazzNm, fields); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.BOOLEAN_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.BOOLEAN_TYPE); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.BYTE_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.BYTE_TYPE); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.SHORT_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.SHORT_TYPE); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.INT_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.INT_TYPE); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.LONG_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.LONG_TYPE); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.DOUBLE_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.DOUBLE_TYPE); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.FLOAT_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.FLOAT_TYPE); enhanceForGetValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.CHAR_TYPE); enhanceForPutValuePrimitive(cw, accessClassNm, clazzNm, fields, Type.CHAR_TYPE); enhanceForInvokeMethod(cw, accessClassNm, clazzNm, methods); cw.visitEnd(); loader.registerClass(accessClassName, cw.toByteArray()); try { accessClass = loader.findClass(accessClassName); } catch (ClassNotFoundException e) { throw new IllegalStateException("AccessClass unexpectedly could not be found", e); } } } try { @SuppressWarnings("unchecked") Constructor<AsmClassAccess<C>> c = (Constructor<AsmClassAccess<C>>) accessClass.getConstructor(new Class[] { Class.class }); access = c.newInstance(clazz); access.isNonStaticMemberClass = isNonStaticMemberClass; CLASS_ACCESSES.putIfAbsent(clazz, access); return access; } catch (Exception ex) { throw new RuntimeException("Error constructing constructor access class: " + accessClassName + "{ " + ex.getMessage() + " }", ex); } }
python
def pyc2py(filename): """ Find corresponding .py name given a .pyc or .pyo """ if re.match(".*py[co]$", filename): if PYTHON3: return re.sub(r'(.*)__pycache__/(.+)\.cpython-%s.py[co]$' % PYVER, '\\1\\2.py', filename) else: return filename[:-1] return filename
python
def required_unique(objects, key): """ A pyrsistent invariant which requires all objects in the given iterable to have a unique key. :param objects: The objects to check. :param key: A one-argument callable to compute the key of an object. :return: An invariant failure if any two or more objects have the same key computed. An invariant success otherwise. """ keys = {} duplicate = set() for k in map(key, objects): keys[k] = keys.get(k, 0) + 1 if keys[k] > 1: duplicate.add(k) if duplicate: return (False, u"Duplicate object keys: {}".format(duplicate)) return (True, u"")
python
def get_right_word(self, cursor=None): """ Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor. """ if cursor is None: cursor = self._editor.textCursor() cursor.movePosition(QtGui.QTextCursor.WordRight, QtGui.QTextCursor.KeepAnchor) return cursor.selectedText().strip()
java
public boolean isDependentOn(String propertyName) { boolean dependent = false; if( getConstraint() instanceof PropertyConstraint ) { dependent = ((PropertyConstraint) getConstraint()).isDependentOn( propertyName ); } return super.isDependentOn( propertyName ) || dependent; }
python
def pop(self): """ Removes the last node from the list """ popped = False result = None current_node = self._first_node while not popped: next_node = current_node.next() next_next_node = next_node.next() if not next_next_node: self._last_node = current_node self._last_node.update_next(None) self._size -= 1 result = next_node.data() popped = True current_node = next_node return result
python
def _get_resource_raw( self, cls, id, extra=None, headers=None, stream=False, **filters ): """Get an individual REST resource""" headers = headers or {} headers.update(self.session.headers) postfix = "/{}".format(extra) if extra else "" if cls.api_root != "a": url = "{}/{}/{}{}".format(self.api_server, cls.collection_name, id, postfix) else: url = "{}/a/{}/{}/{}{}".format( self.api_server, self.app_id, cls.collection_name, id, postfix ) converted_filters = convert_datetimes_to_timestamps( filters, cls.datetime_filter_attrs ) url = str(URLObject(url).add_query_params(converted_filters.items())) response = self._get_http_session(cls.api_root).get( url, headers=headers, stream=stream ) return _validate(response)
python
def column_spec_path(cls, project, location, dataset, table_spec, column_spec): """Return a fully-qualified column_spec string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}", project=project, location=location, dataset=dataset, table_spec=table_spec, column_spec=column_spec, )
java
@Override public void stop() { threadPoolExecutor.shutdown(); BlockingQueue<Runnable> taskQueue = threadPoolExecutor.getQueue(); int bufferSizeBeforeShutdown = threadPoolExecutor.getQueue().size(); boolean gracefulShutdown = true; try { gracefulShutdown = threadPoolExecutor.awaitTermination(shutdownTimeout, TimeUnit.SECONDS); } catch(InterruptedException e) { // we are anyways cleaning up } finally { int bufferSizeAfterShutdown = taskQueue.size(); if(!gracefulShutdown || bufferSizeAfterShutdown > 0) { String errorMsg = "Kinesis Log4J Appender (" + name + ") waited for " + shutdownTimeout + " seconds before terminating but could send only " + (bufferSizeAfterShutdown - bufferSizeBeforeShutdown) + " logevents, it failed to send " + bufferSizeAfterShutdown + " pending log events from it's processing queue"; addError(errorMsg); } } client.shutdown(); }
java
@Override public CommerceAccountUserRel[] findByCommerceAccountId_PrevAndNext( CommerceAccountUserRelPK commerceAccountUserRelPK, long commerceAccountId, OrderByComparator<CommerceAccountUserRel> orderByComparator) throws NoSuchAccountUserRelException { CommerceAccountUserRel commerceAccountUserRel = findByPrimaryKey(commerceAccountUserRelPK); Session session = null; try { session = openSession(); CommerceAccountUserRel[] array = new CommerceAccountUserRelImpl[3]; array[0] = getByCommerceAccountId_PrevAndNext(session, commerceAccountUserRel, commerceAccountId, orderByComparator, true); array[1] = commerceAccountUserRel; array[2] = getByCommerceAccountId_PrevAndNext(session, commerceAccountUserRel, commerceAccountId, orderByComparator, false); return array; } catch (Exception e) { throw processException(e); } finally { closeSession(session); } }
python
def current_length(self): # type: () -> int ''' Calculate the current length of this symlink record. Parameters: None. Returns: Length of this symlink record. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError('SL record not yet initialized!') strlist = [] for comp in self.symlink_components: strlist.append(comp.name()) return RRSLRecord.length(strlist)
java
private <T> T getTyped(PropertyKey key, Class<T> clazz) { Property p = getProperty(key.m_key); if (null == p || null == p.getData()) { return clazz.cast(m_defaults.get(key)); } return clazz.cast(p.getData()); }
java
@NonNull public static PaymentIntentParams createConfirmPaymentIntentWithSourceDataParams( @Nullable SourceParams sourceParams, @NonNull String clientSecret, @NonNull String returnUrl, boolean savePaymentMethod) { return new PaymentIntentParams() .setSourceParams(sourceParams) .setClientSecret(clientSecret) .setReturnUrl(returnUrl) .setSavePaymentMethod(savePaymentMethod); }
java
public void setSharedAwsAccountIds(java.util.Collection<String> sharedAwsAccountIds) { if (sharedAwsAccountIds == null) { this.sharedAwsAccountIds = null; return; } this.sharedAwsAccountIds = new java.util.ArrayList<String>(sharedAwsAccountIds); }
python
def process_runway_configs(runway_dir=''): """Read the _application.json_ files. Args: runway_dir (str): Name of runway directory with app.json files. Returns: collections.defaultdict: Configurations stored for each environment found. """ LOG.info('Processing application.json files from local directory "%s".', runway_dir) file_lookup = FileLookup(runway_dir=runway_dir) app_configs = process_configs(file_lookup, 'application-master-{env}.json', 'pipeline.json') return app_configs
python
def parse_subdomain_record(domain_name, rec, block_height, parent_zonefile_hash, parent_zonefile_index, zonefile_offset, txid, domain_zonefiles_missing, resolver=None): """ Parse a subdomain record, and verify its signature. @domain_name: the stem name @rec: the parsed zone file, with 'txt' records Returns a Subdomain object on success Raises an exception on parse error """ # sanity check: need 'txt' record list txt_entry = rec['txt'] if not isinstance(txt_entry, list): raise ParseError("Tried to parse a TXT record with only a single <character-string>") entries = {} # parts of the subdomain record for item in txt_entry: # coerce string if isinstance(item, unicode): item = str(item) key, value = item.split('=', 1) value = value.replace('\\=', '=') # escape '=' if key in entries: raise ParseError("Duplicate TXT entry '{}'".format(key)) entries[key] = value pubkey = entries[SUBDOMAIN_PUBKEY] n = entries[SUBDOMAIN_N] if SUBDOMAIN_SIG in entries: sig = entries[SUBDOMAIN_SIG] else: sig = None try: zonefile_parts = int(entries[SUBDOMAIN_ZF_PARTS]) except ValueError: raise ParseError("Not an int (SUBDOMAIN_ZF_PARTS)") try: n = int(n) except ValueError: raise ParseError("Not an int (SUBDOMAIN_N)") b64_zonefile = "".join([entries[SUBDOMAIN_ZF_PIECE % zf_index] for zf_index in range(zonefile_parts)]) is_subdomain, _, _ = is_address_subdomain(rec['name']) subd_name = None if not is_subdomain: # not a fully-qualified subdomain, which means it ends with this domain name try: assert is_name_valid(str(domain_name)), domain_name subd_name = str(rec['name'] + '.' + domain_name) assert is_address_subdomain(subd_name)[0], subd_name except AssertionError as ae: if BLOCKSTACK_DEBUG: log.exception(ae) raise ParseError("Invalid names: {}".format(ae)) else: # already fully-qualified subd_name = rec['name'] return Subdomain(str(subd_name), str(domain_name), str(pubkey), int(n), base64.b64decode(b64_zonefile), str(sig), block_height, parent_zonefile_hash, parent_zonefile_index, zonefile_offset, txid, domain_zonefiles_missing=domain_zonefiles_missing, resolver=resolver)
java
protected void startOutgoingConnection (final Connection conn, InetSocketAddress addr) { final SocketChannel sockchan = conn.getChannel(); try { // register our channel with the selector (if this fails, we abandon ship immediately) conn.selkey = sockchan.register(_selector, SelectionKey.OP_CONNECT); // start our connection process (now if we fail we need to clean things up) NetEventHandler handler; if (sockchan.connect(addr)) { _outConnValidator.validateOutgoing(sockchan); // may throw // it is possible even for a non-blocking socket to connect immediately, in which // case we stick the connection in as its event handler immediately handler = conn; } else { // otherwise we wire up a special event handler that will wait for our socket to // finish the connection process and then wire things up fully handler = new OutgoingConnectionHandler(conn); } _handlers.put(conn.selkey, handler); } catch (IOException ioe) { log.warning("Failed to initiate connection for " + sockchan + ".", ioe); conn.connectFailure(ioe); // nothing else to clean up } }
python
def plot_weights(self, index=None, plot_type="motif_raw", figsize=None, ncol=1, **kwargs): """Plot filters as heatmap or motifs index = can be a particular index or a list of indicies **kwargs - additional arguments to concise.utils.plot.heatmap """ if "heatmap" in self.AVAILABLE_PLOTS and plot_type == "heatmap": return self._plot_weights_heatmap(index=index, figsize=figsize, ncol=ncol, **kwargs) elif plot_type[:5] == "motif": return self._plot_weights_motif(index=index, plot_type=plot_type, figsize=figsize, ncol=ncol, **kwargs) else: raise ValueError("plot_type needs to be from {0}".format(self.AVAILABLE_PLOTS))
java
private Node getParent(Node n) { if (n.y_s == null) { return null; } Node c = n.y_s; if (c.o_c == n) { return c; } Node p1 = c.y_s; if (p1 != null && p1.o_c == n) { return p1; } return c; }
python
def get_password(config): """Returns the password for a remote server It tries to fetch the password from the following locations in this order: 1. config file [remote] section, password option 2. GNOME keyring 3. interactively, from the user """ password = config.get_option('remote.password') if password == '': user = config.get_option('remote.user') url = config.get_option('remote.url') url_obj = urlparse.urlparse(url) server = url_obj.hostname protocol = url_obj.scheme if HAS_GNOME_KEYRING_SUPPORT: password = get_password_from_gnome_keyring(user, server, protocol) else: prompt = 'Enter %s password for %s at %s: ' % (get_app(), user, server) password = getpass.getpass(prompt) return password
java
public void marshall(ProvisioningArtifactParameter provisioningArtifactParameter, ProtocolMarshaller protocolMarshaller) { if (provisioningArtifactParameter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(provisioningArtifactParameter.getParameterKey(), PARAMETERKEY_BINDING); protocolMarshaller.marshall(provisioningArtifactParameter.getDefaultValue(), DEFAULTVALUE_BINDING); protocolMarshaller.marshall(provisioningArtifactParameter.getParameterType(), PARAMETERTYPE_BINDING); protocolMarshaller.marshall(provisioningArtifactParameter.getIsNoEcho(), ISNOECHO_BINDING); protocolMarshaller.marshall(provisioningArtifactParameter.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(provisioningArtifactParameter.getParameterConstraints(), PARAMETERCONSTRAINTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public static WarInfo getWarInfo(File war) throws Exception { WarInfo info = new WarInfo(); info.setWarName(war.getName()); CadmiumWar warHelper = null; try { if(war != null && war.exists()) { warHelper = new FileBasedCadmiumWar(war); } else { warHelper = new ClasspathCadmiumWar(); } getDeploymentInfo(info, warHelper); getCadmiumInfo(info, warHelper); getArtifactInfo(info, warHelper); } finally { IOUtils.closeQuietly(warHelper); } return info; }
java
protected boolean isIntegerType(byte type) { return type == Const.T_INT || type == Const.T_BYTE || type == Const.T_BOOLEAN || type == Const.T_CHAR || type == Const.T_SHORT; }
java
public void mergeVertexDescription(VertexDescription src) { _touch(); if (src == m_description) return; // check if we need to do anything (if the src has same attributes) VertexDescription newdescription = VertexDescriptionDesignerImpl.getMergedVertexDescription(m_description, src); if (newdescription == m_description) return; _assignVertexDescriptionImpl(newdescription); }
python
def log(*texts, sep = ""): """Log a text.""" text = sep.join(texts) count = text.count("\n") just_log("\n" * count, *get_time(), text.replace("\n", ""), sep=sep)
java
public void addCACertificatesToTrustStore(BufferedInputStream bis) throws CryptoException, InvalidArgumentException { if (bis == null) { throw new InvalidArgumentException("The certificate stream bis cannot be null"); } try { final Collection<? extends Certificate> certificates = cf.generateCertificates(bis); for (Certificate certificate : certificates) { addCACertificateToTrustStore(certificate); } } catch (CertificateException e) { throw new CryptoException("Unable to add CA certificate to trust store. Error: " + e.getMessage(), e); } }
java
public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) { return openOrCreateDatabase(file.getPath(), factory); }
java
@Deprecated public final T parse(CharSequence source, String moduleName) { return new ScannerState(moduleName, source, 0, new SourceLocator(source)) .run(followedBy(Parsers.EOF)); }
java
public static void callStringBuilderLength(CodeBuilder b) { // Because of JDK1.5 bug which exposes AbstractStringBuilder class, // cannot use reflection to get method signature. TypeDesc stringBuilder = TypeDesc.forClass(StringBuilder.class); b.invokeVirtual(stringBuilder, "length", TypeDesc.INT, null); }
java
public static boolean startsWithPattern( final byte[] byteArray, final byte[] pattern) { Preconditions.checkNotNull(byteArray); Preconditions.checkNotNull(pattern); if (pattern.length > byteArray.length) { return false; } for (int i = 0; i < pattern.length; ++i) { if (byteArray[i] != pattern[i]) { return false; } } return true; }
java
public final void reset() { for (int i = 0; i < combinationIndices.length; i++) { combinationIndices[i] = i; } remainingCombinations = totalCombinations; }
python
def get_seaborn_colorbar(dfr, classes): """Return a colorbar representing classes, for a Seaborn plot. The aim is to get a pd.Series for the passed dataframe columns, in the form: 0 colour for class in col 0 1 colour for class in col 1 ... colour for class in col ... n colour for class in col n """ levels = sorted(list(set(classes.values()))) paldict = { lvl: pal for (lvl, pal) in zip( levels, sns.cubehelix_palette( len(levels), light=0.9, dark=0.1, reverse=True, start=1, rot=-2 ), ) } lvl_pal = {cls: paldict[lvl] for (cls, lvl) in list(classes.items())} col_cb = pd.Series(dfr.index).map(lvl_pal) # The col_cb Series index now has to match the dfr.index, but # we don't create the Series with this (and if we try, it # fails) - so change it with this line col_cb.index = dfr.index return col_cb
java
public void marshall(SourceAlgorithmSpecification sourceAlgorithmSpecification, ProtocolMarshaller protocolMarshaller) { if (sourceAlgorithmSpecification == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(sourceAlgorithmSpecification.getSourceAlgorithms(), SOURCEALGORITHMS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public static RedwoodConfiguration parse(Properties props){ Set<String> used = new HashSet<String>(); //--Construct Pipeline //(handlers) Redwood.ConsoleHandler console = get(props,"log.toStderr","false",used).equalsIgnoreCase("true") ? Redwood.ConsoleHandler.err() : Redwood.ConsoleHandler.out(); VisibilityHandler visibility = new VisibilityHandler(); RepeatedRecordHandler repeat = null; //(initialize pipeline) RedwoodConfiguration config = new RedwoodConfiguration().clear().rootHandler(visibility); //(collapse) String collapseSetting = get(props,"log.collapse","none",used); if(collapseSetting.equalsIgnoreCase("exact")){ repeat = new RepeatedRecordHandler(RepeatedRecordHandler.EXACT); config = config.handler(visibility,repeat); } else if(collapseSetting.equalsIgnoreCase("approximate")){ repeat = new RepeatedRecordHandler(RepeatedRecordHandler.APPROXIMATE); config = config.handler(visibility, repeat); } else if(collapseSetting.equalsIgnoreCase("none")){ //do nothing } else { throw new IllegalArgumentException("Unknown collapse type: " + collapseSetting); } //--Console config.handler(repeat == null ? visibility : repeat, console); //((track color)) console.trackColor = Color.valueOf(get(props,"log.console.trackColor","NONE",used).toUpperCase()); console.trackStyle = Style.valueOf(get(props,"log.console.trackStyle","NONE",used).toUpperCase()); //((other colors)) for(Object propAsObj : props.keySet()) { String prop = propAsObj.toString(); // color Matcher m = consoleColor.matcher(prop); if(m.find()){ String channel = m.group(1); console.colorChannel(channel, Color.valueOf(get(props,prop,"NONE",used))); } // style m = consoleStyle.matcher(prop); if(m.find()){ String channel = m.group(1); console.styleChannel(channel, Style.valueOf(get(props,prop,"NONE",used))); } } //((random colors)) console.setColorChannels(Boolean.parseBoolean(get(props, "log.console.colorChannels", "false", used))); //--File String logFilename = get(props,"log.file",null,used); if(logFilename != null){ Redwood.FileHandler file = new Redwood.FileHandler(logFilename); config.handler(repeat == null ? visibility : repeat, file); //((track colors)) file.trackColor = Color.valueOf(get(props,"log.file.trackColor","NONE",used).toUpperCase()); file.trackStyle = Style.valueOf(get(props,"log.file.trackStyle","NONE",used).toUpperCase()); //((other colors)) for(Object propAsObj : props.keySet()) { String prop = propAsObj.toString(); // color Matcher m = fileColor.matcher(prop); if(m.find()){ String channel = m.group(1); file.colorChannel(channel, Color.valueOf(get(props,prop,"NONE",used))); } // style m = fileStyle.matcher(prop); if(m.find()){ String channel = m.group(1); file.styleChannel(channel, Style.valueOf(get(props,prop,"NONE",used))); } } //((random colors)) file.setColorChannels(Boolean.parseBoolean(get(props,"log.file.colorChannels","false",used))); } //--System Streams if(get(props,"log.captureStreams","false",used).equalsIgnoreCase("true")){ config = config.captureStreams(); } if(get(props,"log.captureStdout","false",used).equalsIgnoreCase("true")){ config = config.captureStdout(); } if(get(props,"log.captureStderr","false",used).equalsIgnoreCase("true")){ config = config.captureStderr(); } //--Neat exit if(get(props,"log.neatExit","false",used).equalsIgnoreCase("true")){ config = config.neatExit(); } String channelsToShow = get(props,"log.showOnlyChannels",null,used); String channelsToHide = get(props,"log.hideChannels",null,used); if (channelsToShow != null && channelsToHide != null) { throw new IllegalArgumentException("Can't specify both log.showOnlyChannels and log.hideChannels"); } //--Channel visibility if (channelsToShow != null) { config = config.showOnlyChannels(channelsToShow.split(",")); } else if (channelsToHide != null) { config = config.hideChannels(channelsToHide.split(",")); } //--Error Check for(Object propAsObj : props.keySet()) { String prop = propAsObj.toString(); if(prop.startsWith("log.") && !used.contains(prop)){ throw new IllegalArgumentException("Could not find Redwood log property: " + prop); } } //--Return return config; }
java
public void init(Range annotation, PropertyMetadata propertyMetadata) { m_maxExclusive = getValue(annotation.maxExclusive()); m_minExclusive = getValue(annotation.minExclusive()); m_maxInclusive = getValue(annotation.maxInclusive()); m_minInclusive = getValue(annotation.minInclusive()); m_maxExclusiveMessage = annotation.maxExclusiveMessage(); m_minExclusiveMessage = annotation.minExclusiveMessage(); m_maxInclusiveMessage = annotation.maxInclusiveMessage(); m_minInclusiveMessage = annotation.minInclusiveMessage(); m_propertyMetadata = propertyMetadata; }
python
def standings(self, league_table, league): """Store output of league standings to a JSON file""" data = [] for team in league_table['standings'][0]['table']: item = {'position': team['position'], 'teamName': team['team'], 'playedGames': team['playedGames'], 'goalsFor': team['goalsFor'], 'goalsAgainst': team['goalsAgainst'], 'goalDifference': team['goalDifference'], 'points': team['points']} data.append(item) self.generate_output({'standings': data})
python
def _get_parameters_from_request(self, request, exception=False): """Get parameters to log in OPERATION_LOG.""" user = request.user referer_url = None try: referer_dic = urlparse.urlsplit( urlparse.unquote(request.META.get('HTTP_REFERER'))) referer_url = referer_dic[2] if referer_dic[3]: referer_url += "?" + referer_dic[3] if isinstance(referer_url, str): referer_url = referer_url.decode('utf-8') except Exception: pass request_url = urlparse.unquote(request.path) if request.META['QUERY_STRING']: request_url += '?' + request.META['QUERY_STRING'] return { 'client_ip': request.META.get('REMOTE_ADDR', None), 'domain_name': getattr(user, 'domain_name', None), 'domain_id': getattr(user, 'domain_id', None), 'project_name': getattr(user, 'project_name', None), 'project_id': getattr(user, 'project_id', None), 'user_name': getattr(user, 'username', None), 'user_id': request.session.get('user_id', None), 'request_scheme': request.scheme, 'referer_url': referer_url, 'request_url': request_url, 'method': request.method if not exception else None, 'param': self._get_request_param(request), }
python
def prepare_handler(cfg): """ Load all files into single object. """ positions, velocities, box = None, None, None _path = cfg.get('_path', './') forcefield = cfg.pop('forcefield', None) topology_args = sanitize_args_for_file(cfg.pop('topology'), _path) if 'checkpoint' in cfg: restart_args = sanitize_args_for_file(cfg.pop('checkpoint'), _path) restart = Restart.load(*restart_args) positions = restart.positions velocities = restart.velocities box = restart.box if 'positions' in cfg: positions_args = sanitize_args_for_file(cfg.pop('positions'), _path) positions = Positions.load(*positions_args) box = BoxVectors.load(*positions_args) if 'velocities' in cfg: velocities_args = sanitize_args_for_file(cfg.pop('velocities'), _path) velocities = Velocities.load(*velocities_args) if 'box' in cfg: box_args = sanitize_args_for_file(cfg.pop('box'), _path) box = BoxVectors.load(*box_args) options = {} for key in 'positions velocities box forcefield'.split(): value = locals()[key] if value is not None: options[key] = value return SystemHandler.load(*topology_args, **options)