answer
stringlengths
15
1.25M
// GLFW - An OpenGL framework // Platform: Any // This software is provided 'as-is', without any express or implied // arising from the use of this software. // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // 3. This notice may not be removed or altered from any source // distribution. // Description: // This module acts as an interface for different image file formats (the // image file format is detected automatically). // By default the loaded image is rescaled (using bilinear interpolation) // to the next higher 2^N x 2^M resolution, unless it has a valid // 2^N x 2^M resolution. The interpolation is quite slow, even if the // routine has been optimized for speed (a 200x200 RGB image is scaled to // 256x256 in ~30 ms on a P3-500). // Paletted images are converted to RGB/RGBA images. // A convenience function is also included (glfwLoadTexture2D), which // loads a texture image from a file directly to OpenGL texture memory, // with an option to generate all mipmap levels. <API key> // is used whenever available, which should give an optimal mipmap // generation speed (possibly performed in hardware). A software fallback // method is included when <API key> is not supported (it // generates all mipmaps of a 256x256 RGB texture in ~3 ms on a P3-500). #include "internal.h" // We want to support automatic mipmap generation #ifndef <API key> #define <API key> 0x8191 #define <API key> 0x8192 #define <API key> 1 #endif // <API key>
module Main where import Graphics.Gnuplot.Simple -- import qualified Graphics.Gnuplot.Terminal.WXT as WXT -- import qualified Graphics.Gnuplot.Terminal.PostScript as PS ops :: [Attribute] -- ops = [(Custom "term" ["postscript", "eps", "enhanced", "color", "solid"]) -- ,(Custom "output" ["temp.eps"]) -- ops = [(terminal $ WXT.persist WXT.cons)] -- ops = [(EPS "temp.eps")] ops = [(PNG "temp.png")] main :: IO () main = do let xs = (linearScale 1000 (0,2*pi)) :: [Double] ys = fmap sin xs points = zip xs ys plotPath ops points
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.one_string.label.xml Template File: sources-sink-66a.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: console Read input from the console * GoodSource: Fixed string * Sinks: popen * BadSink : Execute command in data using popen() * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define FULL_COMMAND "dir " #else #include <unistd.h> #define FULL_COMMAND "ls " #endif /* define POPEN as _popen on Windows and popen otherwise */ #ifdef _WIN32 #define POPEN _popen #define PCLOSE _pclose #else /* NOT _WIN32 */ #define POPEN popen #define PCLOSE pclose #endif #ifndef OMITBAD /* bad function declaration */ void <API key>(char * dataArray[]); void <API key>() { char * data; char * dataArray[5]; char data_buf[100] = FULL_COMMAND; data = data_buf; { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } /* put data in array */ dataArray[2] = data; <API key>(dataArray); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void <API key>(char * dataArray[]); static void goodG2B() { char * data; char * dataArray[5]; char data_buf[100] = FULL_COMMAND; data = data_buf; /* FIX: Append a fixed string to data (not user / external input) */ strcat(data, "*.*"); dataArray[2] = data; <API key>(dataArray); } void <API key>() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
@keyframes linearKeyframes { 0% { background-position: 0; } 100% { background-position: -200%; } } .created-details { display: grid; text-align: right; margin-right: 1vh; align-items: center; } .created-details.loading { height: 100%; width: 100%; box-shadow: none; background: linear-gradient(to left, rgba(166, 158, 157, 0.3) 0%, #E7E2DA 50%, rgba(166, 158, 157, 0.3) 100%); background-size: 200%; animation: linearKeyframes 2s infinite; <API key>: linear; } /*# sourceMappingURL=styles.css.map */
from sklearn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("SGDClassifier" , "iris" , "oracle")
<aside class="main-sidebar"> <section class="sidebar"> <?php $user = app('auth')->user(); ?> @if (! is_null($user)) <div class="user-panel"> <div class="pull-left image"> <img src="{{ app('orchestra.avatar')->user($user) }}" class="img-circle" alt="User Image" /> </div> <div class="pull-left info"> <p>{{ $user->fullname }}</p> <a href="{{ handles('orchestra::account') }}"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> @endif @include('orchestra/foundation::layouts.main._menu', ['menu' => app('orchestra.platform.menu')]) </section> </aside>
#include "config.h" #include "modules/cachestorage/CacheStorage.h" #include "bindings/core/v8/<API key>.h" #include "bindings/core/v8/ScriptState.h" #include "core/dom/DOMException.h" #include "core/dom/ExceptionCode.h" #include "modules/cachestorage/CacheStorageError.h" #include "modules/fetch/Request.h" #include "modules/fetch/Response.h" #include "public/platform/<API key>.h" #include "public/platform/<API key>.h" namespace blink { namespace { DOMException* <API key>() { return DOMException::create(NotSupportedError, "No CacheStorage implementation provided."); } bool commonChecks(ScriptState* scriptState, ExceptionState& exceptionState) { ExecutionContext* executionContext = scriptState->executionContext(); if (!executionContext) return false; String errorMessage; if (!executionContext->isPrivilegedContext(errorMessage)) { exceptionState.throwSecurityError(errorMessage); return false; } return true; } } // FIXME: Consider using <API key>. class CacheStorage::Callbacks final : public <API key>::<API key> { <API key>(Callbacks); public: explicit Callbacks(<API key>* resolver) : m_resolver(resolver) { } ~Callbacks() override { } void onSuccess() override { if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; m_resolver->resolve(true); m_resolver.clear(); } // Ownership of |rawReason| must be passed. void onError(<API key>* rawReason) override { OwnPtr<<API key>> reason = adoptPtr(rawReason); if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; if (*reason == <API key>) m_resolver->resolve(false); else m_resolver->reject(CacheStorageError::createException(*reason)); m_resolver.clear(); } private: Persistent<<API key>> m_resolver; }; // FIXME: Consider using <API key>. class CacheStorage::WithCacheCallbacks final : public <API key>::<API key> { <API key>(WithCacheCallbacks); public: WithCacheCallbacks(const String& cacheName, CacheStorage* cacheStorage, <API key>* resolver) : m_cacheName(cacheName), m_cacheStorage(cacheStorage), m_resolver(resolver) { } ~WithCacheCallbacks() override { } // Ownership of |rawWebCache| must be passed. void onSuccess(<API key>* rawWebCache) override { OwnPtr<<API key>> webCache = adoptPtr(rawWebCache); if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; // FIXME: Remove this once content's <API key> implementation has landed. if (!webCache) { m_resolver->reject("not implemented"); return; } Cache* cache = Cache::create(m_cacheStorage->m_scopedFetcher, webCache.release()); m_cacheStorage->m_nameToCacheMap.set(m_cacheName, cache); m_resolver->resolve(cache); m_resolver.clear(); } // Ownership of |rawReason| must be passed. void onError(<API key>* rawReason) override { OwnPtr<<API key>> reason = adoptPtr(rawReason); if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; if (*reason == <API key>) m_resolver->resolve(); else m_resolver->reject(CacheStorageError::createException(*reason)); m_resolver.clear(); } private: String m_cacheName; Persistent<CacheStorage> m_cacheStorage; Persistent<<API key>> m_resolver; }; // FIXME: Consider using <API key>. class CacheStorage::MatchCallbacks : public <API key>::<API key> { <API key>(MatchCallbacks); public: explicit MatchCallbacks(<API key>* resolver) : m_resolver(resolver) { } void onSuccess(<API key>* webResponse) override { if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; m_resolver->resolve(Response::create(m_resolver->scriptState()->executionContext(), *webResponse)); m_resolver.clear(); } // Ownership of |rawReason| must be passed. void onError(<API key>* rawReason) override { OwnPtr<<API key>> reason = adoptPtr(rawReason); if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; if (*reason == <API key>) m_resolver->resolve(); else m_resolver->reject(CacheStorageError::createException(*reason)); m_resolver.clear(); } private: Persistent<<API key>> m_resolver; }; // FIXME: Consider using <API key>. class CacheStorage::DeleteCallbacks final : public <API key>::<API key> { <API key>(DeleteCallbacks); public: DeleteCallbacks(const String& cacheName, CacheStorage* cacheStorage, <API key>* resolver) : m_cacheName(cacheName), m_cacheStorage(cacheStorage), m_resolver(resolver) { } ~DeleteCallbacks() override { } void onSuccess() override { m_cacheStorage->m_nameToCacheMap.remove(m_cacheName); if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; m_resolver->resolve(true); m_resolver.clear(); } // Ownership of |rawReason| must be passed. void onError(<API key>* rawReason) override { OwnPtr<<API key>> reason = adoptPtr(rawReason); if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; if (*reason == <API key>) m_resolver->resolve(false); else m_resolver->reject(CacheStorageError::createException(*reason)); m_resolver.clear(); } private: String m_cacheName; Persistent<CacheStorage> m_cacheStorage; Persistent<<API key>> m_resolver; }; // FIXME: Consider using <API key>. class CacheStorage::KeysCallbacks final : public <API key>::<API key> { <API key>(KeysCallbacks); public: explicit KeysCallbacks(<API key>* resolver) : m_resolver(resolver) { } ~KeysCallbacks() override { } void onSuccess(WebVector<WebString>* keys) override { if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; Vector<String> wtfKeys; for (size_t i = 0; i < keys->size(); ++i) wtfKeys.append((*keys)[i]); m_resolver->resolve(wtfKeys); m_resolver.clear(); } // Ownership of |rawReason| must be passed. void onError(<API key>* rawReason) override { OwnPtr<<API key>> reason = adoptPtr(rawReason); if (!m_resolver->executionContext() || m_resolver->executionContext()-><API key>()) return; m_resolver->reject(CacheStorageError::createException(*reason)); m_resolver.clear(); } private: Persistent<<API key>> m_resolver; }; CacheStorage* CacheStorage::create(WeakPtr<GlobalFetch::ScopedFetcher> fetcher, <API key>* webCacheStorage) { return new CacheStorage(fetcher, adoptPtr(webCacheStorage)); } ScriptPromise CacheStorage::open(ScriptState* scriptState, const String& cacheName, ExceptionState& exceptionState) { if (!commonChecks(scriptState, exceptionState)) return ScriptPromise(); <API key>* resolver = <API key>::create(scriptState); const ScriptPromise promise = resolver->promise(); if (m_nameToCacheMap.contains(cacheName)) { Cache* cache = m_nameToCacheMap.find(cacheName)->value; resolver->resolve(cache); return promise; } if (m_webCacheStorage) m_webCacheStorage->dispatchOpen(new WithCacheCallbacks(cacheName, this, resolver), cacheName); else resolver->reject(<API key>()); return promise; } ScriptPromise CacheStorage::has(ScriptState* scriptState, const String& cacheName, ExceptionState& exceptionState) { if (!commonChecks(scriptState, exceptionState)) return ScriptPromise(); <API key>* resolver = <API key>::create(scriptState); const ScriptPromise promise = resolver->promise(); if (m_nameToCacheMap.contains(cacheName)) { resolver->resolve(true); return promise; } if (m_webCacheStorage) m_webCacheStorage->dispatchHas(new Callbacks(resolver), cacheName); else resolver->reject(<API key>()); return promise; } ScriptPromise CacheStorage::deleteFunction(ScriptState* scriptState, const String& cacheName, ExceptionState& exceptionState) { if (!commonChecks(scriptState, exceptionState)) return ScriptPromise(); <API key>* resolver = <API key>::create(scriptState); const ScriptPromise promise = resolver->promise(); if (m_webCacheStorage) m_webCacheStorage->dispatchDelete(new DeleteCallbacks(cacheName, this, resolver), cacheName); else resolver->reject(<API key>()); return promise; } ScriptPromise CacheStorage::keys(ScriptState* scriptState, ExceptionState& exceptionState) { if (!commonChecks(scriptState, exceptionState)) return ScriptPromise(); <API key>* resolver = <API key>::create(scriptState); const ScriptPromise promise = resolver->promise(); if (m_webCacheStorage) m_webCacheStorage->dispatchKeys(new KeysCallbacks(resolver)); else resolver->reject(<API key>()); return promise; } ScriptPromise CacheStorage::match(ScriptState* scriptState, const RequestInfo& request, const CacheQueryOptions& options, ExceptionState& exceptionState) { ASSERT(!request.isNull()); if (!commonChecks(scriptState, exceptionState)) return ScriptPromise(); if (request.isRequest()) return matchImpl(scriptState, request.getAsRequest(), options); Request* newRequest = Request::create(scriptState, request.getAsUSVString(), exceptionState); if (exceptionState.hadException()) return ScriptPromise(); return matchImpl(scriptState, newRequest, options); } ScriptPromise CacheStorage::matchImpl(ScriptState* scriptState, const Request* request, const CacheQueryOptions& options) { <API key> webRequest; request-><API key>(webRequest); <API key>* resolver = <API key>::create(scriptState); const ScriptPromise promise = resolver->promise(); if (m_webCacheStorage) m_webCacheStorage->dispatchMatch(new MatchCallbacks(resolver), webRequest, Cache::toWebQueryParams(options)); else resolver->reject(<API key>()); return promise; } CacheStorage::CacheStorage(WeakPtr<GlobalFetch::ScopedFetcher> fetcher, PassOwnPtr<<API key>> webCacheStorage) : m_scopedFetcher(fetcher) , m_webCacheStorage(webCacheStorage) { } CacheStorage::~CacheStorage() { } void CacheStorage::dispose() { m_webCacheStorage.clear(); } DEFINE_TRACE(CacheStorage) { visitor->trace(m_nameToCacheMap); } } // namespace blink
GRNmap Testing Report ## Test Conditions * Date: January 22, 2018 * Run time: Started at 4:54pm * Test Performed by: @maggie-oneil * Code Version: beta * MATLAB Version: R2014b * Computer on which the model was run: cerevisiae CPU5 ## Purpose ## Results * Input sheet: [[Media:]] * Output sheet: [[Media:]] * Output .mat file (zipped): [[Media:]] ** LSE: ** Penalty term: ** Number of iterations (counter): * Figures (all expression graphs .jpg files zipped together): [[Media:]] * Save the progress figure containing the counts manually: [[Media:]] * analysis.xlsx containing bar graphs: [[Media:]] * GRNsight figure of unweighted network: [[Image:]] * GRNsight figure of weighted network: [[Image:*filename here*|thumb|center|400px]]
<?php namespace frontend\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use common\models\SummaryOnSite; /** * SummaryOnSiteSearch represents the model behind the search form about `common\models\SummaryOnSite`. */ class SummaryOnSiteSearch extends SummaryOnSite { /** * @inheritdoc */ public function rules() { return [ [['summary_id', 'software_id', 'computer_id', 'created_by', 'updated_by', 'created_at', 'updated_at','is_status'], 'integer'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = SummaryOnSite::find()->where('is_status != 2'); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => ['attributes' => ['software_id']] ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'summary_id' => $this->summary_id, 'software_id' => $this->software_id, 'computer_id' => $this->computer_id, 'created_by' => $this->created_by, 'updated_by' => $this->updated_by, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'is_status' => $this->is_status, ]); return $dataProvider; } //Search for Computer_id public function get_sos($param) { $query = SummaryOnSite::find()->where(['software_id' => $_REQUEST['id']]); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($param); if(!$this->validate()){ return $dataProvider; } $query->andFilterWhere([ 'summary_id' => $this->summary_id, 'software_id' => $this->software_id, 'computer_id' => $this->computer_id, 'created_by' => $this->created_by, 'updated_by' => $this->updated_by, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]); return $dataProvider; } }
@protocol <API key> - (bycopy NSData *)SkimNotesAtPath:(in bycopy NSString *)aFile; - (bycopy NSData *)RTFNotesAtPath:(in bycopy NSString *)aFile; - (bycopy NSData *)textNotesAtPath:(in bycopy NSString *)aFile encoding:(NSStringEncoding)encoding; @end
module Spree class Recurring < Spree::Base class StripeRecurring < Spree::Recurring module ApiHandler extend ActiveSupport::Concern included do include BeforeEach include PlanApiHandler include <API key> include <API key> end def error_class Stripe::InvalidRequestError end def <API key>(object, type) raise error_class.new("Not a valid object.") unless object.is_a?(type) end def set_api_key Stripe.<TwitterConsumerkey> end end end end end
package net.fusemc.zbungeecontrol.rank; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class RankManager { private static final Map<String, Rank> players = new ConcurrentHashMap<String, Rank>(); private RankListener listener; public RankManager() { listener = new RankListener(this); } public static Rank getRank(String player) { if (player.equalsIgnoreCase("CONSOLE")) { return Rank.CONSOLE; } return players.get(player); } public RankListener getListener() { return listener; } public void set(String player, Rank rank) { players.put(player, rank); } public void remove(String player) { players.remove(player); } }
package org.<API key>.jgoodies.cascading; import com.jgoodies.binding.PresentationModel; import com.jgoodies.common.collect.ObservableList; import com.jgoodies.binding.value.ValueModel; import static org.<API key>.jgoodies.listadapter.ListAdapters.observe; import org.<API key>.jgoodies.listadapter.<API key>; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.beans.PropertyChangeEvent; import java.beans.<API key>; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class <API key><T> extends PresentationModel<T> { private List changeChildren; private boolean changing = false; ChildListListener childListListener; private ObservableList parentList; public <API key>(ValueModel beanChannel) { this(beanChannel, null, null); } public <API key>(ValueModel beanChannel, <API key> parentModel) { this(beanChannel, parentModel, null); } public <API key>(ValueModel beanChannel, <API key> parentModel, ObservableList<T> parentListModel) { super(beanChannel); if (parentModel != null) { parentModel.<API key>(this); } if (parentListModel != null) { addParentListModel(parentListModel); } childListListener = new ChildListListener(); <API key>(<API key>, new <API key>() { public void propertyChange(PropertyChangeEvent evt) { changing = true; } }); <API key>(<API key>, new <API key>() { public void propertyChange(PropertyChangeEvent evt) { changing = false; } }); } public <API key>(ValueModel beanChannel, ObservableList parentListModel) { this(beanChannel, null, parentListModel); } private List getChangeChildren() { if (changeChildren == null) { changeChildren = new ArrayList(4); } return changeChildren; } private void <API key>(final PresentationModel childModel) { getChangeChildren().add(childModel); childModel.<API key>("changed", new <API key>() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getNewValue().equals(Boolean.TRUE)) { if (!changing) { setChanged(true); } } } }); childModel.<API key>(new <API key>() { public void propertyChange(PropertyChangeEvent evt) { } }); } public ObservableList <API key>(String propertyName) { <API key> listHolder = new <API key>(this.getModel(propertyName)); listHolder.addListDataListener(childListListener); return listHolder; } public ObservableList getListModel(String propertyName) { return observe (this.getModel(propertyName)); } public void addParentListModel(final ObservableList parentList) { this.parentList = parentList; this.<API key>(new <API key>() { public void propertyChange(PropertyChangeEvent evt) { fireParentList(); } }); } private void fireParentList() { if (parentList == null) return; Object bean = this.getBean(); int index = parentList.indexOf(bean); parentList.set(index, bean); } public void resetChanged() { super.resetChanged(); if (changeChildren != null) { for (Iterator iterator = changeChildren.iterator(); iterator.hasNext();) { PresentationModel pm = (PresentationModel) iterator.next(); pm.resetChanged(); } } } class ChildListListener implements ListDataListener { public void contentsChanged(ListDataEvent e) { update(); } private void update() { if (!changing) { setChanged(true); fireParentList(); } } public void intervalAdded(ListDataEvent e) { update(); } public void intervalRemoved(ListDataEvent e) { update(); } } }
import pandas as pd import numpy as np import pyaf.ForecastEngine as autof import pyaf.Bench.TS_datasets as tsds import logging import logging.config #logging.config.fileConfig('logging.conf') logging.basicConfig(level=logging.INFO) #get_ipython().magic('matplotlib inline') b1 = tsds.load_ozone() df = b1.mPastData #df.tail(10) #df[:-10].tail() #df[:-10:-1] #df.describe() lEngine = autof.cForecastEngine() lEngine H = b1.mHorizon; # lEngine.mOptions.enable_slow_mode(); lEngine.mOptions.mDebugPerformance = True; lEngine.mOptions.mParallelMode = True; lEngine.mOptions.<API key>(['LSTM']); lEngine.train(df , b1.mTimeVar , b1.mSignalVar, H); lEngine.getModelInfo(); print(lEngine.<API key>.mTrPerfDetails.head()); lEngine.<API key>.mBestModel.mTimeInfo.mResolution lEngine.standardPlots("outputs/my_rnn_ozone"); dfapp_in = df.copy(); dfapp_in.tail() #H = 12 dfapp_out = lEngine.forecast(dfapp_in, H); #dfapp_out.to_csv("outputs/rnn_ozone_apply_out.csv") dfapp_out.tail(2 * H) print("Forecast Columns " , dfapp_out.columns); Forecast_DF = dfapp_out[[b1.mTimeVar , b1.mSignalVar, b1.mSignalVar + '_Forecast']] print(Forecast_DF.info()) print("Forecasts\n" , Forecast_DF.tail(H)); print("\n\n<ModelInfo>") print(lEngine.to_json()); print("</ModelInfo>\n\n") print("\n\n<Forecast>") print(Forecast_DF.tail(2*H).to_json(date_format='iso')) print("</Forecast>\n\n")
import sys import random from test_base import * class TestBlockLD2(TestBase): def generate(self): self.clear_tag() for n in range(50000): tag = random.randint(0, 15) index = random.randint(0,self.sets_p-1) taddr = self.get_addr(tag,index) op = random.randint(0,2) if op == 0: self.send_block_st(taddr) elif op == 1: self.send_block_ld(taddr) else: self.send_aflinv(taddr) self.tg.done() def send_block_st(self, addr): base_addr = addr - (addr % (self.<API key>*4)) for i in range(self.<API key>): self.send_sw(base_addr+(i*4)) # main() if __name__ == "__main__": t = TestBlockLD2() t.generate()
package org.cagrid.trust.service.core; import java.io.File; import org.cagrid.trust.model.DateFilter; import org.cagrid.trust.model.SyncReport; public interface HistoryManager { public File addReport(SyncReport report) throws Exception; public SyncReport getReport(String fileName) throws Exception; public SyncReport[] search(DateFilter startDate, DateFilter end) throws Exception; public SyncReport[] search(DateFilter startDate, DateFilter end, File histDir) throws Exception; public void prune(DateFilter filter) throws Exception; }
{% extends "base.html" %} {% set subtitle = post.title|striptags -%} {% block content %} <article class="post"> {% block post_title %}<h2>{{ post.title|striptags }}</h2>{% endblock %} {% include 'includes/post_meta.html' %} {{ post.content }} </article> {% block <API key> %} {% if post.previtem or post.nextitem %} <div class="post-nav"> {% if post.previtem %} <div class="float-left">←&nbsp;<a href="{{ post.previtem.url }}" title="Previous post">{{ post.previtem.title|striptags }}</a></div> {% endif %} {% if post.nextitem %} <div class="float-right"><a href="{{ post.nextitem.url }}" title="Next post">{{ post.nextitem.title|striptags }}</a>&nbsp;→</div> {% endif %} </div> {% endif %} {% include 'includes/disqus_comments.html' %} {% endblock %} {% endblock %}
#! /usr/bin/env python3 assert __name__ == '__main__' import json import os import pathlib import re import shutil import subprocess import sys from typing import * # mypy annotations REPO_DIR = pathlib.Path.cwd() GN_ENV = dict(os.environ) # We need to set <API key> to 0 for non-Googlers, but otherwise # leave it unset since vs_toolchain.py assumes that the user is a Googler with # the Visual Studio files in depot_tools if <API key> is not # explicitly set to 0. vs_found = False for directory in os.environ['PATH'].split(os.pathsep): vs_dir = os.path.join(directory, 'win_toolchain', 'vs_files') if os.path.exists(vs_dir): vs_found = True break if not vs_found: GN_ENV['<API key>'] = '0' if len(sys.argv) < 3: sys.exit('Usage: export_targets.py OUT_DIR ROOTS...') (OUT_DIR, *ROOTS) = sys.argv[1:] for x in ROOTS: assert x.startswith(' def run_checked(*args, **kwargs): print(' ', args, file=sys.stderr) sys.stderr.flush() return subprocess.run(args, check=True, **kwargs) def sortedi(x): return sorted(x, key=str.lower) def dag_traverse(root_keys: Sequence[str], pre_recurse_func: Callable[[str], list]): visited_keys: Set[str] = set() def recurse(key): if key in visited_keys: return visited_keys.add(key) t = pre_recurse_func(key) try: (next_keys, post_recurse_func) = t except ValueError: (next_keys,) = t post_recurse_func = None for x in next_keys: recurse(x) if post_recurse_func: post_recurse_func(key) return for x in root_keys: recurse(x) return print('Importing graph', file=sys.stderr) try: p = run_checked('gn', 'desc', '--format=json', str(OUT_DIR), '*', stdout=subprocess.PIPE, env=GN_ENV, shell=(True if sys.platform == 'win32' else False)) except subprocess.CalledProcessError: sys.stderr.buffer.write(b'"gn desc" failed. Is depot_tools in your PATH?\n') exit(1) print('\nProcessing graph', file=sys.stderr) descs = json.loads(p.stdout.decode()) # Ready to traverse LIBRARY_TYPES = ('shared_library', 'static_library') def flattened_target(target_name: str, descs: dict, stop_at_lib: bool =True) -> dict: flattened = dict(descs[target_name]) EXPECTED_TYPES = LIBRARY_TYPES + ('source_set', 'group', 'action') def pre(k): dep = descs[k] dep_type = dep['type'] deps = dep['deps'] if stop_at_lib and dep_type in LIBRARY_TYPES: return ((),) if dep_type == 'copy': assert not deps, (target_name, dep['deps']) else: assert dep_type in EXPECTED_TYPES, (k, dep_type) for (k,v) in dep.items(): if type(v) in (list, tuple, set): # This is a workaround for # the value of "public" can be a string instead of a list. existing = flattened.get(k, []) if isinstance(existing, str): existing = [existing] flattened[k] = sortedi(set(existing + v)) else: #flattened.setdefault(k, v) pass return (deps,) dag_traverse(descs[target_name]['deps'], pre) return flattened # Check that includes are valid. (gn's version of this check doesn't seem to work!) INCLUDE_REGEX = re.compile(b'(?:^|\\n) *# *include +([<"])([^>"]+)[>"]') assert INCLUDE_REGEX.match(b'#include "foo"') assert INCLUDE_REGEX.match(b'\n#include "foo"') # Most of these are ignored because this script does not currently handle # #includes in #ifdefs properly, so they will erroneously be marked as being # included, but not part of the source list. IGNORED_INCLUDES = { b'absl/container/flat_hash_map.h', b'compiler/translator/TranslatorESSL.h', b'compiler/translator/TranslatorGLSL.h', b'compiler/translator/TranslatorHLSL.h', b'compiler/translator/TranslatorMetal.h', b'compiler/translator/TranslatorVulkan.h', b'contrib/optimizations/slide_hash_neon.h', b'dirent_on_windows.h', b'dlopen_fuchsia.h', b'kernel/image.h', b'libANGLE/renderer/d3d/d3d11/winrt/NativeWindow11WinRT.h', b'libANGLE/renderer/d3d/DeviceD3D.h', b'libANGLE/renderer/d3d/DisplayD3D.h', b'libANGLE/renderer/d3d/RenderTargetD3D.h', b'libANGLE/renderer/gl/apple/DisplayApple_api.h', b'libANGLE/renderer/gl/cgl/DisplayCGL.h', b'libANGLE/renderer/gl/eagl/DisplayEAGL.h', b'libANGLE/renderer/gl/egl/android/DisplayAndroid.h', b'libANGLE/renderer/gl/egl/DisplayEGL.h', b'libANGLE/renderer/gl/egl/gbm/DisplayGbm.h', b'libANGLE/renderer/gl/glx/DisplayGLX.h', b'libANGLE/renderer/gl/wgl/DisplayWGL.h', b'libANGLE/renderer/metal/DisplayMtl_api.h', b'libANGLE/renderer/null/DisplayNULL.h', b'libANGLE/renderer/vulkan/android/AHBFunctions.h', b'libANGLE/renderer/vulkan/android/DisplayVkAndroid.h', b'libANGLE/renderer/vulkan/fuchsia/DisplayVkFuchsia.h', b'libANGLE/renderer/vulkan/ggp/DisplayVkGGP.h', b'libANGLE/renderer/vulkan/mac/DisplayVkMac.h', b'libANGLE/renderer/vulkan/win32/DisplayVkWin32.h', b'libANGLE/renderer/vulkan/xcb/DisplayVkXcb.h', b'loader_cmake_config.h', b'optick.h', b'spirv-tools/libspirv.h', b'third_party/volk/volk.h', b'<API key>.c', b'vk_snippets.h', b'vulkan_android.h', b'vulkan_beta.h', b'vulkan_directfb.h', b'vulkan_fuchsia.h', b'vulkan_ggp.h', b'vulkan_ios.h', b'vulkan_macos.h', b'vulkan_metal.h', b'vulkan_vi.h', b'vulkan_wayland.h', b'vulkan_win32.h', b'vulkan_xcb.h', b'vulkan_xlib.h', b'vulkan_xlib_xrandr.h', # rapidjson adds these include stubs into their documentation # comments. Since the script doesn't skip comments they are # erroneously marked as valid includes b'rapidjson/...', } <API key> = { b'android', b'Carbon', b'CoreFoundation', b'CoreServices', b'IOSurface', b'mach', b'mach-o', b'OpenGL', b'pci', b'sys', b'wrl', b'X11', } IGNORED_DIRECTORIES = { '//buildtools/third_party/libc++', '//third_party/abseil-cpp', '//third_party/SwiftShader', } def has_all_includes(target_name: str, descs: dict) -> bool: for ignored_directory in IGNORED_DIRECTORIES: if target_name.startswith(ignored_directory): return True flat = flattened_target(target_name, descs, stop_at_lib=False) acceptable_sources = flat.get('sources', []) + flat.get('outputs', []) acceptable_sources = {x.rsplit('/', 1)[-1].encode() for x in acceptable_sources} ret = True desc = descs[target_name] for cur_file in desc.get('sources', []): assert cur_file.startswith('/'), cur_file if not cur_file.startswith(' continue cur_file = pathlib.Path(cur_file[2:]) text = cur_file.read_bytes() for m in INCLUDE_REGEX.finditer(text): if m.group(1) == b'<': continue include = m.group(2) if include in IGNORED_INCLUDES: continue try: (prefix, _) = include.split(b'/', 1) if prefix in <API key>: continue except ValueError: pass include_file = include.rsplit(b'/', 1)[-1] if include_file not in acceptable_sources: #print(' acceptable_sources:') #for x in sorted(acceptable_sources): # print(' ', x) print('Warning in {}: {}: Invalid include: {}'.format(target_name, cur_file, include), file=sys.stderr) ret = False #print('Looks valid:', m.group()) continue return ret # Gather real targets: def gather_libraries(roots: Sequence[str], descs: dict) -> Set[str]: libraries = set() def fn(target_name): cur = descs[target_name] print(' ' + cur['type'], target_name, file=sys.stderr) assert has_all_includes(target_name, descs), target_name if cur['type'] in ('shared_library', 'static_library'): libraries.add(target_name) return (cur['deps'], ) dag_traverse(roots, fn) return libraries libraries = gather_libraries(ROOTS, descs) print(f'\n{len(libraries)} libraries:', file=sys.stderr) for k in libraries: print(f' {k}', file=sys.stderr) print('\nstdout begins:', file=sys.stderr) sys.stderr.flush() # Output out = {k: flattened_target(k, descs) for k in libraries} for (k,desc) in out.items(): dep_libs: Set[str] = set() for dep_name in set(desc['deps']): dep = descs[dep_name] if dep['type'] in LIBRARY_TYPES: dep_libs.add(dep_name[3:]) desc['deps'] = sortedi(dep_libs) json.dump(out, sys.stdout, indent=' ') exit(0)
'use strict'; describe('Controller: TaxonEditorCtrl', function () { // load the controller's module beforeEach(module('BaubleApp')); var TaxonEditorCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller) { scope = {}; TaxonEditorCtrl = $controller('TaxonEditorCtrl', { $scope: scope }); })); // it('should attach a list of awesomeThings to the scope', function () { // expect(scope.awesomeThings.length).toBe(3); });
package cromwell.backend.standard import akka.actor.{Actor, ActorRef} import cromwell.backend._ import cromwell.backend.io.{JobPaths, WorkflowPaths} import cromwell.backend.standard.callcaching.<API key> import cromwell.backend.validation.{<API key>, <API key>} import cromwell.core.logging.JobLogging import cromwell.core.path.Path import cromwell.services.metadata.CallMetadataKeys import wom.graph.TaskCallNode import scala.util.Try /** * Extends the <API key> with standard implementations. * * Like the <API key>, this trait should be extended by a backend, and then __that__ trait should be mixed * into a async job execution actor, and cache hit copying actor. */ trait <API key> extends <API key> { this: Actor with JobLogging => def <API key>: Option[<API key>] /** Typed backend initialization. */ def <API key>[A <: <API key>]: A = <API key>.as[A](<API key>) /** * Returns the service registry actor. Both the <API key> and <API key> traits * implement this method. * * @return Paths to the job. */ def <API key>: ActorRef // So... JobPaths doesn't extend WorkflowPaths, but does contain a self-type lazy val workflowPaths: WorkflowPaths = jobPaths.workflowPaths def getPath(str: String): Try[Path] = workflowPaths.getPath(str) /** * The workflow descriptor for this job. NOTE: This may be different than the workflow descriptor created in the * workflow initialization data. For example, sub workflows use a different workflow descriptor. */ lazy val workflowDescriptor: <API key> = jobDescriptor.workflowDescriptor lazy val call: TaskCallNode = jobDescriptor.key.call lazy val <API key>: <API key> = <API key>. as[<API key>](<API key>) lazy val <API key>: <API key> = { val builder = <API key>.<API key> builder.build(jobDescriptor.runtimeAttributes, jobLogger) } /** * Returns the paths to the job. * * @return Paths to the job. */ lazy val jobPaths: JobPaths = <API key>.workflowPaths.toJobPaths(jobDescriptor) /** * Returns the metadata key values to store before executing a job. * * @return the metadata key values to store before executing a job. */ def <API key>: Map[String, Any] = { val <API key> = <API key>.toMetadataStrings(<API key>) map { case (key, value) => (s"${CallMetadataKeys.RuntimeAttributes}:$key", value) } val fileMetadata = jobPaths.metadataPaths <API key> ++ fileMetadata ++ nonStandardMetadata } /** * Returns any custom metadata for the backend. * * @return any custom metadata for the backend. */ protected def nonStandardMetadata: Map[String, Any] = Map.empty }
package com.gooddata.connector; import static com.gooddata.util.Validate.notEmpty; import com.fasterxml.jackson.annotation.*; import com.gooddata.util.<API key>; import java.util.Objects; /** * Coupa connector instance. */ @JsonTypeName("coupaInstance") @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) @<API key>(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class CoupaInstance { private final String name; private final String apiUrl; private final String apiKey; /** * Constructor. * * @param name instance name * @param apiUrl API URL * @param apiKey API key for this instance (can be hidden = {@code null}) */ @JsonCreator public CoupaInstance( @JsonProperty("name") String name, @JsonProperty("apiUrl") String apiUrl, @JsonProperty("apiKey") String apiKey) { notEmpty(name, "name"); notEmpty(apiUrl, "apiUrl"); this.name = name; this.apiUrl = apiUrl; this.apiKey = apiKey; } public String getName() { return name; } public String getApiUrl() { return apiUrl; } public String getApiKey() { return apiKey; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final CoupaInstance that = (CoupaInstance) o; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (apiUrl != null ? !apiUrl.equals(that.apiUrl) : that.apiUrl != null) return false; return apiKey != null ? apiKey.equals(that.apiKey) : that.apiKey == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (apiUrl != null ? apiUrl.hashCode() : 0); result = 31 * result + (apiKey != null ? apiKey.hashCode() : 0); return result; } @Override public String toString() { return <API key>.defaultToString(this); } }
from django.contrib.gis.geos import Point from data_collection.management.commands import <API key> class Command(<API key>): srid = 27700 council_id = 'W06000021' districts_name = 'polling_district' stations_name = 'polling_station.shp' elections = [ 'local.monmouthshire.2017-05-04', 'parl.2017-06-08' ] def <API key>(self, record): return { 'internal_council_id': str(record[1]).strip(), 'name': str(record[1]).strip(), 'polling_station_id': record[3] } def <API key>(self, record): station = { 'internal_council_id': record[0], 'postcode' : '', 'address' : "%s\n%s" % (record[2].strip(), record[4].strip()), } if str(record[1]).strip() == '10033354925': """ There is a dodgy point in this file. It has too many digits for a UK national grid reference. Joe queried, Monmouthshire provided this corrected point by email """ station['location'] = Point(335973, 206322, srid=27700) return station
import { workerPool } from '../runtime/worker-pool.js'; const WORKER_PATH = `https://$worker/worker.js`; export const pecIndustry = (loader) => { // worker paths are relative to worker location, remap urls from there to here const remap = expandUrls(loader.urlMap); // get real path from meta path const workerUrl = loader.resolve(WORKER_PATH); const urlParams = new URLSearchParams(window.location.search); // use service worker cache instead of generating blobs const useCache = location.protocol === 'https:' && urlParams.has('use-cache'); // get system tracing channel const systemTraceChannel = urlParams.get('systrace') || ''; // provision (cached) Blob url (async, same workerBlobUrl is captured in both closures) let workerBlobUrl; if (!useCache) { loader.provisionObjectUrl(workerUrl).then((url) => workerBlobUrl = url); } // delegate worker and channel creation api to the worker pool factory workerPool.apis = { create: () => ({ worker: new Worker(workerBlobUrl || workerUrl), channel: new MessageChannel(), usage: 0, }) }; // spawn workers ahead of time at runtime initialization // effective only when the use-worker-pool url parameter is supplied workerPool.shrinkOrGrow(); // return a pecfactory const factory = (id, idGenerator) => { if (!workerBlobUrl && !useCache) { console.warn('workerBlob not available, falling back to network URL'); } const poolEntry = workerPool.resume(); const worker = poolEntry ? poolEntry.worker : new Worker(workerBlobUrl || workerUrl); const channel = poolEntry ? poolEntry.channel : new MessageChannel(); // Should emplace if the worker pool management is ON and // a new worker and its messaging channel are created. if (workerPool.active && !poolEntry) { workerPool.emplace(worker, channel); } worker.postMessage({ id: `${id}:inner`, base: remap, logLevel: window['logLevel'], traceChannel: systemTraceChannel, inWorkerPool: workerPool.exist(channel.port2), }, [channel.port1]); // shrink or grow workers at run-time overlapping with new PEC execution // effective only when the use-worker-pool url parameter is supplied workerPool.shrinkOrGrow(); return channel.port2; }; // TODO(sjmiles): PecFactory type is defined against custom `MessageChannel` and `MessagePort` objects, not the // browser-standard objects used here. We need to clean this up, it's only working de facto. return factory; }; const expandUrls = urlMap => { const remap = {}; const { origin, pathname } = window.location; const transform = (path) => { // leading slash without a protocol is considered absolute if (path[0] === '/') { // reroute root in absolute path path = `${origin}${path}`; } // anything with '//' in it is assumed to be non-local (have a protocol) else if (path.indexOf(' // remap local path to absolute path path = `${origin}${pathname.split('/').slice(0, -1).join('/')}/${path}`; } return path; }; Object.keys(urlMap).forEach(k => { const config = urlMap[k]; remap[k] = typeof config === 'string' ? transform(config) : { ...config, root: transform(config.root) }; }); return remap; }; //# sourceMappingURL=pec-industry-web.js.map
package skadistats.clarity.model.engine; import skadistats.clarity.event.Insert; import skadistats.clarity.model.EngineId; import skadistats.clarity.model.EngineType; import skadistats.clarity.processor.packet.PacketReader; import skadistats.clarity.processor.packet.UsesPacketReader; @UsesPacketReader public abstract class AbstractEngineType implements EngineType { @Insert protected PacketReader packetReader = new PacketReader(); // HACK: create one if we do not get one injected private final EngineId id; private final boolean sendTablesContainer; private final int indexBits; private final int serialBits; private final int indexMask; private final int emptyHandle; AbstractEngineType(EngineId id, boolean sendTablesContainer, int indexBits, int serialBits) { this.id = id; this.sendTablesContainer = sendTablesContainer; this.indexBits = indexBits; this.serialBits = serialBits; this.indexMask = (1 << indexBits) - 1; this.emptyHandle = (1 << (indexBits + 10)) - 1; } @Override public EngineId getId() { return id; } @Override public boolean <API key>() { return sendTablesContainer; } @Override public boolean handleDeletions() { return true; } @Override public int getIndexBits() { return indexBits; } @Override public int getSerialBits() { return serialBits; } @Override public int indexForHandle(int handle) { return handle & indexMask; } @Override public int serialForHandle(int handle) { return handle >> indexBits; } @Override public int <API key>(int index, int serial) { return serial << indexBits | index; } @Override public int emptyHandle() { return emptyHandle; } @Override public String toString() { return id.toString(); } }
<!DOCTYPE html> <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>mne.viz.<API key> &#8212; MNE 0.13.1 documentation</title> <link rel="stylesheet" href="../_static/basic.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/gallery.css" type="text/css" /> <link rel="stylesheet" href="../_static/bootswatch-3.3.6/flatly/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" /> <link rel="stylesheet" href="../_static/style.css" type="text/css" /> <script type="text/javascript"> var <API key> = { URL_ROOT: '../', VERSION: '0.13.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=<API key>"></script> <script type="text/javascript" src="../_static/js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../_static/js/jquery-fix.js"></script> <script type="text/javascript" src="../_static/bootstrap-3.3.6/js/bootstrap.min.js"></script> <script type="text/javascript" src="../_static/bootstrap-sphinx.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="top" title="MNE 0.13.1 documentation" href="../index.html" /> <link rel="up" title="Python API Reference" href="../python_reference.html" /> <link rel="next" title="mne.viz.plot_ica_sources" href="mne.viz.plot_ica_sources.html" /> <link rel="prev" title="mne.viz.plot_evoked_white" href="mne.viz.plot_evoked_white.html" /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-37225609-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https: var s = document.<API key>('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> !function(d,s,id){var js,fjs=d.<API key>(s)[0];if(!d.getElementById(id)){js=d.createElement(s); js.id=id;js.src="http://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); </script> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.<API key>('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> <link rel="canonical" href="https://mne.tools/stable/index.html" /> </head> <body role="document"> <div id="navbar" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- .btn-navbar is used as the toggle for collapsed navbar content --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"><span><img src="../_static/mne_logo_small.png"></span> </a> <span class="navbar-text navbar-version pull-left"><b>0.13.1</b></span> </div> <div class="collapse navbar-collapse nav-collapse"> <ul class="nav navbar-nav"> <li><a href="../getting_started.html">Get started</a></li> <li><a href="../tutorials.html">Tutorials</a></li> <li><a href="../auto_examples/index.html">Gallery</a></li> <li><a href="../python_reference.html">API</a></li> <li><a href="../manual/index.html">Manual</a></li> <li><a href="../faq.html">FAQ</a></li> <li class="dropdown globaltoc-container"> <a role="button" id="dLabelGlobalToc" data-toggle="dropdown" data-target=" href="../index.html">Site <b class="caret"></b></a> <ul class="dropdown-menu globaltoc" role="menu" aria-labelledby="dLabelGlobalToc"><ul> <li class="toctree-l1"><a class="reference internal" href="../getting_started.html">Getting started</a></li> <li class="toctree-l1"><a class="reference internal" href="../tutorials.html">Tutorials</a></li> <li class="toctree-l1"><a class="reference internal" href="../auto_examples/index.html">Examples Gallery</a></li> <li class="toctree-l1"><a class="reference internal" href="../faq.html">Frequently Asked Questions</a></li> <li class="toctree-l1"><a class="reference internal" href="../contributing.html">Contribute to MNE</a></li> </ul> <ul class="current"> <li class="toctree-l1 current"><a class="reference internal" href="../python_reference.html">Python API Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/index.html">User Manual</a></li> <li class="toctree-l1"><a class="reference internal" href="../whats_new.html">What&#8217;s new</a></li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="../cite.html">How to cite MNE</a></li> <li class="toctree-l1"><a class="reference internal" href="../references.html">Related publications</a></li> <li class="toctree-l1"><a class="reference internal" href="../cited.html">Publications from MNE users</a></li> </ul> </ul> </li> <li class="dropdown"> <a role="button" id="dLabelLocalToc" data-toggle="dropdown" data-target=" href="#">Page <b class="caret"></b></a> <ul class="dropdown-menu localtoc" role="menu" aria-labelledby="dLabelLocalToc"><ul> <li><a class="reference internal" href="#">mne.viz.<API key></a><ul> <li><a class="reference internal" href="#<API key>">Examples using <code class="docutils literal"><span class="pre">mne.viz.<API key></span></code></a></li> </ul> </li> </ul> </ul> </li> </ul> <form class="navbar-form navbar-right" action="../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> </div> <div class="container"> <div class="row"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="<API key>"> <p class="logo"><a href="../index.html"> <img class="logo" src="../_static/mne_logo_small.png" alt="Logo"/> </a></p><ul> <li><a class="reference internal" href="#">mne.viz.<API key></a><ul> <li><a class="reference internal" href="#<API key>">Examples using <code class="docutils literal"><span class="pre">mne.viz.<API key></span></code></a></li> </ul> </li> </ul> <li> <a href="mne.viz.plot_evoked_white.html" title="Previous Chapter: mne.viz.plot_evoked_white"><span class="glyphicon <API key> visible-sm"></span><span class="hidden-sm hidden-tablet">&laquo; mne.viz.plot_...</span> </a> </li> <li> <a href="mne.viz.plot_ica_sources.html" title="Next Chapter: mne.viz.plot_ica_sources"><span class="glyphicon <API key> visible-sm"></span><span class="hidden-sm hidden-tablet">mne.viz.plot_... &raquo;</span> </a> </li> <form action="../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="col-md-12 content"> <div class="section" id="<API key>"> <h1>mne.viz.<API key><a class="headerlink" href=" <dl class="function"> <dt id="mne.viz.<API key>"> <code class="descclassname">mne.viz.</code><code class="descname"><API key></code><span class="sig-paren">(</span><em>evokeds, picks=[], gfp=False, colors=None, linestyles=['-'], styles=None, vlines=[0.0], ci=0.95, truncate_yaxis=True, ylim={}, invert_y=False, axes=None, title=None, show=True</em><span class="sig-paren">)</span><a class="headerlink" href=" <dd><p>Plot evoked time courses for one or multiple channels and conditions</p> <p>This function is useful for comparing ER[P/F]s at a specific location. It plots Evoked data or, if supplied with a list/dict of lists of evoked instances, grand averages plus confidence intervals.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>evokeds</strong> : instance of mne.Evoked | list | dict</p> <blockquote> <div><p>If a single evoked instance, it is plotted as a time series. If a dict whose values are Evoked objects, the contents are plotted as single time series each and the keys are used as condition labels. If a list of Evokeds, the contents are plotted with indices as labels. If a [dict/list] of lists, the unweighted mean is plotted as a time series and the parametric confidence interval is plotted as a shaded area. All instances must have the same shape - channel numbers, time points etc.</p> </div></blockquote> <p><strong>picks</strong> : int | list of int</p> <blockquote> <div><p>If int or list of int, the indices of the sensors to average and plot. Must all be of the same channel type. If the selected channels are gradiometers, the corresponding pairs will be selected. If multiple channel types are selected, one figure will be returned for each channel type. If an empty list, <cite>gfp</cite> will be set to True, and the Global Field Power plotted.</p> </div></blockquote> <p><strong>gfp</strong> : bool</p> <blockquote> <div><p>If True, the channel type wise GFP is plotted. If <cite>picks</cite> is an empty list (default), this is set to True.</p> </div></blockquote> <p><strong>colors</strong> : list | dict | None</p> <blockquote> <div><p>If a list, will be sequentially used for line colors. If a dict, can map evoked keys or &#8216;/&#8217;-separated (HED) tags to conditions. For example, if <cite>evokeds</cite> is a dict with the keys &#8220;Aud/L&#8221;, &#8220;Aud/R&#8221;, &#8220;Vis/L&#8221;, &#8220;Vis/R&#8221;, <cite>colors</cite> can be <cite>dict(Aud=&#8217;r&#8217;, Vis=&#8217;b&#8217;)</cite> to map both Aud/L and Aud/R to the color red and both Visual conditions to blue. If None (default), a sequence of desaturated colors is used.</p> </div></blockquote> <p><strong>linestyles</strong> : list | dict</p> <blockquote> <div><p>If a list, will be sequentially and repeatedly used for evoked plot linestyles. If a dict, can map the <cite>evoked</cite> keys or &#8216;/&#8217;-separated (HED) tags to conditions. For example, if evokeds is a dict with the keys &#8220;Aud/L&#8221;, &#8220;Aud/R&#8221;, &#8220;Vis/L&#8221;, &#8220;Vis/R&#8221;, <cite>linestyles</cite> can be <cite>dict(L=&#8217;&#8211;&#8217;, R=&#8217;-&#8216;)</cite> to map both Aud/L and Vis/L to dashed lines and both Right-side conditions to straight lines.</p> </div></blockquote> <p><strong>styles</strong> : dict | None</p> <blockquote> <div><p>If a dict, keys must map to evoked keys or conditions, and values must be a dict of legal inputs to <cite>matplotlib.pyplot.plot</cite>. These parameters will be passed to the line plot call of the corresponding condition, overriding defaults. E.g., if evokeds is a dict with the keys &#8220;Aud/L&#8221;, &#8220;Aud/R&#8221;, &#8220;Vis/L&#8221;, &#8220;Vis/R&#8221;, <cite>styles</cite> can be <cite>{&#8220;Aud/L&#8221;:{&#8220;linewidth&#8221;:1}}</cite> to set the linewidth for &#8220;Aud/L&#8221; to 1. Note that HED (&#8216;/&#8217;-separated) tags are not supported.</p> </div></blockquote> <p><strong>vlines</strong> : list of int</p> <blockquote> <div><p>A list of integers corresponding to the positions, in seconds, at which to plot dashed vertical lines.</p> </div></blockquote> <p><strong>ci</strong> : float | None</p> <blockquote> <div><p>If not None and <cite>evokeds</cite> is a [list/dict] of lists, a confidence interval is drawn around the individual time series. This value determines the CI width. E.g., if this value is .95 (the default), the 95% parametric confidence interval is drawn. If None, no shaded confidence band is plotted.</p> </div></blockquote> <p><strong>truncate_yaxis</strong> : bool</p> <blockquote> <div><p>If True, the left y axis is truncated to half the max value and rounded to .25 to reduce visual clutter. Defaults to True.</p> </div></blockquote> <p><strong>ylim</strong> : dict | None</p> <blockquote> <div><p>ylim for plots (after scaling has been applied). e.g. ylim = dict(eeg=[-20, 20]) Valid keys are eeg, mag, grad, misc. If None, the ylim parameter for each channel equals the pyplot default.</p> </div></blockquote> <p><strong>invert_y</strong> : bool</p> <blockquote> <div><p>If True, negative values are plotted up (as is sometimes done for ERPs out of tradition). Defaults to False.</p> </div></blockquote> <p><strong>axes</strong> : None | <cite>matplotlib.pyplot.axes</cite> instance | list of <cite>axes</cite></p> <blockquote> <div><p>What axes to plot to. If None, a new axes is created. When plotting multiple channel types, can also be a list of axes, one per channel type.</p> </div></blockquote> <p><strong>title</strong> : None | str</p> <blockquote> <div><p>If str, will be plotted as figure title. If None, the channel names will be shown.</p> </div></blockquote> <p><strong>show</strong> : bool</p> <blockquote> <div><p>If True, show the figure.</p> </div></blockquote> </td> </tr> <tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>fig</strong> : Figure | list of Figures</p> <blockquote class="last"> <div><p>The figure(s) in which the plot is drawn.</p> </div></blockquote> </td> </tr> </tbody> </table> </dd></dl> <div class="section" id="<API key>"> <h2>Examples using <code class="docutils literal"><span class="pre">mne.viz.<API key></span></code><a class="headerlink" href=" <div class="<API key>" tooltip="===================== Visualize Evoked data ===================== "><div class="figure" id="id1"> <img alt="../_images/<API key>.png" src="../_images/<API key>.png" /> <p class="caption"><span class="caption-text"><a class="reference internal" href="../auto_tutorials/<API key>.html#<API key>"><span class="std std-ref">Visualize Evoked data</span></a></span></p> </div> </div><div style='clear:both'></div></div> </div> </div> </div> </div> <footer class="footer"> <div class="container"> <p class="pull-right"> <a href="#">Back to top</a> <br/> </p> <p> &copy; Copyright 2012-2016, MNE Developers. Last updated on 2016-11-21.<br/> </p> </div> </footer> <script src="https://mne.tools/versionwarning.js"></script> </body> </html>
#ifndef <API key> #include "<API key>.h" #endif /* <API key> */ #ifndef _STDIO_HEADERS_H #include "stdio_headers.h" #endif /* _STDIO_HEADERS_H */ int sscanf(const char *s,const char *format, ...) { int result = EOF; va_list arg; ENTER(); SHOWSTRING(s); SHOWSTRING(format); assert( s != NULL && format != NULL ); #if defined(<API key>) { if(s == NULL || format == NULL) { SHOWMSG("invalid parameters"); __set_errno(EFAULT); goto out; } } #endif /* <API key> */ va_start(arg,format); result = vsscanf(s,format,arg); va_end(arg); out: RETURN(result); return(result); }
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad.Trans (lift) import qualified Data.Text as T import Data.Either import Reflex.Dom import Frontend.Function import Frontend.ImageWidget import Frontend.WebcamWidget main :: IO () main = mainWidget $ do d <- lift askDocument -- imageInputWidget d def functionPage d -- imageInputWidget d def -- webcamWidget d (constDyn mempty) -- loader <- fileImageLoader -- displayImg =<< holdDyn (T.pack "") (fmap snd loader) blank hush :: Either e a -> Maybe a hush (Right a) = Just a hush _ = Nothing
package com.jme3.input.util; public interface IReadTimer { long <API key>(); long getLastUpdateTime(); long getFrameDelta(); }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>IOSS: src/Ioss_Quad8.C File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">IOSS &#160;<span id="projectnumber">2.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('Ioss__Quad8_8C.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#namespaces">Namespaces</a> </div> <div class="headertitle"> <div class="title">Ioss_Quad8.C File Reference</div> </div> </div><!--header <div class="contents"> <div class="textblock"><code>#include &quot;<a class="el" href="<API key>.html">Ioss_CodeTypes.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="<API key>.html"><API key>.h</a>&quot;</code><br /> <code>#include &lt;<a class="el" href="<API key>.html"><API key>.h</a>&gt;</code><br /> <code>#include &lt;<a class="el" href="<API key>.html">Ioss_Quad8.h</a>&gt;</code><br /> <code>#include &lt;cassert&gt;</code><br /> <code>#include &lt;cstddef&gt;</code><br /> </div><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">Ioss::St_Quad8</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">anonymous_namespace{Ioss_Quad8.C}::Constants</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Namespaces</h2></td></tr> <tr class="memitem:namespaceIoss"><td class="memItemLeft" align="right" valign="top"> &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceIoss.html">Ioss</a></td></tr> <tr class="memdesc:namespaceIoss"><td class="mdescLeft">&#160;</td><td class="mdescRight">The main namespace for the <a class="el" href="namespaceIoss.html" title="The main namespace for the Ioss library. ">Ioss</a> library. <br /></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"> &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">anonymous_namespace{Ioss_Quad8.C}</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="<API key>.html">src</a></li><li class="navelem"><a class="el" href="Ioss__Quad8_8C.html">Ioss_Quad8.C</a></li> <li class="footer">Generated by <a href="http: <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
function toRoute(val) { var url = document.URL; var path = url.split('index.php'); return path[0]+'index.php'+'/'+val; } function validePhone(phone) { if(/^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(phone) && phone.length==11){ return true; }else{ $.toast(''); return false; } } function validePassword(pwd) { if(/^[a-zA-Z\d_]{6,12}$/.test(pwd)){ return true; }else{ $.toast("612"); return false; } } function confirmpassword(comfirmpwd) { var pwd1 = $('[name="pwd"]').eq(0).val(); if(comfirmpwd!=pwd1){ $.toast(''); return false; }else{ return true; } } function validecode(code) { if(code.length!=6){ $.toast(''); return false; }else{ return true; } } function open_login(){ $.toast(''); } $(document).on('click','#mine .create-actions', function () { var parent = $('.create-actions'); var buttons1 = [ { text: '', label: true }, { text: '', bold: true, onClick: function() { parent.attr('id',1); parent.html(''); } }, { text: '', onClick: function() { parent.attr('id',2); parent.html(''); } } ]; var buttons2 = [ { text: '' // bg: 'danger' } ]; var groups = [buttons1, buttons2]; $.actions(groups); }); $(document).on('click', '#mine .prompt-title-ok',function () { $.prompt('', function (value) { $.alert('"' + value + '". '); }); }); $(document).on("click",".bar-tab a",function(){ var href = $(this).attr('rel'); var num,title; switch(href){ case "home": num=0; title='“”'; break; case "favourite": num=1; title=""; break; case "cart": num=2; title=""; break; case "setting": num=3; title=""; break; } $('.page-group nav').find('a.tab-item').removeClass('active'); //""class $('.page-group nav').find('a.tab-item').eq(num).addClass('active'); $('.page-group header').find('h1').html(title); if(href!='home'){ $('.page-group header').find('a').attr('class','button button-link button-nav pull-left back'); $('.page-group header').find('a').html('<span class="icon icon-left"></span>'); }else{ $('.page-group header').find('a').attr('class','icon pull-left icon-me open-popup'); $('.page-group header').find('a').attr('data-popup','.popup-about'); $('.page-group header').find('a').html(''); } $(this).attr('href','#'+href); }); //$(document).on("click", "#cart li", function() { // //$.toast(''); // $.openPanel("#cart #panel-js-demo"); * “”*/ //$(document).on("click","#cart .close_panel",function(){ // $.closePanel('#panel-js-demo');
// CEValueRange.cpp // ChartEssentials #include "CEValueRange.h" #include <stdexcept> void CEValueRange::addValue(CGFloat value) { if (!isnan(value)) { if (isnan(_high)) { _high = _low = value; } else { if (value < _low) { _low = value; } else if (_high < value) { _high = value; } } } } void CEValueRange::addHighValue(CGFloat value) { if (!isnan(value)) { if (isnan(_high)) { _high = _low = value; } else { if (_high < value) _high = value; } } } void CEValueRange::addLowValue(CGFloat value) { if (!isnan(value)) { if (isnan(_high)) { _high = _low = value; } else { if (value < _low) _low = value; } } } void CEValueRange::addValues(const CGFloat *values, size_t count) { if (values == NULL) throw std::invalid_argument("values"); if (count == 0) return; while (isnan(_high) && (count > 0)) { _high = _low = *values; values++; count } while (count > 0) { CGFloat value = *values; values++; count if (!isnan(value)) { if (value < _low) { _low = value; } else if (_high < value) { _high = value; } } } } void CEValueRange::addHighValues(const CGFloat *values, size_t count) { if (values == NULL) throw std::invalid_argument("values"); if (count == 0) return; while (isnan(_high) && (count > 0)) { _high = _low = *values; values++; count } while (count > 0) { CGFloat value = *values; values++; count if (!isnan(value) && _high < value) { _high = value; } } } void CEValueRange::addLowValues(const CGFloat *values, size_t count) { if (values == NULL) throw std::invalid_argument("values"); if (count == 0) return; while (isnan(_high) && (count > 0)) { _high = _low = *values; values++; count } while (count > 0) { CGFloat value = *values; values++; count if (!isnan(value) && value < _low) { _low = value; } } }
<?php /** * @namespace */ namespace Zend\Tool\Framework\Client; class Config { protected $_configFilepath = null; /** * @var Zend_Config */ protected $_config = null; /** * @param array $options */ public function __config($options = array()) { if ($options) { $this->setOptions($options); } } /** * @param array $options */ public function setOptions(Array $options) { foreach ($options as $optionName => $optionValue) { $setMethodName = 'set' . $optionName; if (method_exists($this, $setMethodName)) { $this->{$setMethodName}($optionValue); } } } /** * @param string $configFilepath * @return <API key> */ public function setConfigFilepath($configFilepath) { if (!file_exists($configFilepath)) { require_once 'Zend/Tool/Framework/Client/Exception.php'; throw new Exception('Provided path to config ' . $configFilepath . ' does not exist'); } $this->_configFilepath = $configFilepath; $this->loadConfig($configFilepath); return $this; } /** * Load the configuration from the given path. * * @param string $configFilepath */ protected function loadConfig($configFilepath) { $suffix = substr($configFilepath, -4); switch ($suffix) { case '.ini': require_once 'Zend/Config/Ini.php'; $this->_config = new \Zend\Config\Ini($configFilepath, null, array('allowModifications' => true)); break; case '.xml': require_once 'Zend/Config/Xml.php'; $this->_config = new \Zend\Config\Xml($configFilepath, null, array('allowModifications' => true)); break; case '.php': require_once 'Zend/Config.php'; $this->_config = new \Zend\Config\Config(include $configFilepath, true); break; default: require_once 'Zend/Tool/Framework/Client/Exception.php'; throw new Exception('Unknown config file type ' . $suffix . ' at location ' . $configFilepath ); } } /** * Return the filepath of the configuration. * * @return string */ public function getConfigFilepath() { return $this->_configFilepath; } /** * Get a configuration value. * * @param string $name * @param string $defaultValue * @return mixed */ public function get($name, $defaultValue=null) { return $this->getConfigInstance()->get($name, $defaultValue); } /** * Get a configuration value * * @param string $name * @return mixed */ public function __get($name) { return $this->getConfigInstance()->{$name}; } /** * Check if a configuration value isset. * * @param string $name * @return boolean */ public function __isset($name) { if($this->exists() == false) { return false; } return isset($this->getConfigInstance()->{$name}); } /** * @param string $name */ public function __unset($name) { unset($this->getConfigInstance()->$name); } /** * @param string $name * @param mixed $value */ public function __set($name, $value) { return $this->getConfigInstance()->$name = $value; } /** * Check if the User profile has a configuration. * * @return bool */ public function exists() { return ($this->_config!==null); } /** * @throws <API key> * @return Zend_Config */ public function getConfigInstance() { if(!$this->exists()) { require_once "Zend/Tool/Framework/Client/Exception.php"; throw new Exception("Client has no persistent configuration."); } return $this->_config; } /** * Save changes to the configuration into persistence. * * @return bool */ public function save() { if($this->exists()) { $writer = $this->getConfigWriter(); $writer->write($this->getConfigFilepath(), $this->getConfigInstance(), true); $this->loadConfig($this->getConfigFilepath()); return true; } return false; } /** * Get the config writer that corresponds to the current config file type. * * @return <API key> */ protected function getConfigWriter() { $suffix = substr($this->getConfigFilepath(), -4); switch($suffix) { case '.ini': require_once "Zend/Config/Writer/Ini.php"; $writer = new \Zend\Config\Writer\Ini(); $writer-><API key>(); break; case '.xml': require_once "Zend/Config/Writer/Xml.php"; $writer = new \Zend\Config\Writer\Xml(); break; case '.php': require_once "Zend/Config/Writer/Array.php"; $writer = new \Zend\Config\Writer\Array(); break; default: require_once 'Zend/Tool/Framework/Client/Exception.php'; throw new Exception('Unknown config file type ' . $suffix . ' at location ' . $this->getConfigFilepath() ); } return $writer; } }
<?php /** * @namespace */ namespace Zend\Db\Statement\Mysqli; /** * <API key> */ require_once 'Zend/Db/Statement/Exception.php'; class Exception extends \Zend\Db\Statement\Exception { }
<?php namespace Prooph\Common\Messaging; /** * Interface HasMessageName * * A message implementing this interface is aware of its name. * * @package Prooph\Common\Messaging * @author Alexander Miertsch <contact@prooph.de> */ interface HasMessageName { /** * @return string Name of the message */ public function messageName(); }
#ifndef BRW_SCREEN_H #define BRW_SCREEN_H #include "pipe/p_state.h" #include "pipe/p_screen.h" #include "brw_reg.h" #include "brw_structs.h" struct brw_winsys_screen; /** * Subclass of pipe_screen */ struct brw_screen { struct pipe_screen base; int gen; boolean <API key>; boolean needs_ff_sync; boolean is_g4x; int pci_id; struct brw_winsys_screen *sws; boolean no_tiling; }; union brw_surface_id { struct { unsigned level:16; unsigned layer:16; } bits; unsigned value; }; struct brw_surface { struct pipe_surface base; union brw_surface_id id; unsigned offset; unsigned cpp; unsigned pitch; unsigned draw_offset; unsigned tiling; struct brw_surface_state ss; struct brw_winsys_buffer *bo; struct brw_surface *next, *prev; }; /* * Cast wrappers */ static INLINE struct brw_screen * brw_screen(struct pipe_screen *pscreen) { return (struct brw_screen *) pscreen; } static INLINE struct brw_surface * brw_surface(struct pipe_surface *surface) { return (struct brw_surface *)surface; } unsigned brw_surface_pitch( const struct pipe_surface *surface ); #endif /* BRW_SCREEN_H */
{% extends "base.html" %} {% load jmbo_inclusion_tags downloads_tags %} {% block content %} <div class="content download-list"> <div class="foundry-container <API key>"> <div class="title">{{ title }}</div> <div class="items"> {% for category_dict in category_list %} {% render_category category_dict forloop.first forloop.last %} {% endfor %} </div> {% pager page_obj %} </div> </div> {% endblock %}
package org.burroloco.donkey.log; import au.net.netstorm.boost.bullet.incredibles.core.Weaken; import au.net.netstorm.boost.bullet.log.Log; import au.net.netstorm.boost.gunge.layer.Layer; import au.net.netstorm.boost.gunge.layer.Method; import org.burroloco.donkey.config.InputFileName; public class FileReaderLogger implements Layer { private final Object ref; Weaken weaken; Log log; public FileReaderLogger(Object ref) { this.ref = ref; } public Object invoke(Method method, Object[] args) { InputFileName input = (InputFileName) args[0]; log.info("Reading data from " + weaken.w(input)); return method.invoke(ref, args); } }
from piliko import * print print 'example 5' v1,v2 = vector(3,0),vector(0,4) print 'vectors v1, v2:', v1, v2 print ' v1 + v2, v1 - v2: ', v1 + v2, v1 - v2 print ' v1 * 5/4:', v1 * Fraction(5,4) print ' v1 perpendicular v1? ', v1.perpendicular( v1 ) print ' v1 perpendicular v2? ', v1.perpendicular( v2 ) print ' v2 perpendicular v1? ', perpendicular( v2, v1 ) print ' v1 perpendicular v1+v2? ', perpendicular( v1, v1+v2 ) print ' v1 parallel v1? ', v1.parallel( v1 ) print ' v1 parallel v2? ', v1.parallel( v2 ) print ' v1 parallel 5*v1? ', parallel( v1, 5*v1 ) print ' v1 parallel v1+v2? ', parallel( v1, v1+v2 ) v3 = v2 - v1 print 'vector v3 = v2-v1: ', v3 lhs = quadrance( v1 ) + quadrance( v2 ) rhs = quadrance( v3 ) print 'v1 dot v2, v2 dot v3, v1 dot 5*v1:', v1.dot(v2), v2.dot(v3), v1.dot(5*v1) print 'v1 dot (v2+v3), (v1 dot v2)+(v1 dot v3):', v1.dot(v2+v3), v1.dot(v2) + v1.dot(v3) print ' pythagoras: Q(v1)+Q(v2)=Q(v3)?: lhs:', lhs, 'rhs:',rhs v4 = vector( -5, 0 ) v5 = 3 * v4 v6 = v5 - v4 print 'vector v4, v5, and v6=v5-v4:', v4, v5, v6 lhs = sqr( quadrance( v4 ) + quadrance( v5 ) + quadrance( v6 ) ) rhs = 2*(sqr(quadrance(v4))+sqr(quadrance(v5))+sqr(quadrance(v6))) print ' triplequad for v4,v5,v6 : lhs:', lhs, 'rhs:',rhs print 'spread( v1, v1 ):', spread( v1, v1 ) print 'spread( v2, v1 ):', spread( v2, v1 ) print 'spread( v2, 5*v1 ):', spread( v2, 5*v1 ) print 'spread( v1, v2 ):', spread( v1, v2 ) print 'spread( v1, v3 ):', spread( v1, v3 ) print 'spread( v1, 5*v3 ):', spread( v1, 5*v3 ) print 'spread( v2, v3 ):', spread( v2, v3 ) print 'spread( 100*v2, -20*v2 ):', spread( 100*v2, -20*v2 ) print 'quadrance v1 == v1 dot v1?', quadrance(v1), '=?=', v1.dot(v1)
#include "components/autofill_assistant/browser/actions/navigate_action.h" #include <memory> #include <utility> #include "base/callback.h" #include "components/autofill_assistant/browser/actions/action_delegate.h" #include "content/public/browser/web_contents.h" #include "url/gurl.h" namespace autofill_assistant { NavigateAction::NavigateAction(ActionDelegate* delegate, const ActionProto& proto) : Action(delegate, proto) { DCHECK(proto_.has_navigate()); } NavigateAction::~NavigateAction() {} void NavigateAction::<API key>(<API key> callback) { // We know to expect navigation to happen, since we're about to cause it. This // allows scripts to put wait_for_navigation just after navigate, if needed, // without having to add an expect_navigation first. delegate_->ExpectNavigation(); auto& proto = proto_.navigate(); if (!proto.url().empty()) { GURL url(proto_.navigate().url()); delegate_->LoadURL(url); <API key>(ACTION_APPLIED); } else if (proto.go_backward()) { auto& controller = delegate_->GetWebContents()->GetController(); if (controller.CanGoBack()) { controller.GoBack(); <API key>(ACTION_APPLIED); } else { <API key>(PRECONDITION_FAILED); } } else if (proto.go_forward()) { auto& controller = delegate_->GetWebContents()->GetController(); if (controller.CanGoForward()) { controller.GoForward(); <API key>(ACTION_APPLIED); } else { <API key>(PRECONDITION_FAILED); } } else { <API key>(UNSUPPORTED); } std::move(callback).Run(std::move(<API key>)); } } // namespace autofill_assistant
// .NAME vtkParametricTorus - Generate a torus. // .SECTION Description // vtkParametricTorus generates a torus. // For further information about this surface, please consult the // in the "VTK Technical Documents" section in the VTk.org web pages. // .SECTION Thanks // Andrew Maclean andrew.amaclean@gmail.com for creating and contributing the // class. #ifndef <API key> #define <API key> #include "<API key>.h" // For export macro #include "<API key>.h" class <API key> vtkParametricTorus : public <API key> { public: vtkTypeMacro(vtkParametricTorus,<API key>); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Construct a torus with the following parameters: // MinimumU = 0, MaximumU = 2*Pi, // MinimumV = 0, MaximumV = 2*Pi, // JoinU = 1, JoinV = 1, // TwistU = 0, TwistV = 0, // ClockwiseOrdering = 1, // <API key> = 1, // RingRadius = 1, CrossSectionRadius = 0.5. static vtkParametricTorus *New(); // Description: // Set/Get the radius from the center to the middle of the ring of the // torus. Default is 1.0. vtkSetMacro(RingRadius,double); vtkGetMacro(RingRadius,double); // Description: // Set/Get the radius of the cross section of ring of the torus. Default is 0.5. vtkSetMacro(CrossSectionRadius,double); vtkGetMacro(CrossSectionRadius,double); // Description // Return the parametric dimension of the class. virtual int GetDimension() {return 2;} // Description: // A torus. // This function performs the mapping \f$f(u,v) \rightarrow (x,y,x)\f$, returning it // as Pt. It also returns the partial derivatives Du and Dv. // \f$Pt = (x, y, z), Du = (dx/du, dy/du, dz/du), Dv = (dx/dv, dy/dv, dz/dv)\f$. // Then the normal is \f$N = Du X Dv\f$. virtual void Evaluate(double uvw[3], double Pt[3], double Duvw[9]); // Description: // Calculate a user defined scalar using one or all of uvw, Pt, Duvw. // uvw are the parameters with Pt being the the Cartesian point, // Duvw are the derivatives of this point with respect to u, v and w. // Pt, Duvw are obtained from Evaluate(). // This function is only called if the ScalarMode has the value // <API key>::<API key> // If the user does not need to calculate a scalar, then the // instantiated function should return zero. virtual double EvaluateScalar(double uvw[3], double Pt[3], double Duvw[9]); protected: vtkParametricTorus(); ~vtkParametricTorus(); // Variables double RingRadius; double CrossSectionRadius; private: vtkParametricTorus(const vtkParametricTorus&) VTK_DELETE_FUNCTION; void operator=(const vtkParametricTorus&) VTK_DELETE_FUNCTION; }; #endif
#SOL = Sol.app/Contents/MacOS/sol SOL = sol CC = @gcc ECHO = @echo RM = @rm -f LEX = @lex YACC = @yacc -d # profiling mode #CFLAGS = -Wall -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_GNU_SOURCE -g -pg # debug mode #CFLAGS = -Wall -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_GNU_SOURCE -g # release mode CFLAGS = -Wall -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_GNU_SOURCE -fomit-frame-pointer -O3 -fast # profiling mode #LFLAGS = -lobjc -framework OpenGL -framework Cocoa -framework GLUT -pg # non-profiling modes LFLAGS = -lobjc -framework OpenGL -framework Cocoa -framework GLUT -framework Accelerate PARSE_INPUT = \ Lexer.lex \ Parser.y PARSE_FILES = \ lex.yy.c \ y.tab.c \ y.tab.h C_FILES = \ $(PARSE_FILES) \ Array.c \ Box.c \ BSP.c \ Camera.c \ Image.c \ Lights.c \ OpenGL.c \ PhotonMap.c \ Scene.c \ SceneObjects.c \ Sol.c \ Sphere.c \ Triangle.c \ Vector3.c O_FILES = $(patsubst %.c, %.o, $(C_FILES)) all: $(SOL) clean: $(RM) $(O_FILES) $(PARSE_FILES) $(SOL) $(ECHO) "Sol is clean." %.o: %.c $(ECHO) "Compiling $<..." $(CC) $(CFLAGS) -c -o $@ $< $(PARSE_FILES): $(PARSE_INPUT) $(ECHO) "Lex'ing..." $(LEX) Lexer.lex $(ECHO) "Yacc'ing..." $(YACC) Parser.y $(SOL): $(O_FILES) $(ECHO) "Linking..." $(CC) $(LFLAGS) -o $@ $(O_FILES) $(ECHO) "Sol is ready."
// tests for POST /api/product "use strict"; var fluid = require("infusion"); var namespace = "gpii.ul.product.post.tests"; var postTests = fluid.registerNamespace(namespace); postTests.loader = require("../../../../../config/lib/config-loader"); postTests.config = postTests.loader.loadConfig(require("../../../../../config/test-pouch.json")); // TODO: When we add support for version control, we should test it // TODO: When we add support for attribution, we should test it postTests.loginHelper = require("../../../lib/login-helper")(postTests.config); postTests.schemaHelper = require("../../../../schema/lib/schema-helper")(postTests.config); postTests.testUtils = require("../../../tests/lib/testUtils")(postTests.config); postTests.request = require("request"); postTests.validRecord = require("../../../../../test/data/product/product-sample.json"); // We need to remove this to assist with deep comparisons, as "updated" will always be different. // TODO: For now we use an empty record for our 'invalid' tests. Eventually we should use a range of mistakes... postTests.invalidRecord = {}; postTests.apiUrl = postTests.config.express.baseUrl + postTests.config.express.apiPath; postTests.productApiUrl = postTests.apiUrl + "product"; postTests.generalize = function(object) { var newObject = JSON.parse(JSON.stringify(object)); var fieldsToRemove = ["_id","_rev","updated"]; fieldsToRemove.forEach(function(field){ if (newObject[field]){ delete newObject[field]; } }); return newObject; }; postTests.loadPouch = function() { postTests.pouch = require("../../../tests/lib/pouch")(postTests.config); postTests.pouch.start(function() { postTests.startExpress(); }); }; // Spin up an express instance postTests.startExpress = function() { postTests.express = require("../../../tests/lib/express")(postTests.config); postTests.express.start(function() { var bodyParser = require("body-parser"); postTests.express.app.use(bodyParser.json()); // /api/user, provided by express-couchuser var user = require("../../../user")(postTests.config); postTests.express.app.use("/", user.router); var product = require("../../index.js")(postTests.config); postTests.express.app.use(postTests.config.express.apiPath + "product", product.router); postTests.runTests(); }); }; postTests.runTests = function() { console.log("Running tests..."); var jqUnit = require("jqUnit"); jqUnit.module("POST /api/product"); jqUnit.asyncTest("Use POST to create a new record (not logged in)", function() { var options = { "url": postTests.productApiUrl, "json": postTests.validRecord }; var request = require("request"); request.post(options, function(e,r,b) { jqUnit.start(); jqUnit.assertNull("There should be no raw errors returned.", e); jqUnit.assertEquals("The response should indicate that a login is required.", 401, r.statusCode); jqUnit.assertFalse("The response should not be 'ok'", b.ok); jqUnit.assertNull("There should not be a record returned.", b.record); }); }); jqUnit.asyncTest("Use POST to update an existing record (should fail)", function() { postTests.loginHelper.login(jqUnit, {}, function(){ var updatedRecord = JSON.parse(JSON.stringify(postTests.validRecord)); updatedRecord.description = "This record has been updated."; var options = { "url": postTests.productApiUrl, "json": updatedRecord, "jar": postTests.loginHelper.jar }; postTests.request.post(options, function(e,r,b) { jqUnit.start(); jqUnit.assertNull("There should be no raw errors returned", e); jqUnit.assertFalse("The response should not be 'ok'", b.ok); jqUnit.assertEquals("The status code should be 409", 409, r.statusCode); jqUnit.stop(); postTests.loginHelper.logout(jqUnit, {}); }); }); }); jqUnit.asyncTest("Use POST to create a new record (logged in)", function() { postTests.loginHelper.login(jqUnit, {}, function(){ var newRecord = JSON.parse(JSON.stringify(postTests.validRecord)); newRecord.source = "unified"; newRecord.uid = "completelyNewRecord"; newRecord.sid = "completelyNewRecord"; var options = { "url": postTests.productApiUrl, "json": newRecord, "jar": postTests.loginHelper.jar }; postTests.request.post(options, function(e,r,b) { jqUnit.start(); jqUnit.assertNull("There should be no raw errors returned", e); jqUnit.assertNull("There should be no validation errors returned", b.errors); jqUnit.stop(); // Make sure the record was actually created var checkOptions = { "url": postTests.productApiUrl + "/" + newRecord.source + "/" + newRecord.sid }; postTests.request.get(checkOptions, function(e,r,b) { jqUnit.start(); jqUnit.assertNull("There should be no errors returned",e); var jsonData = JSON.parse(b); var savedRecord = jsonData.record; jqUnit.assertValue("There should be a record returned (" + JSON.stringify(b) + ").", savedRecord); if (savedRecord) { // Validate the outPOST for the process to confirm that what is delivered can be handed right back to the API... var errors = postTests.schemaHelper.validate("record", savedRecord); jqUnit.assertFalse("There should be no errors returned when validating the final results of the process...", errors); jqUnit.assertDeepEq("The updated record should be the same (in general) as the POST content", postTests.generalize(newRecord), postTests.generalize(savedRecord)); } jqUnit.stop(); postTests.loginHelper.logout(jqUnit, {}); }); }); }); }); jqUnit.asyncTest("Use POST to attempt to create an invalid record (logged in)", function() { postTests.loginHelper.login(jqUnit, {}, function(){ var newRecord = JSON.parse(JSON.stringify(postTests.invalidRecord)); var options = { "url": postTests.productApiUrl, "json": newRecord, "jar": postTests.loginHelper.jar }; postTests.request.post(options, function(e,r,b) { jqUnit.start(); jqUnit.assertNull("There should be no raw errors returned", e); jqUnit.assertTrue("There should be validation errors returned", b.errors && Object.keys(b.errors).length > 0); jqUnit.stop(); postTests.loginHelper.logout(jqUnit, {}); }); }); }); jqUnit.asyncTest("Use POST to attempt to create a unified record whose sid does not match its uid", function() { postTests.loginHelper.login(jqUnit, {}, function(){ var newRecord = postTests.generalize(JSON.parse(JSON.stringify(postTests.validRecord))); newRecord.source = "unified"; newRecord.sid = "newValue"; newRecord.uid = "anotherNewValue"; var options = { "url": postTests.productApiUrl, "json": newRecord, "jar": postTests.loginHelper.jar }; postTests.request.post(options, function(e,r) { jqUnit.start(); jqUnit.assertNull("There should be no raw errors returned", e); jqUnit.assertEquals("The status code should be '400'", 400, r.statusCode); jqUnit.stop(); postTests.loginHelper.logout(jqUnit, {}); }); }); }); // TODO: Test versioning on all successful adds and updates }; postTests.loadPouch();
/* Drastic Dark by Juan Maria Martinez Arce juan[at]insignia4u.com light grey: #cfcfcf medium grey: #36393d dark grey: #1a1a1a interactive action yellow #ffff88 red #cc0000 light blue #E6EEFC dark blue #0B43A8 */ .small { font-size: 11px; font-style: normal; font-weight: normal; text-transform: normal; letter-spacing: normal; line-height: 1.4em; } .gray { color:#999999; font-family: Georgia, serif; font-size: 13px; font-style: italic; font-weight: normal; text-transform: normal; letter-spacing: normal; line-height: 1.6em; } .hightlight { background-color: #ffff88; font-weight: bold; color: #36393d; } a:link, a:visited, a:hover, a:active, h1, h2, h3 { color: #36393d; } a { -moz-outline: none; } body { color: #222; background: #cfcfcf; font-family: helvetica, arial, sans-serif; } hr { background: #f0f0ee; color: #f0f0ee; } #header { background: #36393d; } #header h1 { padding: 15px 0; font-size: 28px; font-style: normal; font-weight: bold; text-transform: normal; letter-spacing: -1px; line-height: 1.2em; } #header h1 a:link, #header h1 a:active, #header h1 a:hover, #header h1 a:visited { color: #FFF; } #user-navigation { top: auto; bottom: 5px; right: 25px; } #user-navigation a.logout { background: #cc0000; padding: 1px 4px; -moz-border-radius: 4px; -<API key>: 3px; } #main .block .content { background: #FFF; padding-top: 1px; } #main .block .content h2 { margin-left: 15px; font-size: 22px; font-style: normal; font-weight: bold; text-transform: normal; letter-spacing: -1px; line-height: 1.2em; } #main .block .content p { font-size: 13px; font-style: normal; font-weight: normal; text-transform: normal; letter-spacing: normal; line-height: 1.45em; } #sidebar .block { background: #FFF; } #sidebar .block h4 { font-weight: bold; } #sidebar .notice { background: #E6EEFC; } #sidebar .notice h4 { color: #0B43A8; } #main h3, #sidebar h3 { background: #36393d; color: #FFF; border-bottom: 5px solid #1a1a1a; } #main-navigation ul li { padding-left: 15px; } #main-navigation ul li a { padding: 8px 0; } #main-navigation ul li.active { padding: 0; margin-left: 15px; } #main-navigation ul li.active { margin-left: 15px; } #main-navigation ul li.active a { padding: 8px 15px; } /*#sidebar ul li a:link, #sidebar ul li a:visited { background: #FFF; border-bottom: 1px solid #F0F0EE; text-decoration: none; } #sidebar ul li a:hover, #sidebar ul li a:active { background: #666666; color: #ffffff;; }*/ #main-navigation { background: #1a1a1a; } #main-navigation ul li { background: #1a1a1a; margin-right: 0; } #main-navigation ul li.active { background: #f0f0ee; } #main-navigation ul li a:link, #main-navigation ul li a:visited, #main-navigation ul li a:hover, #main-navigation ul li a:active, .<API key> ul li a:link, .<API key> ul li a:visited, .<API key> ul li a:hover, .<API key> ul li a:active, #user-navigation ul li a:link, #user-navigation ul li a:visited, #user-navigation ul li a:hover, #user-navigation ul li a:active { text-decoration: none; color: #FFF; } .<API key> li a:hover { background: #666666; } #main-navigation ul li.active a:link, #main-navigation ul li.active a:visited, #main-navigation ul li.active a:hover, #main-navigation ul li.active a:active { color: #1a1a1a; } .<API key> { background: #36393d; border-bottom-color: #1a1a1a; } .<API key> ul li.active, .<API key> ul li.active a:hover { background-color: #1a1a1a; } #footer .block { color: #FFF; background: #1a1a1a; } #footer .block p { margin: 0; padding: 10px; } /* pagination */ .pagination a, .pagination span { background: #cfcfcf; -moz-border-radius: 3px; border: 1px solid #c1c1c1; } .pagination span.current { background: #36393d; color: #FFF; border: 1px solid #36393d; } .pagination a { color: #1a1a1a; } .pagination a:hover { border: 1px solid #666; } /* tables */ .table th { background: #36393d; color: #FFF; } .table td { border-bottom:1px solid #F0F0EE; } .table tr.even { background: #ebebeb; } /* forms */ .form label.label { color: #666666; } .form input.text_field, .form textarea.text_area { width: 100%; border: 1px solid #cfcfcf; } .form input.button { background: #cfcfcf; -moz-border-radius: 5px; border: 1px solid #c1c1c1; padding: 2px 5px; cursor: pointer; color: #36393d; font-weight: bold; font-size: 11px; } .form input.button:hover { border: 1px solid #666; } .form .description { font-style: italic; color: #8C8C8C; font-size: .9em; } .form .navform a { color: #cc0000; } /* flash-messages */ .flash .message { -moz-border-radius: 3px; -<API key>: 3px; text-align:center; margin: 0 auto 15px; } .flash .message p { margin:8px; } .flash .error { border: 1px solid #fbb; background-color: #fdd; } .flash .warning { border: 1px solid #fffaaa; background-color: #ffffcc; } .flash .notice { border: 1px solid #1FDF00; background-color: #BBFFB6; } /* lists */ ul.list li { border-bottom-color: #F0F0EE; border-bottom-width: 1px; border-bottom-style: solid; } ul.list li .item .avatar { border-color: #F0F0EE; border-width: 1px; border-style: solid; padding: 2px; } /* box */ #box .block { background: #FFF; } #box .block h2 { background: #36393d; color: #FFF; } /* rounded borders */ #main, #main-navigation, #main-navigation li, .<API key>, #main .block, #sidebar .block, #sidebar h3, #main h3, ul.list li, #footer .block, .form input.button, #box .block, #box .block h2 { -<API key>: 4px; -<API key>: 4px; -<API key>: 4px; -<API key>: 4px; } .<API key> li.first a, .<API key> ul li.first, .table th.first, .table th.first { -<API key>: 4px; -<API key>: 4px; } .table th.last { -<API key>: 4px; -<API key>: 4px; } .<API key> ul li.first { -<API key>: 4px; -<API key>: 4px; } #sidebar, #sidebar .block, #main .block, #sidebar ul.navigation, ul.list li, #footer .block, .form input.button, #box .block { -<API key>: 4px; -<API key>: 4px; -<API key>: 4px; -<API key>: 4px; } .<API key> { border-bottom-width: 5px; }
from rtree import index import numpy as np #from shapely.prepared import prep import shapely def polygon2points(p): """ convert a polygon to a sequence of points for DS documents :param p: shapely.geometry.Polygon returns a string representing the set of points """ return ",".join(list("%s,%s"%(x,y) for x,y in p.exterior.coords)) def sPoints2tuplePoints(s): """ convert a string (from DSxml) to a polygon :param s: string = 'x,y x,y...' returns a Geometry """ # lList = s.split(',') # return [(float(x),float(y)) for x,y in zip(lList[0::2],lList[1::2])] return [ (float(x),float(y)) for sxy in s.split(' ') for (x,y) in sxy.split(',') ] def iuo(z1,z2): """ intersection over union :param z1: polygon :param z2: polygon returns z1.intersection(z2) / z1.union(z2) """ assert z1.isvalid assert z2.isvalid return z1.intersection(z2) / z1.union(z2) def populateGeo(lZones:list(),lElements:list()): """ affect lElements i to lZones using argmax(overlap(elt,zone) """ lIndElements = index.Index() dPopulated = {} for pos, z in enumerate(lZones): # lIndElements.insert(pos, cell.toPolygon().bounds) # print (cell,cell.is_valid,cell.bounds) lIndElements.insert(pos, z.bounds) aIntersection = np.zeros((len(lElements),len(lZones)),dtype=float) for j,elt in enumerate(lElements): ll = lIndElements.intersection(elt.bounds) for x in ll: try:aIntersection[j][x] = elt.intersection(lZones[x]).area except shapely.errors.TopologicalError: pass #This operation could not be performed. Reason: unknown for i,e in enumerate(lElements): best = np.argmax(aIntersection[i]) # aIntersection == np.zeros : empty if aIntersection[i][best]>0: try: dPopulated[best].append(i) except KeyError:dPopulated[best] = [i] return dPopulated if __name__ == "__main__": # def test_geo(): from shapely.geometry import Polygon lP= [] for i in range(0,100,10): lP.append(Polygon(((i,i),(i,i+10),(i+10,i+10),(i+10,i)))) # print (lP[-1]) lE= [] for i in range(0,100,5): lE.append(Polygon(((i,i),(i,i+9),(i+9,i+9),(i+9,i)))) # print (lE[-1]) dres = populateGeo(lP,lE) for item in dres: print (lE[item],[lE[x].wkt for x in dres[item]]) # print(polygon2points(lP[0]))
#include "shadow.h" #include <execinfo.h> #include <sys/types.h> #include <unistd.h> guint utility_ipPortHash(in_addr_t ip, in_port_t port) { GString* buffer = g_string_new(NULL); g_string_printf(buffer, "%u:%u", ip, port); guint hash_value = g_str_hash(buffer->str); g_string_free(buffer, TRUE); return hash_value; } guint utility_int16Hash(gconstpointer value) { utility_assert(value); /* make sure upper bits are zero */ gint key = 0; key = (gint) *((gint16*)value); return g_int_hash(&key); } gboolean utility_int16Equal(gconstpointer value1, gconstpointer value2) { utility_assert(value1 && value2); /* make sure upper bits are zero */ gint key1 = 0, key2 = 0; key1 = (gint) *((gint16*)value1); key2 = (gint) *((gint16*)value2); return g_int_equal(&key1, &key2); } gint <API key>(const gdouble* value1, const gdouble* value2, gpointer userData) { utility_assert(value1 && value2); /* return neg if first before second, pos if second before first, 0 if equal */ return value1 == value2 ? 0 : value1 < value2 ? -1 : +1; } gint <API key>(const SimulationTime* value1, const SimulationTime* value2, gpointer userData) { utility_assert(value1 && value2); /* return neg if first before second, pos if second before first, 0 if equal */ return value1 == value2 ? 0 : value1 < value2 ? -1 : +1; } gchar* utility_getHomePath(const gchar* path) { GString* sbuffer = g_string_new(""); if(g_ascii_strncasecmp(path, "~", 1) == 0) { /* replace ~ with home directory */ const gchar* home = g_get_home_dir(); <API key>(sbuffer, "%s%s", home, path+1); } else { <API key>(sbuffer, "%s", path); } return g_string_free(sbuffer, FALSE); } guint <API key>(const gchar* freqFilename) { /* get the raw speed of the experiment machine */ guint rawFrequencyKHz = 0; gchar* contents = NULL; gsize length = 0; GError* error = NULL; if(freqFilename && g_file_get_contents(freqFilename, &contents, &length, &error)) { utility_assert(contents); rawFrequencyKHz = (guint)atoi(contents); g_free(contents); } if(error) { g_error_free(error); } return rawFrequencyKHz; } static GString* <API key>(const gchar* file, gint line, const gchar* function, const gchar* message) { GString* errorString = g_string_new("**ERROR ENCOUNTERED**\n"); <API key>(errorString, "\tAt process: %i (parent %i)\n", (gint) getpid(), (gint) getppid()); <API key>(errorString, "\tAt file: %s\n", file); <API key>(errorString, "\tAt line: %i\n", line); <API key>(errorString, "\tAt function: %s\n", function); <API key>(errorString, "\tMessage: %s\n", message); return errorString; } static GString* <API key>() { GString* backtraceString = g_string_new("**BEGIN BACKTRACE**\n"); void *array[100]; gsize size, i; gchar **strings; size = backtrace(array, 100); strings = backtrace_symbols(array, size); <API key>(backtraceString, "Obtained %zd stack frames:\n", size); for (i = 0; i < size; i++) { <API key>(backtraceString, "\t%s\n", strings[i]); } g_free(strings); <API key>(backtraceString, "**END BACKTRACE**\n"); return backtraceString; } void utility_handleError(const gchar* file, gint line, const gchar* function, const gchar* message) { GString* errorString = <API key>(file, line, function, message); GString* backtraceString = <API key>(); if(!isatty(fileno(stdout))) { g_print("%s%s**ABORTING**\n", errorString->str, backtraceString->str); } g_printerr("%s%s**ABORTING**\n", errorString->str, backtraceString->str); g_string_free(errorString, TRUE); g_string_free(backtraceString, TRUE); abort(); }
# -*- coding: utf-8 -*- from django.shortcuts import render from units.models import Unit def startpage(request): """Start page. Shows list of units available for statistics/filtering. """ units = Unit.objects.all() # t = loader.get_template('startpage.html') # c = RequestContext(request, { # 'units': units, return render(request, 'startpage.html', {'units': units, })
// modification, are permitted provided that the following conditions // are met: // documentation and/or other materials provided with the distribution. // 3. Neither the name of the project nor the names of its contributors // may be used to endorse or promote products derived from this software // THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. #include <Game/GameServer/Common/Constants.hpp> #include <Language/Interface/RequestBuilder.hpp> #include <Test/include/Client.hpp> #include <Test/include/IntegrationTest.hpp> class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "1")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::<API key>, mCommandReply->getCode()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login1", "Password")); mClient.send(mRequestBuilder.<API key>("Login2", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login1", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login1", "Password", "Land", "Settlement")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login2", "Password", "<API key>", "Settlement", "<API key>", "1")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::<API key>, mCommandReply->getCode()); } // TODO: <API key>. class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "60")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "50")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode()); } TEST_F(<API key>, <API key>) { ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "regularfarm", "1")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "workerfarmernovice", "11")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode()); } TEST_F(<API key>, <API key>) { ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "100")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode()); } TEST_F(<API key>, <API key>) { ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "63")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode()); } TEST_F(<API key>, <API key>) { ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "1")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode()); } TEST_F(<API key>, <API key>) { ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "0")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode()); } TEST_F(<API key>, <API key>) { ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "workerjoblessnovice", "1")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode()); } TEST_F(<API key>, <API key>) { ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "BadPassword", "<API key>", "Settlement", "<API key>", "1")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::<API key>, mCommandReply->getCode()); } class <API key> : public IntegrationTest { protected: <API key>() { mClient.send(mRequestBuilder.<API key>("Login", "Password")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land")); mClient.send(mRequestBuilder.<API key>("Login", "Password", "Land", "Settlement")); mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World")); mCommandReply = mClient.send(mRequestBuilder.<API key>( "Login", "Password", "<API key>", "Settlement", "<API key>", "1")); } Client mClient; Language::RequestBuilder mRequestBuilder; Language::Command::Handle mCommandReply; }; TEST_F(<API key>, ReturnsProperID) { ASSERT_EQ(Language::<API key>, mCommandReply->getID()); } TEST_F(<API key>, ReturnsProperCode) { ASSERT_EQ(Game::<API key>, mCommandReply->getCode()); }
package org.jcoderz.commons.taskdefs; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.jcoderz.commons.util.IoUtil; /** * Ant task that performs XSL transformation for a set of input files. * * @author Michael Griffel */ public class XsltBatchProcessor extends Task { private String mStyleSheet = "default.xsl"; private FileSet mFiles = new FileSet(); private boolean <API key> = true; /** terminate ant build on error. */ private boolean mFailOnError = false; /** * Set whether we should fail on an error. * * @param b Whether we should fail on an error. */ public void setFailonerror (boolean b) { mFailOnError = b; } /** * Set the XSL Stylesheet to use. * * @param f The name of the XSL Stylesheet file. * @see XsltBasedTask#<API key>() */ public void setXsl (String f) { mStyleSheet = f; } /** * XML files that are used as input documents for the * transformation. * * @param fs fileset of XML files. */ public void addFiles (FileSet fs) { mFiles = fs; } /** * {@inheritDoc} */ public void execute () throws BuildException { try { final XsltBasedTask xsltTask = new XsltBasedTask() { String <API key> () { return mStyleSheet; } }; final Project myProject = getProject(); final DirectoryScanner ds = mFiles.getDirectoryScanner(myProject); final String[] includedFiles = ds.getIncludedFiles(); log("Transforming " + includedFiles.length + " files in directory " + ds.getBasedir()); for (int i = 0; i < includedFiles.length; i++) { final String f = includedFiles[i]; final File orig = new File(ds.getBasedir(), f); final File out; try { out = File.createTempFile("jcoderz", "tmp"); } catch (IOException e) { throw new BuildException( "Failed to create temp file: " + e, e); } xsltTask.setProject(myProject); xsltTask.setTaskName("xslt"); xsltTask.setIn(orig); xsltTask.setOut(out); xsltTask.setDestdir(myProject.getBaseDir()); xsltTask.setForce(true); xsltTask.setFailonerror(mFailOnError); xsltTask.setLogLevel(Project.MSG_VERBOSE); xsltTask.<API key>(<API key>); log("Transforming file " + orig, Project.MSG_VERBOSE); xsltTask.execute(); if (out.exists()) { if (!orig.delete()) { throw new BuildException("Failed to delete " + orig); } if (!out.renameTo(orig)) { // try copy && delete try { safeMove(out, orig); } catch (IOException e) { throw new BuildException("Failed to move file " + out, e); } } } } } catch (BuildException e) { if (mFailOnError) { throw e; } log(e.getMessage(), Project.MSG_ERR); } } /** * If set to <tt>false</tt>, external entities will not be * resolved. * * @param b new value. */ public void <API key> (boolean b) { <API key> = b; } private void safeMove (File source, File dest) throws IOException { final FileInputStream in = new FileInputStream(source); final FileOutputStream out = new FileOutputStream(dest); try { IoUtil.copy(in, out); if (!source.delete()) { throw new BuildException("Failed to delete " + source); } } finally { IoUtil.close(in); IoUtil.close(out); } } }
package i5.las2peer.services.<API key>.models.microservice; import java.util.ArrayList; import java.util.HashMap; import i5.cae.simpleModel.<API key>; import i5.cae.simpleModel.node.SimpleNode; import i5.las2peer.services.<API key>.exception.ModelParseException; import i5.las2peer.services.<API key>.models.microservice.HttpPayload.PayloadType; /** * * HttpMethod data class. Represents an HTTP method, which is part of a microservice model. * */ public class HttpMethod { /** * * Represents the four possible method types an {@link HttpMethod} can have. * */ public enum MethodType { GET, POST, PUT, DELETE } private MethodType methodType; private String modelId; private String name; private String path; private ArrayList<InternalCall> internalCalls = new ArrayList<InternalCall>(); private ArrayList<HttpPayload> payloads = new ArrayList<HttpPayload>(); private ArrayList<HttpResponse> responses = new ArrayList<HttpResponse>(); private HashMap<String, HttpPayload> nodeIdPayloads = new HashMap<String, HttpPayload>(); private HashMap<String, HttpResponse> nodeIdResponses = new HashMap<String, HttpResponse>(); /** * * Creates a new {@link HttpMethod}. * * @param node a {@link i5.cae.simpleModel.node.SimpleNode} containing the HttpMethod * representation. * * @throws ModelParseException if something goes wrong during parsing the node * */ public HttpMethod(SimpleNode node) throws ModelParseException { this.modelId = node.getId(); for (int nodeIndex = 0; nodeIndex < node.getAttributes().size(); nodeIndex++) { <API key> attribute = node.getAttributes().get(nodeIndex); switch (attribute.getName()) { case "methodType": switch (attribute.getValue()) { case "GET": this.methodType = MethodType.GET; break; case "POST": this.methodType = MethodType.POST; break; case "PUT": this.methodType = MethodType.PUT; break; case "DELETE": this.methodType = MethodType.DELETE; break; default: throw new ModelParseException( "Unknown HTTPMethod methodType: " + attribute.getValue()); } break; case "name": this.name = attribute.getValue(); if (this.name.contains(" ")) { throw new ModelParseException( "HttpMethod name contains invalid characters: " + this.name); } break; case "path": this.path = attribute.getValue(); break; default: throw new ModelParseException( "Unknown HTTPMethod attribute name: " + attribute.getName()); } } } public String getName() { return this.name; } public String getPath() { return this.path; } public ArrayList<InternalCall> getInternalCalls() { return this.internalCalls; } public MethodType getMethodType() { return this.methodType; } public String getModelId() { return this.modelId; } public ArrayList<HttpPayload> getHttpPayloads() { return this.payloads; } public HashMap<String, HttpPayload> getNodeIdPayloads() { return this.nodeIdPayloads; } public ArrayList<HttpResponse> getHttpResponses() { return this.responses; } public HashMap<String, HttpResponse> getNodeIdResponses() { return this.nodeIdResponses; } public void addInternalCall(InternalCall call) { this.internalCalls.add(call); } public void addHttpPayload(HttpPayload payload) { this.payloads.add(payload); } public void addNodeIdPayload(String nodeId, HttpPayload payload) { this.nodeIdPayloads.put(nodeId, payload); } public void addHttpResponse(HttpResponse response) { this.responses.add(response); } public void addNodeIdResponse(String nodeId, HttpResponse payload) { this.nodeIdResponses.put(nodeId, payload); } /** * * Checks the (until now added) payloads and responses for (semantical) correctness. * * @throws ModelParseException if the check revealed incorrectness * */ public void <API key>() throws ModelParseException { // no payload but at least one response is ok if (this.payloads.isEmpty() && !this.responses.isEmpty()) { return; } // has to have at least one response if (this.responses.isEmpty()) { throw new ModelParseException("Http Method " + this.name + " contains no response!"); } // check responses for (int responseIndex = 0; responseIndex < this.responses.size(); responseIndex++) { if (responses.get(responseIndex).getName().contains(" ")) { throw new ModelParseException("HttpResponse name contains invalid characters: " + responses.get(responseIndex).getName()); } if (responses.get(responseIndex).getResultName().contains(" ")) { throw new ModelParseException("HttpResponse result name contains invalid characters: " + responses.get(responseIndex).getResultName()); } } // check payloads boolean <API key> = false; for (int payloadIndex = 0; payloadIndex < this.payloads.size(); payloadIndex++) { if (payloads.get(payloadIndex).getName().contains(" ")) { throw new ModelParseException("HttpPayload name contains invalid characters: " + payloads.get(payloadIndex).getName()); } if (payloads.get(payloadIndex).getPayloadType() != PayloadType.PATH_PARAM) { if (<API key>) { throw new ModelParseException( "More than one content parameter in HTTPMethod " + this.name); } else { <API key> = true; } } } // TODO check more? } }
// Package five00px provides ... package five00px import ( "fmt" "net" "net/http" "net/url" "strings" "github.com/Sirupsen/logrus" "github.com/mrjones/oauth" "github.com/toqueteos/webbrowser" ) // AccessToken is an alias for oauth.AccessToken structure type AccessToken oauth.AccessToken type oAuth struct { c *oauth.Consumer t *oauth.AccessToken Port int } type authResp struct { token string verifier string err error } func (oa *oAuth) Auth() (*AccessToken, error) { log := logger.WithFields(logrus.Fields{ "context": "Auth", }) reqToken, u, err := oa.c.<API key>(fmt.Sprint("http://127.0.0.1:", oa.Port)) if err != nil { log.WithError(err).Error("Unable to create OAuth provider") return nil, ErrAuth } l, err := net.Listen("tcp", fmt.Sprint(":", oa.Port)) if err != nil { log.WithError(err).Error("Cannot start TCP service") return nil, ErrAuth } c := make(chan authResp) go serveOAuthResp(l, &c) err = webbrowser.Open(u) if err != nil { log.WithError(err).Error("Cannot start browser") return nil, ErrAuth } auth := <-c _ = l.Close() if auth.err != nil { log.WithError(auth.err).Error("Authentication error") return nil, auth.err } accessToken, err := oa.c.AuthorizeToken(reqToken, auth.verifier) if err != nil { log.WithError(err).Error("Unable to authorize token") return nil, err } token := AccessToken(*accessToken) return &token, nil } func (oa *oAuth) createClient(t *AccessToken) (*http.Client, error) { at := oauth.AccessToken(*t) return oa.c.MakeHttpClient(&at) } func serveOAuthResp(l net.Listener, stop *chan authResp) { s := &http.Server{ Handler: &myHandler{ stop, }, } _ = s.Serve(l) } type myHandler struct { a *chan authResp } func newOAuth(key, secret string) oAuth { return oAuth{ c: genOAuthConsumer(key, secret), Port: 8088, } } func genOAuthConsumer(consumerKey, consumerSecret string) *oauth.Consumer { return oauth.NewConsumer( consumerKey, consumerSecret, oauth.ServiceProvider{ RequestTokenUrl: mainAPIUrl + "oauth/request_token", AuthorizeTokenUrl: mainAPIUrl + "oauth/authorize", AccessTokenUrl: mainAPIUrl + "oauth/access_token", }) } func parseAccessToken(urlQuery string) (oauthToken string, oauthVerifier string, err error) { if strings.HasPrefix(urlQuery, "/?") { urlQuery = urlQuery[2:] } val, err := url.ParseQuery(urlQuery) if err != nil { return "", "", err } tokens := val["oauth_token"] verifiers := val["oauth_verifier"] if tokens != nil && verifiers != nil { oauthToken = tokens[0] oauthVerifier = verifiers[0] } return oauthToken, oauthVerifier, nil } func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { oauthToken, oauthVerifier, err := parseAccessToken(r.URL.String()) if err != nil { *h.a <- authResp{"", "", err} } fmt.Fprintln(w, "Authentication complete.") *h.a <- authResp{oauthToken, oauthVerifier, nil} }
<?php require_once('./class/paypal.php'); //where necessary require_once('./class/httprequest.php'); //where necessary //Use this form for production server //$r = new PayPal(true); //Use this form for sandbox tests $r = new PayPal(); $ret = ($r->doExpressCheckout(10, 'A perfect item!')); //An error occured. The auxiliary information is in the $ret array echo 'Error:'; print_r($ret); ?>
"""Showcases *Automatic Colour Conversion Graph* computations.""" import numpy as np import colour from colour.utilities import message_box message_box("Automatic Colour Conversion Graph") message_box( 'Converting a "ColorChecker" "dark skin" sample spectral distribution to ' '"Output-Referred" "sRGB" colourspace.' ) sd_dark_skin = colour.SDS_COLOURCHECKERS["ColorChecker N Ohta"]["dark skin"] print(colour.convert(sd_dark_skin, "Spectral Distribution", "sRGB")) print( colour.XYZ_to_sRGB( colour.sd_to_XYZ( sd_dark_skin, illuminant=colour.SDS_ILLUMINANTS["D65"] ) / 100 ) ) print("\n") RGB = np.array([0.45675795, 0.30986982, 0.24861924]) message_box( f'Converting to the "CAM16-UCS" colourspace from given "Output-Referred" ' f'"sRGB" colourspace values:\n\n\t{RGB}' ) print(colour.convert(RGB, "Output-Referred RGB", "CAM16UCS")) specification = colour.XYZ_to_CAM16( colour.sRGB_to_XYZ(RGB) * 100, XYZ_w=colour.xy_to_XYZ( colour.CCS_ILLUMINANTS["CIE 1931 2 Degree Standard Observer"]["D65"] ) * 100, L_A=64 / np.pi * 0.2, Y_b=20, ) print( colour.<API key>( colour.utilities.tstack( [ specification.J, specification.M, specification.h, ] ) ) / 100 ) print("\n") Jpapbp = np.array([0.39994811, 0.09206558, 0.0812752]) message_box( f'Converting to the "Output-Referred" "sRGB" colourspace from given ' f'"CAM16-UCS" colourspace colourspace values:\n\n\t{RGB}' ) print( colour.convert( Jpapbp, "CAM16UCS", "sRGB", verbose_kwargs={"describe": "Extended", "width": 75}, ) ) J, M, h = colour.utilities.tsplit(colour.<API key>(Jpapbp * 100)) specification = colour.<API key>(J=J, M=M, h=h) print( colour.XYZ_to_sRGB( colour.CAM16_to_XYZ( specification, XYZ_w=colour.xy_to_XYZ( colour.CCS_ILLUMINANTS["CIE 1931 2 Degree Standard Observer"][ "D65" ] ) * 100, L_A=64 / np.pi * 0.2, Y_b=20, ) / 100 ) )
// viztool - a tool for visualizing collections of java classes package com.samskivert.viztool; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import com.samskivert.swing.*; /** * The top-level frame in which visualizations are displayed. */ public class VizFrame extends JFrame { public VizFrame (Visualizer viz) { super("viztool"); // quit if we're closed <API key>(EXIT_ON_CLOSE); // create our controller and panel for displaying visualizations VizPanel vpanel = new VizPanel(viz); VizController vctrl = new VizController(vpanel); // create some control buttons GroupLayout gl = new HGroupLayout(GroupLayout.NONE); gl.setJustification(GroupLayout.RIGHT); JPanel bpanel = new JPanel(gl); JButton btn; btn = new JButton("Print"); btn.setActionCommand(VizController.PRINT); btn.addActionListener(VizController.DISPATCHER); bpanel.add(btn); btn = new JButton("Previous page"); btn.setActionCommand(VizController.BACKWARD_PAGE); btn.addActionListener(VizController.DISPATCHER); bpanel.add(btn); btn = new JButton("Next page"); btn.setActionCommand(VizController.FORWARD_PAGE); btn.addActionListener(VizController.DISPATCHER); bpanel.add(btn); btn = new JButton("Quit"); btn.setActionCommand(VizController.QUIT); btn.addActionListener(VizController.DISPATCHER); bpanel.add(btn); // create a content pane to contain everything JPanel content = new ContentPanel(vctrl); gl = new VGroupLayout(GroupLayout.STRETCH); content.setLayout(gl); content.setBorder(BorderFactory.createEmptyBorder( BORDER, BORDER, BORDER, BORDER)); content.add(vpanel); content.add(bpanel, GroupLayout.FIXED); setContentPane(content); } protected static final class ContentPanel extends JPanel implements ControllerProvider { public ContentPanel (VizController ctrl) { _ctrl = ctrl; } public Controller getController () { return _ctrl; } protected Controller _ctrl; } protected static final int BORDER = 5; // pixels }
#ifndef <API key> #define <API key> #include "Cosa/Types.h" #include "Cosa/Bits.h" #include "Cosa/Watchdog.hh" /** * Serial programming using the SPI interface and RESET pin. Connect the * device to the Arduino SPI pins; MOSI, MISO, SCK and SS/RESET. The member * functions implement the serial programming instruction set and * additional support functions for block read and write. */ class Programmer { private: /** Number of words (16-bits) per page */ uint8_t m_flash_pagesize; /** Number of bytes (8-bits) per page */ uint8_t m_eeprom_pagesize; public: /** * Construct programmer with given page size for read/write of * avr micro-controllers. * @param[in] pagesize number of words per program memory page. */ Programmer(uint8_t pagesize = 32) : m_flash_pagesize(pagesize), m_eeprom_pagesize(4) {} /** * Transfer data to and from the device. * @param[in] data to transfer. * @return data received. */ uint8_t transfer(uint8_t data) { #if defined(__ARDUINO_TINY__) USIDR = data; USISR = _BV(USIOIF); do { USICR = (_BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC)); } while ((USISR & _BV(USIOIF)) == 0); return (USIDR); #else SPDR = data; <API key>(SPSR, SPIF); return (SPDR); #endif } /** * Transfer instruction to the device and receive possible value. * @param[in] ip pointer to instruction (4 bytes) * @return data received. */ uint8_t transfer(uint8_t* ip) { transfer(ip[0]); transfer(ip[1]); transfer(ip[2]); return (transfer(ip[3])); } /** * Transfer instruction to the device and receive possible value. * @param[in] i0 to transfer (operation code). * @param[in] i1 to transfer (modifier or parameter). * @param[in] i2 to transfer (parameter). * @param[in] i3 to transfer (data). * @return data received. */ uint8_t transfer(uint8_t i0, uint8_t i1, uint8_t i2, uint8_t i3) { transfer(i0); transfer(i1); transfer(i2); return (transfer(i3)); } /** * Connect to the device over the SPI interface, reset and enable * programming. Returns true if the connection was successful * otherwise false. * @return bool. */ bool begin(); /** * Disconnect from the SPI interface. */ void end(); /** * Set the program memory page size in given number of bytes. * @param[in] bytes page size. */ void set_flash_pagesize(uint8_t bytes) { m_flash_pagesize = bytes / 2; } /** * Set the eeprom memory page size in given number of bytes. * @param[in] bytes page size. */ void set_eeprom_pagesize(uint8_t bytes) { m_eeprom_pagesize = bytes; } /** * Get the current program memory page size (number of words, 16-bits). * @return words page size. */ uint16_t get_flash_page(uint16_t addr) { return (addr & ~(m_flash_pagesize - 1)); } /** * Get the eeprom memory page size (number of bytes, 8-bits). * @return bytes page size. */ uint16_t get_eeprom_page(uint16_t addr) { return (addr & ~(m_eeprom_pagesize - 1)); } /** * Issue Programming Enable Serial Programming Instruction. Return * true if successful otherwise false. * @return bool. */ bool programming_enable() { transfer(0xAC); transfer(0x53); uint8_t res = transfer((uint8_t) 0x00); transfer((uint8_t) 0x00); return (res == 0x53); } /** * Issue Chip Erase (Program Memory/EEPROM) Serial Programming * Instruction. Waits for erase to complete. */ void chip_erase() { transfer(0xAC, 0x80, 0x00, 0x00); await(); } /** * Issue Poll (RDY/BSY) Serial Programming Instruction and return * true if the device is busy otherwise false. * @return bool. */ bool isbusy() { return (transfer(0xF0, 0x00, 0x00, 0x00) & 0x1); } /** * Wait for the device to complete the issued instruction. */ void await() { while (isbusy()) DELAY(1000); } /** * Issue Load Extended Address byte Serial Programming Instruction. * @param[in] addr extended program address. */ void <API key>(uint8_t addr) { transfer(0x4D, 0x00, addr, 0x00); } /** * Issue Load Program Memory Page, High byte, Serial Programming * Instruction. * @param[in] addr program word address. * @param[in] data high byte. */ void <API key>(uint8_t addr, uint8_t data) { transfer(0x48, 0x00, addr, data); } /** * Issue Load Program Memory Page, Low byte, Serial Programming * Instruction. * @param[in] addr program word address. * @param[in] data low byte. */ void <API key>(uint8_t addr, uint8_t data) { transfer(0x40, 0x00, addr, data); } /** * Issue Load EEPROM Memory Page (page access) Serial Programming * Instruction. * @param[in] addr eeprom byte address. * @param[in] data low byte. */ void <API key>(uint8_t addr, uint8_t data) { transfer(0xC1, 0x00, addr & 0x3, data); } /** * Issue Read Program Memory, High byte, Serial Programming * Instruction. * @param[in] addr program word address. * @return byte read. */ uint8_t <API key>(uint16_t addr) { return (transfer(0x28, addr >> 8, addr, 0x00)); } /** * Issue Read Program Memory, Low byte, Serial Programming * Instruction. * @param[in] addr program word address. * @return byte read. */ uint8_t <API key>(uint16_t addr) { return (transfer(0x20, addr >> 8, addr, 0x00)); } /** * Issue Read Program Memory, High and Low byte, Serial Programming * Instructions and return word (16-bit). * @param[in] addr program word address. * @return word read. */ uint16_t read_program_memory(uint16_t addr) { univ16_t data; data.high = <API key>(addr); data.low = <API key>(addr); return (data.as_uint16); } /** * Issue Read EEPROM Memory Serial Programming Instruction. * @param[in] addr eeprom byte address. * @return byte read. */ uint8_t read_eeprom_memory(uint16_t addr) { return (transfer(0xA0, addr >> 8, addr, 0x00)); } /** * Issue Read Lock bits Serial Programming Instruction. * @return byte read. */ uint8_t read_lock_bits() { return (transfer(0x58, 0x00, 0x00, 0x00)); } /** * Issue Read Signature Byte Serial Programming Instruction with * given address. * @param[in] addr signature byte address (0..2). * @return byte read. */ uint8_t read_signature_byte(uint8_t addr) { return (transfer(0x30, 0x00, addr & 0x3, 0x00)); } /** * Issue Read Fuse bits Serial Programming Instruction. * @return byte read. */ uint8_t read_fuse_bits() { return (transfer(0x50, 0x00, 0x00, 0x00)); } /** * Issue Read Fuse High bits Serial Programming Instruction. * @return byte read. */ uint8_t read_fuse_high_bits() { return (transfer(0x58, 0x08, 0x00, 0x00)); } /** * Issue Read Extended Fuse bits Serial Programming Instruction. * @return byte read. */ uint8_t <API key>() { return (transfer(0x50, 0x08, 0x00, 0x00)); } /** * Issue Read Calibration byte Serial Programming Instruction. * @return byte read. */ uint8_t <API key>() { return (transfer(0x38, 0x00, 0x00, 0x00)); } /** * Issue Write Program Memory Page Serial Programming Instruction * for given address. * @param[in] addr program word address. */ void <API key>(uint16_t addr) { transfer(0x4C, addr >> 8, addr, 0x00); await(); } /** * Issue Write EEPROM Memory Serial Programming Instruction at * given address with data. * @param[in] addr eeprom byte address (lsb). * @param[in] data to write. */ void write_eeprom_memory(uint16_t addr, uint8_t data) { transfer(0xC0, addr >> 8, addr, data); await(); } /** * Issue Write EEPROM Memory Page Serial Programming Instruction * for given address. * @param[in] page eeprom byte address (lsb). */ void <API key>(uint8_t page) { transfer(0xC2, page >> 8, page, 0x00); await(); } /** * Issue Write Lock bits Serial Programming Instruction * for given data. * @param[in] page eeprom byte address (lsb). */ void write_lock_bits(uint8_t data) { transfer(0xAC, 0xE0, 0x00, data); await(); } /** * Issue Write Fuse bits Serial Programming Instruction for given data. * @param[in] data fuse. */ void write_fuse_bits(uint8_t data) { transfer(0xAC, 0xA0, 0x00, data); await(); } /** * Issue Write Fuse High bits Serial Programming Instruction for given data. * @param[in] data fuse. */ void <API key>(uint8_t data) { transfer(0xAC, 0xA8, 0x00, data); await(); } /** * Issue Write Extended Fuse bits Serial Programming Instruction for * given data. * @param[in] data fuse. */ void <API key>(uint8_t data) { transfer(0xAC, 0xA4, 0x00, data); await(); } /** * Read program memory from the given source word address to the * destination buffer with the given size in bytes. Return the * number of bytes read or negative error code. * @param[in] dest destination buffer pointer. * @param[in] src source program word address. * @param[in] size number of bytes to read. */ int read_program_memory(uint8_t* dest, uint16_t src, size_t size); /** * Write program memory from the given source buffer with the given * size in bytes to the destination program word address. Return the * number of bytes written or negative error code. * @param[in] dest destination program word address. * @param[in] src source buffer pointer. * @param[in] size number of bytes to write. */ int <API key>(uint16_t dest, uint8_t* src, size_t size); /** * Read eeprom memory from the given source byte address to the * destination buffer with the given size in bytes. Return the * number of bytes read or negative error code. * @param[in] dest destination buffer pointer. * @param[in] src source eeprom memory byte address. * @param[in] size number of bytes to read. */ int read_eeprom_memory(uint8_t* dest, uint16_t src, size_t size); /** * Write eeprom memory from the given source buffer with the given * size in bytes to the destination program word address. Return the * number of bytes written or negative error code. * @param[in] dest destination eeprom memory byte address. * @param[in] src source buffer pointer. * @param[in] size number of bytes to write. */ int write_eeprom_memory(uint16_t dest, uint8_t* src, size_t size); }; #endif
## 1.1.3 * Update Flutter SDK constraint. ## 1.1.2 * Update lower bound of dart dependency to 2.1.0. ## 1.1.1 * Add attribute serverAuthCode. ## 1.1.0 * Add hasRequestedScope method to determine if an Oauth scope has been granted. * Add requestScope Method to request new Oauth scopes be granted by the user. ## 1.0.4 * Make the pedantic dev_dependency explicit. ## 1.0.3 * Remove the deprecated `author:` field from pubspec.yaml * Require Flutter SDK 1.10.0 or greater. ## 1.0.2 * Add missing documentation. ## 1.0.1 * Switch away from quiver_hashcode. ## 1.0.0 * Initial release.
<!DOCTYPE html> <html xmlns="http: <head> <meta charset="utf-8" /> <title>statsmodels.stats.moment_helpers.se_cov &#8212; statsmodels v0.10.1 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="<API key>" data-url_root="../" src="../_static/<API key>.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=<API key>"></script> <link rel="shortcut icon" href="../_static/<API key>.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.stats.mediation.Mediation" href="statsmodels.stats.mediation.Mediation.html" /> <link rel="prev" title="statsmodels.stats.moment_helpers.corr2cov" href="statsmodels.stats.moment_helpers.corr2cov.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/<API key>.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.stats.mediation.Mediation.html" title="statsmodels.stats.mediation.Mediation" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.stats.moment_helpers.corr2cov.html" title="statsmodels.stats.moment_helpers.corr2cov" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../stats.html" accesskey="U">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="<API key>"> <h1>statsmodels.stats.moment_helpers.se_cov<a class="headerlink" href=" <dl class="function"> <dt id="statsmodels.stats.moment_helpers.se_cov"> <code class="sig-prename descclassname">statsmodels.stats.moment_helpers.</code><code class="sig-name descname">se_cov</code><span class="sig-paren">(</span><em class="sig-param">cov</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/stats/moment_helpers.html <dd><p>get standard deviation from covariance matrix</p> <p>just a shorthand function np.sqrt(np.diag(cov))</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl class="simple"> <dt><strong>cov</strong><span class="classifier">array_like, square</span></dt><dd><p>covariance matrix</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl class="simple"> <dt><strong>std</strong><span class="classifier">ndarray</span></dt><dd><p>standard deviation from diagonal of cov</p> </dd> </dl> </dd> </dl> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="<API key>"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.stats.moment_helpers.corr2cov.html" title="previous chapter">statsmodels.stats.moment_helpers.corr2cov</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.stats.mediation.Mediation.html" title="next chapter">statsmodels.stats.mediation.Mediation</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.stats.moment_helpers.se_cov.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> & Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2. </div> </body> </html>
import random import numpy as np import copy class Genotype(): def __init__(self, L, M, N): self.genotype = np.random.randint(0, M, (L,N)) self.L = L self.M = M self.N = N def apply_mutation(self, i, j): gene = self.genotype[i][j] + random.randint(-2, 2) if gene < 0: gene += self.M elif gene > self.M - 1: gene -= self.M self.genotype[i][j] = gene def mutate(self): for i in range(self.L): for j in range(self.N): if random.random() < 1.0 / (self.L * self.N): self.apply_mutation(i, j) def return_genotype(self): return self.genotype def overwrite(self, genotype): self.genotype = copy.deepcopy(genotype) class Genetic(): def __init__(self, L, M, N, pop): """L: layers, M: units in each layer, N: number of active units, pop: number of gene""" self.genotypes = [Genotype(L, M, N) for _ in range(pop)] self.pop = pop self.control_fixed = random.sample(self.genotypes,1)[0] def <API key>(self): genotypes = [gene.return_genotype() for gene in self.genotypes] return genotypes def return_control(self): return self.control_fixed def <API key>(self): return self.control_fixed.return_genotype() def sample(self): return random.sample(self.genotypes, 2) def overwrite(self, genotypes, fitnesses): win = genotypes[fitnesses.index(max(fitnesses))] lose = genotypes[fitnesses.index(min(fitnesses))] genotype = win.return_genotype() lose.overwrite(genotype) lose.mutate()
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_22) on Mon Apr 04 20:31:34 CEST 2016 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.slf4j.impl.JDK14LoggerFactory (SLF4J 1.7.21 API) </TITLE> <META NAME="date" CONTENT="2016-04-04"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.slf4j.impl.JDK14LoggerFactory (SLF4J 1.7.21 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/slf4j/impl/JDK14LoggerFactory.html" title="class in org.slf4j.impl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/slf4j/impl/\<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JDK14LoggerFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>org.slf4j.impl.JDK14LoggerFactory</B></H2> </CENTER> No usage of org.slf4j.impl.JDK14LoggerFactory <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/slf4j/impl/JDK14LoggerFactory.html" title="class in org.slf4j.impl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/slf4j/impl/\<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JDK14LoggerFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright & </BODY> </HTML>
id: <API key> title: Set the Font Family of an Element challengeType: 0 videoUrl: 'https://scrimba.com/c/c3bvpCg' forumTopicId: 18278 localeTitle: ## Description <section id='description'> <code>font-family</code> <code>h2</code><code>sans-serif</code> CSS css h2 { font-family: sans-serif; } </section> ## Instructions <section id='instructions'> <code>p</code><code>monospace</code> </section> ## Tests <section id='tests'> yml tests: - text: '<code>p</code><code>monospace</code>' testString: assert($("p").not(".red-text").css("font-family").match(/monospace/i)); </section> ## Challenge Seed <section id='challengeSeed'> <div id='html-seed'> html <style> .red-text { color: red; } p { font-size: 16px; } </style> <h2 class="red-text">CatPhotoApp</h2> <main> <p class="red-text"><a href=" <a href=" <div> <p></p> <ul> <li></li> <li></li> <li></li> </ul> <p></p> <ol> <li></li> <li></li> <li></li> </ol> </div> <form action="/submit-cat-photo"> <label><input type="radio" name="indoor-outdoor"></label> <label><input type="radio" name="indoor-outdoor"></label><br> <label><input type="checkbox" name="personality"></label> <label><input type="checkbox" name="personality"></label> <label><input type="checkbox" name="personality"></label><br> <input type="text" placeholder="" required> <button type="submit"></button> </form> </main> </div> </section> ## Solution <section id='solution'> html // solution required </section>
/*global YUI*/ YUI.add('loader-group1', function (Y, NAME) { "use strict"; Y.applyConfig({ groups: { group1: Y.merge((Y.config.groups && Y.config.groups.group1) || {}, { modules: { "foo": { group: "group1", requires: ["node-base", "json-stringify"] }, "loader-group1": { group: "group1" } } }) } }); }, '@VERSION@');
from app import db, app from hashlib import md5 import flask.ext.whooshalchemy as whooshalchemy ROLE_USER = 0 ROLE_ADMIN = 1 followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')) ) class User(db.Model): id = db.Column(db.Integer, primary_key = True) nickname = db.Column(db.String(64), unique = True) email = db.Column(db.String(120), index = True, unique = True) role = db.Column(db.SmallInteger, default = ROLE_USER) posts = db.relationship('Post', backref = 'author', lazy = 'dynamic') about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime) followed = db.relationship('User', secondary = followers, primaryjoin = (followers.c.follower_id == id), secondaryjoin = (followers.c.followed_id == id), backref = db.backref('followers', lazy = 'dynamic'), lazy = 'dynamic') def __repr__(self): return '<User %r>' % (self.nickname) def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return unicode(self.id) def avatar(self,size): return 'http: md5(self.email).hexdigest() + '?d=mm&s=' + str(size) @staticmethod def <API key>(nickname): if User.query.filter_by(nickname = nickname).first() == None: return nickname version = 2 while True: new_nickname = nickname + str(version) if User.query.filter_by(nickname = new_nickname).first() == None: break version += 1 return new_nickname def follow(self, user): if not self.is_following(user): self.followed.append(user) return self def unfollow(self, user): if self.is_following(user): self.followed.remove(user) return self def is_following(self, user): return self.followed.filter(followers.c.followed_id == user.id).count() > 0 def followed_posts(self): return Post.query.join(followers, (followers.c.followed_id == Post.user_id)).filter(followers.c.follower_id == self.id).order_by(Post.timestamp.desc()) class Post(db.Model): __tablename__ = 'post' __searchable__ = ['body'] id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) @classmethod def all_posts(self): return self.query.join(User, (self.user_id == User.id)).order_by(Post.timestamp.desc()) whooshalchemy.whoosh_index(app, Post)
$(document).ready(function(){ var $container = $('#masonary-content'); $container.isotope({ filter: '*', animationOptions: { duration: 750, easing: 'linear', queue: false, } }); $("#masonay-nav > ul > li > a").click(function(){ if ($("#masonay-nav > ul > li > a").hasClass('active')) { $("#masonay-nav > ul > li > a").removeClass('active'); } $(this).addClass('active'); }); $('#masonay-nav a').click(function(){ var selector = $(this).attr('data-filter'); $container.isotope({ filter: selector, animationOptions: { duration: 750, easing: 'linear', queue: false, } }); return false; }); });
<?php namespace dektrium\user; use yii\base\Component; /** * ModelManager is used in order to create models and find users. * * @method models\User createUser * @method models\Profile createProfile * @method models\Account createAccount * @method models\ResendForm createResendForm * @method models\LoginForm createLoginForm * @method models\RecoveryForm <API key> * @method models\RecoveryRequestForm create<API key> * @method \yii\db\ActiveQuery createUserQuery * @method \yii\db\ActiveQuery createProfileQuery * @method \yii\db\ActiveQuery createAccountQuery * * @author Dmitry Erofeev <dmeroff@gmail.com> */ class ModelManager extends Component { /** * @var string */ public $userClass = 'dektrium\user\models\User'; /** * @var string */ public $profileClass = 'dektrium\user\models\Profile'; /** * @var string */ public $accountClass = 'dektrium\user\models\Account'; /** * @var string */ public $resendFormClass = 'dektrium\user\models\ResendForm'; /** * @var string */ public $loginFormClass = 'dektrium\user\models\LoginForm'; /** * @var string */ public $recoveryFormClass = 'dektrium\user\models\RecoveryForm'; /** * @var string */ public $<API key> = 'dektrium\user\models\RecoveryRequestForm'; /** * Finds a user by id. * * @param integer $id * * @return null|models\User */ public function findUserById($id) { return $this->findUser(['id' => $id])->one(); } /** * Finds a user by username. * * @param string $username * * @return null|models\User */ public function findUserByUsername($username) { return $this->findUser(['username' => $username])->one(); } /** * Finds a user by email. * * @param string $email * * @return null|models\User */ public function findUserByEmail($email) { return $this->findUser(['email' => $email])->one(); } /** * Finds a user either by email, or username. * * @param string $value * * @return null|models\User */ public function <API key>($value) { if (filter_var($value, <API key>)) { return $this->findUserByEmail($value); } return $this->findUserByUsername($value); } /** * Finds a user by id and confirmation token * * @param integer $id * @param string $token * * @return null|models\User */ public function <API key>($id, $token) { return $this->findUser(['id' => $id, 'confirmation_token' => $token])->one(); } /** * Finds a user by id and recovery token * * @param integer $id * @param string $token * * @return null|models\User */ public function <API key>($id, $token) { return $this->findUser(['id' => $id, 'recovery_token' => $token])->one(); } /** * Finds a user * * @param $condition * @return \yii\db\ActiveQuery */ public function findUser($condition) { return $this->createUserQuery()->where($condition); } /** * Finds a profile by user id. * * @param integer $id * * @return null|models\Profile */ public function findProfileById($id) { return $this->findProfile(['user_id' => $id])->one(); } /** * Finds a profile * * @param mixed $condition * * @return \yii\db\ActiveQuery */ public function findProfile($condition) { return $this->createProfileQuery()->where($condition); } /** * Finds an account by id. * * @param integer $id * * @return models\Account|null */ public function findAccountById($id) { return $this->createAccountQuery()->where(['id' => $id])->one(); } /** * Finds an account by client id and provider name. * * @param string $provider * @param string $clientId * * @return models\Account|null */ public function findAccount($provider, $clientId) { return $this->createAccountQuery()->where([ 'provider' => $provider, 'client_id' => $clientId ])->one(); } /** * @param string $name * @param array $params * @return mixed|object */ public function __call($name, $params) { $property = (false !== ($query = strpos($name, 'Query'))) ? mb_substr($name, 6, -5) : mb_substr($name, 6); $property = lcfirst($property) . 'Class'; if ($query) { return forward_static_call([$this->$property, 'find']); } if (isset($this->$property)) { $config = []; if (isset($params[0]) && is_array($params[0])) { $config = $params[0]; } $config['class'] = $this->$property; return \Yii::createObject($config); } return parent::__call($name, $params); } }
#include "third_party/blink/renderer/platform/graphics/paint/<API key>.h" #include "third_party/blink/renderer/platform/geometry/float_rect.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h" namespace blink { PaintRecordBuilder::PaintRecordBuilder( printing::MetafileSkia* metafile, GraphicsContext* containing_context, PaintController* paint_controller, paint_preview::PaintPreviewTracker* tracker) : paint_controller_(nullptr) { if (paint_controller) { paint_controller_ = paint_controller; } else { <API key> = std::make_unique<PaintController>(PaintController::kTransient); paint_controller_ = <API key>.get(); } paint_controller_-><API key>( nullptr, PropertyTreeState::Root()); context_ = std::make_unique<GraphicsContext>(*paint_controller_, metafile, tracker); if (containing_context) { context_->SetDarkMode(containing_context->dark_mode_settings()); context_-><API key>(containing_context->DeviceScaleFactor()); context_->SetPrinting(containing_context->Printing()); context_-><API key>(containing_context->IsPaintingPreview()); } } PaintRecordBuilder::~PaintRecordBuilder() = default; sk_sp<PaintRecord> PaintRecordBuilder::EndRecording( const PropertyTreeState& replay_state) { paint_controller_-><API key>(); paint_controller_->FinishCycle(); return paint_controller_->GetPaintArtifact().GetPaintRecord(replay_state); } void PaintRecordBuilder::EndRecording(cc::PaintCanvas& canvas, const PropertyTreeState& replay_state) { paint_controller_-><API key>(); paint_controller_->FinishCycle(); paint_controller_->GetPaintArtifact().Replay(canvas, replay_state); } } // namespace blink
from __future__ import absolute_import, unicode_literals from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ class Profile(models.Model): """ Extension for the user class """ user = models.OneToOneField(User) full_name = models.CharField(verbose_name=_("Full name"), max_length=128, null=True) change_password = models.BooleanField(default=False, help_text=_("User must change password on next login"))
#ifndef SETUP_TRANSFER_HPP #define SETUP_TRANSFER_HPP #include "libtorrent/session.hpp" #include <boost/tuple/tuple.hpp> #include "test.hpp" namespace libtorrent { class alert; struct add_torrent_params; struct session_status; } int EXPORT print_failures(); unsigned char EXPORT random_byte(); int EXPORT load_file(std::string const& filename, std::vector<char>& v, libtorrent::error_code& ec, int limit = 8000000); void EXPORT save_file(char const* filename, char const* data, int size); void EXPORT report_failure(char const* err, char const* file, int line); std::auto_ptr<libtorrent::alert> EXPORT wait_for_alert( libtorrent::session& ses, int type, char const* name = ""); void EXPORT print_ses_rate(float time , libtorrent::torrent_status const* st1 , libtorrent::torrent_status const* st2 , libtorrent::torrent_status const* st3 = NULL); bool EXPORT print_alerts(libtorrent::session& ses, char const* name , bool allow_disconnects = false , bool allow_no_torrents = false , bool <API key> = false , bool (*)(libtorrent::alert*) = 0 , bool no_output = false); void EXPORT wait_for_listen(libtorrent::session& ses, char const* name); void EXPORT test_sleep(int millisec); void EXPORT create_random_files(std::string const& path, const int file_sizes[], int num_files); boost::intrusive_ptr<libtorrent::torrent_info> EXPORT create_torrent(std::ostream* file = 0 , int piece_size = 16 * 1024, int num_pieces = 13, bool add_tracker = true , std::string ssl_certificate = ""); boost::tuple<libtorrent::torrent_handle , libtorrent::torrent_handle , libtorrent::torrent_handle> EXPORT setup_transfer(libtorrent::session* ses1, libtorrent::session* ses2 , libtorrent::session* ses3, bool clear_files, bool <API key> = true , bool connect = true, std::string suffix = "", int piece_size = 16 * 1024 , boost::intrusive_ptr<libtorrent::torrent_info>* torrent = 0, bool super_seeding = false , libtorrent::add_torrent_params const* p = 0, bool stop_lsd = true, bool use_ssl_ports = false , boost::intrusive_ptr<libtorrent::torrent_info>* torrent2 = 0); int EXPORT start_web_server(bool ssl = false, bool chunked = false); void EXPORT stop_web_server(); int EXPORT start_proxy(int type); void EXPORT stop_proxy(int port); void EXPORT stop_all_proxies(); #endif
// This file was generated using Parlex's cpp_generator #include "BINARY_LOGICAL_OP.hpp" #include "plange_grammar.hpp" #include "parlex/detail/document.hpp" #include "AND.hpp" #include "IFF.hpp" #include "IMPLICATION.hpp" #include "MAPS_TO.hpp" #include "NAND.hpp" #include "NOR.hpp" #include "OR.hpp" #include "XOR.hpp" #include "BINARY_LOGICAL_OP.hpp" namespace plc { BINARY_LOGICAL_OP BINARY_LOGICAL_OP::build(parlex::detail::ast_node const & n) { static auto const * b = state_machine().behavior; parlex::detail::document::walk w{ n.children.cbegin(), n.children.cend() }; return BINARY_LOGICAL_OP(parlex::detail::document::element<<API key>>::build(b, w)); } } // namespace plc parlex::detail::state_machine const & plc::BINARY_LOGICAL_OP::state_machine() { static auto const & result = *static_cast<parlex::detail::state_machine const *>(&plange_grammar::get().get_recognizer(plange_grammar::get().BINARY_LOGICAL_OP)); return result; }
{% load leprikon_tags sekizai_tags staticfiles %} <form action="{% url 'leprikon:school_year' %}" method="post" class="form-horizontal" id="id_school_year_form"> {% csrf_token %} <input type="hidden" name="{% param_back %}" value="{% current_url %}"/> {{ school_year_form.school_year }} </form> {% include 'leprikon/static/<API key>.html' %} {% addtoblock 'js' %} <script type="text/javascript"> $(document).ready(function() { $('#id_school_year').multiselect({ numberDisplayed: 1, onChange: function(element, checked) { $('#id_school_year_form').submit(); }, }); }); </script> {% endaddtoblock %}
<?php namespace app\modules\admin\controllers; use Yii; use app\modules\admin\models\Gallery; //use yii\base\ErrorException; use yii\data\ActiveDataProvider; use yii\web\Controller; //use yii\web\HttpException; use yii\web\<API key>; use yii\filters\VerbFilter; use yii\web\UploadedFile; use app\modules\admin\models\UploadForm; /** * GalleryController implements the CRUD actions for Gallery model. */ class GalleryController extends BehaviorsController { public function myGetGalleryCount() { $model = new Gallery(); return $model->find()->count('id'); } /** * Lists all Gallery models. * @return mixed */ public function actionIndex() { $dataProvider = new ActiveDataProvider([ 'query' => Gallery::find(), ]); return $this->render('index', compact('dataProvider')); } /** * Displays a single Gallery model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Gallery model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Gallery(); $file = new UploadForm(); $file->imageFile = UploadedFile::getInstance($file, 'imageFile'); if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($file->upload($model->id, null, $file::TYPE_GALLERY)) { $model->image = $file->getNameImage($model->id, null, $file::TYPE_GALLERY); $model->save(); } else { $model->image = null; $model->save(); } return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', compact('file', 'model')); } } /** * Updates an existing Gallery model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $file = new UploadForm(); $file->imageFile = UploadedFile::getInstance($file, 'imageFile'); if ($model->load(Yii::$app->request->post())) { if ($file->upload($id, null, $file::TYPE_GALLERY)) { $model->image = $file->getNameImage($id, null, $file::TYPE_GALLERY); $model->save(); } else { $model->image = null; $model->save(); return $this->redirect(['view', 'id' => $id]); } return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', compact('file', 'model')); } } public function actionImage($id) { $file = new UploadForm(); $model = $this->findModel($id); $file->imageFile = UploadedFile::getInstance($file, 'imageFile'); if (Yii::$app->request->isPost) { if ($file->upload($id, null, $file::TYPE_GALLERY)) { $model->image = $file->getNameImage($id, null, $file::TYPE_GALLERY); $model->save(); return $this->redirect(['view', 'id' => $id]); } else { $model->image = null; $model->save(); return $this->redirect(['view', 'id' => $id]); } } else { return $this->render('image', compact('file', 'model')); } } /** * Deletes an existing Gallery model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Gallery model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Gallery the loaded model * @throws <API key> if the model cannot be found */ protected function findModel($id) { if (($model = Gallery::findOne($id)) !== null) { return $model; } else { throw new <API key>('The requested page does not exist.'); } } }
#!/usr/bin/env perl use Getopt::Long; use Pod::Usage; use FindBin; use lib "$FindBin::Bin/../lib"; use Blast qw (parse_xml revcomp_hsp); use Genbank qw (parse_genbank get_sequence); use Subfunctions qw (parse_fasta reverse_complement split_seq find_sequences consensus_str); use File::Temp qw (tempfile); use Data::Dumper; use YAML::Tiny; my $help = 0; my $outfile = ""; my $reffile = ""; my $contigfile = ""; my $join = 0; if (@ARGV == 0) { pod2usage(-verbose => 1); } GetOptions ('reffile=s' => \$reffile, 'contigfile=s' => \$contigfile, 'outfile=s' => \$outfile, 'join' => \$join, 'help|?' => \$help) or pod2usage(-msg => "GetOptions failed.", -exitval => 2); if ($help){ pod2usage(-verbose => 1); } if ($reffile eq "") { pod2usage(-verbose => 1, -msg => "need to specify reference file"); } if ($contigfile eq "") { pod2usage(-verbose => 1, -msg => "need to specify contig file"); } if ($outfile eq "") { pod2usage(-verbose => 1, -msg => "need to specify output path"); } my $refseq = ""; if ($reffile =~ /\.gb$/) { my $gb = parse_genbank($reffile); $refseq = get_sequence($gb); } else { my ($ref_hash, $ref_array) = parse_fasta($reffile); $refseq = $ref_hash->{@$ref_array[0]}; } my $reflen = length ($refseq); my ($reffh, $refseqfile) = tempfile(); print $reffh ">reference\n$refseq\n"; close $reffh; print "finding inverted repeats\n"; my ($fh, $refblast) = tempfile(); system("blastn -query $refseqfile -subject $refseqfile -outfmt 5 -out $refblast.xml -evalue 1e-90"); my $self_array = parse_xml ("$refblast.xml"); my @irs = (); foreach my $hit (@$self_array) { my @hsps = sort <API key> @{$hit->{"hsps"}}; foreach my $hsp (@hsps) { # only look at identical pieces that are smaller than the entire reference if ((($hsp->{"query-to"} - $hsp->{"query-from"}) < ($reflen - 1)) && (($hsp->{"query-to"} - $hsp->{"query-from"}) > 10000)) { push @irs, $hsp; } } } if (@irs > 2) { die "Error! There seem to be more than two inverted repeats. Are you sure this is a plastome sequence?"; } my $curr_pos = 1; my $regions = (); my $regions_hash = {}; # LSC goes from 1 to the start of @$irs[0] - 1: my $region = {}; $regions_hash->{"LSC"} = $region; $region->{"name"} = "LSC"; $region->{"start"} = 1; $region->{"end"} = $irs[0]->{"query-from"} - 1; (undef, $region->{"sequence"}, undef) = split_seq ($refseq, $region->{"start"}, $region->{"end"}); push @$regions, $region; # IRB goes from the start of @$irs[0] to the end of @$irs[0] (inclusive): $region = {}; $regions_hash->{"IRB"} = $region; $region->{"name"} = "IRB"; $region->{"sequence"} = $irs[0]{"hseq"}; $region->{"start"} = $irs[0]->{"query-from"}; $region->{"end"} = $irs[0]->{"query-to"}; push @$regions, $region; # SSC goes from the end of @$irs[0] + 1 to the start of @$irs[1] - 1: $region = {}; $regions_hash->{"SSC"} = $region; $region->{"name"} = "SSC"; $region->{"start"} = $irs[0]->{"query-to"} + 1; $region->{"end"} = $irs[1]->{"query-from"} - 1; (undef, $region->{"sequence"}, undef) = split_seq ($refseq, $region->{"start"}, $region->{"end"}); push @$regions, $region; # IRA goes from the start of @$irs[1] to the end of @$irs[1] (inclusive): $region = {}; $regions_hash->{"IRA"} = $region; $region->{"name"} = "IRA"; $region->{"sequence"} = $irs[1]{"hseq"}; $region->{"start"} = $irs[1]->{"query-from"}; $region->{"end"} = $irs[1]->{"query-to"}; push @$regions, $region; my ($fh, $refregions) = tempfile(); foreach $region (@$regions) { print $fh ">" . $region->{"name"} . "\n" . $region->{"sequence"}. "\n"; # clean up the region hash for later use. delete $region->{"sequence"}; # set up a hash value to receive the hits when we get them. $region->{"hits"} = (); $region->{"length"} = $region->{"end"} - $region->{"start"} + 1; } close $fh; if (-e "$outfile.xml") { print "skipping blastn\n"; } else { print "running blastn\n"; system("blastn -query $contigfile -subject $refregions -outfmt 5 -out $outfile.xml -culling_limit 1 -evalue 1e-70"); } print "parsing results\n"; my $hit_array = parse_xml ("$outfile.xml"); my @hit_list = (); foreach my $hit (@$hit_array) { # each hit represents a contig that we want to assign to a region. my $contig = {}; $contig->{"name"} = $hit->{"query"}->{"name"}; $contig->{"length"} = $hit->{"query"}->{"length"}; push @hit_list, $contig->{"name"}; # push it into the appropriate region's bucket of hits. my $region = $hit->{"subject"}->{"name"}; push @{$regions_hash->{$region}->{"hits"}}, $contig; $contig->{"region"} = $region; # each hsp represents a matching segment of this contig to this region. foreach my $hsp (@{$hit->{"hsps"}}) { if ($hsp->{"hit-from"} > $hsp->{"hit-to"}) { # tag this contig as being revcomped, so we can fix it when we deal with whole contigs. $contig->{"revcomp"} = " (reverse complement)"; } } # consolidate all of the matching segments into one large overall match. my @query_ends = (); my @hit_ends = (); foreach my $hsp (@{$hit->{"hsps"}}) { push @query_ends, $hsp->{"query-from"}; push @query_ends, $hsp->{"query-to"}; push @hit_ends, $hsp->{"hit-from"}; push @hit_ends, $hsp->{"hit-to"}; } @query_ends = sort {$a <=> $b} @query_ends; @hit_ends = sort {$a <=> $b} @hit_ends; my $regoffset = $regions_hash->{$region}->{"start"} - 1; $contig->{"hit-from"} = $hit_ends[0] + $regoffset; $contig->{"hit-to"} = $hit_ends[@hit_ends-1] + $regoffset; $contig->{"query-from"} = $query_ends[0]; $contig->{"query-to"} = $query_ends[@query_ends-1]; } open OUTFH, ">", "$outfile.raw.yml"; print OUTFH YAML::Tiny->Dump(@$hit_array); close OUTFH; # put the sequences for the matching contigs back into the output hash. my $contig_seqs = find_sequences ($contigfile, \@hit_list); # write these best seqs out: open OUTFH, ">", "$outfile.best.fasta"; foreach my $key (keys %$contig_seqs) { print "$key\n"; print OUTFH ">$key\n"; print OUTFH $contig_seqs->{$key} . "\n"; } close OUTFH; my @all_hits = (); foreach $region (@$regions) { foreach my $contig (@{$region->{"hits"}}) { $contig->{"sequence"} = $contig_seqs->{$contig->{"name"}}; if (exists $contig->{"revcomp"}) { delete $contig->{"revcomp"}; $contig->{"sequence"} = reverse_complement ($contig->{"sequence"}); $contig->{"name"} .= "_rc"; # flip the query's indices: the q-from is now going to be (length - q-from) and the q-to is (length - q-to) my $old_qto = $contig->{"query-to"}; $contig->{"query-to"} = $contig->{"length"} - $contig->{"query-from"}; $contig->{"query-from"} = $contig->{"length"} - $old_qto; } # do some cleanup of the hit and query windows. # each contig's putative hit span is from the amount of query extending before the start of the match (hit-from), which is (hit-from - query-from), plus whatever portion of its length is beyond that (length - query-from + hit-from) $contig->{"hit-to"} = $contig->{"hit-from"} - $contig->{"query-from"} + $contig->{"length"}; $contig->{"hit-from"} = $contig->{"hit-from"} - $contig->{"query-from"}; # print "cleaning up " . $contig->{"name"} . ", has length " . $contig->{"length"} . " and its " . $contig->{"query-from"} . "-" . $contig->{"query-to"} . " covers the ref " . $contig->{"hit-from"} . "-" . $contig->{"hit-to"} . "\n"; } my @ordered_hits = sort order_by_hit_start @{$region->{"hits"}}; push @all_hits, @ordered_hits; $region->{"hits"} = \@ordered_hits; } open OUTFH, ">", "$outfile.yml"; print OUTFH YAML::Tiny->Dump(@$regions); close OUTFH; # do the contigs connect to each other? my @final_contigs = (); my $first_hit = shift @all_hits; push @final_contigs, $first_hit; # compare the end of the last contig in final_contigs to the start of the next contig in all_hits # while there's still anything left in all_hits while (@all_hits > 0) { # first contig to compare is the last one in final_contigs my $contig_seq1 = @final_contigs[@final_contigs - 1]; # second contig to compare is the next unanalyzed one from all_hits my $contig_seq2 = shift @all_hits; print "comparing " . $contig_seq1->{"name"} . ", maps " . $contig_seq1->{"hit-from"}. "-" . $contig_seq1->{"hit-to"} . ", to " . $contig_seq2->{"name"} . ", maps " . ($contig_seq2->{"hit-to"} - $contig_seq2->{"length"}) ."-". $contig_seq2->{"hit-to"} . "\n"; # if the second contig's putative hit range is within the first, drop it. if ($contig_seq2->{"hit-to"} <= $contig_seq1->{"hit-to"}) { next; } # compare these two contigs' ends print "can we meld these contigs? "; (my $fh1, my $contig1) = tempfile(); my $contig_end = $contig_seq1->{"sequence"}; if ($contig_seq1->{"sequence"} =~ /^(.*)(.{50})$/) { $contig_seq1->{"sequence"} = $1; $contig_end = $2; } print $fh1 ">" . $contig_seq1->{"name"} . "_end\n$contig_end\n"; my $contig_start = $contig_seq2->{"sequence"}; if ($contig_seq2->{"sequence"} =~ /^(.{50})/) { $contig_start = $1; } print $fh1 ">" . $contig_seq2->{"name"} . "_start\n$contig_start\n"; close $fh1; (undef, my $temp_out) = tempfile(OPEN => 0); system ("mafft --retree 2 --maxiterate 0 --op 10 $contig1 > $temp_out 2>/dev/null"); # the resulting sequences are a match if the consensus sequence has few ambiguous characters. (my $aligned_bits, my $alignarray) = parse_fasta($temp_out); my @seqs = (); foreach my $k (@$alignarray) { push @seqs, $aligned_bits->{$k}; } my $cons_seq = consensus_str(\@seqs); my @ambigs = $cons_seq =~ m/[NMRWSYKVHDB]/g; if (@ambigs < 5) { # if there are less than 5 ambiguities when we align them... # meld the sequence: $contig_seq1->{"sequence"} = $contig_seq1->{"sequence"} . $cons_seq . $contig_seq2->{"sequence"}; # update the parameters for the newly-melded contig. $contig_seq1->{"name"} = $contig_seq1->{"name"} . "+" . $contig_seq2->{"name"}; $contig_seq1->{"region"} = $contig_seq1->{"region"} . "+" . $contig_seq2->{"region"}; $contig_seq1->{"length"} = length $contig_seq1->{"sequence"}; $contig_seq1->{"hit-to"} = $contig_seq2->{"hit-to"}; $contig_seq1->{"query-to"} = "" . ($contig_seq1->{"length"} - $contig_seq1->{"query-from"}); print "yes, new length is " . $contig_seq1->{"length"} . ", covers " . $contig_seq1->{"hit-from"} . "-" . $contig_seq1->{"hit-to"} . "\n"; } elsif (($contig_seq2->{"hit-from"} - $contig_seq1->{"hit-to"}) < 300) { # if the two contigs' hit ends are within 100 bp of each other, scaffold them together by adding Ns $contig_seq1->{"sequence"} .= "N" x ($contig_seq2->{"hit-from"} - $contig_seq1->{"hit-to"}) . $contig_seq2->{"sequence"}; # update the parameters for the newly-melded contig. $contig_seq1->{"name"} = $contig_seq1->{"name"} . "+" . $contig_seq2->{"name"}; $contig_seq1->{"region"} = $contig_seq1->{"region"} . "+" . $contig_seq2->{"region"}; $contig_seq1->{"length"} = length $contig_seq1->{"sequence"}; $contig_seq1->{"hit-to"} = $contig_seq2->{"hit-to"}; $contig_seq1->{"query-to"} = "" . ($contig_seq1->{"length"} - $contig_seq1->{"query-from"}); print "maybe? new length is " . $contig_seq1->{"length"} . ", covers " . $contig_seq1->{"hit-from"} . "-" . $contig_seq1->{"hit-to"} . "\n"; } else { # if not meldable, push the second contig onto the final contigs too. $contig_seq1->{"sequence"} .= $contig_end; $contig_seq2->{"sequence"} = $contig_start . $contig_seq2->{"sequence"}; push @final_contigs, $contig_seq2; print "no, span too large: " . $contig_seq2->{"hit-from"} ."-". $contig_seq1->{"hit-to"} . " = ". ($contig_seq2->{"hit-from"} - $contig_seq1->{"hit-to"}) . "\n"; } } my $final_len = 0; foreach my $c (@final_contigs) { $final_len += $c->{"length"}; } print "final assembly has " . @final_contigs . " contigs, total length $final_len\n"; open OUTFH, ">", "$outfile.final.yml"; print OUTFH YAML::Tiny->Dump(@final_contigs); close OUTFH; open OUTFH, ">", "$outfile.draft.fasta"; if ($join) { print OUTFH ">$outfile.draft.fasta\n"; foreach my $c (@final_contigs) { print OUTFH $c->{"sequence"} . "NNNNNNNNNNN"; } } else { foreach my $c (@final_contigs) { print OUTFH ">" . $c->{"name"} . "\n" . $c->{"sequence"} . "\n"; } } close OUTFH; Sorting functions # if $a starts earlier than $b, return -1 sub order_by_hit_start { my $bstart = $b->{"hit-from"}; my $astart = $a->{"hit-from"}; if ($astart < $bstart) { return -1; } if ($astart > $bstart) { return 1; } return 0; } sub order_by_ref_start { my $bstart = $b->{"hit-from"}; my $astart = $a->{"hit-from"}; if ($astart < $bstart) { return -1; } if ($astart > $bstart) { return 1; } return 0; } sub <API key> { my $bstart = $b->{"query-from"}; my $astart = $a->{"query-from"}; if ($astart < $bstart) { return -1; } if ($astart > $bstart) { return 1; } return 0; } __END__ =head1 NAME contigs_to_cp.pl =head1 SYNOPSIS contigs_to_cp.pl [-reffile reffile] [-contigfile contigfile] [-outputfile outputfile] =head1 OPTIONS -reffile: genbank or fasta file of reference plastome -contigfile: fasta file of putative cp contigs -outputfile: name of output file =head1 DESCRIPTION Aligns a list of putative cp contigs along a reference plastome. Outputs a YAML file of the best-matching contigs, in order. =cut
/* $NetBSD: bztzscvar.h,v 1.2 1997/10/04 04:01:22 mhitch Exp $ */ struct bztzsc_softc { struct ncr53c9x_softc sc_ncr53c9x; /* glue to MI code */ struct isr sc_isr; /* Interrupt chain struct */ volatile u_char *sc_reg; /* the registers */ volatile u_char *sc_dmabase; int sc_active; /* Pseudo-DMA state vars */ int sc_datain; int sc_tc; size_t sc_dmasize; size_t sc_dmatrans; char **sc_dmaaddr; size_t *sc_pdmalen; vm_offset_t sc_pa; u_char sc_pad1[18]; /* XXX */ u_char sc_alignbuf[256]; u_char sc_pad2[16]; u_char sc_hardbits; u_char sc_portbits; u_char sc_xfr_align; }; #define BZTZSC_PB_LED 0x02 /* clear to turn LED on */
{% extends "newman/change_list.html" %} {% block <API key> %} <a href="timeline/" class="js-hashadr icn btn timeline">{% trans "Timeline view" %}</a> {{ block.super }} {% endblock %}
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-792 // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.08.23 at 08:13:31 AM MESZ package org.iso.mpeg.dash; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.namespace.QName; import org.w3c.dom.Element; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SegmentTimelineType", propOrder = { "ss", "anies" }) public class SegmentTimelineType { @XmlElement(name = "S", required = true) protected List<SegmentTimelineType.S> ss; @XmlAnyElement protected List<Element> anies; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the ss property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ss property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSS().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SegmentTimelineType.S } * * */ public List<SegmentTimelineType.S> getSS() { if (ss == null) { ss = new ArrayList<SegmentTimelineType.S>(); } return this.ss; } /** * Gets the value of the anies property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the anies property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAnies().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Element } * * */ public List<Element> getAnies() { if (anies == null) { anies = new ArrayList<Element>(); } return this.anies; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class S { @XmlAttribute @XmlSchemaType(name = "unsignedLong") protected BigInteger t; @XmlAttribute(required = true) @XmlSchemaType(name = "unsignedLong") protected BigInteger d; @XmlAttribute protected BigInteger r; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the t property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getT() { return t; } /** * Sets the value of the t property. * * @param value * allowed object is * {@link BigInteger } * */ public void setT(BigInteger value) { this.t = value; } /** * Gets the value of the d property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getD() { return d; } /** * Sets the value of the d property. * * @param value * allowed object is * {@link BigInteger } * */ public void setD(BigInteger value) { this.d = value; } /** * Gets the value of the r property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getR() { if (r == null) { return new BigInteger("0"); } else { return r; } } /** * Sets the value of the r property. * * @param value * allowed object is * {@link BigInteger } * */ public void setR(BigInteger value) { this.r = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } } }
#include "chrome/renderer/safe_browsing/<API key>.h" #include <algorithm> #include <string> #include <vector> #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/test/perftimer.h" #include "chrome/renderer/safe_browsing/features.h" #include "net/base/<API key>/<API key>.h" #include "url/gurl.h" namespace safe_browsing { <API key>::<API key>() {} <API key>::~<API key>() {} bool <API key>::ExtractFeatures(const GURL& url, FeatureMap* features) { PerfTimer timer; if (url.HostIsIPAddress()) { if (!features->AddBooleanFeature(features::kUrlHostIsIpAddress)) return false; } else { std::string host; TrimString(url.host(), ".", &host); // Remove any leading/trailing dots. // TODO(bryner): Ensure that the url encoding is consistent with // the features in the model. // Disallow unknown registries so that we don't classify size_t registry_length = net::<API key>::GetRegistryLength( host, net::<API key>::<API key>, net::<API key>::<API key>); if (registry_length == 0 || registry_length == std::string::npos) { DVLOG(1) << "Could not find TLD for host: " << host; return false; } DCHECK_LT(registry_length, host.size()) << "Non-zero registry length, but " "host is only a TLD: " << host; size_t tld_start = host.size() - registry_length; if (!features->AddBooleanFeature(features::kUrlTldToken + host.substr(tld_start))) return false; // Pull off the TLD and the preceeding dot. host.erase(tld_start - 1); std::vector<std::string> host_tokens; base::SplitStringDontTrim(host, '.', &host_tokens); // Get rid of any empty components. std::vector<std::string>::iterator new_end = std::remove(host_tokens.begin(), host_tokens.end(), ""); host_tokens.erase(new_end, host_tokens.end()); if (host_tokens.empty()) { DVLOG(1) << "Could not find domain for host: " << host; return false; } if (!features->AddBooleanFeature(features::kUrlDomainToken + host_tokens.back())) return false; host_tokens.pop_back(); // Now we're just left with the "other" host tokens. for (std::vector<std::string>::iterator it = host_tokens.begin(); it != host_tokens.end(); ++it) { if (!features->AddBooleanFeature(features::kUrlOtherHostToken + *it)) return false; } if (host_tokens.size() > 1) { if (!features->AddBooleanFeature(features::<API key>)) return false; if (host_tokens.size() > 3) { if (!features->AddBooleanFeature( features::<API key>)) return false; } } } std::vector<std::string> long_tokens; <API key>(url.path(), &long_tokens); for (std::vector<std::string>::iterator it = long_tokens.begin(); it != long_tokens.end(); ++it) { if (!features->AddBooleanFeature(features::kUrlPathToken + *it)) return false; } UMA_HISTOGRAM_TIMES("SBClientPhishing.URLFeatureTime", timer.Elapsed()); return true; } // static void <API key>::<API key>( const std::string& full, std::vector<std::string>* tokens) { // Split on common non-alphanumerics. // TODO(bryner): Split on all(?) non-alphanumerics and handle %XX properly. static const char kTokenSeparators[] = ".,\\/_-|=%:!&"; std::vector<std::string> raw_splits; Tokenize(full, kTokenSeparators, &raw_splits); // Copy over only the splits that are 3 or more chars long. // TODO(bryner): Determine a meaningful min size. for (std::vector<std::string>::iterator it = raw_splits.begin(); it != raw_splits.end(); ++it) { if (it->length() >= <API key>) tokens->push_back(*it); } } } // namespace safe_browsing
layout: organization category: local title: Animal Haven impact_area: Environment keywords: - Animals - Education - Global Problems location_services: Manhattan location_offices: Manhattan website: www.animalhavenshelter.org description: | How many of you have a cat or a dog at home? Dogs and cats are just like us! They need food, water, shelter, doctors, and people to love them. What do you think happens to a cat or a dog that is unwanted or doesn't have a home? Could you survive without a home? Many homeless animals in New York City end up at an animal shelter that will take care of them. That's what we do! We take care of dogs and cats without homes and help them find families who will love them forever. Every penny donated to us provides food, water, and medical care for dozens of animals every day. At Animal Haven, YOUR pennies save lives. mission: | To carefully place cats and dogs in loving homes, as well as give lifetime care for those who cannot be placed. We fulfill our no-kill mission through adoption programs at our shelter <about.html> in Queens, Animal Haven @ Biscuits and Bath <biscbath.html> in Midtown Manhattan, and our Mobile Adoption Program <petspeople.html>. Animal Haven University <university.html> provides courses in positive reinforcement training to help keep dogs in their original homes. Animal Haven Acres <acres.html> is a sanctuary and rehabilitation Center in Delaware County, NY where hard to place dogs and cats can live out their lives in a homelike setting. cash_grants: yes grants: - | $25: Collars and leashes for 5 dogs. Every dog receives a new collar when they enter the shelter. Pink for girls and blue for boys! $30: Vaccinates 5 animals against deadly diseases. $50: Spay/Neuter one animal $200: Feeds one shelter animal for a whole year $500: Provides almost 50 animals with needed medication. Sometimes cats and dogs come into the shelter with colds or broken bones, so we need to help them get better! service_opp: yes services: - | Pennies for Paws Sale - Hold a "sale" at your school, library, or local community center. You can sell cupcakes or candy, pencils, greeting cards (you can even make these yourself!), or anything else you can think up! When someone buys something, you give them a "Fact Card" along with their cupcake or pencil. Each "Fact Card" should tell them something important about animals that YOU want them to know. It can say: " Spaying and Neutering is the responsible choice," Chaining dogs outside is animal cruelty," "Adult cats are the largest percentage of the homeless pet population," etc. OR you can hand out "See Something, Say Something Cards" that give people the name and number of the local authority to call if they witness a case of animal abuse. With a Pennies for Paws Sale, you can raise money for the shelter AND teach you friends about being kind to animals. - | Wish List Drive - Taking care of all the cats and dogs at the shelter takes a lot of time, energy and supplies. You can make a big difference to the animals by holding a Wish List Drive at your school, library or local community center. What types of supplies do we need? * Fancy Feast cat food * Paper Towels * Bleach * Beef, Chicken or Turkey Baby Food (All Meat, no onion powder) * Sponge Mops * Dust Pans and Brooms * Laundry Detergent * Pro Plan dog and cat food * Just Born or KMR kitten formula learn: - Give students a tour of our office and facilities - Speak over the phone about our work cont_relationship: - Help students develop a community service project with us - Help students tell local newspapers and media about their grant and/or project with us salutation: first_name: Kendra last_name: Mara <API key>: Associate Director city: New York state: NY address: | 251 Centre Street New York NY 10013 lat: 40.720134 lng: -73.998238 phone: 201-835-3803 ext: fax: email: kendram@ah-nyc.org preferred_contact: email <API key>: | Hi! My name is Kendra and I do a lot of different things at Animal Haven! I run our volunteer program, supervise the humane education program for kids, update the website and handle all new cat intakes. I have been at Animal Haven since March 2008, and have visited and hosted tours for many schools. I think it's very important to teach kids about animal-related issues such as puppy mills and being a responsible pet owner. How many of you have a cat or a dog at home? Dogs and cats are just like us! They need food, water, shelter, doctors, and people to love them. What do you think happens to a cat or a dog that is unwanted or doesn't have a home? Could you survive without a home? Many homeless animals in New York City end up at an animal shelter that will take care of them. That's what we do! We take care of dogs and cats without homes and help them find families who will love them forever. Every penny donated to us provides food, water, and medical care for dozens of animals every day. At Animal Haven, YOUR pennies save lives.
<?php /* @var $this PostenController */ /* @var $model Posten */ $this->breadcrumbs=array( 'Startup Spel Overzicht'=>array('/startup/startupOverview','event_id'=>$model->event_ID), ); $this->menu=array( array('label'=>'Post Toevoegen', 'url'=>array('/Posten/create', 'event_id'=>$model->event_ID)), array('label'=>'Verwijder deze Post', 'url'=>' 'linkOptions'=>array('submit'=>array('delete', 'id'=>$model->post_ID, 'event_id'=>$model->event_ID), 'confirm'=>'Are you sure you want to delete this item?')), ); ?> <h1>Bijwerken van post <?php echo Posten::model()->getPostName($model->post_ID); ?> voor hike: <?php echo EventNames::model()->getEventName($model->event_ID); ?></h1> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?>
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.one_string.label.xml Template File: sources-sink-84_bad.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: console Read input from the console * GoodSource: Fixed string * Sinks: system * BadSink : Execute command in data using system() * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #ifndef OMITBAD #include "std_testcase.h" #include "<API key>.h" #ifdef _WIN32 #define SYSTEM system #else /* NOT _WIN32 */ #define SYSTEM system #endif namespace <API key> { <API key>::<API key>(char * dataCopy) { data = dataCopy; { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } } <API key>::~<API key>() { /* POTENTIAL FLAW: Execute command in data possibly leading to command injection */ if (SYSTEM(data) != 0) { printLine("command execution failed!"); exit(1); } } } #endif /* OMITBAD */
<?php namespace Respect\Data\Collections; class Typed extends Collection { public static function __callStatic($name, $children) { $collection = new self(); $collection->extra('type', ''); return $collection->__call($name, $children); } public static function by($type) { $collection = new Collection(); $collection->extra('type', $type); return $collection; } }
FROM php:7.4 RUN pecl install swoole > /dev/null && \ <API key> swoole RUN <API key> pdo_mysql > /dev/null ADD ./ /lumen WORKDIR /lumen COPY deploy/swoole/php.ini /usr/local/etc/php/ RUN mkdir -p /lumen/storage/framework/sessions RUN mkdir -p /lumen/storage/framework/views RUN mkdir -p /lumen/storage/framework/cache RUN chmod -R 777 /lumen # This method was chosen because composer is not part of the apt repositories that are in the default PHP 7.2 docker image # Adding alternate apt php repos can potentially cause problems with extension compatibility between the php build from the docker image and the alternate php build # An additional benefit of this method is that the correct version of composer will be used for the environment and version of the php system in the docker image RUN deploy/swoole/install-composer.sh RUN apt-get update -yqq > /dev/null && \ apt-get install -yqq git unzip > /dev/null COPY deploy/swoole/composer* ./ RUN php composer.phar install --optimize-autoloader --<API key> --no-dev --quiet RUN echo "APP_SWOOLE=true" >> .env RUN chmod -R 777 /lumen CMD php artisan swoole:http start
#ifndef <API key> #define <API key> #include <vector> #include "chrome/browser/ui/webui/options/options_ui.h" #include "ui/gfx/display_observer.h" namespace base { class DictionaryValue; class ListValue; } namespace chromeos { namespace options { // Display options overlay page UI handler. class <API key> : public ::options::<API key>, public gfx::DisplayObserver { public: <API key>(); virtual ~<API key>(); // <API key> implementation. virtual void GetLocalizedValues( base::DictionaryValue* localized_strings) OVERRIDE; virtual void InitializePage() OVERRIDE; // WebUIMessageHandler implementation. virtual void RegisterMessages() OVERRIDE; // gfx::DisplayObserver implementation. virtual void <API key>(const gfx::Display& display) OVERRIDE; virtual void OnDisplayAdded(const gfx::Display& new_display) OVERRIDE; virtual void OnDisplayRemoved(const gfx::Display& old_display) OVERRIDE; private: // Updates the display section visibility based on the current display // configurations. Specify the number of display. void <API key>(size_t num_displays); // Sends all of the current display information to the web_ui of options page. void SendAllDisplayInfo(); // Sends the specified display information to the web_ui of options page. void SendDisplayInfo(const std::vector<const gfx::Display*> displays); // Called when the fade-out animation for mirroring status change is finished. void <API key>(bool is_mirroring); // Called when the fade-out animation for secondary display layout change is // finished. |layout| specifies the four positions of the secondary display // (left/right/top/bottom), and |offset| is the offset length from the // left/top edge of the primary display. void <API key>(int layout, int offset); // Handlers of JS messages. void HandleDisplayInfo(const base::ListValue* unused_args); void HandleMirroring(const base::ListValue* args); void HandleSetPrimary(const base::ListValue* args); void HandleDisplayLayout(const base::ListValue* args); <API key>(<API key>); }; } // namespace options } // namespace chromeos #endif // <API key>
module Horbits.Body (bodyUiColor, getBody, fromBodyId, module X) where import Control.Lens hiding ((*~), _2, _3, _4) import Horbits.Body.Atmosphere as X import Horbits.Body.Body as X import Horbits.Body.Color as X import Horbits.Body.Data as X import Horbits.Body.Id as X bodyUiColor :: Fold BodyId (RgbaColor Float) bodyUiColor = to getColor . traverse -- Data getBody :: BodyId -> Body getBody bId = Body bId (_bodyName bId) mu r t soi atm where soi = <API key> bId (r, t, mu) = getPhysicalAttrs bId atm = getAtmosphere bId _bodyName :: BodyId -> String _bodyName Sun = "Kerbol" _bodyName b = show b fromBodyId :: Getter BodyId Body fromBodyId = to getBody
using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Mvc; using Microsoft.Framework.ConfigurationModel; using SampleWeb.Models; using WopiDiscovery.Enumerations; using WopiHost.Contracts; using WopiHost.Urls; namespace SampleWeb.Controllers { public class HomeController : Controller { private <API key> SecurityHandler { get; } private IWopiFileProvider FileProvider { get; } private IConfiguration Configuration { get; } public string WopiClientUrl => Configuration.Get("WopiClientUrl"); public string WopiHostUrl => Configuration.Get("WopiHostUrl"); protected WopiUrlGenerator WopiUrlGenerator => new WopiUrlGenerator(WopiClientUrl, WopiHostUrl, SecurityHandler); public HomeController(<API key> securityHandler, IWopiFileProvider fileProvider, IConfiguration configuration) { SecurityHandler = securityHandler; FileProvider = fileProvider; Configuration = configuration; } public ActionResult Index() { return View(GetFiles()); } private IEnumerable<FileModel> GetFiles() { return FileProvider.GetWopiFiles().Select(file => new FileModel { FileName = file.Name, FileUrl = WopiUrlGenerator.GetUrl(file.Extension, file.Identifier, WopiActionEnum.Edit) }); } } }
#flux-examples Example isomorphic [Flux][] applications using [Fluxible][], [fluxible-router][], and [<API key>][]. The server-side rendered React components and store instances get dehydrated and sent to the client using [express-state][]. The client.js (compiled by [webpack][]) then bootstraps and rehydrates the dispatcher instance and the stores to same state as what they were on the server. There are multiple examples in this repo: * [Chat](chat) - Port of [Facebook's Flux chat example](https://github.com/facebook/flux/tree/master/examples/flux-chat). * [Fluxible Routing](fluxible-router) - Simple isomorphic routing using [Fluxible][]. * [React Routing](react-router) - Isomorphic routing using [react-router](https://github.com/rackt/react-router). * [To Do](todo) - Port of [ToDo MVC](https://github.com/tastejs/todomvc). Alternatively, for a fully featured application you can check out the [fluxible.io][Fluxible] docs website repository for more integration examples: * https://github.com/yahoo/fluxible/tree/master/site Want more examples? Check out our [community reference applications](https://github.com/yahoo/fluxible/blob/master/docs/community/<API key>.md). Usage npm install cd <folder> npm run dev Open http://localhost:3000 For more information on what's going on, you can use `DEBUG=* node` to see full debug output on the server. Unless otherwise specified, this software is free to use under the Yahoo! Inc. BSD license. See the [LICENSE file][] for license text and copyright information. [LICENSE file]: https: [Flux]: http://facebook.github.io/react/docs/flux-overview.html [Fluxible]: http://fluxible.io [fluxible-router]: https://github.com/yahoo/blob/master/packages/fluxible-router [<API key>]: https://github.com/yahoo/blob/master/packages/<API key> [express-state]: https://github.com/yahoo/express-state [webpack]: https://github.com/webpack/webpack
# modification, are permitted provided that the following conditions are met: # documentation and/or other materials provided with the distribution. # * Neither Geoscience Australia nor the names of its contributors may be # used to endorse or promote products derived from this software # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from datacube.api.query import Month __author__ = "Simon Oldfield" import argparse import logging import os from datacube.api.model import Satellite, DatasetType from datacube.api.utils import PqaMask, WofsMask, OutputFormat _log = logging.getLogger() def satellite_arg(s): if s in [sat.name for sat in Satellite]: return Satellite[s] raise argparse.ArgumentTypeError("{0} is not a supported satellite".format(s)) def month_arg(s): if s in [month.name for month in Month]: return Month[s] raise argparse.ArgumentTypeError("{0} is not a supported month".format(s)) def pqa_mask_arg(s): if s in [m.name for m in PqaMask]: return PqaMask[s] raise argparse.ArgumentTypeError("{0} is not a supported PQA mask".format(s)) def wofs_mask_arg(s): if s in [m.name for m in WofsMask]: return WofsMask[s] raise argparse.ArgumentTypeError("{0} is not a supported WOFS mask".format(s)) def dataset_type_arg(s): if s in [t.name for t in DatasetType]: return DatasetType[s] raise argparse.ArgumentTypeError("{0} is not a supported dataset type".format(s)) def writeable_dir(prospective_dir): if not os.path.exists(prospective_dir): raise argparse.ArgumentTypeError("{0} doesn't exist".format(prospective_dir)) if not os.path.isdir(prospective_dir): raise argparse.ArgumentTypeError("{0} is not a directory".format(prospective_dir)) if not os.access(prospective_dir, os.W_OK): raise argparse.ArgumentTypeError("{0} is not writeable".format(prospective_dir)) return prospective_dir def readable_dir(prospective_dir): if not os.path.exists(prospective_dir): raise argparse.ArgumentTypeError("{0} doesn't exist".format(prospective_dir)) if not os.path.isdir(prospective_dir): raise argparse.ArgumentTypeError("{0} is not a directory".format(prospective_dir)) if not os.access(prospective_dir, os.R_OK): raise argparse.ArgumentTypeError("{0} is not readable".format(prospective_dir)) return prospective_dir def readable_file(prospective_file): if not os.path.exists(prospective_file): raise argparse.ArgumentTypeError("{0} doesn't exist".format(prospective_file)) if not os.path.isfile(prospective_file): raise argparse.ArgumentTypeError("{0} is not a file".format(prospective_file)) if not os.access(prospective_file, os.R_OK): raise argparse.ArgumentTypeError("{0} is not readable".format(prospective_file)) return prospective_file def date_arg(s): try: return parse_date(s) except ValueError: raise argparse.ArgumentTypeError("{0} is not a valid date".format(s)) def date_min_arg(s): try: return parse_date_min(s) except ValueError: raise argparse.ArgumentTypeError("{0} is not a valid date".format(s)) def date_max_arg(s): try: return parse_date_max(s) except ValueError: raise argparse.ArgumentTypeError("{0} is not a valid date".format(s)) def dummy(path): _log.debug("Creating dummy output %s" % path) import os if not os.path.exists(path): with open(path, "w") as f: pass def parse_date(s): from datetime import datetime return datetime.strptime(s, "%Y-%m-%d").date() def parse_date_min(s): from datetime import datetime if s: if len(s) == len("YYYY"): return datetime.strptime(s, "%Y").date() elif len(s) == len("YYYY-MM"): return datetime.strptime(s, "%Y-%m").date() elif len(s) == len("YYYY-MM-DD"): return datetime.strptime(s, "%Y-%m-%d").date() return None def parse_date_max(s): from datetime import datetime import calendar if s: if len(s) == len("YYYY"): d = datetime.strptime(s, "%Y").date() d = d.replace(month=12, day=31) return d elif len(s) == len("YYYY-MM"): d = datetime.strptime(s, "%Y-%m").date() first, last = calendar.monthrange(d.year, d.month) d = d.replace(day=last) return d elif len(s) == len("YYYY-MM-DD"): d = datetime.strptime(s, "%Y-%m-%d").date() return d return None def output_format_arg(s): if s in [f.name for f in OutputFormat]: return OutputFormat[s] raise argparse.ArgumentTypeError("{0} is not a supported output format".format(s))
{% load staticfiles %} <div id='viewer' class="embed-responsive <API key> datapoint"> <iframe class="<API key>" src="{{ object.file.url }}"></iframe> </div>
package edu.northwestern.bioinformatics.studycalendar.web.schedule; import edu.northwestern.bioinformatics.studycalendar.core.accesscontrol.<API key>; import edu.northwestern.bioinformatics.studycalendar.dao.UserActionDao; import edu.northwestern.bioinformatics.studycalendar.domain.*; import edu.northwestern.bioinformatics.studycalendar.domain.auditing.AuditEvent; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment; import edu.northwestern.bioinformatics.studycalendar.security.authorization.<API key>; import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscUser; import edu.northwestern.bioinformatics.studycalendar.service.DeltaService; import edu.northwestern.bioinformatics.studycalendar.web.ControllerTestCase; import gov.nih.nci.cabig.ctms.lang.DateTools; import java.util.Calendar; import java.util.Set; import java.util.TreeSet; import static edu.northwestern.bioinformatics.studycalendar.domain.Fixtures.*; import static edu.northwestern.bioinformatics.studycalendar.domain.Fixtures.createPopulation; import static edu.northwestern.bioinformatics.studycalendar.domain.Fixtures.setId; import static edu.nwu.bioinformatics.commons.DateUtils.createDate; import static java.util.Calendar.AUGUST; import static org.easymock.EasyMock.expect; /** * @author Jalpa Patel */ public class <API key> extends ControllerTestCase { private <API key> controller; private <API key> command; private <API key> <API key>; private UserActionDao userActionDao; private PscUser pscUser = <API key>.createPscUser("user", 12L); private String applicationPath = "psc/application"; private Set pops = new TreeSet<Population>(); private DeltaService deltaService; private <API key> assignment; private Amendment a0, a1, a2, a3; protected void setUp() throws Exception { super.setUp(); <API key> = registerMockFor(<API key>.class); deltaService = registerMockFor(DeltaService.class); userActionDao = registerDaoMockFor(UserActionDao.class); Study study = new Study(); study.<API key>("Study A"); StudySite ss = createStudySite(study, createSite("NU")); a3 = createAmendments("A0", "A1", "A2", "A3"); a2 = a3.<API key>(); a1 = a2.<API key>(); a0 = a1.<API key>(); study.setAmendment(a3); ss.approveAmendment(a0, DateTools.createDate(2003, AUGUST, 1)); ss.approveAmendment(a1, DateTools.createDate(2003, AUGUST, 2)); ss.approveAmendment(a2, DateTools.createDate(2003, AUGUST, 3)); Subject subject = createSubject("1111", "Perry", "Duglas", createDate(1980, Calendar.JANUARY, 15, 0, 0, 0), Gender.MALE); subject.setGridId("1111"); assignment = setId(12, createAssignment(ss, subject)); assignment.setCurrentAmendment(a0); Population pop = setId(11, createPopulation("T", "Test")); pops.add(pop); assignment.setPopulations(pops); command = new <API key>(assignment, deltaService); command.getAmendments().put(a0, false); command.getAmendments().put(a1, true); command.getAmendments().put(a2, true); controller = new <API key>(); controller.setControllerTools(controllerTools); controller.setApplicationPath(applicationPath); controller.<API key>(<API key>); controller.setDeltaService(deltaService); controller.setUserActionDao(userActionDao); } public void <API key>() throws Exception { UserAction userAction = new UserAction(); String context = applicationPath.concat("/api/v1/subjects/1111/schedules"); userAction.setContext(context); userAction.setActionType("amendment"); userAction.setUser(pscUser.getCsmUser()); String des = "Amendment [01/02/2001 (A1)][01/03/2001 (A2)] applied to Perry Duglas for Study A"; userAction.setDescription(des); expect(<API key>.getUser()).andReturn(pscUser); deltaService.amend(assignment, a1); deltaService.amend(assignment, a2); userActionDao.save(userAction); replayMocks(); controller.onSubmit(request, response, command, null); verifyMocks(); UserAction actualUa = AuditEvent.getUserAction(); assertNotNull("User Action is not set", actualUa); assertEquals("User action's context is different", context, actualUa.getContext()); assertEquals("User action's actionType is different", "amendment", actualUa.getActionType()); assertEquals("User action's des is different", des, actualUa.getDescription()); assertEquals("User action's user is different", pscUser.getCsmUser(), actualUa.getUser()); } }
package com.techempower; import com.fasterxml.jackson.databind.ObjectMapper; import io.jooby.hikari.HikariModule; import io.jooby.json.JacksonModule; import io.jooby.rocker.RockerModule; import javax.sql.DataSource; import static io.jooby.ExecutionMode.EVENT_LOOP; import static io.jooby.Jooby.runApp; public class JaxrsApp { public static void main(String[] args) { runApp(args, EVENT_LOOP, app -> { /** JSON: */ app.install(new JacksonModule()); /** Database: */ app.install(new HikariModule()); /** Template engine: */ app.install(new RockerModule()); app.mvc(new Resource(app.require(DataSource.class), app.require(ObjectMapper.class))); }); } }
*> \brief \b SLANSB * * =========== DOCUMENTATION =========== * * Online html documentation available at * http: * *> \htmlonly *> Download SLANSB + dependencies *> <a href="http: *> [TGZ]</a> *> <a href="http: *> [ZIP]</a> *> <a href="http: *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * REAL FUNCTION SLANSB( NORM, UPLO, N, K, AB, LDAB, * WORK ) * * .. Scalar Arguments .. * CHARACTER NORM, UPLO * INTEGER K, LDAB, N * .. * .. Array Arguments .. * REAL AB( LDAB, * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> SLANSB returns the value of the one norm, or the Frobenius norm, or *> the infinity norm, or the element of largest absolute value of an *> n by n symmetric band matrix A, with k super-diagonals. *> \endverbatim *> *> \return SLANSB *> \verbatim *> *> SLANSB = ( max(abs(A(i,j))), NORM = 'M' or 'm' *> ( *> ( norm1(A), NORM = '1', 'O' or 'o' *> ( *> ( normI(A), NORM = 'I' or 'i' *> ( *> ( normF(A), NORM = 'F', 'f', 'E' or 'e' *> *> where norm1 denotes the one norm of a matrix (maximum column sum), *> normI denotes the infinity norm of a matrix (maximum row sum) and *> normF denotes the Frobenius norm of a matrix (square root of sum of *> squares). Note that max(abs(A(i,j))) is not a consistent matrix norm. *> \endverbatim * * Arguments: * ========== * *> \param[in] NORM *> \verbatim *> NORM is CHARACTER*1 *> Specifies the value to be returned in SLANSB as described *> above. *> \endverbatim *> *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> Specifies whether the upper or lower triangular part of the *> band matrix A is supplied. *> = 'U': Upper triangular part is supplied *> = 'L': Lower triangular part is supplied *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix A. N >= 0. When N = 0, SLANSB is *> set to zero. *> \endverbatim *> *> \param[in] K *> \verbatim *> K is INTEGER *> The number of super-diagonals or sub-diagonals of the *> band matrix A. K >= 0. *> \endverbatim *> *> \param[in] AB *> \verbatim *> AB is REAL array, dimension (LDAB,N) *> The upper or lower triangle of the symmetric band matrix A, *> stored in the first K+1 rows of AB. The j-th column of A is *> stored in the j-th column of the array AB as follows: *> if UPLO = 'U', AB(k+1+i-j,j) = A(i,j) for max(1,j-k)<=i<=j; *> if UPLO = 'L', AB(1+i-j,j) = A(i,j) for j<=i<=min(n,j+k). *> \endverbatim *> *> \param[in] LDAB *> \verbatim *> LDAB is INTEGER *> The leading dimension of the array AB. LDAB >= K+1. *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is REAL array, dimension (MAX(1,LWORK)), *> where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise, *> WORK is not referenced. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup realOTHERauxiliary * * ===================================================================== REAL FUNCTION SLANSB( NORM, UPLO, N, K, AB, LDAB, $ WORK ) * * -- LAPACK auxiliary routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER NORM, UPLO INTEGER K, LDAB, N * .. * .. Array Arguments .. REAL AB( LDAB, * ), WORK( * ) * .. * * ===================================================================== * * .. Parameters .. REAL ONE, ZERO PARAMETER ( ONE = 1.0E+0, ZERO = 0.0E+0 ) * .. * .. Local Scalars .. INTEGER I, J, L REAL ABSA, SCALE, SUM, VALUE * .. * .. External Subroutines .. EXTERNAL SLASSQ * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. Intrinsic Functions .. INTRINSIC ABS, MAX, MIN, SQRT * .. * .. Executable Statements .. * IF( N.EQ.0 ) THEN VALUE = ZERO ELSE IF( LSAME( NORM, 'M' ) ) THEN * * Find max(abs(A(i,j))). * VALUE = ZERO IF( LSAME( UPLO, 'U' ) ) THEN DO 20 J = 1, N DO 10 I = MAX( K+2-J, 1 ), K + 1 VALUE = MAX( VALUE, ABS( AB( I, J ) ) ) 10 CONTINUE 20 CONTINUE ELSE DO 40 J = 1, N DO 30 I = 1, MIN( N+1-J, K+1 ) VALUE = MAX( VALUE, ABS( AB( I, J ) ) ) 30 CONTINUE 40 CONTINUE END IF ELSE IF( ( LSAME( NORM, 'I' ) ) .OR. ( LSAME( NORM, 'O' ) ) .OR. $ ( NORM.EQ.'1' ) ) THEN * * Find normI(A) ( = norm1(A), since A is symmetric). * VALUE = ZERO IF( LSAME( UPLO, 'U' ) ) THEN DO 60 J = 1, N SUM = ZERO L = K + 1 - J DO 50 I = MAX( 1, J-K ), J - 1 ABSA = ABS( AB( L+I, J ) ) SUM = SUM + ABSA WORK( I ) = WORK( I ) + ABSA 50 CONTINUE WORK( J ) = SUM + ABS( AB( K+1, J ) ) 60 CONTINUE DO 70 I = 1, N VALUE = MAX( VALUE, WORK( I ) ) 70 CONTINUE ELSE DO 80 I = 1, N WORK( I ) = ZERO 80 CONTINUE DO 100 J = 1, N SUM = WORK( J ) + ABS( AB( 1, J ) ) L = 1 - J DO 90 I = J + 1, MIN( N, J+K ) ABSA = ABS( AB( L+I, J ) ) SUM = SUM + ABSA WORK( I ) = WORK( I ) + ABSA 90 CONTINUE VALUE = MAX( VALUE, SUM ) 100 CONTINUE END IF ELSE IF( ( LSAME( NORM, 'F' ) ) .OR. ( LSAME( NORM, 'E' ) ) ) THEN * * Find normF(A). * SCALE = ZERO SUM = ONE IF( K.GT.0 ) THEN IF( LSAME( UPLO, 'U' ) ) THEN DO 110 J = 2, N CALL SLASSQ( MIN( J-1, K ), AB( MAX( K+2-J, 1 ), J ), $ 1, SCALE, SUM ) 110 CONTINUE L = K + 1 ELSE DO 120 J = 1, N - 1 CALL SLASSQ( MIN( N-J, K ), AB( 2, J ), 1, SCALE, $ SUM ) 120 CONTINUE L = 1 END IF SUM = 2*SUM ELSE L = 1 END IF CALL SLASSQ( N, AB( L, 1 ), LDAB, SCALE, SUM ) VALUE = SCALE*SQRT( SUM ) END IF * SLANSB = VALUE RETURN * * End of SLANSB * END
SELECT D.duration , D.protocol_type , D.service , D.flag , D.src_bytes , D.dst_bytes , D.land , D.wrong_fragment , D.urgent , D.hot , D.num_failed_logins , D.logged_in , D.num_compromised , D.root_shell , D.su_attempted , D.num_root , D.num_file_creations , D.num_shells , D.num_access_files , D.num_outbound_cmds , D.is_host_login , D.is_guest_login , D.count , D.srv_count , D.serror_rate , D.srv_serror_rate , D.rerror_rate , D.srv_rerror_rate , D.same_srv_rate , D.diff_srv_rate , D.srv_diff_host_rate , D.dst_host_count , D.dst_host_srv_count , D.<API key> , D.<API key> , D.<API key> , D.<API key> , D.<API key> , D.<API key> , D.<API key> , D.<API key> , D.class_attribute FROM KDD_TRAIN_DATA D;
import logging import os import socket import subprocess import sys import tempfile import time from django.core.management.base import BaseCommand import redisutils import redis as redislib log = logging.getLogger('z.redis') # We process the keys in chunks of size CHUNK. CHUNK = 3000 # Remove any sets with less than MIN or more than MAX elements. MIN = 10 MAX = 50 # Expire keys after EXPIRE seconds. EXPIRE = 60 * 5 # Calling redis can raise raise these errors. RedisError = redislib.RedisError, socket.error def vacuum(master, slave): def keys(): ks = slave.keys() log.info('There are %s keys to clean up.' % len(ks)) ks = iter(ks) while 1: buffer = [] for _ in xrange(CHUNK): try: buffer.append(ks.next()) except StopIteration: yield buffer return yield buffer tmp = tempfile.NamedTemporaryFile(delete=False) for ks in keys(): tmp.write('\n'.join(ks)) tmp.close() # It's hard to get Python to clean up the memory from slave.keys(), so # we'll let the OS do it. You have to pass sys.executable both as the # thing to run and so argv[0] is set properly. os.execl(sys.executable, sys.executable, sys.argv[0], sys.argv[1], tmp.name) def cleanup(master, slave, filename): tmp = open(filename) total = [1, 0] p = subprocess.Popen(['wc', '-l', filename], stdout=subprocess.PIPE) total[0] = int(p.communicate()[0].strip().split()[0]) def file_keys(): while 1: buffer = [] for _ in xrange(CHUNK): line = tmp.readline() if line: buffer.append(line.strip()) else: yield buffer return yield buffer num = 0 for ks in file_keys(): pipe = slave.pipeline() for k in ks: pipe.scard(k) try: drop = [k for k, size in zip(ks, pipe.execute()) if 0 < size < MIN or size > MAX] except RedisError: continue num += len(ks) percent = round(float(num) / total[0] * 100, 1) if total[0] else 0 total[1] += len(drop) log.debug('[%s %.1f%%] Dropping %s keys.' % (num, percent, len(drop))) pipe = master.pipeline() for k in drop: pipe.expire(k, EXPIRE) try: pipe.execute() except RedisError: continue time.sleep(1) # Poor man's rate limiting. if total[0]: log.info('Dropped %s keys [%.1f%%].' % (total[1], round(float(total[1]) / total[0] * 100, 1))) class Command(BaseCommand): help = "Clean up the redis used by cache machine." def handle(self, *args, **kw): try: master = redisutils.connections['cache'] slave = redisutils.connections['cache_slave'] except Exception: log.error('Could not connect to redis.', exc_info=True) return if args: filename = args[0] try: cleanup(master, slave, filename) finally: os.unlink(filename) else: vacuum(master, slave)
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ko_KR"> <context> <name>Backend</name> <message> <location filename="../TarBackend.cpp" line="249"/> <source>Could not read archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TarBackend.cpp" line="251"/> <source>Archive Loaded</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TarBackend.cpp" line="284"/> <source>Extraction Finished</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TarBackend.cpp" line="286"/> <source>Modification Finished</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainUI</name> <message> <location filename="../MainUI.ui" line="35"/> <source>Archive:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="69"/> <location filename="../MainUI.cpp" line="331"/> <source>File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="125"/> <source>&amp;File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="134"/> <source>&amp;Edit</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="145"/> <source>&amp;Burn to Disk</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="178"/> <source>&amp;Open Archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="181"/> <source>Open archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="186"/> <source>&amp;New Archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="189"/> <source>New archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="194"/> <source>&amp;Quit</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="199"/> <source>Add File(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="202"/> <source>Add files to archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="207"/> <source>Remove File(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="210"/> <source>Remove selection from archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="215"/> <source>Extract All</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="218"/> <source>Extract archive into a directory</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="223"/> <source>Add Directory</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="226"/> <source>Add directory to archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="231"/> <source>Extract Selection</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="234"/> <source>Extract Selected Items</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="239"/> <source>USB Image</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="242"/> <source>Copy an IMG to a USB device (may require admin permission)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="28"/> <source>Archive Manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="29"/> <source>Admin Mode</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="55"/> <source>CTRL+N</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="56"/> <source>CTRL+O</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="57"/> <source>CTRL+Q</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="58"/> <source>CTRL+E</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="69"/> <location filename="../MainUI.cpp" line="331"/> <source>MimeType</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="69"/> <location filename="../MainUI.cpp" line="331"/> <source>Size</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="94"/> <location filename="../MainUI.cpp" line="236"/> <source>Opening Archive...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="180"/> <source>All Types %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="181"/> <location filename="../MainUI.cpp" line="199"/> <source>Uncompressed Archive (*.tar)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="182"/> <location filename="../MainUI.cpp" line="200"/> <source>GZip Compressed Archive (*.tar.gz *.tgz)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="183"/> <location filename="../MainUI.cpp" line="201"/> <source>BZip Compressed Archive (*.tar.bz *.tbz)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="184"/> <location filename="../MainUI.cpp" line="202"/> <source>BZip2 Compressed Archive (*.tar.bz2 *.tbz2)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="185"/> <location filename="../MainUI.cpp" line="204"/> <source>LMZA Compressed Archive (*.tar.lzma *.tlz)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="186"/> <location filename="../MainUI.cpp" line="203"/> <source>XZ Compressed Archive (*.tar.xz *.txz)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="187"/> <location filename="../MainUI.cpp" line="205"/> <source>CPIO Archive (*.cpio)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="188"/> <location filename="../MainUI.cpp" line="206"/> <source>PAX Archive (*.pax)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="189"/> <location filename="../MainUI.cpp" line="207"/> <source>AR Archive (*.ar)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="190"/> <location filename="../MainUI.cpp" line="208"/> <source>SHAR Archive (*.shar)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="191"/> <location filename="../MainUI.cpp" line="209"/> <source>Zip Archive (*.zip)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="192"/> <location filename="../MainUI.cpp" line="210"/> <source>7-Zip Archive (*.7z)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="198"/> <source>All Known Types %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="211"/> <source>READ-ONLY: ISO image (*.iso *.img)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="212"/> <source>READ-ONLY: XAR archive (*.xar)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="213"/> <source>READ-ONLY: Java archive (*.jar)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="214"/> <source>READ-ONLY: RedHat Package (*.rpm)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="215"/> <source>Show All Files (*)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="223"/> <source>Create Archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="226"/> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="226"/> <source>Could not overwrite file:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="234"/> <source>Open Archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="242"/> <location filename="../MainUI.cpp" line="249"/> <source>Add to Archive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="244"/> <location filename="../MainUI.cpp" line="251"/> <location filename="../MainUI.cpp" line="300"/> <source>Adding Items...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="262"/> <source>Removing Items...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="267"/> <location filename="../MainUI.cpp" line="311"/> <source>Extract Into Directory</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="269"/> <location filename="../MainUI.cpp" line="287"/> <location filename="../MainUI.cpp" line="294"/> <location filename="../MainUI.cpp" line="313"/> <location filename="../MainUI.cpp" line="325"/> <source>Extracting...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="345"/> <source>Link To: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>XDGDesktopList</name> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/> <source>Multimedia</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/> <source>Development</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/> <source>Education</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="621"/> <source>Games</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="622"/> <source>Graphics</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="623"/> <source>Network</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="624"/> <source>Office</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="625"/> <source>Science</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="626"/> <source>Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="627"/> <source>System</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="628"/> <source>Utility</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="629"/> <source>Wine</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="630"/> <source>Unsorted</source> <translation type="unfinished"></translation> </message> </context> <context> <name>imgDialog</name> <message> <location filename="../imgDialog.ui" line="14"/> <source>Burn IMG to device</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="29"/> <source>IMG File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="54"/> <source>Block Size</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="84"/> <source>USB Device</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="96"/> <source>Refresh Device List</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="108"/> <source>Wipe all extra space on device (conv = sync)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="132"/> <source>Burning to USB:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="166"/> <source>Time Elapsed:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="222"/> <source>Cancel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.ui" line="229"/> <source>Start</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="22"/> <source>Admin Mode</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="36"/> <source>Kilobyte(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="37"/> <source>Megabyte(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="38"/> <source>Gigabyte(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="110"/> <source>Cancel Image Burn?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="21"/> <source>Burn Disk Image to Device</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="110"/> <source>Warning: This will leave the USB device in an inconsistent state</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="110"/> <source>Do you wish to stop the current disk image burn process?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="170"/> <source>Administrator Permissions Needed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="170"/> <source>This operation requires administrator priviledges.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="170"/> <source>Would you like to enable these priviledges?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="175"/> <source>ERROR</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="175"/> <source>The process could not be completed:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="178"/> <source>SUCCESS</source> <translation type="unfinished"></translation> </message> <message> <location filename="../imgDialog.cpp" line="178"/> <source>The image was successfully burned to the device</source> <translation type="unfinished"></translation> </message> </context> </TS>
package org.geneontology.minerva.json; public class JsonOwlFact extends JsonAnnotatedObject { public String subject; public String property; public String object; @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((object == null) ? 0 : object.hashCode()); result = prime * result + ((property == null) ? 0 : property.hashCode()); result = prime * result + ((subject == null) ? 0 : subject.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } JsonOwlFact other = (JsonOwlFact) obj; if (object == null) { if (other.object != null) { return false; } } else if (!object.equals(other.object)) { return false; } if (property == null) { if (other.property != null) { return false; } } else if (!property.equals(other.property)) { return false; } if (subject == null) { if (other.subject != null) { return false; } } else if (!subject.equals(other.subject)) { return false; } return true; } }
#include "ace/Service_Config.h" #include "ace/Logging_Strategy.h" #include "ace/Sig_Adapter.h" #include "TS_Clerk_Handler.h" #include "TS_Server_Handler.h" #include "<API key>.h" #include "Name_Handler.h" #include "Token_Handler.h" #include "<API key>.h" int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { // Try to link in the svc.conf entries dynamically, enabling the // "ignore_debug_flag" as the last parameter so that we can override // the default ACE_Log_Priority settings in the svc.conf file. // Warning - do not try to move the ACE_Reactor signal handling work // up to before this call - if the user specified -b (be a daemon), // all handles will be closed, including the Reactor's pipe. if (ACE_Service_Config::open (argc, argv, <API key>, 1, 0, 1) == -1) { if (errno != ENOENT) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("open")), 1); else // Use static linking. { if (ACE::debug () == 0) ACE_LOG_MSG->priority_mask (~LM_DEBUG, ACE_Log_Msg::PROCESS); // Calling ACE_SVC_INVOKE to create a new Service_Object. // Stash the newly created Service_Object into an // <API key> which is an <auto_ptr> specialized // for ACE_Service_Object. ACE_TCHAR *l_argv[3]; ACE_TCHAR name_port[] = ACE_TEXT ("-p ") ACE_TEXT (<API key>); l_argv[0] = name_port; l_argv[1] = 0; <API key> sp_1 = ACE_SVC_INVOKE (ACE_Name_Acceptor); if (sp_1->init (1, l_argv) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("Name Service")), 1); ACE_TCHAR time_port[] = ACE_TEXT ("-p ") ACE_TEXT (<API key>); l_argv[0] = time_port; l_argv[1] = 0; <API key> sp_2 = ACE_SVC_INVOKE (<API key>); if (sp_2->init (1, l_argv) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("TS Server Acceptor")), 1); ACE_TCHAR clerk_port[] = ACE_TEXT ("-p 10011"); l_argv[0] = argv[0]; l_argv[1] = clerk_port; l_argv[2] = 0; <API key> sp_3 = ACE_SVC_INVOKE (<API key>); if (sp_3->init (2, l_argv) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("TS Clerk Processor")), 1); #if defined (<API key>) ACE_TCHAR token_port[] = ACE_TEXT ("-p ") ACE_TEXT (ACE_DEFAULT_<API key>); l_argv[0] = token_port; l_argv[1] = 0; <API key> sp_4 = ACE_SVC_INVOKE (ACE_Token_Acceptor); if (sp_4->init (1, l_argv) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("Token Service")), 1); #endif /* <API key> */ ACE_TCHAR thr_logging_port[] = ACE_TEXT ("-p ") ACE_TEXT (<API key>); l_argv[0] = thr_logging_port; l_argv[1] = 0; <API key> sp_5 = ACE_SVC_INVOKE (<API key>); if (sp_5->init (1, l_argv) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("Threaded Logging Server")), 1); ACE_TCHAR logging_port[] = ACE_TEXT ("-p ") ACE_TEXT (<API key>); l_argv[0] = logging_port; l_argv[1] = 0; <API key> sp_6 = ACE_SVC_INVOKE (<API key>); if (sp_6->init (1, l_argv) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("Logging Server")), 1); l_argv[0] = logging_port; l_argv[1] = 0; <API key> sp_7 = ACE_SVC_INVOKE (<API key>); if (sp_7->init (1, l_argv) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("Logging Client")), 1); // Run forever, performing the configured services until we // are shut down by a SIGINT/SIGQUIT signal. // Create an adapter to end the event loop. ACE_Sig_Adapter sa ((ACE_Sig_Handler_Ex) ACE_Reactor::end_event_loop); ACE_Sig_Set sig_set; sig_set.sig_add (SIGINT); sig_set.sig_add (SIGQUIT); if (ACE_Reactor::instance ()->register_handler (sig_set, &sa) == -1) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("register signals")), 1); } else { ACE_Reactor::instance ()-><API key> (); // Back from running the reactor we have to remove our signal handler ACE_Reactor::instance ()->remove_handler (sig_set); } // Destructors of <API key>'s automagically // call fini(). } } else // Use dynamic linking. { // Run forever, performing the configured services until we are // shut down by a SIGINT/SIGQUIT signal. // Create an adapter to end the event loop. ACE_Sig_Adapter sa ((ACE_Sig_Handler_Ex) ACE_Reactor::end_event_loop); ACE_Sig_Set sig_set; sig_set.sig_add (SIGINT); sig_set.sig_add (SIGQUIT); // Register ourselves to receive signals so we can shut down // gracefully. if (ACE_Reactor::instance ()->register_handler (sig_set, &sa) == -1) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("register signals2")), 1); } else { ACE_Reactor::instance ()-><API key> (); // Back from running the reactor we have to remove our signal handler ACE_Reactor::instance ()->remove_handler (sig_set); } } return 0; }
<a name="listDocuments"></a>The **listDocuments** operation returns a JSON object containing a list of all the <a href="#documents">**Documents**</a> to which the authenticated user has access.
import { connect } from 'react-redux'; import { I18nProvider } from '@lingui/react'; import { Store } from '../../stores'; import { selectLocale } from '../../selectors/locale/select_locale'; import { CatalogsMap, Locales } from '../../application/locales'; interface Props { readonly catalogs: CatalogsMap; readonly language: string; } interface Actions { } const mapStateToProps = (appStore: Store): Props => ({ catalogs: Locales.catalogsMap(), language: selectLocale(appStore), }); const mapDispatchToProps = (): Actions => ({}); export const <API key> = connect(mapStateToProps, mapDispatchToProps)(I18nProvider);
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE <API key> #-} -- | All types. module HIndent.Types (Printer(..) ,PrintState(..) ,Extender(..) ,Style(..) ,Config(..) ,defaultConfig ,NodeInfo(..) ,ComInfo(..) ,ComInfoLocation(..) ) where import Control.Applicative import Control.Monad import Control.Monad.State.Strict (MonadState(..),StateT) import Control.Monad.Trans.Maybe import Data.Data import Data.Default import Data.Functor.Identity import Data.Int (Int64) import Data.Text (Text) import Data.Text.Lazy.Builder (Builder) import Language.Haskell.Exts.Comments import Language.Haskell.Exts.Parser import Language.Haskell.Exts.SrcLoc -- | A pretty printing monad. newtype Printer s a = Printer {runPrinter :: StateT (PrintState s) (MaybeT Identity) a} deriving (Applicative,Monad,Functor,MonadState (PrintState s),MonadPlus,Alternative) -- | The state of the pretty printer. data PrintState s = PrintState {psIndentLevel :: !Int64 -- ^ Current indentation level. ,psOutput :: !Builder -- ^ The current output. ,psNewline :: !Bool -- ^ Just outputted a newline? ,psColumn :: !Int64 -- ^ Current column. ,psLine :: !Int64 -- ^ Current line number. ,psUserState :: !s -- ^ User state. ,psExtenders :: ![Extender s] -- ^ Extenders. ,psConfig :: !Config -- ^ Config which styles may or may not pay attention to. ,psEolComment :: !Bool -- ^ An end of line comment has just been outputted. ,psInsideCase :: !Bool -- ^ Whether we're in a case statement, used for Rhs printing. ,psParseMode :: !ParseMode -- ^ Mode used to parse the original AST. } instance Eq (PrintState s) where PrintState ilevel out newline col line _ _ _ eolc inc pm == PrintState ilevel' out' newline' col' line' _ _ _ eolc' inc' pm' = (ilevel,out,newline,col,line,eolc, inc) == (ilevel',out',newline',col',line',eolc', inc') -- | A printer extender. Takes as argument the user state that the -- printer was run with, and the current node to print. Use -- 'prettyNoExt' to fallback to the built-in printer. data Extender s where Extender :: forall s a. (Typeable a) => (a -> Printer s ()) -> Extender s CatchAll :: forall s. (forall a. Typeable a => s -> a -> Maybe (Printer s ())) -> Extender s -- | A printer style. data Style = forall s. Style {styleName :: !Text -- ^ Name of the style, used in the commandline interface. ,styleAuthor :: !Text -- ^ Author of the printer (as opposed to the author of the style). ,styleDescription :: !Text -- ^ Description of the style. ,styleInitialState :: !s -- ^ User state, if needed. ,styleExtenders :: ![Extender s] -- ^ Extenders to the printer. ,styleDefConfig :: !Config -- ^ Default config to use for this style. } -- | Configurations shared among the different styles. Styles may pay -- attention to or completely disregard this configuration. data Config = Config {configMaxColumns :: !Int64 -- ^ Maximum columns to fit code into ideally. ,configIndentSpaces :: !Int64 -- ^ How many spaces to indent? ,<API key> :: !Bool -- ^ Remove spaces on lines that are otherwise empty? } instance Default Config where def = Config {configMaxColumns = 80 ,configIndentSpaces = 2 ,<API key> = False} -- | Default style configuration. defaultConfig :: Config defaultConfig = def -- | Information for each node in the AST. data NodeInfo = NodeInfo {nodeInfoSpan :: !SrcSpanInfo -- ^ Location info from the parser. ,nodeInfoComments :: ![ComInfo] -- ^ Comments which are attached to this node. } deriving (Typeable,Show,Data) -- | Comment relative locations. data ComInfoLocation = Before | After deriving (Show,Typeable,Data,Eq) -- | Comment with some more info. data ComInfo = ComInfo {comInfoComment :: !Comment -- ^ The normal comment type. ,comInfoLocation :: !(Maybe ComInfoLocation) -- ^ Where the comment lies relative to the node. } deriving (Show,Typeable,Data)
#include <sys/types.h> #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int conv_escape_str(char *); static char *conv_escape(char *, int *); static int getchr(void); static double getdouble(void); static intmax_t getintmax(void); static uintmax_t getuintmax(void); static char *getstr(void); static char *mklong(const char *, const char *); static void check_conversion(const char *, const char *); static int rval; static char **gargv; #define isodigit(c) ((c) >= '0' && (c) <= '7') #define octtobin(c) ((c) - '0') #include "bltin.h" #include "system.h" #include "output.h" #define PF(f, func) { \ switch ((char *)param - (char *)array) { \ default: \ (void)printf(f, array[0], array[1], func); \ break; \ case sizeof(*param): \ (void)printf(f, array[0], func); \ break; \ case 0: \ (void)printf(f, func); \ break; \ } \ } int printfcmd(int argc, char *argv[]) { (void)argc; char *fmt; char *format; int ch; rval = 0; nextopt(nullstr); argv = argptr; format = *argv; if (!format) { warnx("usage: printf format [arg ...]"); goto err; } gargv = ++argv; #define SKIP1 " #define SKIP2 "*0123456789" do { /* * Basic algorithm is to scan the format string for conversion * specifications -- once one is found, find out if the field * width or precision is a '*'; if it is, gather up value. * Note, format strings are reused as necessary to use up the * provided arguments, arguments of zero/null string are * provided to use up the format string. */ /* find next format specification */ for (fmt = format; (ch = *fmt++) ;) { char *start; char nextch; int array[2]; int *param; if (ch == '\\') { int c_ch; fmt = conv_escape(fmt, &c_ch); ch = c_ch; goto pc; } if (ch != '%' || (*fmt == '%' && (++fmt || 1))) { pc: putchar(ch); continue; } /* Ok - we've found a format specification, Save its address for a later printf(). */ start = fmt - 1; param = array; /* skip to field width */ fmt += strspn(fmt, SKIP1); if (*fmt == '*') *param++ = getintmax(); /* skip to possible '.', get following precision */ fmt += strspn(fmt, SKIP2); if (*fmt == '.') ++fmt; if (*fmt == '*') *param++ = getintmax(); fmt += strspn(fmt, SKIP2); ch = *fmt; if (!ch) { warnx("missing format character"); goto err; } /* null terminate format string to we can use it as an argument to printf. */ nextch = fmt[1]; fmt[1] = 0; switch (ch) { case 'b': { int done = conv_escape_str(getstr()); char *p = stackblock(); *fmt = 's'; PF(start, p); /* escape if a \c was encountered */ if (done) goto out; *fmt = 'b'; break; } case 'c': { int p = getchr(); PF(start, p); break; } case 's': { char *p = getstr(); PF(start, p); break; } case 'd': case 'i': { intmax_t p = getintmax(); char *f = mklong(start, fmt); PF(f, p); break; } case 'o': case 'u': case 'x': case 'X': { uintmax_t p = getuintmax(); char *f = mklong(start, fmt); PF(f, p); break; } case 'e': case 'E': case 'f': case 'g': case 'G': { double p = getdouble(); PF(start, p); break; } default: warnx("%s: invalid directive", start); goto err; } *++fmt = nextch; } } while (gargv != argv && *gargv); out: return rval; err: return 1; } /* * Print SysV echo(1) style escape string * Halts processing string if a \c escape is encountered. */ static int conv_escape_str(char *str) { int ch; char *cp; /* convert string into a temporary buffer... */ STARTSTACKSTR(cp); do { int c; ch = *str++; if (ch != '\\') continue; ch = *str++; if (ch == 'c') { /* \c as in SYSV echo - abort all processing.... */ ch = 0x100; continue; } /* * %b string octal constants are not like those in C. * They start with a \0, and are followed by 0, 1, 2, * or 3 octal digits. */ if (ch == '0') { unsigned char i; i = 3; ch = 0; do { unsigned k = octtobin(*str); if (k > 7) break; str++; ch <<= 3; ch += k; } while (--i); continue; } /* Finally test for sequences valid in the format string */ str = conv_escape(str - 1, &c); ch = c; } while (STPUTC(ch, cp), (char)ch); return ch; } /* * Print "standard" escape characters */ static char * conv_escape(char *str, int *conv_ch) { int value; int ch; ch = *str; switch (ch) { default: case 0: value = '\\'; goto out; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': ch = 3; value = 0; do { value <<= 3; value += octtobin(*str++); } while (isodigit(*str) && --ch); goto out; case '\\': value = '\\'; break; /* backslash */ case 'a': value = '\a'; break; /* alert */ case 'b': value = '\b'; break; /* backspace */ case 'f': value = '\f'; break; /* form-feed */ case 'n': value = '\n'; break; /* newline */ case 'r': value = '\r'; break; /* carriage-return */ case 't': value = '\t'; break; /* tab */ case 'v': value = '\v'; break; /* vertical-tab */ } str++; out: *conv_ch = value; return str; } static char * mklong(const char *str, const char *ch) { /* * Replace a string like "%92.3u" with "%92.3"PRIuMAX. * * Although C99 does not guarantee it, we assume PRIiMAX, * PRIoMAX, PRIuMAX, PRIxMAX, and PRIXMAX are all the same * as PRIdMAX with the final 'd' replaced by the corresponding * character. */ char *copy; size_t len; len = ch - str + sizeof(PRIdMAX); STARTSTACKSTR(copy); copy = makestrspace(len, copy); memcpy(copy, str, len - sizeof(PRIdMAX)); memcpy(copy + len - sizeof(PRIdMAX), PRIdMAX, sizeof(PRIdMAX)); copy[len - 2] = *ch; return (copy); } static int getchr(void) { int val = 0; if (*gargv) val = **gargv++; return val; } static char * getstr(void) { char *val = nullstr; if (*gargv) val = *gargv++; return val; } static intmax_t getintmax(void) { intmax_t val = 0; char *cp, *ep; cp = *gargv; if (cp == NULL) goto out; gargv++; val = (unsigned char) cp[1]; if (*cp == '\"' || *cp == '\'') goto out; errno = 0; val = strtoimax(cp, &ep, 0); check_conversion(cp, ep); out: return val; } static uintmax_t getuintmax(void) { uintmax_t val = 0; char *cp, *ep; cp = *gargv; if (cp == NULL) goto out; gargv++; val = (unsigned char) cp[1]; if (*cp == '\"' || *cp == '\'') goto out; errno = 0; val = strtoumax(cp, &ep, 0); check_conversion(cp, ep); out: return val; } static double getdouble(void) { double val; char *cp, *ep; cp = *gargv; if (cp == NULL) return 0; gargv++; if (*cp == '\"' || *cp == '\'') return (unsigned char) cp[1]; errno = 0; val = strtod(cp, &ep); check_conversion(cp, ep); return val; } static void check_conversion(const char *s, const char *ep) { if (*ep) { if (ep == s) warnx("%s: expected numeric value", s); else warnx("%s: not completely converted", s); rval = 1; } else if (errno == ERANGE) { warnx("%s: %s", s, strerror(ERANGE)); rval = 1; } } int echocmd(int argc, char **argv) { (void)argc; int nonl = 0; struct output *outs = out1; if (!*++argv) goto end; if (equal(*argv, "-n")) { nonl = ~nonl; if (!*++argv) goto end; } do { int c; nonl += conv_escape_str(*argv); outstr(stackblock(), outs); if (nonl > 0) break; c = ' '; if (!*++argv) { end: if (nonl) { break; } c = '\n'; } outc(c, outs); } while (*argv); return 0; }
#include "content/browser/service_worker/<API key>.h" #include <algorithm> #include <memory> #include <tuple> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/macros.h" #include "base/optional.h" #include "base/<API key>.h" #include "base/task/post_task.h" #include "base/threading/<API key>.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/navigation_request.h" #include "content/browser/frame_host/navigator.h" #include "content/browser/frame_host/<API key>.h" #include "content/browser/service_worker/<API key>.h" #include "content/browser/service_worker/<API key>.h" #include "content/browser/service_worker/<API key>.h" #include "content/browser/service_worker/<API key>.h" #include "content/browser/<API key>.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/<API key>.h" #include "content/public/common/child_process_host.h" #include "content/public/common/content_client.h" #include "content/public/common/<API key>.h" #include "third_party/blink/public/mojom/loader/<API key>.mojom.h" #include "ui/base/<API key>.h" #include "url/gurl.h" #include "url/origin.h" // hops between UI and IO, can likely be simplified when the service worker core // thread moves to the UI thread. namespace content { namespace <API key> { namespace { using OpenURLCallback = base::OnceCallback<void(int, int)>; // The OpenURLObserver class is a WebContentsObserver that will wait for a // WebContents to be initialized, run the |callback| passed to its constructor // then self destroy. // The callback will receive the process and frame ids. If something went wrong // those will be (kInvalidUniqueID, MSG_ROUTING_NONE). // The callback will be called on the core thread. class OpenURLObserver : public WebContentsObserver { public: OpenURLObserver(WebContents* web_contents, int frame_tree_node_id, OpenURLCallback callback) : WebContentsObserver(web_contents), frame_tree_node_id_(frame_tree_node_id), callback_(std::move(callback)) {} void DidFinishNavigation(NavigationHandle* navigation_handle) override { DCHECK(web_contents()); if (!navigation_handle->HasCommitted()) { // Return error. RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); return; } if (navigation_handle->GetFrameTreeNodeId() != frame_tree_node_id_) { // Return error. RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); return; } RenderFrameHost* render_frame_host = navigation_handle->GetRenderFrameHost(); RunCallback(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); } void RenderProcessGone(base::TerminationStatus status) override { RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); } void <API key>() override { RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); } private: void RunCallback(int render_process_id, int render_frame_id) { // After running the callback, |this| will stop observing, thus // web_contents() should return nullptr and |RunCallback| should no longer // be called. Then, |this| will self destroy. DCHECK(web_contents()); DCHECK(callback_); base::PostTask(FROM_HERE, {<API key>::GetCoreThreadId()}, base::BindOnce(std::move(callback_), render_process_id, render_frame_id)); Observe(nullptr); base::<API key>::Get()->DeleteSoon(FROM_HERE, this); } int frame_tree_node_id_; OpenURLCallback callback_; <API key>(OpenURLObserver); }; blink::mojom::<API key> <API key>( int render_process_id, int render_frame_id, base::TimeTicks create_time, const std::string& client_uuid) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* render_frame_host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); if (!render_frame_host) return nullptr; // Treat items in backforward cache as not existing. if (render_frame_host-><API key>()) return nullptr; // TODO(mlamouri,michaeln): it is possible to end up collecting information // for a frame that is actually being navigated and isn't exactly what we are // expecting. PageVisibilityState visibility = render_frame_host->GetVisibilityState(); bool page_hidden = visibility != PageVisibilityState::kVisible; return blink::mojom::<API key>::New( render_frame_host->GetLastCommittedURL(), render_frame_host->GetParent() ? blink::mojom::<API key>::kNested : blink::mojom::<API key>::kTopLevel, client_uuid, blink::mojom::<API key>::kWindow, page_hidden, render_frame_host->IsFocused(), render_frame_host->IsFrozen() ? blink::mojom::<API key>::kFrozen : blink::mojom::<API key>::kActive, render_frame_host->frame_tree_node()->last_focus_time(), create_time); } blink::mojom::<API key> FocusOnUI( int render_process_id, int render_frame_id, base::TimeTicks create_time, const std::string& client_uuid) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* render_frame_host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( WebContents::FromRenderFrameHost(render_frame_host)); if (!render_frame_host || !web_contents) return nullptr; FrameTreeNode* frame_tree_node = render_frame_host->frame_tree_node(); // Focus the frame in the frame tree node, in case it has changed. frame_tree_node->frame_tree()->SetFocusedFrame( frame_tree_node, render_frame_host->GetSiteInstance()); // Focus the frame's view to make sure the frame is now considered as focused. render_frame_host->GetView()->Focus(); // Move the web contents to the foreground. web_contents->Activate(); return <API key>(render_process_id, render_frame_id, create_time, client_uuid); } // This is only called for main frame navigations in OpenWindowOnUI(). void DidOpenURLOnUI(WindowType type, OpenURLCallback callback, WebContents* web_contents) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!web_contents) { <API key>( FROM_HERE, <API key>::GetCoreThreadId(), base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } // <API key>::OpenURL calls ui::BaseWindow::Show which // makes the destination window the main+key window, but won't make Chrome // always called from a user gesture (e.g. notification click), we should // explicitly activate the window, which brings Chrome to the front. static_cast<WebContentsImpl*>(web_contents)->Activate(); RenderFrameHostImpl* rfhi = static_cast<RenderFrameHostImpl*>(web_contents->GetMainFrame()); new OpenURLObserver(web_contents, rfhi->frame_tree_node()->frame_tree_node_id(), std::move(callback)); if (type == WindowType::<API key>) { // Set the opened web_contents to payment app provider to manage its life // cycle. PaymentAppProvider::GetInstance()->SetOpenedWindow(web_contents); } } void OpenWindowOnUI( const GURL& url, const GURL& script_url, int worker_id, int worker_process_id, const scoped_refptr<<API key>>& context_wrapper, WindowType type, OpenURLCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderProcessHost* render_process_host = RenderProcessHost::FromID(worker_process_id); if (render_process_host->IsForGuestsOnly()) { <API key>( FROM_HERE, <API key>::GetCoreThreadId(), base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } SiteInstance* site_instance = context_wrapper->process_manager()-><API key>(worker_id); if (!site_instance) { // Worker isn't running anymore. Fail. <API key>( FROM_HERE, <API key>::GetCoreThreadId(), base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } // The following code is a rough copy of Navigator::RequestOpenURL. That // function can't be used directly since there is no render frame host yet // that the navigation will occur in. OpenURLParams params( url, Referrer::SanitizeForRequest( url, Referrer(script_url, network::mojom::ReferrerPolicy::kDefault)), type == WindowType::<API key> ? <API key>::NEW_POPUP : <API key>::NEW_FOREGROUND_TAB, ui::<API key>, true /* <API key> */); params.<API key> = type == WindowType::NEW_TAB_WINDOW; params.initiator_origin = url::Origin::Create(script_url.GetOrigin()); // End of RequestOpenURL copy. GetContentClient()->browser()->OpenURL( site_instance, params, base::<API key>( base::BindOnce(&DidOpenURLOnUI, type, std::move(callback)))); } void NavigateClientOnUI(const GURL& url, const GURL& script_url, int process_id, int frame_id, OpenURLCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* rfhi = RenderFrameHostImpl::FromID(process_id, frame_id); WebContents* web_contents = WebContents::FromRenderFrameHost(rfhi); if (!rfhi || !web_contents) { <API key>( FROM_HERE, <API key>::GetCoreThreadId(), base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } // Reject the navigate() call if there is an ongoing browser-initiated // navigation. Not rejecting it would allow websites to prevent the user from NavigationRequest* <API key> = rfhi->frame_tree_node()->frame_tree()->root()->navigation_request(); if (<API key> && <API key>->browser_initiated()) { <API key>( FROM_HERE, <API key>::GetCoreThreadId(), base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } int frame_tree_node_id = rfhi->frame_tree_node()->frame_tree_node_id(); Navigator* navigator = rfhi->frame_tree_node()->navigator(); navigator->RequestOpenURL( rfhi, url, <API key>() /* <API key> */, url::Origin::Create(script_url), nullptr /* post_body */, std::string() /* extra_headers */, Referrer::SanitizeForRequest( url, Referrer(script_url, network::mojom::ReferrerPolicy::kDefault)), <API key>::CURRENT_TAB, false /* <API key> */, false /* user_gesture */, blink::TriggeringEventInfo::kUnknown, std::string() /* href_translate */, nullptr /* <API key> */, base::nullopt); new OpenURLObserver(web_contents, frame_tree_node_id, std::move(callback)); } void AddWindowClient( const <API key>* container_host, std::vector<std::tuple<int, int, base::TimeTicks, std::string>>* client_info) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); if (!container_host-><API key>()) { return; } if (!container_host->is_execution_ready()) return; client_info->push_back(std::make_tuple( container_host->process_id(), container_host->frame_id(), container_host->create_time(), container_host->client_uuid())); } void AddNonWindowClient( const <API key>* container_host, blink::mojom::<API key> client_type, std::vector<blink::mojom::<API key>>* out_clients) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); blink::mojom::<API key> host_client_type = container_host->GetClientType(); if (host_client_type == blink::mojom::<API key>::kWindow) return; if (client_type != blink::mojom::<API key>::kAll && client_type != host_client_type) return; if (!container_host->is_execution_ready()) return; // TODO(dtapuska): Need to get frozen state for dedicated workers from // DedicatedWorkerHost. crbug.com/968417 auto client_info = blink::mojom::<API key>::New( container_host->url(), blink::mojom::<API key>::kNone, container_host->client_uuid(), host_client_type, /*page_hidden=*/true, /*is_focused=*/false, blink::mojom::<API key>::kActive, base::TimeTicks(), container_host->create_time()); out_clients->push_back(std::move(client_info)); } void <API key>( // The tuple contains process_id, frame_id, create_time, client_uuid. const std::vector<std::tuple<int, int, base::TimeTicks, std::string>>& clients_info, const GURL& script_url, blink::mojom::ServiceWorkerHost::GetClientsCallback callback, std::vector<blink::mojom::<API key>> out_clients) { DCHECK_CURRENTLY_ON(BrowserThread::UI); for (const auto& it : clients_info) { blink::mojom::<API key> info = <API key>( std::get<0>(it), std::get<1>(it), std::get<2>(it), std::get<3>(it)); // If the request to the container_host returned a null // <API key>, that means that it wasn't possible to associate // it with a valid RenderFrameHost. It might be because the frame was killed // or navigated in between. if (!info) continue; DCHECK(!info->client_uuid.empty()); // We can get info for a frame that was navigating end ended up with a // different URL than expected. In such case, we should make sure to not // expose cross-origin WindowClient. if (info->url.GetOrigin() != script_url.GetOrigin()) continue; out_clients.push_back(std::move(info)); } <API key>( FROM_HERE, <API key>::GetCoreThreadId(), base::BindOnce(std::move(callback), std::move(out_clients))); } struct <API key> { bool operator()(const blink::mojom::<API key>& a, const blink::mojom::<API key>& b) const { // Clients for windows should be appeared earlier. if (a->client_type == blink::mojom::<API key>::kWindow && b->client_type != blink::mojom::<API key>::kWindow) { return true; } if (a->client_type != blink::mojom::<API key>::kWindow && b->client_type == blink::mojom::<API key>::kWindow) { return false; } // Clients focused recently should be appeared earlier. if (a->last_focus_time != b->last_focus_time) return a->last_focus_time > b->last_focus_time; // Clients created before should be appeared earlier. return a->creation_time < b->creation_time; } }; void DidGetClients( blink::mojom::ServiceWorkerHost::GetClientsCallback callback, std::vector<blink::mojom::<API key>> clients) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); std::sort(clients.begin(), clients.end(), <API key>()); std::move(callback).Run(std::move(clients)); } void GetNonWindowClients( const base::WeakPtr<<API key>>& controller, blink::mojom::<API key> options, blink::mojom::ServiceWorkerHost::GetClientsCallback callback, std::vector<blink::mojom::<API key>> clients) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); if (!options-><API key>) { for (const auto& controllee : controller->controllee_map()) AddNonWindowClient(controllee.second, options->client_type, &clients); } else if (controller->context()) { GURL origin = controller->script_url().GetOrigin(); for (auto it = controller->context()-><API key>( origin, false /* <API key> */, false /* <API key> */); !it->IsAtEnd(); it->Advance()) { AddNonWindowClient(it->GetContainerHost(), options->client_type, &clients); } } DidGetClients(std::move(callback), std::move(clients)); } void DidGetWindowClients( const base::WeakPtr<<API key>>& controller, blink::mojom::<API key> options, blink::mojom::ServiceWorkerHost::GetClientsCallback callback, std::vector<blink::mojom::<API key>> clients) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); if (options->client_type == blink::mojom::<API key>::kAll) { GetNonWindowClients(controller, std::move(options), std::move(callback), std::move(clients)); return; } DidGetClients(std::move(callback), std::move(clients)); } void GetWindowClients( const base::WeakPtr<<API key>>& controller, blink::mojom::<API key> options, blink::mojom::ServiceWorkerHost::GetClientsCallback callback, std::vector<blink::mojom::<API key>> clients) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); DCHECK(options->client_type == blink::mojom::<API key>::kWindow || options->client_type == blink::mojom::<API key>::kAll); std::vector<std::tuple<int, int, base::TimeTicks, std::string>> clients_info; if (!options-><API key>) { for (const auto& controllee : controller->controllee_map()) AddWindowClient(controllee.second, &clients_info); } else if (controller->context()) { GURL origin = controller->script_url().GetOrigin(); for (auto it = controller->context()-><API key>( origin, false /* <API key> */, false /* <API key> */); !it->IsAtEnd(); it->Advance()) { AddWindowClient(it->GetContainerHost(), &clients_info); } } if (clients_info.empty()) { DidGetWindowClients(controller, std::move(options), std::move(callback), std::move(clients)); return; } <API key>( FROM_HERE, BrowserThread::UI, base::BindOnce(&<API key>, clients_info, controller->script_url(), base::BindOnce(&DidGetWindowClients, controller, std::move(options), std::move(callback)), std::move(clients))); } void <API key>( const base::WeakPtr<<API key>>& context, const std::string& client_uuid, const GURL& sane_origin, NavigationCallback callback) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); if (!context) { std::move(callback).Run(blink::<API key>::kErrorAbort, nullptr /* client_info */); return; } <API key>* container_host = context-><API key>(client_uuid); if (!container_host || !container_host->is_execution_ready()) { // The page was destroyed before it became execution ready. Tell the // renderer the page opened but it doesn't have access to it. std::move(callback).Run(blink::<API key>::kOk, nullptr /* client_info */); return; } CHECK_EQ(container_host->url().GetOrigin(), sane_origin); if (<API key>::<API key>()) { blink::mojom::<API key> info = <API key>( container_host->process_id(), container_host->frame_id(), container_host->create_time(), container_host->client_uuid()); std::move(callback).Run(blink::<API key>::kOk, std::move(info)); } else { base::<API key>( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&<API key>, container_host->process_id(), container_host->frame_id(), container_host->create_time(), container_host->client_uuid()), base::BindOnce(std::move(callback), blink::<API key>::kOk)); } } } // namespace void FocusWindowClient(<API key>* container_host, ClientCallback callback) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); DCHECK(container_host-><API key>()); if (<API key>::<API key>()) { blink::mojom::<API key> info = FocusOnUI(container_host->process_id(), container_host->frame_id(), container_host->create_time(), container_host->client_uuid()); std::move(callback).Run(std::move(info)); } else { base::<API key>( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&FocusOnUI, container_host->process_id(), container_host->frame_id(), container_host->create_time(), container_host->client_uuid()), std::move(callback)); } } void OpenWindow(const GURL& url, const GURL& script_url, int worker_id, int worker_process_id, const base::WeakPtr<<API key>>& context, WindowType type, NavigationCallback callback) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); <API key>( FROM_HERE, BrowserThread::UI, base::BindOnce( &OpenWindowOnUI, url, script_url, worker_id, worker_process_id, base::WrapRefCounted(context->wrapper()), type, base::BindOnce(&DidNavigate, context, script_url.GetOrigin(), std::move(callback)))); } void NavigateClient(const GURL& url, const GURL& script_url, int process_id, int frame_id, const base::WeakPtr<<API key>>& context, NavigationCallback callback) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); <API key>( FROM_HERE, BrowserThread::UI, base::BindOnce( &NavigateClientOnUI, url, script_url, process_id, frame_id, base::BindOnce(&DidNavigate, context, script_url.GetOrigin(), std::move(callback)))); } void GetClient(<API key>* container_host, ClientCallback callback) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); DCHECK(container_host-><API key>()); blink::mojom::<API key> host_client_type = container_host->GetClientType(); if (host_client_type == blink::mojom::<API key>::kWindow) { if (<API key>::<API key>()) { blink::mojom::<API key> info = <API key>( container_host->process_id(), container_host->frame_id(), container_host->create_time(), container_host->client_uuid()); base::<API key>::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), std::move(info))); return; } base::<API key>( FROM_HERE, BrowserThread::UI, base::BindOnce(&<API key>, container_host->process_id(), container_host->frame_id(), container_host->create_time(), container_host->client_uuid()), std::move(callback)); return; } // TODO(dtapuska): Need to get frozen state for dedicated workers from // DedicatedWorkerHost. crbug.com/968417 auto client_info = blink::mojom::<API key>::New( container_host->url(), blink::mojom::<API key>::kNone, container_host->client_uuid(), host_client_type, /*page_hidden=*/true, /*is_focused=*/false, blink::mojom::<API key>::kActive, base::TimeTicks(), container_host->create_time()); base::<API key>::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), std::move(client_info))); } void GetClients(const base::WeakPtr<<API key>>& controller, blink::mojom::<API key> options, blink::mojom::ServiceWorkerHost::GetClientsCallback callback) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); auto clients = std::vector<blink::mojom::<API key>>(); if (!controller->HasControllee() && !options-><API key>) { DidGetClients(std::move(callback), std::move(clients)); return; } // For Window clients we want to query the info on the UI thread first. if (options->client_type == blink::mojom::<API key>::kWindow || options->client_type == blink::mojom::<API key>::kAll) { GetWindowClients(controller, std::move(options), std::move(callback), std::move(clients)); return; } GetNonWindowClients(controller, std::move(options), std::move(callback), std::move(clients)); } void DidNavigate(const base::WeakPtr<<API key>>& context, const GURL& origin, NavigationCallback callback, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(<API key>::GetCoreThreadId()); if (!context) { std::move(callback).Run(blink::<API key>::kErrorAbort, nullptr /* client_info */); return; } if (render_process_id == ChildProcessHost::kInvalidUniqueID && render_frame_id == MSG_ROUTING_NONE) { std::move(callback).Run(blink::<API key>::kErrorFailed, nullptr /* client_info */); return; } for (std::unique_ptr<<API key>::<API key>> it = context-><API key>( origin, true /* <API key> */, false /* <API key> */); !it->IsAtEnd(); it->Advance()) { <API key>* container_host = it->GetContainerHost(); DCHECK(container_host-><API key>()); if (container_host->process_id() != render_process_id || container_host->frame_id() != render_frame_id) { continue; } // DidNavigate must be called with a preparation complete client (the // navigation was committed), but the client might not be execution ready // yet (Blink hasn't yet created the Document). DCHECK(container_host-><API key>()); if (!container_host->is_execution_ready()) { container_host-><API key>(base::BindOnce( &<API key>, context, container_host->client_uuid(), origin, std::move(callback))); return; } <API key>(context, container_host->client_uuid(), origin, std::move(callback)); return; } // If here, it means that no container_host was found, in which case, the // renderer should still be informed that the window was opened. std::move(callback).Run(blink::<API key>::kOk, nullptr /* client_info */); } } // namespace <API key> } // namespace content
<?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\DetailView; use util\Util; use app\models\Estado; use app\models\Fuente; use app\models\Usuario; use app\models\Ruta; use app\models\Solicitud; use yii\helpers\Url; use yii\bootstrap\Modal; /* @var $this yii\web\View */ /* @var $model app\models\Solicitud */ //$this->title = $model->id_solicitud; $this->params['breadcrumbs'][] = ['label' => 'Solicitudes', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="solicitud-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Volver', ['index'], ['class' => 'btn btn-success']) ?> <?php if(\util\Acf::hasRol(\util\Acf::ADMIN)) { if ($model->id_estado == 1){ Modal::begin([ 'header' => '<h2>Desea aprobar la solicitud?</h2>', 'toggleButton' => ['label' => 'Aprobar','class'=>'btn btn-success'], ]); echo $this->render('_aprobar', ['model' => new Solicitud()]) ; Modal::end(); Modal::begin([ 'header' => '<h2>Desea rechazar la solicitud/</h2>', 'toggleButton' => ['label' => 'Rechazar','class'=>'btn btn-danger'], ]); echo $this->render('_rechazar', ['model' => new Solicitud()]) ; Modal::end(); } } ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id_solicitud', 'fecha', 'telefono', 'email:email', 'nombre', 'direccion:ntext', 'observacion:ntext', [ 'attribute'=>'id_estado', 'value'=>Estado::findOne($model->id_estado)->estado ], [ 'attribute'=>'id_fuente', 'value'=>Fuente::findOne($model->id_fuente)->fuente ], 'id_usuario', 'referencia', [ 'attribute'=>'id_ruta', 'value'=>Ruta::findOne($model->id_ruta)->nombre ], ], ]) ?> </div>
#include "stdafx.h" #include "Player.h" #include "Socket.h" #include "<API key>.h" #include "TimeManager.h" #include "Log.h" using namespace Packets ; Player::Player( BOOL bIsServer ) { __ENTER_FUNCTION m_PID = INVALID_ID ; m_UID = INVALID_ID ; m_PlayerManagerID = INVALID_ID ; m_pSocket = new Socket ; Assert( m_pSocket ) ; if( bIsServer ) { <API key> = new SocketInputStream( m_pSocket, <API key>, 64 * 1024 * 1024 ) ; Assert( <API key> ) ; <API key> = new SocketOutputStream( m_pSocket, <API key>, 64 * 1024 * 1024 ) ; Assert( <API key> ) ; } else { <API key> = new SocketInputStream( m_pSocket ) ; Assert( <API key> ) ; <API key> = new SocketOutputStream( m_pSocket ) ; Assert( <API key> ) ; } m_IsEmpty = TRUE ; m_IsDisconnect = FALSE ; m_PacketIndex = 0 ; __LEAVE_FUNCTION } Player::~Player() { __ENTER_FUNCTION SAFE_DELETE( <API key> ) ; SAFE_DELETE( <API key> ) ; SAFE_DELETE( m_pSocket ) ; __LEAVE_FUNCTION } VOID Player::CleanUp() { __ENTER_FUNCTION m_pSocket->close() ; <API key>->CleanUp() ; <API key>->CleanUp() ; SetPlayerManagerID( INVALID_ID ) ; SetUserID( INVALID_ID ) ; m_PacketIndex = 0 ; SetDisconnect( FALSE ) ; __LEAVE_FUNCTION } VOID Player::Disconnect() { __ENTER_FUNCTION _MY_TRY { m_pSocket->close() ; } _MY_CATCH { } __LEAVE_FUNCTION } BOOL Player::IsValid() { __ENTER_FUNCTION if ( NULL == m_pSocket ) return FALSE ; if ( !m_pSocket->isValid() ) return FALSE ; return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL Player::ProcessInput() { __ENTER_FUNCTION if ( IsDisconnect() ) return TRUE ; _MY_TRY { UINT ret = <API key>->Fill() ; if ( SOCKET_ERROR >= ( INT )ret ) { Log::SaveLog( "./Log/LoginError.log", "[%d] <API key>->Fill() ret: %d %s", g_pTimeManager->Time2DWORD(), ( INT )ret, MySocketError() ) ; return FALSE ; } } _MY_CATCH { return FALSE ; } return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL Player::ProcessCommand( BOOL Option ) { __ENTER_FUNCTION BOOL ret ; CHAR header[ PACKET_HEADER_SIZE ] ; PacketID_t packetID ; UINT packetuint, packetSize, packetIndex, packetTick ; Packet* pPacket = NULL ; if ( IsDisconnect() ) return TRUE ; _MY_TRY { if( Option ) { } for( ; ; ) { if( !<API key>->Peek( &header[ 0 ], PACKET_HEADER_SIZE ) ) { break ; } this->DecryptHead_CS( header ) ; memcpy( &packetID, &header[0], sizeof( PacketID_t ) ) ; memcpy( &packetTick, &header[ sizeof( UINT ) ], sizeof( UINT ) ) ; memcpy( &packetuint, &header[ sizeof( UINT ) + sizeof( PacketID_t )], sizeof( UINT ) ) ; packetSize = GET_PACKET_LEN( packetuint ) ; packetIndex = GET_PACKET_INDEX( packetuint ) ; if ( ( PacketID_t )PACKET_MAX <= packetID ) { Assert( FALSE ) ; return FALSE ; } //--Begin { UINT t_uSize = packetSize + PACKET_HEADER_SIZE ; UINT t_uHead = <API key>->GetHead() ; UINT t_uTail = <API key>->GetTail() ; UINT t_uBufferLen = <API key>->GetBuffLen() ; CHAR* t_szBuffer = <API key>->GetBuff() ; if ( t_uHead < t_uTail ) { this->Decrypt_CS( &t_szBuffer[ t_uHead ], t_uSize, 0 ) ; } else { UINT rightLen = t_uBufferLen - t_uHead ; if ( t_uSize <= rightLen ) { this->Decrypt_CS( &t_szBuffer[ t_uHead ], t_uSize, 0 ) ; } else { this->Decrypt_CS( &t_szBuffer[ t_uHead ], rightLen, 0 ) ; this->Decrypt_CS( t_szBuffer, t_uSize-rightLen, rightLen ) ; } } } //--End _MY_TRY { if ( <API key>->Length() < PACKET_HEADER_SIZE + packetSize ) { break ; } if ( packetSize > <API key>->GetPacketMaxSize( packetID ) ) { Assert( FALSE ) ; // <API key>->Skip( PACKET_HEADER_SIZE+packetSize ) ; return FALSE ; } Packet* pPacket = <API key>->CreatePacket( packetID ) ; if ( NULL == pPacket ) { Assert( FALSE ) ; // <API key>->Skip( PACKET_HEADER_SIZE+packetSize ) ; return FALSE ; } pPacket->SetPacketIndex( packetIndex ) ; ret = <API key>->ReadPacket( pPacket ) ; if ( FALSE == ret ) { Assert( FALSE ) ; <API key>->RemovePacket( pPacket ) ; return FALSE ; } #ifdef _DEBUG Log::SaveLog( "./Log/Login.txt", " [%d, ID=%dsize=%d]", <API key>->m_pSocket->m_Port, pPacket->GetPacketID(), pPacket->GetPacketSize() ) ; #endif BOOL bNeedRemove = TRUE ; _MY_TRY { //m_KickTimem_KickTime this->ResetKick() ; UINT uret = pPacket->Execute( this ) ; if ( PACKET_EXE_ERROR == uret ) { if ( pPacket ) <API key>->RemovePacket( pPacket ) ; return FALSE ; } else if ( PACKET_EXE_BREAK == uret ) { if ( pPacket ) <API key>->RemovePacket( pPacket ) ; break ; } else if ( PACKET_EXE_CONTINUE == uret ) { } else if ( <API key> == uret ) { bNeedRemove = FALSE ; } else if ( <API key> == uret ) { return FALSE ; } else { Assert( FALSE ) ; } } _MY_CATCH { } if ( pPacket && bNeedRemove ) <API key>->RemovePacket( pPacket ) ; } _MY_CATCH { return FALSE ; } } } _MY_CATCH { } return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL Player::ProcessOutput() { __ENTER_FUNCTION if ( IsDisconnect() ) return TRUE ; _MY_TRY { UINT size = <API key>->Length() ; if ( 0 == size ) { return TRUE ; } UINT ret = <API key>->Flush() ; if ( SOCKET_ERROR >= ( INT )ret ) { Log::SaveLog( "./Log/LoginError.log", "[%d] <API key>->Flush ret: %d %s", g_pTimeManager->Time2DWORD(), ( INT )ret, MySocketError() ) ; return FALSE ; } } _MY_CATCH { return FALSE ; } return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL Player::SendPacket( Packet* pPacket ) { __ENTER_FUNCTION if ( IsDisconnect() ) return TRUE ; if ( NULL != <API key> ) { pPacket->SetPacketIndex( m_PacketIndex++ ) ; PacketID_t packetID = pPacket->GetPacketID() ; UINT w ; if ( PACKET_LC_MAXCOUNT > packetID ) { w = <API key>->Write( PACK_COMPART, PACK_COMPART_SIZE ) ; } UINT t_uTail_Begin = <API key>->GetTail() ; w = <API key>->Write( ( CHAR* )&packetID, sizeof( PacketID_t ) ) ; UINT packetTick = g_pTimeManager->RunTick() ; w = <API key>->Write( ( CHAR* )&packetTick, sizeof( UINT ) ) ; UINT packetUINT ; UINT packetSize = pPacket->GetPacketSize() ; UINT packetIndex = pPacket->GetPacketIndex() ; SET_PACKET_INDEX( packetUINT, packetIndex ) ; SET_PACKET_LEN( packetUINT, packetSize ) ; w = <API key>->Write( ( CHAR* )&packetUINT, sizeof( UINT ) ) ; BOOL ret = pPacket->Write( *<API key> ) ; UINT t_uTail_End = <API key>->GetTail() ; #ifdef _DEBUG Log::SaveLog( "./Log/Login.txt", " [%d, ID=%dsize=%d]", <API key>->m_pSocket->m_Port, pPacket->GetPacketID(), pPacket->GetPacketSize() ) ; #endif //--Begin { UINT t_uSize = t_uTail_End - t_uTail_Begin ; UINT t_uHead = <API key>->GetHead() ; UINT t_uTail = <API key>->GetTail() ; UINT t_uBufferLen = <API key>->GetBuffLen() ; CHAR* t_szBuffer = <API key>->GetBuff() ; if ( t_uHead < t_uTail ) { this->Encrypt_SC( &( t_szBuffer[ t_uTail_Begin ] ), t_uSize, 0 ) ; } else { UINT rightLen = t_uBufferLen - t_uHead ; if ( t_uSize <= rightLen ) { this->Encrypt_SC( &( t_szBuffer[ t_uTail_Begin ] ), t_uSize, 0 ) ; } else { this->Encrypt_SC( &( t_szBuffer[ t_uTail_Begin ] ), rightLen, 0 ) ; this->Encrypt_SC( t_szBuffer, t_uSize - rightLen, rightLen ) ; } } } //--End //BOOL ret = <API key>->WritePacket( pPacket ) ; Assert( ret ) ; } return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL Player::HeartBeat( UINT uTime ) { __ENTER_FUNCTION return TRUE ; __LEAVE_FUNCTION return FALSE ; } VOID Player::ResetKick() { __ENTER_FUNCTION __LEAVE_FUNCTION } //INT Player::WhereThisPlayerFrom(VOID) const // if(NULL!=m_pSocket) // return g_Config.m_InternalIpofProxy.WhereThisIpFrom(m_pSocket->m_Host) ; // return INVALID_ISP ; //CHAR* <API key>(Player const* pPlayer, ID_t ServerID) // __ENTER_FUNCTION // _SERVER_DATA* pData = g_pServerManager->FindServerInfo( ServerID ) ; // if(NULL==pData) // CHAR szLog[1024] ; // tsnprintf(szLog, sizeof(szLog), "[<API key>] Error: Can't found the specific server(%d).", ServerID) ; // szLog[sizeof(szLog)-1] = '\0' ; // AssertEx(pData, szLog) ; // INT nIsp = pPlayer->WhereThisPlayerFrom() ; // if(INVALID_ISP==nIsp) // return pData->m_IP0 ; // else // if(TRUE==<API key>(nIsp, 0, NUM_OF_ISP-1, "<API key>")) // PROXY_DATA& rProxy = pData->m_aProxy[nIsp] ; // if(TRUE==rProxy.m_bEnabled) // return rProxy.m_szIP ; // return pData->m_IP0 ; // else // return pData->m_IP0 ; // __LEAVE_FUNCTION // return NULL ; //UINT <API key>(Player const* pPlayer, ID_t ServerID) // __ENTER_FUNCTION // _SERVER_DATA* pData = g_pServerManager->FindServerInfo( ServerID ) ; // if(NULL==pData) // CHAR szLog[1024] ; // tsnprintf(szLog, sizeof(szLog), "[<API key>] Error: Can't found the specific server(%d).", ServerID) ; // szLog[sizeof(szLog)-1] = '\0' ; // AssertEx(pData, szLog) ; // INT nIsp = pPlayer->WhereThisPlayerFrom() ; // if(INVALID_ISP==nIsp) // return pData->m_Port0 ; // else // if(TRUE==<API key>(nIsp, 0, NUM_OF_ISP-1, "<API key>")) // PROXY_DATA& rProxy = pData->m_aProxy[nIsp] ; // if(TRUE==rProxy.m_bEnabled) // return rProxy.m_nPort ; // return pData->m_Port0 ; // else // return pData->m_Port0 ; // __LEAVE_FUNCTION // return NULL ;