text stringlengths 2 1.04M | meta dict |
|---|---|
extern "C" {
// Functions and labels exposed from our .asm test stub.
extern int assembly_func();
extern int unreachable_label();
extern int interrupt_label();
extern int assembly_func_end();
extern int case_0();
extern int case_1();
extern int case_default();
extern int jump_table();
extern int case_table();
// Functions invoked or referred by the .asm test stub. These are defined in
// basic_block_test_util.cc.
extern int func1();
extern int func2();
} // extern "C"
namespace testing {
// A utility class for generating test data built around the function in
// basic_block_assembly_func.asm. When assembly_func_ is decomposed as a basic
// block subgraph the layout is as follows:
//
// BB0: offset 0, code, assembly_func, 4 instructions, 0 successors
// BB1: offset 23, code/padding (unreachable code)
// BB2: offset 24, code, case_0, 2 instructions, 1 successor
// BB3: offset 31, code, sub eax to jnz, 1 instruction, 2 successors
// BB4: offset 36, code, ret, 1 instruction, 0 successors
// BB5: offset 37, code, case_1, 1 instruction, 1 successor
// BB6: offset 42, code, case_default, 2 instructions, 0 successors
// BB7: offset 49, code/padding, interrupt_label, 3 instruction, 0 successors
// BB8: offset 50, data, jump_table, 12 bytes
// BB9: offset 62, data, case_table, 256 bytes
class BasicBlockTest : public ::testing::Test {
public:
typedef core::RelativeAddress RelativeAddress;
typedef block_graph::BlockGraph BlockGraph;
typedef block_graph::BasicBlockDecomposer BasicBlockDecomposer;
typedef block_graph::BasicBlockSubGraph BasicBlockSubGraph;
typedef BasicBlockSubGraph::BasicBlock BasicBlock;
typedef BasicBlockSubGraph::BlockDescription BlockDescription;
typedef BlockGraph::Block Block;
typedef BlockGraph::Reference Reference;
typedef BlockGraph::Section Section;
// The number and type of basic blocks.
static const size_t kNumCodeBasicBlocks = 8;
static const size_t kNumDataBasicBlocks = 2;
static const size_t kNumEndBasicBlocks = 1;
static const size_t kNumCodePaddingBasicBlocks = 2;
static const size_t kNumDataPaddingBasicBlocks = 0;
static const size_t kNumBasicBlocks =
kNumCodeBasicBlocks + kNumDataBasicBlocks + kNumEndBasicBlocks;
BasicBlockTest();
// Initializes block_graph, assembly_func, func1, func2 and data. Meant to be
// wrapped in ASSERT_NO_FATAL_FAILURE.
void InitBlockGraph();
// Initializes subgraph, bbs and bds. Meant to be wrapped in
// ASSERT_NO_FATAL_FAILURE.
// @pre InitBlockGraph must have been called successfully.
void InitBasicBlockSubGraph();
// Initializes block_graph_, text_section_, func1_, and func2_. Leaves
// data_section_, assembly_func_ and data_ NULL. func2_ contains a function
// with a debug-end label past the end of the block, and internally it calls
// func1_.
void InitBasicBlockSubGraphWithLabelPastEnd();
// Initialized by InitBlockGraph.
// @{
// Start address of the assembly function.
RelativeAddress start_addr_;
testing::DummyTransformPolicy policy_;
BlockGraph block_graph_;
Section* text_section_;
Section* data_section_;
Block* assembly_func_;
Block* func1_;
Block* func2_;
Block* data_;
// @}
// Initialized by InitBasicBlockSubGraph and
// InitBasicBlockSubGraphWithLabelPastEnd.
// @{
BasicBlockSubGraph subgraph_;
std::vector<BasicBlock*> bbs_;
std::vector<BlockDescription*> bds_;
// @}
};
} // namespace testing
#endif // SYZYGY_BLOCK_GRAPH_BASIC_BLOCK_TEST_UTIL_H_
| {
"content_hash": "652502fda40c26ff40c89be82266f841",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 79,
"avg_line_length": 34.23529411764706,
"alnum_prop": 0.7373997709049256,
"repo_name": "sebmarchand/syzygy",
"id": "44113b53f0ac93415a15f43f2e6e49416009594f",
"size": "4387",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "syzygy/block_graph/basic_block_test_util.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "13748"
},
{
"name": "C",
"bytes": "8422"
},
{
"name": "C++",
"bytes": "7598735"
},
{
"name": "CSS",
"bytes": "1333"
},
{
"name": "HTML",
"bytes": "3182"
},
{
"name": "Protocol Buffer",
"bytes": "6472"
},
{
"name": "Python",
"bytes": "841963"
},
{
"name": "Shell",
"bytes": "19040"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\CatalogRule\Controller\Adminhtml\Promo\Widget;
class Chooser extends \Magento\CatalogRule\Controller\Adminhtml\Promo\Widget
{
/**
* Prepare block for chooser
*
* @return void
*/
public function execute()
{
$request = $this->getRequest();
switch ($request->getParam('attribute')) {
case 'sku':
$block = $this->_view->getLayout()->createBlock(
'Magento\CatalogRule\Block\Adminhtml\Promo\Widget\Chooser\Sku',
'promo_widget_chooser_sku',
['data' => ['js_form_object' => $request->getParam('form')]]
);
break;
case 'category_ids':
$ids = $request->getParam('selected', []);
if (is_array($ids)) {
foreach ($ids as $key => &$id) {
$id = (int)$id;
if ($id <= 0) {
unset($ids[$key]);
}
}
$ids = array_unique($ids);
} else {
$ids = [];
}
$block = $this->_view->getLayout()->createBlock(
'Magento\Catalog\Block\Adminhtml\Category\Checkboxes\Tree',
'promo_widget_chooser_category_ids',
['data' => ['js_form_object' => $request->getParam('form')]]
)->setCategoryIds(
$ids
);
break;
default:
$block = false;
break;
}
if ($block) {
$this->getResponse()->setBody($block->toHtml());
}
}
}
| {
"content_hash": "2762459bd2d21074063cc264795c9bf1",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 83,
"avg_line_length": 30.275862068965516,
"alnum_prop": 0.4174259681093394,
"repo_name": "enettolima/magento-training",
"id": "0c626b9b7081878d9a27edc7b87f866fb9936d77",
"size": "1857",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "magento2ce/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Widget/Chooser.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "22648"
},
{
"name": "CSS",
"bytes": "3382928"
},
{
"name": "HTML",
"bytes": "8749335"
},
{
"name": "JavaScript",
"bytes": "7355635"
},
{
"name": "PHP",
"bytes": "58607662"
},
{
"name": "Perl",
"bytes": "10258"
},
{
"name": "Shell",
"bytes": "41887"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
from random import randrange, shuffle
get_alpha = lambda: chr(randrange(97, 123))
get_word = lambda: ''.join([get_alpha() for i in range(randrange(4, 10))])
get_article = lambda: ' '.join([' '.join([get_word()] * randrange(10))
for i in range(randrange(2000, 3000))])
def get_words():
words = get_article().split()
shuffle(words)
return words
| {
"content_hash": "89e77c2ec21206bd1eaa18892f9cccf0",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 74,
"avg_line_length": 21.58823529411765,
"alnum_prop": 0.6403269754768393,
"repo_name": "phyng/c-lang",
"id": "1ec14e3658eeb4de6097f9c84f0716c99702833c",
"size": "368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter6/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "27753"
},
{
"name": "Python",
"bytes": "4978"
},
{
"name": "Shell",
"bytes": "59"
}
],
"symlink_target": ""
} |
var jasmine = {};
jasmine.createSpy = function() {};
function CodeMirror() {};
CodeMirror.prototype.setValue = function(a) {};
| {
"content_hash": "82107daba6cacd7560806b9745492203",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 47,
"avg_line_length": 18.571428571428573,
"alnum_prop": 0.676923076923077,
"repo_name": "GoogleCloudPlatform/PerfKitExplorer",
"id": "7eb03025ddb1cb8528d4a26c45090cea53554280",
"size": "1018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/externs.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "932"
},
{
"name": "CSS",
"bytes": "27281"
},
{
"name": "HTML",
"bytes": "96732"
},
{
"name": "JavaScript",
"bytes": "1051249"
},
{
"name": "Python",
"bytes": "261404"
},
{
"name": "Shell",
"bytes": "738"
}
],
"symlink_target": ""
} |
namespace web {
class WebState;
} // namespace web
// Gets notified when translate::LanguageDetectionDetails becomes available for
// the given web state.
class FakeLanguageDetectionTabHelperObserver
: public language::IOSLanguageDetectionTabHelper::Observer {
public:
FakeLanguageDetectionTabHelperObserver(web::WebState* web_state);
~FakeLanguageDetectionTabHelperObserver() override;
// language::IOSLanguageDetectionTabHelper::Observer
void OnLanguageDetermined(
const translate::LanguageDetectionDetails& details) override;
void IOSLanguageDetectionTabHelperWasDestroyed(
language::IOSLanguageDetectionTabHelper* tab_helper) override;
translate::LanguageDetectionDetails* GetLanguageDetectionDetails();
void ResetLanguageDetectionDetails();
private:
web::WebState* web_state_;
std::unique_ptr<translate::LanguageDetectionDetails>
language_detection_details_;
// Stops observing the IOSLanguageDetectionTabHelper instance associated with
// |web_state_| and sets |web_state_| to null.
void StopObservingIOSLanguageDetectionTabHelper();
DISALLOW_COPY_AND_ASSIGN(FakeLanguageDetectionTabHelperObserver);
};
#endif // IOS_CHROME_TEST_FAKES_FAKE_LANGUAGE_DETECTION_TAB_HELPER_OBSERVER_H_
| {
"content_hash": "3ec5515f068355899fb3635a8344a38a",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 79,
"avg_line_length": 36.6764705882353,
"alnum_prop": 0.7995188452285485,
"repo_name": "endlessm/chromium-browser",
"id": "a2f8062ee1270741fc25f7dcf0607ea9d137b905",
"size": "1692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ios/chrome/test/fakes/fake_language_detection_tab_helper_observer.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "77cc5a505123e2d9b7fa372bd9ba4a84",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "d11250b1bb3d23366c8c7715cc9f28b36a072486",
"size": "209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pinophyta/Pinopsida/Pinales/Podocarpaceae/Bracteocarpus/Bracteocarpus leptophyllus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
This in an Alpha version of the Replicated YAML Config Preview Atom Plugin. For more info please see: [https://vendor.replicated.com/yaml-tool](https://vendor.replicated.com/yaml-tool)
##Screenshot:

| {
"content_hash": "add4865b65a9659de39be178eb17e978",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 184,
"avg_line_length": 55,
"alnum_prop": 0.7636363636363637,
"repo_name": "marccampbell/replicated-preview",
"id": "e8c466cbbe2ebce0323daf169deb1cbfcca6d598",
"size": "304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2153"
},
{
"name": "CoffeeScript",
"bytes": "12716"
}
],
"symlink_target": ""
} |
package com.dm.service.video.web.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dm.service.video.web.mq.MessageReceiver;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
/**
* ffmpeg本地应用程序调用服务
* <p>
* 负责调用ffmpeg程序,为摄像头与nginx流媒体服务器建立流媒体通道,提供直播资源。
* </p>
* Created by chenlichao on 15/6/18.
*/
@Service
public class LiveCameraService {
private static final Logger logger = LoggerFactory.getLogger(LiveCameraService.class);
private Map<String, ProcessHolder> runningProcesses = new ConcurrentHashMap<>();
private ExecutorService executorService = Executors.newCachedThreadPool();
@Value("${system.nginx.server}")
private String nginxServer;
@Value("${system.video.params}")
private String videoParams;
@Value("${system.video.transport}")
private String videoTransport;
@Value("${interface.url.camera}")
public String url;
@Autowired
MessageReceiver messageReceiver;
public boolean isLiving(String orderId) {
return runningProcesses.containsKey(orderId);
}
public void startLiveCamera(String camera, String orderId) throws IOException {
ProcessHolder ph = new ProcessHolder(camera, orderId);
executorService.submit(ph);
this.runningProcesses.put(orderId, ph);
}
public void closeLiveCamera(String orderId) throws IOException {
ProcessHolder ph = runningProcesses.get(orderId);
if(ph != null) {
if(ph.closeProcess()) {
runningProcesses.remove(orderId);
}
}
}
public String getCamera(String orderId) {
ProcessHolder ph = runningProcesses.get(orderId);
if(ph != null) {
return ph.camera;
}
return null;
}
public void openCmaeraAll(){
logger.info("访问所有摄像头调用接口{}", url);
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
try {
HttpResponse httpResponse = client.execute(httpget);
String result= EntityUtils.toString(httpResponse
.getEntity());
JSONObject resultObject = JSONObject.parseObject(result);
int code = resultObject.getInteger("code");
logger.info("返回值:{}",resultObject);
if (code == 0) {
JSONArray data = resultObject.getJSONArray("data");
for (int i = 0; i < data.size(); i++) {
JSONObject object = data.getJSONObject(i);
logger.info("摄像头id{}ip{}",object.getString("cameraId"),object.getString("privateIp"));
String url =messageReceiver.cameraPrev.trim()+object.getString("privateIp")+messageReceiver.cameraAfter.trim();
this.startLiveCamera(url,"c"+object.getString("cameraId"));
}
}else{
logger.error("接口返回值有误");
}
} catch (IOException e) {
logger.error("访问接口异常");
e.printStackTrace();
}
}
private String[] getCmd(String camera, String orderId) {
String str = "ffmpeg " + videoTransport + " -i " + camera
+ " " + videoParams + " "
+ nginxServer + orderId;
logger.info("execute cmd: {}", str);
return str.split(" ");
// return ("ffmpeg -re -i /Users/chenlichao/Desktop/test.mp4 -vcodec libx264 -vprofile baseline -acodec aac -ar 44100 -strict -2 -ac -1 -f flv -s 640*480 -q 10 rtmp://centos7:1935/hls/" + orderId).split(" ");
}
public void testCamera() {
List list = new ArrayList();
list.add("192.168.10.41");
list.add("192.168.10.42");
list.add("192.168.10.43");
list.add("192.168.10.44");
for(int i=0;i<list.size();i++){
try {
String url =messageReceiver.cameraPrev.trim()+list.get(i).toString()+messageReceiver.cameraAfter.trim();
this.startLiveCamera(url,"c"+i);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 本地进程信息
*/
private class ProcessHolder implements Runnable{
Process process;
String camera;
String orderId;
Boolean started = false;
ProcessHolder(String camera, String orderId) {
this.camera = camera;
this.orderId = orderId;
}
@Override
public void run() {
ProcessBuilder processBuilder = new ProcessBuilder(getCmd(camera,orderId));
File outFile = new File("/tmp/video/" + orderId + ".log");
processBuilder.redirectError(outFile);
logger.info("启动视频直播:[order:{}][{}] ...",orderId, camera);
try {
process = processBuilder.start();
if(process.waitFor(120, TimeUnit.SECONDS)) {
int resultCode = process.exitValue();
if (resultCode != 0) {
logger.error("视频直播进程[order:{}][{}],异常退出[{}]!", orderId, camera, resultCode);
} else {
logger.info("视频直播进程[order:{}][{}],正常执行结束!", orderId, camera);
}
runningProcesses.remove(orderId);
return;
}
started = true;
logger.info("视频直播进程 [order:{}][{}] 启动成功!", orderId, camera);
int resultCode = process.waitFor();
if (resultCode != 0) {
logger.error("视频直播进程[order:{}][{}],异常退出, 退出码:{}!", orderId, camera, resultCode);
} else {
logger.info("视频直播进程[order:{}][{}],正常执行结束!", orderId, camera);
}
runningProcesses.remove(orderId);
} catch (IOException e) {
logger.error("视频直播进程 [order:{}][{}] 启动失败!", orderId, camera, e);
} catch (InterruptedException e) {
logger.error("线程意外中断!", e);
}
}
public boolean closeProcess() {
logger.info("停止视频直播[order:{}][{}]...", orderId, camera);
OutputStream os = process.getOutputStream();
if(os != null) {
try {
os.write("q".getBytes());
os.flush();
return process.waitFor(30, TimeUnit.SECONDS) || forceDestroy();
} catch (IOException e) {
logger.error("正常结束视频直播进程[order:{}][{}]失败,强制结束!", orderId, camera);
return forceDestroy();
} catch (InterruptedException e) {
logger.error("等待视频直播进程结束时出错!", e);
return forceDestroy();
}
} else {
return forceDestroy();
}
}
private boolean forceDestroy() {
process.destroyForcibly();
try {
if(!process.waitFor(30, TimeUnit.SECONDS)) {
logger.error("强制停止失败,请联系管理员!!!");
return false;
}
} catch (InterruptedException e1) {
logger.error("强制停止视频直播时出错!", e1);
return false;
}
return true;
}
}
}
| {
"content_hash": "7ded25ece0cc09335f14910682c61edc",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 215,
"avg_line_length": 35.86363636363637,
"alnum_prop": 0.5593155893536121,
"repo_name": "wxuedong/dm-service-video",
"id": "d19563647e461b06c7b6ed774c90ffba984e0ff5",
"size": "8358",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/src/main/java/com/dm/service/video/web/service/LiveCameraService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "26219"
},
{
"name": "JavaScript",
"bytes": "48370"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Symfony2PluginSettings">
<option name="directoryToWeb" value="www" />
<option name="pluginEnabled" value="true" />
<option name="profilerCsvPath" value="" />
<option name="lastServiceGeneratorLanguage" value="yaml" />
</component>
</project> | {
"content_hash": "c5c931bef32507326be70e5b96e9925b",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 63,
"avg_line_length": 37.666666666666664,
"alnum_prop": 0.6814159292035398,
"repo_name": "fadykstas/food.serv",
"id": "0f4622a4ef860c5cd3d405b210c34773b89a4af3",
"size": "339",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": ".idea/symfony2.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18512"
},
{
"name": "HTML",
"bytes": "124248"
},
{
"name": "JavaScript",
"bytes": "11121"
},
{
"name": "PHP",
"bytes": "153249"
}
],
"symlink_target": ""
} |
<?php
namespace Assetic\Test\Cache;
use Assetic\Cache\ExpiringCache;
class ExpiringCacheTest extends \PHPUnit_Framework_TestCase
{
private $inner;
private $lifetime;
private $cache;
protected function setUp()
{
$this->inner = $this->getMock('Assetic\\Cache\\CacheInterface');
$this->lifetime = 3600;
$this->cache = new ExpiringCache($this->inner, $this->lifetime);
}
public function testHasExpired()
{
$key = 'asdf';
$expiresKey = 'asdf.expires';
$thePast = 0;
$this->inner->expects($this->once())
->method('has')
->with($key)
->will($this->returnValue(true));
$this->inner->expects($this->once())
->method('get')
->with($expiresKey)
->will($this->returnValue($thePast));
$this->inner->expects($this->at(2))
->method('remove')
->with($expiresKey);
$this->inner->expects($this->at(3))
->method('remove')
->with($key);
$this->assertFalse($this->cache->has($key), '->has() returns false if an expired value exists');
}
public function testHasNotExpired()
{
$key = 'asdf';
$expiresKey = 'asdf.expires';
$theFuture = time() * 2;
$this->inner->expects($this->once())
->method('has')
->with($key)
->will($this->returnValue(true));
$this->inner->expects($this->once())
->method('get')
->with($expiresKey)
->will($this->returnValue($theFuture));
$this->assertTrue($this->cache->has($key), '->has() returns true if a value the not expired');
}
public function testSetLifetime()
{
$key = 'asdf';
$expiresKey = 'asdf.expires';
$value = 'qwerty';
$this->inner->expects($this->at(0))
->method('set')
->with($expiresKey, $this->greaterThanOrEqual(time() + $this->lifetime));
$this->inner->expects($this->at(1))
->method('set')
->with($key, $value);
$this->cache->set($key, $value);
}
public function testRemove()
{
$key = 'asdf';
$expiresKey = 'asdf.expires';
$this->inner->expects($this->at(0))
->method('remove')
->with($expiresKey);
$this->inner->expects($this->at(1))
->method('remove')
->with($key);
$this->cache->remove($key);
}
public function testGet()
{
$this->inner->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue('bar'));
$this->assertEquals('bar', $this->cache->get('foo'), '->get() returns the cached value');
}
}
| {
"content_hash": "989dd0d7d9dbc627c3794d2d60efa2f4",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 104,
"avg_line_length": 28.03846153846154,
"alnum_prop": 0.4900548696844993,
"repo_name": "lrt/lrt",
"id": "2fb4e41ba3866fcbf3157a9c0bbad715e9749fb8",
"size": "3164",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/kriswallsmith/assetic/tests/Assetic/Test/Cache/ExpiringCacheTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "143710"
},
{
"name": "PHP",
"bytes": "256054"
},
{
"name": "Perl",
"bytes": "1091"
},
{
"name": "Shell",
"bytes": "2275"
}
],
"symlink_target": ""
} |
import {Directive, AfterViewChecked} from '@angular/core';
declare var componentHandler: any;
@Directive({
selector: '[mdl]'
})
export class MDL implements AfterViewChecked {
ngAfterViewChecked() {
if (componentHandler) {
componentHandler.upgradeAllRegistered();
}
}
} | {
"content_hash": "c40e1b64f2f2436b338a8cd8b7892eea",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 58,
"avg_line_length": 19.5,
"alnum_prop": 0.6634615384615384,
"repo_name": "Relja92/Hero_Association",
"id": "b5f88a4b4c5eb1620dc1715f9e0c4ba522d87c28",
"size": "312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Directives/MaterialDesignLiteUpgradeElement.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3307"
},
{
"name": "HTML",
"bytes": "11618"
},
{
"name": "JavaScript",
"bytes": "17495"
},
{
"name": "TypeScript",
"bytes": "21354"
}
],
"symlink_target": ""
} |
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bgstation0.android.sample.view_;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int textview1=0x7f060000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int hello_world=0x7f040001;
public static final int textview1_text=0x7f040002;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f050000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f050001;
}
}
| {
"content_hash": "606552985cf66054d3c1e924d6ce83ff",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 81,
"avg_line_length": 34.58181818181818,
"alnum_prop": 0.6771819137749737,
"repo_name": "bg1bgst333/Sample",
"id": "6e8b73eeef44184bab4039c1da2f84b7ec9ee064",
"size": "1902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/View/setAnimation/src/View/View_/gen/com/bgstation0/android/sample/view_/R.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "306893"
},
{
"name": "C",
"bytes": "1135468"
},
{
"name": "C#",
"bytes": "1243665"
},
{
"name": "C++",
"bytes": "4221060"
},
{
"name": "CMake",
"bytes": "147011"
},
{
"name": "CSS",
"bytes": "92700"
},
{
"name": "D",
"bytes": "504"
},
{
"name": "Go",
"bytes": "714"
},
{
"name": "HTML",
"bytes": "22314"
},
{
"name": "Java",
"bytes": "6233694"
},
{
"name": "JavaScript",
"bytes": "9675"
},
{
"name": "Kotlin",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "34822"
},
{
"name": "PHP",
"bytes": "12476"
},
{
"name": "Perl",
"bytes": "86739"
},
{
"name": "Python",
"bytes": "6272"
},
{
"name": "Raku",
"bytes": "160"
},
{
"name": "Roff",
"bytes": "1054"
},
{
"name": "Ruby",
"bytes": "747"
},
{
"name": "Rust",
"bytes": "209"
},
{
"name": "Shell",
"bytes": "186"
}
],
"symlink_target": ""
} |
import six
from six.moves import range
from webob import exc
from nova import context
from nova import exception
from nova.i18n import _
from nova import objects
from nova import utils
CHUNKS = 4
CHUNK_LENGTH = 255
MAX_SIZE = CHUNKS * CHUNK_LENGTH
def extract_password(instance):
result = ''
sys_meta = utils.instance_sys_meta(instance)
for key in sorted(sys_meta.keys()):
if key.startswith('password_'):
result += sys_meta[key]
return result or None
def convert_password(context, password):
"""Stores password as system_metadata items.
Password is stored with the keys 'password_0' -> 'password_3'.
"""
password = password or ''
if six.PY3 and isinstance(password, bytes):
password = password.decode('utf-8')
meta = {}
for i in range(CHUNKS):
meta['password_%d' % i] = password[:CHUNK_LENGTH]
password = password[CHUNK_LENGTH:]
return meta
def handle_password(req, meta_data):
ctxt = context.get_admin_context()
if req.method == 'GET':
return meta_data.password
elif req.method == 'POST':
# NOTE(vish): The conflict will only happen once the metadata cache
# updates, but it isn't a huge issue if it can be set for
# a short window.
if meta_data.password:
raise exc.HTTPConflict()
if (req.content_length > MAX_SIZE or len(req.body) > MAX_SIZE):
msg = _("Request is too large.")
raise exc.HTTPBadRequest(explanation=msg)
im = objects.InstanceMapping.get_by_instance_uuid(ctxt, meta_data.uuid)
with context.target_cell(ctxt, im.cell_mapping) as cctxt:
try:
instance = objects.Instance.get_by_uuid(cctxt, meta_data.uuid)
except exception.InstanceNotFound as e:
raise exc.HTTPBadRequest(explanation=e.format_message())
instance.system_metadata.update(convert_password(ctxt, req.body))
instance.save()
else:
msg = _("GET and POST only are supported.")
raise exc.HTTPBadRequest(explanation=msg)
| {
"content_hash": "38d7e35ccf645d5670bd3b6e19e23acd",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 79,
"avg_line_length": 32.15151515151515,
"alnum_prop": 0.6357210179076344,
"repo_name": "gooddata/openstack-nova",
"id": "c906de78908c479288bf20b19477fca0c752ab61",
"size": "2750",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "nova/api/metadata/password.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3858"
},
{
"name": "HTML",
"bytes": "1386"
},
{
"name": "PHP",
"bytes": "43584"
},
{
"name": "Python",
"bytes": "23012372"
},
{
"name": "Shell",
"bytes": "32567"
},
{
"name": "Smarty",
"bytes": "429290"
}
],
"symlink_target": ""
} |
Calico endpoints are assigned their network policy by configuring them with a policy profile. In the previous examples we created profiles and assigned endpoints to them. By default, `calicoctl profile add` adds default config to profiles so endpoints with the profile can all communicate with one another. In this section, we look at how to customize policy profiles for more advanced policy.
## Overview
A policy profile comprises two elements: *tags* and *rules*.
*Tags* identify different groups or sets of Calico endpoints. A tag might represent a role or network permission, for example, you might define a tag `db_access` that represents permission to send data to your database containers on port 3590.
*Rules* are the policy statements that Calico's firewall will enforce for your endpoints.
## Worked Example
This example assumes you have a working Calico-enabled cluster, as described in [Getting Started](./GettingStarted.md)
Let's create a new profile and look at the default rules.
./calicoctl profile add WEB
./calicoctl profile WEB rule show
You should see the following output.
Inbound rules:
1 allow from tag WEB
Outbound rules:
1 allow
Notice that profiles define policy for inbound packets and outbound packets separately. This profile allows inbound traffic from other endpoints with the tag `WEB`, and (implicitly) denies inbound traffic from all other addresses. It allows all outbound traffic regardless of destination.
Let's modify this profile to make it more appropriate for a public webserver. First, let's remove the default rule that allows traffic between nodes in the same profile:
```
./calicoctl profile WEB rule remove inbound --at=1
```
Then, let's allow TCP traffic on ports 80 and 443 and also allow ICMP ping traffic (which is type 8).
```
./calicoctl profile WEB rule add inbound allow tcp to ports 80,443
./calicoctl profile WEB rule add inbound allow icmp type 8
```
(By default, the add command appends to the list, but it also supports the `--at` parameter to trigger an insert.)
Now, we can list the rules again and see the changes:
```
./calicoctl profile WEB rule show
```
should print
```
Inbound rules:
1 allow tcp to ports 80,443
2 allow icmp type 8
Outbound rules:
1 allow
```
calicoctl also supports importing rules in JSON format. Let's say your WEB containers will need access to some backend services. Create a profile called APP for these services.
./calicoctl profile add APP
For this example, let's say the APP containers present a service on port 7890. We'll define a new tag, `APP_7890` to give containers access to this service port. Using a tag allows us to grant and revoke access to different other profiles. In this example, the WEB containers need access, but we might also have other groups, like health checks, or operations dashboards that also need access.
Create a file `APP-rules.json` with the following contents.
{
"id": "APP",
"inbound_rules": [
{
"action": "allow",
"protocol": "tcp",
"dst_ports": [7890],
"src_tag": "APP_7890"
},
{
"action": "allow",
"protocol": "icmp",
"icmp_type": 8
}
],
"outbound_rules": [
{
"action": "allow"
}
]
}
This grants access to port 7890 to containers with the `APP_7890` tag, and to ICMP for pings. Update the APP profile rules.
./calicoctl profile APP rule update < APP-rules.json
Finally, to enable access from the WEB containers, you need to tag them with the `APP_7890` tag.
./calicoctl profile WEB tag add APP_7890
Verify the tag was accepted by running
$ ./calicoctl profile WEB tag show
WEB
APP_7890
| {
"content_hash": "25cce08da5b52e664c2b3c3b1b1fb15b",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 396,
"avg_line_length": 37.57425742574257,
"alnum_prop": 0.7138339920948616,
"repo_name": "TeaBough/calico-docker",
"id": "55eccaf22ea19fe9ad4b8356e73d1844922d963c",
"size": "3822",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "docs/AdvancedNetworkPolicy.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "5820"
},
{
"name": "Python",
"bytes": "365615"
},
{
"name": "Shell",
"bytes": "5335"
}
],
"symlink_target": ""
} |
if [[ $1 = "--help" ]]; then
cat <<EOF
${0##*/}, version %version%
This script implements the pressure update
Usage: ${0##*/} infile outfile
EOF
exit 0
fi
[[ -z $1 || -z $2 ]] && die "${0##*/}: Missing arguments"
[[ -f $2 ]] && die "${0##*/}: $2 is already there"
[[ $(csg_get_interaction_property bondtype) = "thermforce" ]] && die "${0##*/}: pressure correction for thermforce makes no sense!"
step_nr="$(get_current_step_nr)"
sim_prog="$(csg_get_property cg.inverse.program)"
[[ $sim_prog != gromacs ]] && die "${0##*/}: pressure correction for ${sim_prog} is not implemented yet!"
name=$(csg_get_interaction_property name)
min=$(csg_get_interaction_property min)
max=$(csg_get_interaction_property max)
step=$(csg_get_interaction_property step)
p_file="${name}.pressure"
do_external pressure "$sim_prog" "$p_file"
p_now="$(sed -n 's/^Pressure=\(.*\)/\1/p' "$p_file")" || die "${0##*/}: sed of Pressure failed"
[[ -z $p_now ]] && die "${0##*/}: Could not get pressure from simulation"
echo "New pressure $p_now"
ptype="$(csg_get_interaction_property inverse.post_update_options.pressure.type)"
pscheme=( $(csg_get_interaction_property inverse.post_update_options.pressure.do) )
pscheme_nr=$(( ( $step_nr - 1 ) % ${#pscheme[@]} ))
if [[ ${pscheme[$pscheme_nr]} = 1 ]]; then
echo "Apply ${ptype} pressure correction for interaction ${name}"
# wjk needs rdf
if [[ ! -f ${name}.dist.new && $ptype = wjk ]]; then
do_external rdf $(csg_get_property cg.inverse.program)
fi
do_external pressure_cor $ptype $p_now ${name}.pressure_correction
comment="$(get_table_comment ${name}.pressure_correction)"
tmpfile=$(critical mktemp ${name}.pressure_correction_cut.XXX)
critical csg_resample --in ${name}.pressure_correction --out ${tmpfile} --grid $min:$step:$max --comment "$comment"
do_external table add "$1" ${tmpfile} "$2"
else
echo "NO pressure correction for interaction ${name}"
do_external postupd dummy "$1" "$2"
fi
| {
"content_hash": "0ea31eef3e20975a68a06be215c83d82",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 131,
"avg_line_length": 39.3,
"alnum_prop": 0.648854961832061,
"repo_name": "vaidyanathanms/votca.csg",
"id": "76451d9fa515ad003a17fb7166771ebfca4760a0",
"size": "2601",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "share/scripts/inverse/postupd_pressure.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "487976"
},
{
"name": "CMake",
"bytes": "36946"
},
{
"name": "Makefile",
"bytes": "121293"
},
{
"name": "Matlab",
"bytes": "126"
},
{
"name": "Perl",
"bytes": "88717"
},
{
"name": "Python",
"bytes": "14714"
},
{
"name": "Shell",
"bytes": "245593"
}
],
"symlink_target": ""
} |
module Comable
module Inventory
describe Unit do
let(:variant) { build(:variant) }
subject { described_class.new(variant) }
it { is_expected.to have_attr_accessor(:variant) }
describe '#initialize' do
it 'sets the variant as @variant' do
unit = described_class.new(variant)
expect(unit.instance_variable_get(:@variant)).to eq(variant)
end
end
describe '#to_shipment_item' do
it 'returns an instance of ShipmentItem' do
stock = build(:stock)
allow(subject).to receive(:find_stock_item).and_return(stock)
shipment = build(:shipment)
shipment_item = subject.to_shipment_item(shipment)
expect(shipment_item).to be_instance_of(ShipmentItem)
end
it 'has the stock item' do
stock = build(:stock)
allow(subject).to receive(:find_stock_item).and_return(stock)
shipment = build(:shipment)
shipment_item = subject.to_shipment_item(shipment)
expect(shipment_item.stock).to eq(stock)
end
end
describe '#find_stock_item' do
it 'returns the stock item' do
product = build(:product)
stock = build(:stock)
variant.update!(product: product, stocks: [stock])
shipment = build(:shipment, stock_location: stock.stock_location)
expect(subject.send(:find_stock_item, shipment)).to eq(stock)
end
end
end
end
end
| {
"content_hash": "1f517030ffe87187088180f2469cbd37",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 75,
"avg_line_length": 28.846153846153847,
"alnum_prop": 0.6033333333333334,
"repo_name": "appirits/comable",
"id": "97ba1e02cdcec33d186f24c89b739fe1a0b614b6",
"size": "1500",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/spec/models/comable/inventory/unit_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "28864"
},
{
"name": "CoffeeScript",
"bytes": "42813"
},
{
"name": "HTML",
"bytes": "144134"
},
{
"name": "JavaScript",
"bytes": "1198"
},
{
"name": "Ruby",
"bytes": "404138"
}
],
"symlink_target": ""
} |
# Specific Constructors for Open Generics
As described in the [main open generic constructor injection topic](generics.md), Rezolver is able to bind
dynamically to the best-matched constructor for a particular closed generic when built from an open generic
registration.
However, it's also possible (starting from 1.3.2) to instruct Rezolver to use a *specific* constructor when
creating an instance from an open generic registration.
Use cases for this are, of course, pretty niche - especially if your own classes typically stick to the standard
pattern of only having a single constructor (as is enforced by some IOC containers). But the reality is there will
always be types which legitimately have multiple constructors (take a lot of .Net collection types, for example)
which you might also want to create via constructor injection.
## When you might need to use this
The most likely scenario for needing to be able to provide a specific constructor to be used when creating an
instance from an open generic is to disambiguate between constructors when a generic type argument might
can cause a conflict with the concrete type of an argument on one or more constructors.
For example, consider the `List<T>` type, which has the following constructors:
- `List<T>()`
- `List<T>(IEnumerable<T>)`
- `List<T>(int)`
> [!TIP]
> `List<T>` is a type that, by default, Rezolver [can build automatically for you](../arrays-lists-collections/lists.md)
> by extending its own support for [enumerables](../enumerables.md).
> ***
> In fact, the scenario described here is taken specifically from how Rezolver handles the `List<T>` type.
Now, if you were to explicitly register the `List<T>` type for constructor injection (after disabling Rezolver's
own support for it of course), Rezolver will happily bind to the `IEnumerable<T>` constructor for all types of `T`
except one: `int`.
When you request a `List<int>`, Rezolver immediately hits a problem - unless you've not got any `int` registrations
(which presumably you would have if you're requesting a list of `int`!) - because it sees *two* constructors that
could be satisfied. It doesn't *know* that you could only ever want the `IEnumerable<T>` one - how could it? - so
instead of getting a shiny new list to play with, you get an exception.
So how do we get around it?
What we need to be able to do, of course, is to instruct Rezolver to use the `IEnumerable<T>` constructor for all
`T`.
Thankfully, there are a couple of ways to do that.
## The `RegisterGenericConstructor` overload
When registering targets into the @Rezolver.IRootTargetContainer, you can use one of these two methods:
- Rezolver.TargetContainerExtensions.RegisterGenericConstructor``1(Rezolver.ITargetContainer,System.Linq.Expressions.Expression{System.Func{``0}},Rezolver.IMemberBindingBehaviour)
- Rezolver.TargetContainerExtensions.RegisterGenericConstructor``2(Rezolver.ITargetContainer,System.Linq.Expressions.Expression{System.Func{``0}},Rezolver.IMemberBindingBehaviour)
Both functions expect an expression in which you provide a 'model' constructor call to the generic type whose
constructor you want to bind. The actual constructor arguments you pass are not important - only that the
expression binds to the correct constructor.
Now, clearly, if you try to do this over the *open* generic, your code won't compile - e.g:
```cs
class MyGeneric<T, U> {
public MyGeneric(T t) { }
public MyGeneric(T t, U u) { }
public MyGeneric(T t, U u, string s) { }
}
// ...
targets.RegisterGenericConstructor(() => new MyGeneric<,>(null, null));
```
Because using the `MyGeneric<>` type in this way requires the type arguments to be provided.
Instead, you stub out the type arguments with any types you want, and Rezolver will match the constructor with its
definition on the open generic type:
```cs
targets.RegisterGenericConstructor(() => new MyGeneric<object, object>(null, null))
```
This will create a registration in the container which, for any closed `MyGeneric<,>` will explicitly bind to
the two-parameter constructor, even if registrations exist which satisfy the `s` parameter on the 3-parameter
version.
### Example 1
Here's a tested example with a type which extends the `List<T>` scenario:
[!code-csharp[HasAmbiguousGenericCtor.cs](../../../../../test/Rezolver.Tests.Examples/Types/HasAmbiguousGenericCtor.cs#example)]
In this case, if we want to resolve an `HasAmbiguousGenericCtor<string>`, Rezolver will, by default, use the
[best-match rule](index.md#best-match-examples), meaning that the last `string` we registered will be used both
as the last item in the enumerable but also as the argument for the single `string` parameter.
But that's not a problem with the `RegisterGenericConstructor` function:
[!code-csharp[ConstructorExamples.cs](../../../../../test/Rezolver.Tests.Examples/ConstructorExamples.cs#example200)]
### Example 2 - Different 'service' type
When we register a type for constructor injection normally, we can also tell the container to create an instance
of one type when another type is requested - e.g:
```cs
// construct a Foo whenever we want an IFoo
container.RegisterType<Foo, IFoo>();
// construct a Foo<T> whenever we want an IFoo<T>
container.RegisterType(typeof(Foo<>), typeof(IFoo<>));
```
We can do the same with the other `RegisterGenericConstructor` overload which accepts two type arguments. In
this case, you'll have noticed that our `HasAmbiguousGenericCtor<T>` generic also implements `IGeneric<T>` - so
let's bind a specific constructor *and* register it to be used for a generic service type:
[!code-csharp[ConstructorExamples.cs](../../../../../test/Rezolver.Tests.Examples/ConstructorExamples.cs#example201)]
As the comment says, it's somewhat unfortunate that we have to use specify those generic arguments - just remember
that the `RegisterGenericConstructor` method is specifically looking to bind an open generic.
## Alternatives
The `RegisterGenericConstructor` overload is merely a wrapper for one of the many overloads
of the @Rezolver.Target.ForConstructor* factory method, which creates targets from a @System.Reflection.ConstructorInfo.
This overload will create a @Rezolver.Targets.GenericConstructorTarget if the `ConstructorInfo` passed belongs to
an open generic type. After creating the target, you can then register it directly into the container using the
normal @Rezolver.ITargetContainer.Register* function or one of its overloads.
The same is also true of the @Rezolver.TargetContainerExtensions.RegisterConstructor* overload.
Be aware, though - in all cases, it's not possible to provide named constructor argument bindings, either by dictionary
or as an object, because of the inherent difficulty of providing a single target for one or more arguments whose type
comes from a generic type argument. | {
"content_hash": "80d66c0a931c5113d41934fca860ad3b",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 179,
"avg_line_length": 50.5,
"alnum_prop": 0.7751892836342458,
"repo_name": "LordZoltan/Rezolver",
"id": "ab40f855195f66cb92e0cd1261a27261fbc4e991",
"size": "6870",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/Rezolver.Docs/_docfx_proj/docs/constructor-injection/generics-manual-constructor.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "112"
},
{
"name": "Batchfile",
"bytes": "521"
},
{
"name": "C#",
"bytes": "1266520"
},
{
"name": "CSS",
"bytes": "1097"
},
{
"name": "HTML",
"bytes": "12697"
},
{
"name": "JavaScript",
"bytes": "21040"
},
{
"name": "Pascal",
"bytes": "3239"
},
{
"name": "PowerShell",
"bytes": "9359"
}
],
"symlink_target": ""
} |
#include "NonSmoothLaw.hpp"
#include "RuntimeException.hpp"
// Constructors
// warning -> this is an abstract class, so constructors are usefull only for
// calls in derived classes constructors
NonSmoothLaw::NonSmoothLaw(unsigned int size): _size(size)
{}
NonSmoothLaw::~NonSmoothLaw()
{}
bool NonSmoothLaw::isVerified() const
{
RuntimeException::selfThrow("NonSmoothLaw::isVerified, not yet implemented!");
return false;
}
| {
"content_hash": "c9436eeaaaa589c0225633adb8df16cb",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 80,
"avg_line_length": 19.043478260869566,
"alnum_prop": 0.7511415525114156,
"repo_name": "siconos/siconos-deb",
"id": "a898d5d30c6e17b6f926b2bc8b87ea3b27fdd8e3",
"size": "1128",
"binary": false,
"copies": "2",
"ref": "refs/heads/ubuntu/xenial",
"path": "kernel/src/modelingTools/NonSmoothLaw.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2725"
},
{
"name": "C",
"bytes": "4317052"
},
{
"name": "C++",
"bytes": "8854932"
},
{
"name": "CMake",
"bytes": "381170"
},
{
"name": "CSS",
"bytes": "29334"
},
{
"name": "Fortran",
"bytes": "2539066"
},
{
"name": "GAMS",
"bytes": "5614"
},
{
"name": "HTML",
"bytes": "4771178"
},
{
"name": "JavaScript",
"bytes": "422105"
},
{
"name": "Makefile",
"bytes": "11474"
},
{
"name": "PostScript",
"bytes": "1435858"
},
{
"name": "Python",
"bytes": "1207294"
},
{
"name": "Shell",
"bytes": "44867"
},
{
"name": "TeX",
"bytes": "82998"
}
],
"symlink_target": ""
} |
package io.schinzel.basicutils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author schinzel
*/
public class EmptyObjectsTest extends EmptyObjects {
@Test
public void emptyString_EmptyString() {
assertThat(EmptyObjects.EMPTY_STRING)
.isEmpty();
}
@Test
public void emptyBooleanArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_BOOLEAN_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyLongArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_LONG_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyFloatArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_FLOAT_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyDoubleArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_DOUBLE_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyObjectArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_OBJECT_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyStringArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_STRING_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyIntArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_INT_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyByteArray_EmptyNonNull() {
assertThat(EmptyObjects.EMPTY_BYTE_ARRAY)
.isNotNull()
.isEmpty();
}
@Test
public void emptyList_EmptyNonNull() {
assertThat(EmptyObjects.emptyList())
.isNotNull()
.isEmpty();
}
@Test
public void emptyMap_EmptyNonNull() {
assertThat(EmptyObjects.emptyMap())
.isNotNull()
.isEmpty();
}
@Test
public void emptySet_EmptyNonNull() {
assertThat(EmptyObjects.emptySet())
.isNotNull()
.isEmpty();
}
} | {
"content_hash": "61b5c9c0196f2d5a26b659674f399c84",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 57,
"avg_line_length": 20.766355140186917,
"alnum_prop": 0.5517551755175517,
"repo_name": "Schinzel/basic-utils",
"id": "8288903ad43985839df427a6b49a82d1847f6de3",
"size": "2222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/io/schinzel/basicutils/EmptyObjectsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "313575"
}
],
"symlink_target": ""
} |
'use strict';
var _ = require('lodash');
var ESCAPES = { 'n': '\n', 'f': '\f', 'r': '\r', 't': '\t',
'v': '\v', '\'': '\'', '"': '"' };
function parse (expr) {
var lexer = new Lexer();
var parser = new Parser(lexer);
return parser.parse(expr);
}
function Lexer () { }
Lexer.prototype.lex = function (text) {
//Tokenization done here
this.text = text;
this.index = 0;
this.ch = undefined;
this.tokens = [];
while (this.index < this.text.length) {
this.ch = this.text.charAt(this.index);
if (this.isNumber(this.ch) ||
(this.ch === '.' && this.isNumber(this.peek()))) {
this.readNumber();
} else if (this.ch === '\'' || this.ch === '"') {
this.readString(this.ch);
} else if (this.isIdent(this.ch)) {
this.readIdent();
} else if (this.isWhitespace(this.ch)) {
this.index++;
} else {
throw 'Unexpected next character ' + this.ch;
}
}
return this.tokens;
};
Lexer.prototype.isNumber = function (ch) {
return '0' <= ch && ch <= '9'; //use lexicographical comparison
};
Lexer.prototype.readNumber = function () {
var number = '';
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index).toLowerCase();
if (ch === '.' || this.isNumber(ch)) {
number += ch;
} else {
var nextCh = this.peek();
var prevCh = number.charAt(number.length - 1);
if (ch === 'e' && this.isExpOperator(nextCh)) {
number += ch;
} else if (this.isExpOperator(ch) && prevCh === 'e' &&
nextCh && this.isNumber(nextCh)) {
number += ch;
} else if (this.isExpOperator(ch) && prevCh === 'e' &&
(!nextCh || !this.isNumber(nextCh))) {
throw 'Invalid exponent';
} else {
break;
}
}
this.index++;
}
this.tokens.push({
text: number,
value: Number(number)
});
};
Lexer.prototype.peek = function () {
return this.index < this.text.length - 1 ? this.text.charAt(this.index + 1) : false;
};
Lexer.prototype.isExpOperator = function (ch) {
return ch === '-' || ch === '+' || this.isNumber(ch);
};
Lexer.prototype.readString = function (quote) {
this.index++;
var string = '';
var escape = false;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (escape) {
if (ch === 'u') {
var hex = this.text.substring(this.index + 1, this.index + 5); //next 4 chars after the 'u'
if (!hex.match(/[\da-f]{4}/i)){
throw 'Invalid unicode escape';
}
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var replacement = ESCAPES[ch];
if (replacement) {
string += replacement;
} else {
string += ch;
}
}
escape = false;
} else if (ch === quote) {
this.index++;
this.tokens.push({
text: string,
value: string
});
return;
} else if (ch === '\\') {
escape = true;
} else {
string += ch;
}
this.index++;
}
throw 'Unmatched quote';
};
Lexer.prototype.isIdent = function (ch) {
return ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
ch === '_' || ch === '$');
};
Lexer.prototype.readIdent = function () {
var text = '';
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (this.isIdent(ch) || this.isNumber(ch)) {
text += ch;
} else {
break;
}
this.index++;
}
var token = { text: text };
this.tokens.push(token);
};
Lexer.prototype.isWhitespace = function (ch) {
return (ch === ' ' || ch === '\r' || ch === '\t' ||
ch === '\n' || ch === '\v' || ch === '\u00A0');
};
function AST (lexer) {
this.lexer = lexer;
}
AST.Program = 'Program';
AST.Literal = 'Literal';
AST.prototype.ast = function (text) {
this.tokens = this.lexer.lex(text);
//AST building done here
return this.program();
};
AST.prototype.program = function () {
return {
type: AST.Program,
body: this.primary()
};
};
AST.prototype.primary = function () {
if (this.constants.hasOwnProperty(this.tokens[0].text)) {
return this.constants[this.tokens[0].text];
} else {
return this.constant();
}
};
AST.prototype.constant = function () {
return {
type: AST.Literal,
value: this.tokens[0].value
};
};
AST.prototype.constants = {
'null': { type: AST.Literal, value: null },
'true': { type: AST.Literal, value: true },
'false': { type: AST.Literal, value: false }
};
function ASTCompiler (astBuilder) {
this.astBuilder = astBuilder;
}
ASTCompiler.prototype.compile = function (text) {
var ast = this.astBuilder.ast(text);
//AST compilation done here
this.state = { body: [] };
this.recurse(ast);
//js-hint does not like 'eval', which is basically the same as calling the Function constructor
/* jshint -W054 */
return new Function(this.state.body.join(''));
/* jshint +W054 */
};
ASTCompiler.prototype.recurse = function (ast) {
switch (ast.type) {
case AST.Program:
this.state.body.push('return ' + this.recurse(ast.body), ';');
break;
case AST.Literal:
return this.escape(ast.value);
}
};
ASTCompiler.prototype.escape = function (value) {
if (_.isString(value)) {
return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
} else if (_.isNull(value)) {
return 'null';
} else {
return value;
}
};
ASTCompiler.prototype.stringEscapeRegex = /[^ a-zA-Z0-9]/g;
ASTCompiler.prototype.stringEscapeFn = function (c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
};
function Parser (lexer) {
this.lexer = lexer;
this.ast = new AST(this.lexer);
this.astCompiler = new ASTCompiler(this.ast);
}
Parser.prototype.parse = function (text) {
return this.astCompiler.compile(text);
};
module.exports = parse; | {
"content_hash": "14605d448a0ce290ee005deab6287990",
"timestamp": "",
"source": "github",
"line_count": 288,
"max_line_length": 96,
"avg_line_length": 19.85763888888889,
"alnum_prop": 0.5864661654135338,
"repo_name": "jasonody/building-angular",
"id": "6e45c8e132af5503f5d08deda7a151d721cbc361",
"size": "5719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/parse.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "67434"
}
],
"symlink_target": ""
} |
var BackgroundPage = chrome.extension.getBackgroundPage();
//
// URLList オブジェクト
//
var URLList = BackgroundPage.URLList;
| {
"content_hash": "8e738f27dd9cbdf9295656db2793b219",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 58,
"avg_line_length": 20.666666666666668,
"alnum_prop": 0.75,
"repo_name": "Kerupani129/Chrome-GetMultipleWindowsAndTabs",
"id": "5e0cd64e1e91080d0cfa99034dfb6c96b95c0f69",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "script.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34"
},
{
"name": "HTML",
"bytes": "736"
},
{
"name": "JavaScript",
"bytes": "2387"
}
],
"symlink_target": ""
} |
<%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see https://jhipster.github.io/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
<div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2 data-translate="settings.title" translate-values="{username: '{{vm.settingsAccount.login}}'}">User settings for [<b>{{vm.settingsAccount.login}}</b>]</h2>
<div class="alert alert-success" ng-show="vm.success" data-translate="settings.messages.success">
<strong>Settings saved!</strong>
</div>
<jhi-alert-error></jhi-alert-error>
<form name="form" role="form" novalidate ng-submit="vm.save()" show-validation>
<div class="form-group">
<label class="control-label" for="firstName" data-translate="settings.form.firstname">First Name</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="{{'settings.form.firstname.placeholder' | translate}}"
ng-model="vm.settingsAccount.firstName" ng-minlength=1 ng-maxlength=50 required maxlength="50">
<div ng-show="form.firstName.$dirty && form.firstName.$invalid">
<p class="help-block"
ng-show="form.firstName.$error.required" data-translate="settings.messages.validate.firstname.required">
Your first name is required.
</p>
<p class="help-block"
ng-show="form.firstName.$error.minlength" data-translate="settings.messages.validate.firstname.minlength">
Your first name is required to be at least 1 character.
</p>
<p class="help-block"
ng-show="form.firstName.$error.maxlength" data-translate="settings.messages.validate.firstname.maxlength">
Your first name cannot be longer than 50 characters.
</p>
</div>
</div>
<div class="form-group">
<label class="control-label" for="lastName" data-translate="settings.form.lastname">Last Name</label>
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="{{'settings.form.lastname.placeholder' | translate}}"
ng-model="vm.settingsAccount.lastName" ng-minlength=1 ng-maxlength=50 required maxlength="50">
<div ng-show="form.lastName.$dirty && form.lastName.$invalid">
<p class="help-block"
ng-show="form.lastName.$error.required" data-translate="settings.messages.validate.lastname.required">
Your last name is required.
</p>
<p class="help-block"
ng-show="form.lastName.$error.minlength" data-translate="settings.messages.validate.lastname.minlength">
Your last name is required to be at least 1 character.
</p>
<p class="help-block"
ng-show="form.lastName.$error.maxlength" data-translate="settings.messages.validate.lastname.maxlength">
Your last name cannot be longer than 50 characters.
</p>
</div>
</div>
<div class="form-group">
<label class="control-label" for="email" data-translate="global.form.email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="{{'global.form.email.placeholder' | translate}}"
ng-model="vm.settingsAccount.email" ng-minlength=5 ng-maxlength=100 required maxlength="100">
<div ng-show="form.email.$dirty && form.email.$invalid">
<p class="help-block"
ng-show="form.email.$error.required" data-translate="global.messages.validate.email.required">
Your email is required.
</p>
<p class="help-block"
ng-show="form.email.$error.email" data-translate="global.messages.validate.email.invalid">
Your email is invalid.
</p>
<p class="help-block"
ng-show="form.email.$error.minlength" data-translate="global.messages.validate.email.minlength">
Your email is required to be at least 5 characters.
</p>
<p class="help-block"
ng-show="form.email.$error.maxlength" data-translate="global.messages.validate.email.maxlength">
Your email cannot be longer than 100 characters.
</p>
</div>
</div><% if (enableTranslation){ %>
<div class="form-group">
<label for="langKey" data-translate="settings.form.language">Language</label>
<select id="langKey" name="langKey" class="form-control" ng-model="vm.settingsAccount.langKey" ng-controller="<%=jhiPrefixCapitalized%>LanguageController as languageVm" ng-options="code as (code | findLanguageFromKey) for code in languageVm.languages"></select>
</div><% } %>
<button type="submit" ng-disabled="form.$invalid" class="btn btn-primary" data-translate="settings.form.button">Save</button>
</form>
</div>
</div>
</div>
| {
"content_hash": "2b12f181ec991ec405950b6bfea0e407",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 281,
"avg_line_length": 62.56310679611651,
"alnum_prop": 0.5567970204841713,
"repo_name": "yongli82/generator-jhipster",
"id": "311b209d1101384552cca4f2b7b6ba833505f4a5",
"size": "6444",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "generators/client/templates/angularjs/src/main/webapp/app/account/settings/_settings.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "53455"
},
{
"name": "Gherkin",
"bytes": "179"
},
{
"name": "HTML",
"bytes": "418096"
},
{
"name": "Java",
"bytes": "822100"
},
{
"name": "JavaScript",
"bytes": "1127692"
},
{
"name": "Scala",
"bytes": "7022"
},
{
"name": "Shell",
"bytes": "30055"
},
{
"name": "TypeScript",
"bytes": "359261"
}
],
"symlink_target": ""
} |
<div class="box">
<div class="box-table">
<?php
echo show_alert_message($this->session->flashdata('message'), '<div class="alert alert-auto-close alert-dismissible alert-info"><button type="button" class="close alertclose" >×</button>', '</div>');
$attributes = array('class' => 'form-inline', 'name' => 'flist', 'id' => 'flist');
echo form_open(current_full_url(), $attributes);
?>
<div class="box-table-header">
<?php
ob_start();
?>
<div class="btn-group pull-right" role="group" aria-label="...">
<a href="<?php echo element('listall_url', $view); ?>" class="btn btn-outline btn-default btn-sm">전체목록</a>
<button type="button" class="btn btn-outline btn-default btn-sm btn-list-trash btn-list-selected disabled" data-list-trash-url = "<?php echo element('list_trash_url', $view); ?>" >휴지통</button>
<button type="button" class="btn btn-outline btn-default btn-sm btn-list-delete btn-list-selected disabled" data-list-delete-url = "<?php echo element('list_delete_url', $view); ?>" >선택삭제</button>
</div>
<?php
$buttons = ob_get_contents();
ob_end_flush();
?>
<?php if (element('boardlist', $view)) { ?>
<div class="pull-right mr10">
<select name="brd_id" class="form-control" onChange="location.href='<?php echo current_url(); ?>?brd_id=' + this.value;">
<option value="">전체게시판</option>
<?php foreach (element('boardlist', $view) as $key => $value) { ?>
<option value="<?php echo element('brd_id', $value); ?>" <?php echo set_select('brd_id', element('brd_id', $value), ($this->input->get('brd_id') === element('brd_id', $value) ? true : false)); ?>><?php echo html_escape(element('brd_name', $value)); ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
</div>
<div class="row">전체 : <?php echo element('total_rows', element('data', $view), 0); ?>건</div>
<div class="table-responsive">
<table class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th><a href="<?php echo element('post_id', element('sort', $view)); ?>">번호</a></th>
<th>게시판</th>
<th>이미지</th>
<th>제목</th>
<th>작성자</th>
<th>조회</th>
<th>추천 / 비추</th>
<th>날짜</th>
<th>IP 주소</th>
<th>상태</th>
<th><input type="checkbox" name="chkall" id="chkall" /></th>
</tr>
</thead>
<tbody>
<?php
if (element('list', element('data', $view))) {
foreach (element('list', element('data', $view)) as $result) {
?>
<tr>
<td><?php echo number_format(element('num', $result)); ?></td>
<td><a href="?brd_id=<?php echo element('brd_id', $result); ?>"><?php echo html_escape(element('brd_name', element('board', $result))); ?></a> <a href="<?php echo goto_url(element('boardurl', $result)); ?>" target="_blank"><span class="fa fa-external-link"></span></a></td>
<td>
<?php if (element('thumb_url', $result)) {?>
<a href="<?php echo goto_url(element('posturl', $result)); ?>" target="_blank">
<img src="<?php echo element('thumb_url', $result); ?>" alt="<?php echo html_escape(element('post_title', $result)); ?>" title="<?php echo html_escape(element('post_title', $result)); ?>" class="thumbnail mg0" style="width:80px;" />
</a>
<?php } ?>
</td>
<td>
<?php if (element('category', $result)) { ?><span class="label label-default"><?php echo html_escape(element('bca_value', element('category', $result))); ?></span><?php } ?>
<a href="<?php echo goto_url(element('posturl', $result)); ?>" target="_blank"><?php echo html_escape(element('post_title', $result)); ?></a>
</td>
<td><?php echo element('post_display_name', $result); ?> <?php if (element('post_userid', $result)) { ?> ( <a href="?sfield=mem_id&skeyword=<?php echo element('mem_id', $result); ?>"><?php echo html_escape(element('post_userid', $result)); ?></a> ) <?php } ?></td>
<td><?php echo number_format(element('post_hit', $result)); ?></td>
<td><?php echo number_format(element('post_like', $result)); ?> / <?php echo number_format(element('post_dislike', $result)); ?></td>
<td><?php echo display_datetime(element('post_datetime', $result), 'full'); ?></td>
<td><a href="?sfield=post_ip&skeyword=<?php echo display_admin_ip(element('post_ip', $result)); ?>"><?php echo display_admin_ip(element('post_ip', $result)); ?></a></td>
<td><?php echo element('post_secret', $result) === '1' ? '비밀' : '공개'; ?></td>
<td><input type="checkbox" name="chk[]" class="list-chkbox" value="<?php echo element(element('primary_key', $view), $result); ?>" /></td>
</tr>
<?php
}
}
if ( ! element('list', element('data', $view))) {
?>
<tr>
<td colspan="11" class="nopost">자료가 없습니다</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div class="box-info">
<?php echo element('paging', $view); ?>
<div class="pull-left ml20"><?php echo admin_listnum_selectbox();?></div>
<?php echo $buttons; ?>
</div>
<?php echo form_close(); ?>
</div>
<form name="fsearch" id="fsearch" action="<?php echo current_full_url(); ?>" method="get">
<div class="box-search">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<select class="form-control" name="sfield" >
<?php echo element('search_option', $view); ?>
</select>
<div class="input-group">
<input type="text" class="form-control" name="skeyword" value="<?php echo html_escape(element('skeyword', $view)); ?>" placeholder="Search for..." />
<span class="input-group-btn">
<button class="btn btn-default btn-sm" name="search_submit" type="submit">검색!</button>
</span>
</div>
</div>
</div>
</div>
</form>
</div>
| {
"content_hash": "56481d16a76457cafa0c7fe0fc11631e",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 301,
"avg_line_length": 65.54782608695652,
"alnum_prop": 0.4403024674980101,
"repo_name": "hiadone/vtm",
"id": "b2c889b50af98482bcb6bdb5b1387f287cb6addd",
"size": "7652",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "views/admin/basic/board/post/index.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "587"
},
{
"name": "CSS",
"bytes": "603201"
},
{
"name": "HTML",
"bytes": "573827"
},
{
"name": "JavaScript",
"bytes": "1213461"
},
{
"name": "PHP",
"bytes": "8670415"
},
{
"name": "Ruby",
"bytes": "302"
}
],
"symlink_target": ""
} |
/**
* Specifies the type of the cloud that is added to a {@link CloudCollection} in {@link CloudCollection#add}.
*
* @enum {Number}
*/
const CloudType = {
/**
* Cumulus cloud.
*
* @type {Number}
* @constant
*/
CUMULUS: 0,
};
/**
* Validates that the provided cloud type is a valid {@link CloudType}
*
* @param {CloudType} cloudType The cloud type to validate.
* @returns {Boolean} <code>true</code> if the provided cloud type is a valid value; otherwise, <code>false</code>.
*
* @example
* if (!Cesium.CloudType.validate(cloudType)) {
* throw new Cesium.DeveloperError('cloudType must be a valid value.');
* }
*/
CloudType.validate = function (cloudType) {
return cloudType === CloudType.CUMULUS;
};
export default Object.freeze(CloudType);
| {
"content_hash": "3c773e636df4111a1eeec5860d35221f",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 115,
"avg_line_length": 23.696969696969695,
"alnum_prop": 0.6662404092071611,
"repo_name": "AnalyticalGraphicsInc/cesium",
"id": "7f0664ff89e897164c50c8bf65b7406af70a02af",
"size": "782",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Source/Scene/CloudType.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "56873"
},
{
"name": "GLSL",
"bytes": "278771"
},
{
"name": "HTML",
"bytes": "1180668"
},
{
"name": "JavaScript",
"bytes": "17931584"
}
],
"symlink_target": ""
} |
var Builder = require('systemjs-builder');
var builder = new Builder('./', './jspmConfig.js');
console.log('buildling...');
builder
.buildStatic('./src/index.js', './dist/main.0.0.1.min.js', {
minify: true,
sourceMaps: false
})
.then(function() {
console.log('build success');
})
.catch(function(e) {
console.log('build failed');
console.error(e.stack);
});
| {
"content_hash": "9f1e52f97ab328468b6efcafb12163eb",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 62,
"avg_line_length": 21.833333333333332,
"alnum_prop": 0.6081424936386769,
"repo_name": "dzdrazil/mdnd-client",
"id": "2c6f9cde81f4ad684cc87d9a65a3edac6f890a58",
"size": "393",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "make.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "261"
},
{
"name": "JavaScript",
"bytes": "31670"
}
],
"symlink_target": ""
} |
class History < ApplicationRecord
belongs_to :soul
belongs_to :device
def self.souls_by_device_id(device_id)
Soul.where(id: History.where(device: device_id).pluck(:soul_id))
end
def self.make_history(inputSoul, inputDevices)
# puts "made history for " + inputDevices.count.to_s + " devices (incl blocked)"
inputDevices.each do |currentDevice|
# if currentDevice.not_blocked?(inputSoul.device)
History.create(soul: inputSoul, device: currentDevice)
# end
end
end
end
| {
"content_hash": "d79b6500aeedda659cb5cf830cd03c19",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 84,
"avg_line_length": 30.352941176470587,
"alnum_prop": 0.6996124031007752,
"repo_name": "cwaffles/soulcast-server",
"id": "43f1f1f61c7f40f57edc87abeb1aad48e116d190",
"size": "516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/history.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3918"
},
{
"name": "CoffeeScript",
"bytes": "1899"
},
{
"name": "HTML",
"bytes": "40758"
},
{
"name": "JavaScript",
"bytes": "5147"
},
{
"name": "Ruby",
"bytes": "169433"
},
{
"name": "Shell",
"bytes": "3199"
}
],
"symlink_target": ""
} |
import { Subscription } from 'most';
import 'setimmediate';
export declare type Dispatch<Msg> = (msg: Msg) => void;
export declare type Update<Msg, State> = (state: State, msg: Msg) => State;
export declare type Service<Msg> = (dispatch: Dispatch<Msg>) => (msg: Msg) => any;
export declare type Init<Msg, State> = (dispatch: Dispatch<Msg>) => State;
export declare type View<Msg, State, VNode> = (dispatch: Dispatch<Msg>) => (state: State) => VNode;
export declare type Render<VNode> = (target: HTMLElement) => (vNode: VNode) => any;
export interface App<Msg, State, VNode> {
init: Init<Msg, State>;
update: Update<Msg, State>;
service: Service<Msg>;
view: View<Msg, State, VNode>;
}
export interface AppInstance<VNode> {
target: HTMLElement;
subscription: Subscription<VNode>;
}
export declare const mount: <Msg, State, VNode>(app: App<Msg, State, VNode>, target: HTMLElement, render: Render<VNode>) => AppInstance<VNode>;
export declare const unmount: <VNode>({subscription}: AppInstance<VNode>) => void;
| {
"content_hash": "a291c63725d2cc198ea68a03852264b6",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 143,
"avg_line_length": 51.55,
"alnum_prop": 0.6954413191076625,
"repo_name": "bocodigitalmedia/tea-ts",
"id": "5a81c20e386f2e7934e21917f33310090a22bc45",
"size": "1031",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/index.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "1662"
}
],
"symlink_target": ""
} |
'use strict';
const stylelint = require('../../lib');
const { caseConfigFile, caseFilesForFix, prepForSnapshot } = require('../systemTestUtils');
const CASE_NUMBER = '003';
it('fs - zen garden CSS with standard config', async () => {
expect(
prepForSnapshot(
await stylelint.lint({
files: await caseFilesForFix(CASE_NUMBER),
configFile: caseConfigFile(CASE_NUMBER),
fix: true,
}),
),
).toMatchSnapshot();
}, 10000);
| {
"content_hash": "a7390260c8a42f20b5238cc37f6bca33",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 91,
"avg_line_length": 24.61111111111111,
"alnum_prop": 0.6681715575620768,
"repo_name": "stylelint/stylelint",
"id": "a03baea7366961b3b5ed79ce57a5d9f11eb15887",
"size": "443",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "system-tests/003/fs.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15253"
},
{
"name": "HTML",
"bytes": "697"
},
{
"name": "JavaScript",
"bytes": "2806050"
},
{
"name": "Less",
"bytes": "4"
},
{
"name": "SCSS",
"bytes": "2514"
},
{
"name": "Sass",
"bytes": "2"
},
{
"name": "Shell",
"bytes": "314"
},
{
"name": "TypeScript",
"bytes": "4133"
}
],
"symlink_target": ""
} |
<!DOCTYPE html >
<html>
<head>
<title>DFSJarStoreService - io.gearpump.jarstore.dfs.DFSJarStoreService</title>
<meta name="description" content="DFSJarStoreService - io.gearpump.jarstore.dfs.DFSJarStoreService" />
<meta name="keywords" content="DFSJarStoreService io.gearpump.jarstore.dfs.DFSJarStoreService" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../../lib/template.js"></script>
<script type="text/javascript" src="../../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../../../index.html';
var hash = 'io.gearpump.jarstore.dfs.DFSJarStoreService';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="type">
<div id="definition">
<img alt="Class" src="../../../../lib/class_big.png" />
<p id="owner"><a href="../../../package.html" class="extype" name="io">io</a>.<a href="../../package.html" class="extype" name="io.gearpump">gearpump</a>.<a href="../package.html" class="extype" name="io.gearpump.jarstore">jarstore</a>.<a href="package.html" class="extype" name="io.gearpump.jarstore.dfs">dfs</a></p>
<h1>DFSJarStoreService</h1><h3><span class="morelinks"><div>Related Doc:
<a href="package.html" class="extype" name="io.gearpump.jarstore.dfs">package dfs</a>
</div></span></h3><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">DFSJarStoreService</span><span class="result"> extends <a href="../JarStoreService.html" class="extype" name="io.gearpump.jarstore.JarStoreService">JarStoreService</a></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>DFSJarStoreService store the uploaded jar on HDFS
</p></div><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><a href="../JarStoreService.html" class="extype" name="io.gearpump.jarstore.JarStoreService">JarStoreService</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By Inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="io.gearpump.jarstore.dfs.DFSJarStoreService"><span>DFSJarStoreService</span></li><li class="in" name="io.gearpump.jarstore.JarStoreService"><span>JarStoreService</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show All</span></li>
</ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="io.gearpump.jarstore.dfs.DFSJarStoreService#<init>" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="<init>():io.gearpump.jarstore.dfs.DFSJarStoreService"></a>
<a id="<init>:DFSJarStoreService"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">DFSJarStoreService</span><span class="params">()</span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@<init>():io.gearpump.jarstore.dfs.DFSJarStoreService" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@!=(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@##():Int" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@==(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@asInstanceOf[T0]:T0" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@clone():Object" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="io.gearpump.jarstore.dfs.DFSJarStoreService#copyFromLocal" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="copyFromLocal(localFile:java.io.File):io.gearpump.jarstore.FilePath"></a>
<a id="copyFromLocal(File):FilePath"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">copyFromLocal</span><span class="params">(<span name="localFile">localFile: <span class="extype" name="java.io.File">File</span></span>)</span><span class="result">: <a href="../FilePath.html" class="extype" name="io.gearpump.jarstore.FilePath">FilePath</a></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@copyFromLocal(localFile:java.io.File):io.gearpump.jarstore.FilePath" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">This function will copy the local file to the remote JarStore, called from client side.</p><div class="fullcomment"><div class="comment cmt"><p>This function will copy the local file to the remote JarStore, called from client side.</p></div><dl class="paramcmts block"><dt class="param">localFile</dt><dd class="cmt"><p>The local file</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="io.gearpump.jarstore.dfs.DFSJarStoreService">DFSJarStoreService</a> → <a href="../JarStoreService.html" class="extype" name="io.gearpump.jarstore.JarStoreService">JarStoreService</a></dd></dl></div>
</li><li name="io.gearpump.jarstore.dfs.DFSJarStoreService#copyToLocalFile" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="copyToLocalFile(localFile:java.io.File,remotePath:io.gearpump.jarstore.FilePath):Unit"></a>
<a id="copyToLocalFile(File,FilePath):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">copyToLocalFile</span><span class="params">(<span name="localFile">localFile: <span class="extype" name="java.io.File">File</span></span>, <span name="remotePath">remotePath: <a href="../FilePath.html" class="extype" name="io.gearpump.jarstore.FilePath">FilePath</a></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@copyToLocalFile(localFile:java.io.File,remotePath:io.gearpump.jarstore.FilePath):Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">This function will copy the remote file to local file system, called from client side.</p><div class="fullcomment"><div class="comment cmt"><p>This function will copy the remote file to local file system, called from client side.</p></div><dl class="paramcmts block"><dt class="param">localFile</dt><dd class="cmt"><p>The destination of file path</p></dd><dt class="param">remotePath</dt><dd class="cmt"><p>The remote file path from JarStore</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="io.gearpump.jarstore.dfs.DFSJarStoreService">DFSJarStoreService</a> → <a href="../JarStoreService.html" class="extype" name="io.gearpump.jarstore.JarStoreService">JarStoreService</a></dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@equals(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@finalize():Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@getClass():Class[_]" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@hashCode():Int" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="io.gearpump.jarstore.dfs.DFSJarStoreService#init" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="init(config:com.typesafe.config.Config,actorRefFactory:akka.actor.ActorSystem):Unit"></a>
<a id="init(Config,ActorSystem):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">init</span><span class="params">(<span name="config">config: <span class="extype" name="com.typesafe.config.Config">Config</span></span>, <span name="actorRefFactory">actorRefFactory: <span class="extype" name="akka.actor.ActorSystem">ActorSystem</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@init(config:com.typesafe.config.Config,actorRefFactory:akka.actor.ActorSystem):Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Init the Jar Store.</p><div class="fullcomment"><div class="comment cmt"><p>Init the Jar Store.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="io.gearpump.jarstore.dfs.DFSJarStoreService">DFSJarStoreService</a> → <a href="../JarStoreService.html" class="extype" name="io.gearpump.jarstore.JarStoreService">JarStoreService</a></dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@isInstanceOf[T0]:Boolean" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@notify():Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@notifyAll():Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="io.gearpump.jarstore.dfs.DFSJarStoreService#scheme" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="scheme:String"></a>
<a id="scheme:String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">scheme</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@scheme:String" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">The scheme of the JarStoreService.</p><div class="fullcomment"><div class="comment cmt"><p>The scheme of the JarStoreService.
Like "hdfs" for HDFS file system, and "file" for a local
file system.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="io.gearpump.jarstore.dfs.DFSJarStoreService">DFSJarStoreService</a> → <a href="../JarStoreService.html" class="extype" name="io.gearpump.jarstore.JarStoreService">JarStoreService</a></dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@synchronized[T0](x$1:=>T0):T0" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@toString():String" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@wait():Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../index.html#io.gearpump.jarstore.dfs.DFSJarStoreService@wait(x$1:Long):Unit" title="Permalink" target="_top">
<img src="../../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="io.gearpump.jarstore.JarStoreService">
<h3>Inherited from <a href="../JarStoreService.html" class="extype" name="io.gearpump.jarstore.JarStoreService">JarStoreService</a></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html>
| {
"content_hash": "0d2bd888469bf32cb73df22f5855f98c",
"timestamp": "",
"source": "github",
"line_count": 577,
"max_line_length": 780,
"avg_line_length": 58.01386481802427,
"alnum_prop": 0.5996893111071279,
"repo_name": "stanleyxu2005/gearpump.github.io",
"id": "349cbe95e02443a9aa0ce96eb7dba0e56b962066",
"size": "33500",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "releases/latest/api/scala/io/gearpump/jarstore/dfs/DFSJarStoreService.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "386903"
},
{
"name": "HTML",
"bytes": "236673589"
},
{
"name": "JavaScript",
"bytes": "2196377"
},
{
"name": "Shell",
"bytes": "213"
}
],
"symlink_target": ""
} |
<?php
global $hooks, $mod_name;
$hooks = array(
'integrate_pre_include' => '$sourcedir/PaganVerseHooks.php',
'integrate_general_mod_settings' => 'addPaganAdminPerms',
'integrate_load_theme' => 'addPaganVerseLayer',
);
$mod_name = 'Pagan Verse';
// ---------------------------------------------------------------------------------------------------------------------
define('SMF_INTEGRATION_SETTINGS', serialize(array(
'integrate_menu_buttons' => 'install_menu_button',)));
if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('SMF'))
require_once(dirname(__FILE__) . '/SSI.php');
elseif (!defined('SMF'))
exit('<b>Error:</b> Cannot install - please verify you put this in the same place as SMF\'s index.php.');
if (SMF == 'SSI')
{
// Let's start the main job
install_mod();
// and then let's throw out the template! :P
obExit(null, null, true);
}
else
{
setup_hooks();
}
function install_mod ()
{
global $context, $mod_name;
$context['mod_name'] = $mod_name;
$context['sub_template'] = 'install_script';
$context['page_title_html_safe'] = 'Hook installer for: ' . $mod_name;
if (isset($_GET['action']))
$context['uninstalling'] = $_GET['action'] == 'uninstall' ? true : false;
$context['html_headers'] .= '
<style type="text/css">
.buttonlist ul {
margin:0 auto;
display:table;
}
</style>';
// Sorry, only logged in admins...
isAllowedTo('admin_forum');
if (isset($context['uninstalling']))
setup_hooks();
}
function setup_hooks ()
{
global $context, $hooks;
$integration_function = empty($context['uninstalling']) ? 'add_integration_function' : 'remove_integration_function';
foreach ($hooks as $hook => $function)
$integration_function($hook, $function);
$context['installation_done'] = true;
}
function install_menu_button (&$buttons)
{
global $boardurl, $context;
$context['sub_template'] = 'install_script';
$context['current_action'] = 'install';
$buttons['install'] = array(
'title' => 'Installation script',
'show' => allowedTo('admin_forum'),
'href' => $boardurl . '/do_hooks.php',
'active_button' => true,
'sub_buttons' => array(
),
);
}
function template_install_script ()
{
global $boardurl, $context;
echo '
<div class="tborder login"">
<div class="cat_bar">
<h3 class="catbg">
Welcome to the install script of the mod: ' . $context['mod_name'] . '
</h3>
</div>
<span class="upperframe"><span></span></span>
<div class="roundframe centertext">';
if (!isset($context['installation_done']))
echo '
<strong>Please select the action you want to perform:</strong>
<div class="buttonlist">
<ul>
<li>
<a class="active" href="' . $boardurl . '/do_hooks.php?action=install">
<span>Install</span>
</a>
</li>
<li>
<a class="active" href="' . $boardurl . '/do_hooks.php?action=uninstall">
<span>Uninstall</span>
</a>
</li>
</ul>
</div>';
else
echo '<strong>Database adaptation successful!</strong>';
echo '
</div>
<span class="lowerframe"><span></span></span>
</div>';
}
?> | {
"content_hash": "5d52aa0586e6942b41e7f76b7968a3d1",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 120,
"avg_line_length": 25.363636363636363,
"alnum_prop": 0.602476376669925,
"repo_name": "Gazmanafc/mods",
"id": "ca18409cf1523dc2e01fa68b1b774e61b2aaa616",
"size": "3069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PaganVerse3.1/do_hooks.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "6349"
},
{
"name": "PHP",
"bytes": "130861"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.coreoz</groupId>
<artifactId>ppt-templates</artifactId>
<version>1.0.2-SNAPSHOT</version>
<packaging>jar</packaging>
<name>PPT Templates</name>
<description>PPT Template is a small templating library to generate PowerPoint presentations.</description>
<url>https://github.com/Coreoz/PPT-Templates</url>
<organization>
<name>Coreoz</name>
<url>http://coreoz.com/</url>
</organization>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>Aurélien Manteaux</name>
<email>amanteaux@coreoz.com</email>
<organization>Coreoz</organization>
<organizationUrl>http://coreoz.com/</organizationUrl>
</developer>
</developers>
<scm>
<developerConnection>scm:git:git@github.com:Coreoz/PPT-Templates.git</developerConnection>
<connection>scm:git:git@github.com:Coreoz/PPT-Templates.git</connection>
<url>https://github.com/Coreoz/PPT-Templates</url>
<tag>HEAD</tag>
</scm>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
</repository>
</distributionManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<additionalparam>-Xdoclint:none</additionalparam>
<poi.version>3.17</poi.version>
</properties>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<stylesheet>java</stylesheet>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<useReleaseProfile>false</useReleaseProfile>
<releaseProfiles>release</releaseProfiles>
<goals>deploy</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
<plugin>
<groupId>org.eluder.coveralls</groupId>
<artifactId>coveralls-maven-plugin</artifactId>
<version>4.3.0</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- mandatory to change images -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "65e6b355edd3fc6da44e95fd3446ced9",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 201,
"avg_line_length": 26.524752475247524,
"alnum_prop": 0.6620007465472191,
"repo_name": "Coreoz/PPT-Templates",
"id": "fc1ee24f3adb75a5134beb5d99796fbe91d9f0ac",
"size": "5359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "46021"
}
],
"symlink_target": ""
} |
package io.ejf.intentexamples;
/**
* Created by ejf3 on 11/7/15.
*/
public class Constants {
public static final String SAY_TEXT = "say_text";
public static final String SAY_RECEIVER_ACTION = "io.ejf.intentexamples.say";
public static final String MAIN_RECEIVER_ACTION = "io.ejf.intentexamples";
public static final String EXTRA_CONTENT = "EXTRA_CONTENT";
// stock demo
public static final String STOCKY_RECEIVER_ACTION = "io.ejf.intentexamples.stocky";
public static final String CLIENT_ID = "CLIENT_ID";
public static final String CLIENT_SECRET = "CLIENT_SECRET";
public static final String VALUE = "VALUE";
public static final String INVESTED = "INVESTED";
}
| {
"content_hash": "4f4e7e2ab113fcc216987a3dadcaa1ff",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 87,
"avg_line_length": 35.4,
"alnum_prop": 0.7161016949152542,
"repo_name": "emil10001/AndroidIntentExamples",
"id": "db24c61d5b7bcf92abfd172ebf6d57973a5f3eca",
"size": "708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/io/ejf/intentexamples/Constants.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "31178"
}
],
"symlink_target": ""
} |
var miridanApp = angular.module('miridanApp', ['ui.bootstrap']);
miridanApp.controller('EntityListController', function ($scope, $rootScope, $http) {
$scope.entities = [];
$scope.url = '../world';
//$scope.url = 'test/testworld';
$scope.getUpdate = function() {
$http.get($scope.url).success(function(data) {
$scope.entities = data.entities;
});
}
$scope.getUpdate();
$scope.selectEntity = function(entity) {
$rootScope.$broadcast('selectTarget', entity);
};
$scope.$on('refreshData', function(event) {
$scope.getUpdate();
});
});
miridanApp.controller('InventoryListController', function ($scope, $rootScope) {
$scope.entities = [];
});
miridanApp.controller('InputController', function ($scope, $rootScope, $http) {
$scope.targets = [];
$scope.possibleActions = [{'name': 'explode', 'args': ['target', 'explosive']},
{'name': 'hug', 'args': ['target_player']}];
$scope.selectedAction = $scope.possibleActions[0];
$scope.url = '../action';
//$scope.url = 'test/testaction';
$scope.posturl = '../action/';
$http.get($scope.url).success(function(data) {
$scope.possibleActions = [];
var curaction;
for(var k in data.actions) {
curaction = data.actions[k];
curaction.name = k;
$scope.possibleActions.push(curaction);
}
$scope.selectedAction = $scope.possibleActions[0];
});
$scope.$on('selectTarget', function(event, newtarget) {
$scope.targets.push(newtarget);
});
$scope.formatActionName = function(action) {
return action.name + ":[" + action.args.join("][") + "]";
}
$scope.doaction = function() {
var theaction = $scope.selectedAction;
var actionstr = $scope.selectedAction.name;
var aargs = $scope.selectedAction.args;
for(var i = 0; i < $scope.targets.length; ++i) {
actionstr += (" [" + (aargs[i] || "?") + ":" + $scope.targets[i].name + "]");
}
$rootScope.$broadcast('addLogs', [{'message': actionstr}]);
var purl = $scope.posturl + theaction.name + "?";
var arglist = [];
for(var j = 0; j < theaction.args.length && j < $scope.targets.length; ++j) {
arglist.push(theaction.args[j] + "=" + $scope.targets[j].name);
}
purl += arglist.join("&");
console.log("PURL: " + purl);
$http.put(purl).success(function(data) {
console.log("Action succeeded?");
$rootScope.$broadcast('refreshData', 12);
}).error(function(data, status) {
console.log("Action failed: ");
console.log(data);
console.log(status);
$rootScope.$broadcast('refreshData', 12);
});
};
});
miridanApp.controller('LogController', function ($scope, $http) {
$scope.logs = [{'message': 'WELCOM TO MIRIDAN!!!'}];
$scope.url = '../log';
//$scope.url = 'test/testlog';
$scope.getUpdate = function() {
$http.get($scope.url).success(function(data) {
$scope.logs = data.logs;
});
}
$scope.getUpdate();
$scope.$on('addLogs', function(event, newlogs) {
for(var i = 0; i < newlogs.length; ++i) {
$scope.logs.push(newlogs[i]);
}
});
$scope.$on('refreshData', function(event) {
$scope.getUpdate();
});
}); | {
"content_hash": "809470e2f8269818c891d9713c32a7a4",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 84,
"avg_line_length": 29.47222222222222,
"alnum_prop": 0.5991203267357839,
"repo_name": "psigen/miridan",
"id": "93813e486289a1f975085c5d8d1ed12a783ffd2a",
"size": "3183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "miridan/static/js/controllers.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "137"
},
{
"name": "JavaScript",
"bytes": "3183"
},
{
"name": "Python",
"bytes": "30484"
}
],
"symlink_target": ""
} |
<?php
App::uses('Set', 'Utility');
/**
* A class that helps wrap Request information and particulars about a single request.
* Provides methods commonly used to introspect on the request headers and request body.
*
* Has both an Array and Object interface. You can access framework parameters using indexes:
*
* `$request['controller']` or `$request->controller`.
*
* @package Cake.Network
*/
class CakeRequest implements ArrayAccess {
/**
* Array of parameters parsed from the url.
*
* @var array
*/
public $params = array(
'plugin' => null,
'controller' => null,
'action' => null,
);
/**
* Array of POST data. Will contain form data as well as uploaded files.
* Inputs prefixed with 'data' will have the data prefix removed. If there is
* overlap between an input prefixed with data and one without, the 'data' prefixed
* value will take precedence.
*
* @var array
*/
public $data = array();
/**
* Array of querystring arguments
*
* @var array
*/
public $query = array();
/**
* The url string used for the request.
*
* @var string
*/
public $url;
/**
* Base url path.
*
* @var string
*/
public $base = false;
/**
* webroot path segment for the request.
*
* @var string
*/
public $webroot = '/';
/**
* The full address to the current request
*
* @var string
*/
public $here = null;
/**
* The built in detectors used with `is()` can be modified with `addDetector()`.
*
* There are several ways to specify a detector, see CakeRequest::addDetector() for the
* various formats and ways to define detectors.
*
* @var array
*/
protected $_detectors = array(
'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
'ssl' => array('env' => 'HTTPS', 'value' => 1),
'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone', 'iPad',
'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
'webOS', 'Windows CE', 'Windows Phone OS', 'Xiino'
)),
'requested' => array('param' => 'requested', 'value' => 1)
);
/**
* Copy of php://input. Since this stream can only be read once in most SAPI's
* keep a copy of it so users don't need to know about that detail.
*
* @var string
*/
protected $_input = '';
/**
* Constructor
*
* @param string $url Trimmed url string to use. Should not contain the application base path.
* @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
*/
public function __construct($url = null, $parseEnvironment = true) {
$this->_base();
if (empty($url)) {
$url = $this->_url();
}
if ($url[0] == '/') {
$url = substr($url, 1);
}
$this->url = $url;
if ($parseEnvironment) {
$this->_processPost();
$this->_processGet();
$this->_processFiles();
}
$this->here = $this->base . '/' . $this->url;
}
/**
* process the post data and set what is there into the object.
* processed data is available at `$this->data`
*
* Will merge POST vars prefixed with `data`, and ones without
* into a single array. Variables prefixed with `data` will overwrite those without.
*
* If you have mixed POST values be careful not to make any top level keys numeric
* containing arrays. Set::merge() is used to merge data, and it has possibly
* unexpected behavior in this situation.
*
* @return void
*/
protected function _processPost() {
$this->data = $_POST;
if (ini_get('magic_quotes_gpc') === '1') {
$this->data = stripslashes_deep($this->data);
}
if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
}
if (isset($this->data['_method'])) {
if (!empty($_SERVER)) {
$_SERVER['REQUEST_METHOD'] = $this->data['_method'];
} else {
$_ENV['REQUEST_METHOD'] = $this->data['_method'];
}
unset($this->data['_method']);
}
$data = $this->data;
if (isset($this->data['data'])) {
$data = $this->data['data'];
}
if (count($this->data) <= 1) {
$this->data = $data;
} else {
unset($this->data['data']);
$this->data = Set::merge($this->data, $data);
}
}
/**
* Process the GET parameters and move things into the object.
*
* @return void
*/
protected function _processGet() {
if (ini_get('magic_quotes_gpc') === '1') {
$query = stripslashes_deep($_GET);
} else {
$query = $_GET;
}
unset($query['/' . str_replace('.', '_', urldecode($this->url))]);
if (strpos($this->url, '?') !== false) {
list(, $querystr) = explode('?', $this->url);
parse_str($querystr, $queryArgs);
$query += $queryArgs;
}
if (isset($this->params['url'])) {
$query = array_merge($this->params['url'], $query);
}
$this->query = $query;
}
/**
* Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
* by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
* Each of these server variables have the base path, and query strings stripped off
*
* @return string URI The CakePHP request path that is being accessed.
*/
protected function _url() {
if (!empty($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
$uri = $_SERVER['REQUEST_URI'];
} elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
$uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
} elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
$uri = $_SERVER['HTTP_X_REWRITE_URL'];
} elseif ($var = env('argv')) {
$uri = $var[0];
}
$base = $this->base;
if (strlen($base) > 0 && strpos($uri, $base) === 0) {
$uri = substr($uri, strlen($base));
}
if (strpos($uri, '?') !== false) {
list($uri) = explode('?', $uri, 2);
}
if (empty($uri) || $uri == '/' || $uri == '//') {
return '/';
}
return $uri;
}
/**
* Returns a base URL and sets the proper webroot
*
* @return string Base URL
*/
protected function _base() {
$dir = $webroot = null;
$config = Configure::read('App');
extract($config);
if (!isset($base)) {
$base = $this->base;
}
if ($base !== false) {
$this->webroot = $base . '/';
return $this->base = $base;
}
if (!$baseUrl) {
$base = dirname(env('PHP_SELF'));
if ($webroot === 'webroot' && $webroot === basename($base)) {
$base = dirname($base);
}
if ($dir === 'app' && $dir === basename($base)) {
$base = dirname($base);
}
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base . '/';
return $this->base = $base;
}
$file = '/' . basename($baseUrl);
$base = dirname($baseUrl);
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base . '/';
$docRoot = env('DOCUMENT_ROOT');
$docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
if (!empty($base) || !$docRootContainsWebroot) {
if (strpos($this->webroot, '/' . $dir . '/') === false) {
$this->webroot .= $dir . '/';
}
if (strpos($this->webroot, '/' . $webroot . '/') === false) {
$this->webroot .= $webroot . '/';
}
}
return $this->base = $base . $file;
}
/**
* Process $_FILES and move things into the object.
*
* @return void
*/
protected function _processFiles() {
if (isset($_FILES) && is_array($_FILES)) {
foreach ($_FILES as $name => $data) {
if ($name != 'data') {
$this->params['form'][$name] = $data;
}
}
}
if (isset($_FILES['data'])) {
foreach ($_FILES['data'] as $key => $data) {
foreach ($data as $model => $fields) {
if (is_array($fields)) {
foreach ($fields as $field => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$this->data[$model][$field][$k][$key] = $v;
}
} else {
$this->data[$model][$field][$key] = $value;
}
}
} else {
$this->data[$model][$key] = $fields;
}
}
}
}
}
/**
* Get the IP the client is using, or says they are using.
*
* @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
* header. Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
* @return string The client IP.
*/
public function clientIp($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} else {
if (env('HTTP_CLIENT_IP') != null) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
}
if (env('HTTP_CLIENTADDRESS') != null) {
$tmpipaddr = env('HTTP_CLIENTADDRESS');
if (!empty($tmpipaddr)) {
$ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
}
}
return trim($ipaddr);
}
/**
* Returns the referer that referred this request.
*
* @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
* @return string The referring address for this request.
*/
public function referer($local = false) {
$ref = env('HTTP_REFERER');
$forwarded = env('HTTP_X_FORWARDED_HOST');
if ($forwarded) {
$ref = $forwarded;
}
$base = '';
if (defined('FULL_BASE_URL')) {
$base = FULL_BASE_URL . $this->webroot;
}
if (!empty($ref) && !empty($base)) {
if ($local && strpos($ref, $base) === 0) {
$ref = substr($ref, strlen($base));
if ($ref[0] != '/') {
$ref = '/' . $ref;
}
return $ref;
} elseif (!$local) {
return $ref;
}
}
return '/';
}
/**
* Missing method handler, handles wrapping older style isAjax() type methods
*
* @param string $name The method called
* @param array $params Array of parameters for the method call
* @return mixed
* @throws CakeException when an invalid method is called.
*/
public function __call($name, $params) {
if (strpos($name, 'is') === 0) {
$type = strtolower(substr($name, 2));
return $this->is($type);
}
throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
}
/**
* Magic get method allows access to parsed routing parameters directly on the object.
*
* Allows access to `$this->params['controller']` via `$this->controller`
*
* @param string $name The property being accessed.
* @return mixed Either the value of the parameter or null.
*/
public function __get($name) {
if (isset($this->params[$name])) {
return $this->params[$name];
}
return null;
}
/**
* Magic isset method allows isset/empty checks
* on routing parameters.
*
* @param string $name The property being accessed.
* @return bool Existence
*/
public function __isset($name) {
return isset($this->params[$name]);
}
/**
* Check whether or not a Request is a certain type. Uses the built in detection rules
* as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
* as `is($type)` or `is$Type()`.
*
* @param string $type The type of request you want to check.
* @return boolean Whether or not the request is the type you are checking.
*/
public function is($type) {
$type = strtolower($type);
if (!isset($this->_detectors[$type])) {
return false;
}
$detect = $this->_detectors[$type];
if (isset($detect['env'])) {
if (isset($detect['value'])) {
return env($detect['env']) == $detect['value'];
}
if (isset($detect['pattern'])) {
return (bool)preg_match($detect['pattern'], env($detect['env']));
}
if (isset($detect['options'])) {
$pattern = '/' . implode('|', $detect['options']) . '/i';
return (bool)preg_match($pattern, env($detect['env']));
}
}
if (isset($detect['param'])) {
$key = $detect['param'];
$value = $detect['value'];
return isset($this->params[$key]) ? $this->params[$key] == $value : false;
}
if (isset($detect['callback']) && is_callable($detect['callback'])) {
return call_user_func($detect['callback'], $this);
}
return false;
}
/**
* Add a new detector to the list of detectors that a request can use.
* There are several different formats and types of detectors that can be set.
*
* ### Environment value comparison
*
* An environment value comparison, compares a value fetched from `env()` to a known value
* the environment value is equality checked against the provided value.
*
* e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
*
* ### Pattern value comparison
*
* Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
*
* e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
*
* ### Option based comparison
*
* Option based comparisons use a list of options to create a regular expression. Subsequent calls
* to add an already defined options detector will merge the options.
*
* e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
*
* ### Callback detectors
*
* Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
* receive the request object as its only parameter.
*
* e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
*
* ### Request parameter detectors
*
* Allows for custom detectors on the request parameters.
*
* e.g `addDetector('post', array('param' => 'requested', 'value' => 1)`
*
* @param string $name The name of the detector.
* @param array $options The options for the detector definition. See above.
* @return void
*/
public function addDetector($name, $options) {
$name = strtolower($name);
if (isset($this->_detectors[$name]) && isset($options['options'])) {
$options = Set::merge($this->_detectors[$name], $options);
}
$this->_detectors[$name] = $options;
}
/**
* Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
* This modifies the parameters available through `$request->params`.
*
* @param array $params Array of parameters to merge in
* @return The current object, you can chain this method.
*/
public function addParams($params) {
$this->params = array_merge($this->params, (array)$params);
return $this;
}
/**
* Add paths to the requests' paths vars. This will overwrite any existing paths.
* Provides an easy way to modify, here, webroot and base.
*
* @param array $paths Array of paths to merge in
* @return CakeRequest the current object, you can chain this method.
*/
public function addPaths($paths) {
foreach (array('webroot', 'here', 'base') as $element) {
if (isset($paths[$element])) {
$this->{$element} = $paths[$element];
}
}
return $this;
}
/**
* Get the value of the current requests url. Will include named parameters and querystring arguments.
*
* @param boolean $base Include the base path, set to false to trim the base path off.
* @return string the current request url including query string args.
*/
public function here($base = true) {
$url = $this->here;
if (!empty($this->query)) {
$url .= '?' . http_build_query($this->query, null, '&');
}
if (!$base) {
$url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
}
return $url;
}
/**
* Read an HTTP header from the Request information.
*
* @param string $name Name of the header you want.
* @return mixed Either false on no header being set or the value of the header.
*/
public static function header($name) {
$name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (!empty($_SERVER[$name])) {
return $_SERVER[$name];
}
return false;
}
/**
* Get the HTTP method used for this request.
* There are a few ways to specify a method.
*
* - If your client supports it you can use native HTTP methods.
* - You can set the HTTP-X-Method-Override header.
* - You can submit an input with the name `_method`
*
* Any of these 3 approaches can be used to set the HTTP method used
* by CakePHP internally, and will effect the result of this method.
*
* @return string The name of the HTTP method used.
*/
public function method() {
return env('REQUEST_METHOD');
}
/**
* Get the host that the request was handled on.
*
* @return void
*/
public function host() {
return env('HTTP_HOST');
}
/**
* Get the domain name and include $tldLength segments of the tld.
*
* @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* While `example.co.uk` contains 2.
* @return string Domain name without subdomains.
*/
public function domain($tldLength = 1) {
$segments = explode('.', $this->host());
$domain = array_slice($segments, -1 * ($tldLength + 1));
return implode('.', $domain);
}
/**
* Get the subdomains for a host.
*
* @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* While `example.co.uk` contains 2.
* @return array of subdomains.
*/
public function subdomains($tldLength = 1) {
$segments = explode('.', $this->host());
return array_slice($segments, 0, -1 * ($tldLength + 1));
}
/**
* Find out which content types the client accepts or check if they accept a
* particular type of content.
*
* #### Get all types:
*
* `$this->request->accepts();`
*
* #### Check for a single type:
*
* `$this->request->accepts('json');`
*
* This method will order the returned content types by the preference values indicated
* by the client.
*
* @param string $type The content type to check for. Leave null to get all types a client accepts.
* @return mixed Either an array of all the types the client accepts or a boolean if they accept the
* provided type.
*/
public function accepts($type = null) {
$raw = $this->parseAccept();
$accept = array();
foreach ($raw as $value => $types) {
$accept = array_merge($accept, $types);
}
if ($type === null) {
return $accept;
}
return in_array($type, $accept);
}
/**
* Parse the HTTP_ACCEPT header and return a sorted array with content types
* as the keys, and pref values as the values.
*
* Generally you want to use CakeRequest::accept() to get a simple list
* of the accepted content types.
*
* @return array An array of prefValue => array(content/types)
*/
public function parseAccept() {
$accept = array();
$header = explode(',', $this->header('accept'));
foreach (array_filter($header) as $value) {
$prefPos = strpos($value, ';');
if ($prefPos !== false) {
$prefValue = substr($value, strpos($value, '=') + 1);
$value = trim(substr($value, 0, $prefPos));
} else {
$prefValue = '1.0';
$value = trim($value);
}
if (!isset($accept[$prefValue])) {
$accept[$prefValue] = array();
}
if ($prefValue) {
$accept[$prefValue][] = $value;
}
}
krsort($accept);
return $accept;
}
/**
* Get the languages accepted by the client, or check if a specific language is accepted.
*
* Get the list of accepted languages:
*
* {{{ CakeRequest::acceptLanguage(); }}}
*
* Check if a specific language is accepted:
*
* {{{ CakeRequest::acceptLanguage('es-es'); }}}
*
* @param string $language The language to test.
* @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
*/
public static function acceptLanguage($language = null) {
$accepts = preg_split('/[;,]/', self::header('Accept-Language'));
foreach ($accepts as &$accept) {
$accept = strtolower($accept);
if (strpos($accept, '_') !== false) {
$accept = str_replace('_', '-', $accept);
}
}
if ($language === null) {
return $accepts;
}
return in_array($language, $accepts);
}
/**
* Provides a read/write accessor for `$this->data`. Allows you
* to use a syntax similar to `CakeSession` for reading post data.
*
* ## Reading values.
*
* `$request->data('Post.title');`
*
* When reading values you will get `null` for keys/values that do not exist.
*
* ## Writing values
*
* `$request->data('Post.title', 'New post!');`
*
* You can write to any value, even paths/keys that do not exist, and the arrays
* will be created for you.
*
* @param string $name,... Dot separated name of the value to read/write
* @return mixed Either the value being read, or this so you can chain consecutive writes.
*/
public function data($name) {
$args = func_get_args();
if (count($args) == 2) {
$this->data = Set::insert($this->data, $name, $args[1]);
return $this;
}
return Set::classicExtract($this->data, $name);
}
/**
* Read data from `php://input`. Useful when interacting with XML or JSON
* request body content.
*
* Getting input with a decoding function:
*
* `$this->request->input('json_decode');`
*
* Getting input using a decoding function, and additional params:
*
* `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
*
* Any additional parameters are applied to the callback in the order they are given.
*
* @param string $callback A decoding callback that will convert the string data to another
* representation. Leave empty to access the raw input data. You can also
* supply additional parameters for the decoding callback using var args, see above.
* @return The decoded/processed request data.
*/
public function input($callback = null) {
$input = $this->_readInput();
$args = func_get_args();
if (!empty($args)) {
$callback = array_shift($args);
array_unshift($args, $input);
return call_user_func_array($callback, $args);
}
return $input;
}
/**
* Read data from php://input, mocked in tests.
*
* @return string contents of php://input
*/
protected function _readInput() {
if (empty($this->_input)) {
$fh = fopen('php://input', 'r');
$content = stream_get_contents($fh);
fclose($fh);
$this->_input = $content;
}
return $this->_input;
}
/**
* Array access read implementation
*
* @param string $name Name of the key being accessed.
* @return mixed
*/
public function offsetGet($name) {
if (isset($this->params[$name])) {
return $this->params[$name];
}
if ($name == 'url') {
return $this->query;
}
if ($name == 'data') {
return $this->data;
}
return null;
}
/**
* Array access write implementation
*
* @param string $name Name of the key being written
* @param mixed $value The value being written.
* @return void
*/
public function offsetSet($name, $value) {
$this->params[$name] = $value;
}
/**
* Array access isset() implementation
*
* @param string $name thing to check.
* @return boolean
*/
public function offsetExists($name) {
return isset($this->params[$name]);
}
/**
* Array access unset() implementation
*
* @param string $name Name to unset.
* @return void
*/
public function offsetUnset($name) {
unset($this->params[$name]);
}
}
| {
"content_hash": "bb22a9596f815eca5660bcf609eedc8e",
"timestamp": "",
"source": "github",
"line_count": 837,
"max_line_length": 109,
"avg_line_length": 27.989247311827956,
"alnum_prop": 0.6189439535578606,
"repo_name": "rxcnet/BrandweerMonnickendam.nl",
"id": "35bb977981c0c95a3a39220e597efcbceccad4bd",
"size": "23995",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "blog/lib/Cake/Network/CakeRequest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1300"
},
{
"name": "Batchfile",
"bytes": "2804"
},
{
"name": "CSS",
"bytes": "168034"
},
{
"name": "HTML",
"bytes": "14431"
},
{
"name": "JavaScript",
"bytes": "8863"
},
{
"name": "PHP",
"bytes": "7062129"
},
{
"name": "Shell",
"bytes": "3163"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# Module API
from .enum import check_enum
from .maximum import check_maximum
from .maxLength import check_maxLength
from .minimum import check_minimum
from .minLength import check_minLength
from .pattern import check_pattern
from .required import check_required
from .unique import check_unique
| {
"content_hash": "766275695f40b516c88bf07285726a4a",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 39,
"avg_line_length": 27.9375,
"alnum_prop": 0.7986577181208053,
"repo_name": "okfn/json-table-schema-py",
"id": "5854d663b216421c30284b30a840097b8fc105bc",
"size": "471",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "tableschema/constraints/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "453"
},
{
"name": "Python",
"bytes": "134974"
}
],
"symlink_target": ""
} |
sudo rm -rf "${HOME}/apache24"
| {
"content_hash": "baa50b8d891562b84e72a088314ee390",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 30,
"avg_line_length": 31,
"alnum_prop": 0.6451612903225806,
"repo_name": "JBlond/debian_build_apache24",
"id": "253a9e613a334552691b6ff4dd08b06d218af17f",
"size": "43",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "1205"
},
{
"name": "Shell",
"bytes": "8927"
}
],
"symlink_target": ""
} |
/**
* @file ActuatorEffectivenessMultirotorParams.c
*
* Parameters for the actuator effectiveness of multirotors.
*
* @author Julien Lecoeur <julien.lecoeur@gmail.com>
*/
/**
* Position of rotor 0 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_PX, 0.0);
/**
* Position of rotor 0 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_PY, 0.0);
/**
* Position of rotor 0 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_PZ, 0.0);
/**
* Axis of rotor 0 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_AX, 0.0);
/**
* Axis of rotor 0 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_AY, 0.0);
/**
* Axis of rotor 0 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_AZ, -1.0);
/**
* Thrust coefficient of rotor 0
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT0_MIN and CA_ACT0_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_CT, 0.0);
/**
* Moment coefficient of rotor 0
*
* The moment coefficient if defined as Torque = KM * Thrust
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R0_KM, 0.05);
/**
* Position of rotor 1 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_PX, 0.0);
/**
* Position of rotor 1 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_PY, 0.0);
/**
* Position of rotor 1 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_PZ, 0.0);
/**
* Axis of rotor 1 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_AX, 0.0);
/**
* Axis of rotor 1 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_AY, 0.0);
/**
* Axis of rotor 1 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_AZ, -1.0);
/**
* Thrust coefficient of rotor 1
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT1_MIN and CA_ACT1_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_CT, 0.0);
/**
* Moment coefficient of rotor 1
*
* The moment coefficient if defined as Torque = KM * Thrust,
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R1_KM, 0.05);
/**
* Position of rotor 2 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_PX, 0.0);
/**
* Position of rotor 2 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_PY, 0.0);
/**
* Position of rotor 2 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_PZ, 0.0);
/**
* Axis of rotor 2 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_AX, 0.0);
/**
* Axis of rotor 2 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_AY, 0.0);
/**
* Axis of rotor 2 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_AZ, -1.0);
/**
* Thrust coefficient of rotor 2
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT2_MIN and CA_ACT2_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_CT, 0.0);
/**
* Moment coefficient of rotor 2
*
* The moment coefficient if defined as Torque = KM * Thrust
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R2_KM, 0.05);
/**
* Position of rotor 3 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_PX, 0.0);
/**
* Position of rotor 3 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_PY, 0.0);
/**
* Position of rotor 3 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_PZ, 0.0);
/**
* Axis of rotor 3 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_AX, 0.0);
/**
* Axis of rotor 3 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_AY, 0.0);
/**
* Axis of rotor 3 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_AZ, -1.0);
/**
* Thrust coefficient of rotor 3
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT3_MIN and CA_ACT3_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_CT, 0.0);
/**
* Moment coefficient of rotor 3
*
* The moment coefficient if defined as Torque = KM * Thrust
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R3_KM, 0.05);
/**
* Position of rotor 4 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_PX, 0.0);
/**
* Position of rotor 4 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_PY, 0.0);
/**
* Position of rotor 4 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_PZ, 0.0);
/**
* Axis of rotor 4 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_AX, 0.0);
/**
* Axis of rotor 4 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_AY, 0.0);
/**
* Axis of rotor 4 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_AZ, -1.0);
/**
* Thrust coefficient of rotor 4
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT4_MIN and CA_ACT4_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_CT, 0.0);
/**
* Moment coefficient of rotor 4
*
* The moment coefficient if defined as Torque = KM * Thrust
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R4_KM, 0.05);
/**
* Position of rotor 5 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_PX, 0.0);
/**
* Position of rotor 5 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_PY, 0.0);
/**
* Position of rotor 5 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_PZ, 0.0);
/**
* Axis of rotor 5 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_AX, 0.0);
/**
* Axis of rotor 5 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_AY, 0.0);
/**
* Axis of rotor 5 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_AZ, -1.0);
/**
* Thrust coefficient of rotor 5
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT5_MIN and CA_ACT5_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_CT, 0.0);
/**
* Moment coefficient of rotor 5
*
* The moment coefficient if defined as Torque = KM * Thrust
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R5_KM, 0.05);
/**
* Position of rotor 6 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_PX, 0.0);
/**
* Position of rotor 6 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_PY, 0.0);
/**
* Position of rotor 6 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_PZ, 0.0);
/**
* Axis of rotor 6 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_AX, 0.0);
/**
* Axis of rotor 6 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_AY, 0.0);
/**
* Axis of rotor 6 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_AZ, -1.0);
/**
* Thrust coefficient of rotor 6
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT6_MIN and CA_ACT6_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_CT, 0.0);
/**
* Moment coefficient of rotor 6
*
* The moment coefficient if defined as Torque = KM * Thrust
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R6_KM, 0.05);
/**
* Position of rotor 7 along X body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_PX, 0.0);
/**
* Position of rotor 7 along Y body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_PY, 0.0);
/**
* Position of rotor 7 along Z body axis
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_PZ, 0.0);
/**
* Axis of rotor 7 thrust vector, X body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_AX, 0.0);
/**
* Axis of rotor 7 thrust vector, Y body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_AY, 0.0);
/**
* Axis of rotor 7 thrust vector, Z body axis component
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_AZ, -1.0);
/**
* Thrust coefficient of rotor 7
*
* The thrust coefficient if defined as Thrust = CT * u^2,
* where u (with value between CA_ACT7_MIN and CA_ACT7_MAX)
* is the output signal sent to the motor controller.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_CT, 0.0);
/**
* Moment coefficient of rotor 7
*
* The moment coefficient if defined as Torque = KM * Thrust
*
* Use a positive value for a rotor with CCW rotation.
* Use a negative value for a rotor with CW rotation.
*
* @group Control Allocation
*/
PARAM_DEFINE_FLOAT(CA_MC_R7_KM, 0.05);
| {
"content_hash": "1bba5b668acdaf4ed1c2d62835c4dfff",
"timestamp": "",
"source": "github",
"line_count": 529,
"max_line_length": 61,
"avg_line_length": 20.650283553875237,
"alnum_prop": 0.6726473819113877,
"repo_name": "acfloria/Firmware",
"id": "2fea6eac571a93f548d8f41c51bd04cb00c3ed50",
"size": "12655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessMultirotorParams.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3738677"
},
{
"name": "C++",
"bytes": "9489997"
},
{
"name": "CMake",
"bytes": "1106585"
},
{
"name": "EmberScript",
"bytes": "93414"
},
{
"name": "GDB",
"bytes": "41"
},
{
"name": "Groovy",
"bytes": "66180"
},
{
"name": "HTML",
"bytes": "5343"
},
{
"name": "MATLAB",
"bytes": "9938"
},
{
"name": "Makefile",
"bytes": "20040"
},
{
"name": "Perl",
"bytes": "11401"
},
{
"name": "Python",
"bytes": "1300486"
},
{
"name": "Shell",
"bytes": "301338"
}
],
"symlink_target": ""
} |
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.extensions.client;
import java.util.EnumSet;
import java.util.Set;
/** Output options available when using {@code /groups/} RPCs. */
public enum ListGroupsOption {
/** Return information on the direct group members. */
MEMBERS(0),
/** Return information on the directly included groups. */
INCLUDES(1);
private final int value;
ListGroupsOption(int v) {
this.value = v;
}
public int getValue() {
return value;
}
public static Set<ListGroupsOption> fromBits(int v) {
EnumSet<ListGroupsOption> r = EnumSet.noneOf(ListGroupsOption.class);
for (ListGroupsOption o : ListGroupsOption.values()) {
if ((v & (1 << o.value)) != 0) {
r.add(o);
v &= ~(1 << o.value);
}
if (v == 0) {
return r;
}
}
if (v != 0) {
throw new IllegalArgumentException("unknown " + Integer.toHexString(v));
}
return r;
}
public static int toBits(Set<ListGroupsOption> set) {
int r = 0;
for (ListGroupsOption o : set) {
r |= 1 << o.value;
}
return r;
}
}
| {
"content_hash": "bd4b55bcbe8ac1c6ab1e285cde5d074c",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 78,
"avg_line_length": 27.370967741935484,
"alnum_prop": 0.657631113730112,
"repo_name": "WANdisco/gerrit",
"id": "0d67efc52b0df831904825a23ebc652510f280fa",
"size": "1697",
"binary": false,
"copies": "1",
"ref": "refs/heads/2.16.21_WD",
"path": "java/com/google/gerrit/extensions/client/ListGroupsOption.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "47431"
},
{
"name": "GAP",
"bytes": "4119"
},
{
"name": "Go",
"bytes": "5563"
},
{
"name": "HTML",
"bytes": "726266"
},
{
"name": "Java",
"bytes": "11491861"
},
{
"name": "JavaScript",
"bytes": "404723"
},
{
"name": "Makefile",
"bytes": "7107"
},
{
"name": "PLpgSQL",
"bytes": "3576"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "17904"
},
{
"name": "Python",
"bytes": "267395"
},
{
"name": "Roff",
"bytes": "32749"
},
{
"name": "Shell",
"bytes": "133358"
}
],
"symlink_target": ""
} |
// Copyright 2010 Chris Patterson
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Stact.Configuration.RegistryConfigurators
{
public interface RegistryBuilderConfigurator :
Configurator
{
RegistryBuilder Configure(RegistryBuilder builder);
}
} | {
"content_hash": "1b4b474fae966d41e426ef828abf1b67",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 83,
"avg_line_length": 39.9,
"alnum_prop": 0.7406015037593985,
"repo_name": "phatboyg/Stact",
"id": "90126a4ffda3d5133c44bd7173ede323cd3869e4",
"size": "800",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Stact/Actors/Configuration/RegistryConfigurators/RegistryBuilderConfigurator.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "4229"
},
{
"name": "C#",
"bytes": "1543409"
},
{
"name": "CSS",
"bytes": "435"
},
{
"name": "JavaScript",
"bytes": "17382"
},
{
"name": "Ruby",
"bytes": "12694"
},
{
"name": "Shell",
"bytes": "243"
}
],
"symlink_target": ""
} |
/**
* \file dummy_base.h
* \brief dummy class for any base python wrappers
* \author Miryanov Sergey
* \date 08.05.2008
*/
#ifndef BS_DUMMY_BASE_H_
#define BS_DUMMY_BASE_H_
#include "bs_object_base.h"
#include "bs_link.h"
namespace blue_sky
{
/**
* \brief dummy linear_solver base
*/
class BS_API_PLUGIN dummy_base : public objbase
{
public:
BLUE_SKY_TYPE_DECL (dummy_base);
};
} // namespace blue_sky
#endif // #ifndef BS_DUMMY_BASE_H_
| {
"content_hash": "d90dae6cbc3c9e6fc48234f782bac71c",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 50,
"avg_line_length": 16.24137931034483,
"alnum_prop": 0.6454352441613588,
"repo_name": "bs-eagle/bs-eagle",
"id": "4438ac6d2095e21b7f016fd7da5ef7646fc7464f",
"size": "471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bs_bos_core_base/include/dummy_base.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "1703"
},
{
"name": "C",
"bytes": "5278838"
},
{
"name": "C++",
"bytes": "4111959"
},
{
"name": "Makefile",
"bytes": "349"
},
{
"name": "Objective-C",
"bytes": "46566"
},
{
"name": "Python",
"bytes": "32468"
}
],
"symlink_target": ""
} |
import { Column, Entity, PrimaryGeneratedColumn } from "../../../src/index"
import { Author } from "./Author"
import { ManyToOne } from "../../../src/decorator/relations/ManyToOne"
@Entity("sample25_post")
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
@ManyToOne((type) => Author, (author) => author.posts)
author: Author
}
| {
"content_hash": "db048e3f798b0a371c93ef3802b684a0",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 75,
"avg_line_length": 23.22222222222222,
"alnum_prop": 0.638755980861244,
"repo_name": "typeorm/typeorm",
"id": "7f48acf296b07ffa60e51b6d970b809b2dd044c2",
"size": "418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sample/sample25-insert-from-inverse-side/entity/Post.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "580"
},
{
"name": "JavaScript",
"bytes": "16233"
},
{
"name": "Shell",
"bytes": "2208"
},
{
"name": "TypeScript",
"bytes": "8547494"
}
],
"symlink_target": ""
} |
#include "pngpriv.h"
void* FXMEM_DefaultAlloc(int byte_size, int);
void FXMEM_DefaultFree(void* pointer, int);
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
/* Free a png_struct */
void /* PRIVATE */
png_destroy_png_struct(png_structrp png_ptr)
{
if (png_ptr != NULL)
{
/* png_free might call png_error and may certainly call
* png_get_mem_ptr, so fake a temporary png_struct to support this.
*/
png_struct dummy_struct = *png_ptr;
memset(png_ptr, 0, (sizeof *png_ptr));
png_free(&dummy_struct, png_ptr);
# ifdef PNG_SETJMP_SUPPORTED
/* We may have a jmp_buf left to deallocate. */
png_free_jmpbuf(&dummy_struct);
# endif
}
}
/* Allocate memory. For reasonable files, size should never exceed
* 64K. However, zlib may allocate more than 64K if you don't tell
* it not to. See zconf.h and png.h for more information. zlib does
* need to allocate exactly 64K, so whatever you call here must
* have the ability to do that.
*/
PNG_FUNCTION(png_voidp,PNGAPI
png_calloc,(png_const_structrp png_ptr, png_alloc_size_t size),PNG_ALLOCATED)
{
png_voidp ret;
ret = png_malloc(png_ptr, size);
if (ret != NULL)
memset(ret, 0, size);
return ret;
}
/* png_malloc_base, an internal function added at libpng 1.6.0, does the work of
* allocating memory, taking into account limits and PNG_USER_MEM_SUPPORTED.
* Checking and error handling must happen outside this routine; it returns NULL
* if the allocation cannot be done (for any reason.)
*/
PNG_FUNCTION(png_voidp /* PRIVATE */,
png_malloc_base,(png_const_structrp png_ptr, png_alloc_size_t size),
PNG_ALLOCATED)
{
/* Moved to png_malloc_base from png_malloc_default in 1.6.0; the DOS
* allocators have also been removed in 1.6.0, so any 16-bit system now has
* to implement a user memory handler. This checks to be sure it isn't
* called with big numbers.
*/
#ifndef PNG_USER_MEM_SUPPORTED
PNG_UNUSED(png_ptr)
#endif
/* Some compilers complain that this is always true. However, it
* can be false when integer overflow happens.
*/
if (size > 0 && size <= PNG_SIZE_MAX
# ifdef PNG_MAX_MALLOC_64K
&& size <= 65536U
# endif
)
{
#ifdef PNG_USER_MEM_SUPPORTED
if (png_ptr != NULL && png_ptr->malloc_fn != NULL)
return png_ptr->malloc_fn(png_constcast(png_structrp,png_ptr), size);
else
#endif
return FXMEM_DefaultAlloc((int)size, 0);
}
else
return NULL;
}
#if defined(PNG_TEXT_SUPPORTED) || defined(PNG_sPLT_SUPPORTED) ||\
defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED)
/* This is really here only to work round a spurious warning in GCC 4.6 and 4.7
* that arises because of the checks in png_realloc_array that are repeated in
* png_malloc_array.
*/
static png_voidp
png_malloc_array_checked(png_const_structrp png_ptr, int nelements,
size_t element_size)
{
png_alloc_size_t req = nelements; /* known to be > 0 */
if (req <= PNG_SIZE_MAX/element_size)
return png_malloc_base(png_ptr, req * element_size);
/* The failure case when the request is too large */
return NULL;
}
PNG_FUNCTION(png_voidp /* PRIVATE */,
png_malloc_array,(png_const_structrp png_ptr, int nelements,
size_t element_size),PNG_ALLOCATED)
{
if (nelements <= 0 || element_size == 0)
png_error(png_ptr, "internal error: array alloc");
return png_malloc_array_checked(png_ptr, nelements, element_size);
}
PNG_FUNCTION(png_voidp /* PRIVATE */,
png_realloc_array,(png_const_structrp png_ptr, png_const_voidp old_array,
int old_elements, int add_elements, size_t element_size),PNG_ALLOCATED)
{
/* These are internal errors: */
if (add_elements <= 0 || element_size == 0 || old_elements < 0 ||
(old_array == NULL && old_elements > 0))
png_error(png_ptr, "internal error: array realloc");
/* Check for overflow on the elements count (so the caller does not have to
* check.)
*/
if (add_elements <= INT_MAX - old_elements)
{
png_voidp new_array = png_malloc_array_checked(png_ptr,
old_elements+add_elements, element_size);
if (new_array != NULL)
{
/* Because png_malloc_array worked the size calculations below cannot
* overflow.
*/
if (old_elements > 0)
memcpy(new_array, old_array, element_size*(unsigned)old_elements);
memset((char*)new_array + element_size*(unsigned)old_elements, 0,
element_size*(unsigned)add_elements);
return new_array;
}
}
return NULL; /* error */
}
#endif /* TEXT || sPLT || STORE_UNKNOWN_CHUNKS */
/* Various functions that have different error handling are derived from this.
* png_malloc always exists, but if PNG_USER_MEM_SUPPORTED is defined a separate
* function png_malloc_default is also provided.
*/
PNG_FUNCTION(png_voidp,PNGAPI
png_malloc,(png_const_structrp png_ptr, png_alloc_size_t size),PNG_ALLOCATED)
{
png_voidp ret;
if (png_ptr == NULL)
return NULL;
ret = png_malloc_base(png_ptr, size);
if (ret == NULL)
png_error(png_ptr, "Out of memory"); /* 'm' means png_malloc */
return ret;
}
#ifdef PNG_USER_MEM_SUPPORTED
PNG_FUNCTION(png_voidp,PNGAPI
png_malloc_default,(png_const_structrp png_ptr, png_alloc_size_t size),
PNG_ALLOCATED PNG_DEPRECATED)
{
png_voidp ret;
if (png_ptr == NULL)
return NULL;
/* Passing 'NULL' here bypasses the application provided memory handler. */
ret = png_malloc_base(NULL/*use malloc*/, size);
if (ret == NULL)
png_error(png_ptr, "Out of Memory"); /* 'M' means png_malloc_default */
return ret;
}
#endif /* USER_MEM */
/* This function was added at libpng version 1.2.3. The png_malloc_warn()
* function will issue a png_warning and return NULL instead of issuing a
* png_error, if it fails to allocate the requested memory.
*/
PNG_FUNCTION(png_voidp,PNGAPI
png_malloc_warn,(png_const_structrp png_ptr, png_alloc_size_t size),
PNG_ALLOCATED)
{
if (png_ptr != NULL)
{
png_voidp ret = png_malloc_base(png_ptr, size);
if (ret != NULL)
return ret;
png_warning(png_ptr, "Out of memory");
}
return NULL;
}
/* Free a pointer allocated by png_malloc(). If ptr is NULL, return
* without taking any action.
*/
void PNGAPI
png_free(png_const_structrp png_ptr, png_voidp ptr)
{
if (png_ptr == NULL || ptr == NULL)
return;
#ifdef PNG_USER_MEM_SUPPORTED
if (png_ptr->free_fn != NULL)
png_ptr->free_fn(png_constcast(png_structrp,png_ptr), ptr);
else
png_free_default(png_ptr, ptr);
}
PNG_FUNCTION(void,PNGAPI
png_free_default,(png_const_structrp png_ptr, png_voidp ptr),PNG_DEPRECATED)
{
if (png_ptr == NULL || ptr == NULL)
return;
#endif /* USER_MEM */
FXMEM_DefaultFree(ptr, 0);
}
#ifdef PNG_USER_MEM_SUPPORTED
/* This function is called when the application wants to use another method
* of allocating and freeing memory.
*/
void PNGAPI
png_set_mem_fn(png_structrp png_ptr, png_voidp mem_ptr, png_malloc_ptr
malloc_fn, png_free_ptr free_fn)
{
if (png_ptr != NULL)
{
png_ptr->mem_ptr = mem_ptr;
png_ptr->malloc_fn = malloc_fn;
png_ptr->free_fn = free_fn;
}
}
/* This function returns a pointer to the mem_ptr associated with the user
* functions. The application should free any memory associated with this
* pointer before png_write_destroy and png_read_destroy are called.
*/
png_voidp PNGAPI
png_get_mem_ptr(png_const_structrp png_ptr)
{
if (png_ptr == NULL)
return NULL;
return png_ptr->mem_ptr;
}
#endif /* USER_MEM */
#endif /* READ || WRITE */
| {
"content_hash": "6cd8acf0b839f35de68a6254a98c8906",
"timestamp": "",
"source": "github",
"line_count": 271,
"max_line_length": 80,
"avg_line_length": 28.321033210332104,
"alnum_prop": 0.6588925081433225,
"repo_name": "DrAlexx/pdfium",
"id": "b5507134fb492c8522e8948940774340bcf5890c",
"size": "8426",
"binary": false,
"copies": "4",
"ref": "refs/heads/light_version",
"path": "third_party/libpng16/pngmem.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "294931"
},
{
"name": "C++",
"bytes": "17923467"
},
{
"name": "CMake",
"bytes": "43227"
},
{
"name": "Objective-C",
"bytes": "3510"
},
{
"name": "Objective-C++",
"bytes": "4498"
},
{
"name": "Python",
"bytes": "124288"
},
{
"name": "Shell",
"bytes": "545"
}
],
"symlink_target": ""
} |
source common.sh
cd "$SCRIPT_DIR/../.." || die "cd fail"
autoreconf --install
LD_LIBRARY_PATH="$INSTALL_DIR/lib:$LD_LIBRARY_PATH" \
LD_RUN_PATH="$INSTALL_DIR/lib:$LD_RUN_PATH" \
LDFLAGS="-L$INSTALL_DIR/lib $LDFLAGS" \
CPPFLAGS="-I$INSTALL_DIR/include $CPPFLAGS" \
FBTHRIFT_BIN="$INSTALL_DIR/bin/" \
./configure --prefix="$INSTALL_DIR"
make $MAKE_ARGS && make install $MAKE_ARGS
| {
"content_hash": "750d546261d61d325cf44dd9707a953d",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 53,
"avg_line_length": 33.333333333333336,
"alnum_prop": 0.6575,
"repo_name": "facebook/mcrouter",
"id": "9206056f0e376db7e5c5e5175a0a59c3dcee049b",
"size": "600",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "mcrouter/scripts/recipes/mcrouter.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "103743"
},
{
"name": "C++",
"bytes": "6438246"
},
{
"name": "Dockerfile",
"bytes": "1885"
},
{
"name": "M4",
"bytes": "79438"
},
{
"name": "Makefile",
"bytes": "29378"
},
{
"name": "Python",
"bytes": "284816"
},
{
"name": "Ragel",
"bytes": "30888"
},
{
"name": "Shell",
"bytes": "35466"
},
{
"name": "Thrift",
"bytes": "57019"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Thu Jan 03 13:25:57 EST 2013 -->
<TITLE>
Uses of Class com.sun.squawk.debugger.JDWPConnection.ClosedException (2013 FRC Java API)
</TITLE>
<META NAME="date" CONTENT="2013-01-03">
<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 com.sun.squawk.debugger.JDWPConnection.ClosedException (2013 FRC Java API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/sun/squawk/debugger/JDWPConnection.ClosedException.html" title="class in com.sun.squawk.debugger"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
"<p style=\"background-color:${javadoc.bgcolor}; color:${javadoc.fgcolor}; padding:4px 5px 2px 3px; margin-top:-1px\"><b>2013 FRC Java API</b></p>"</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/sun/squawk/debugger/\class-useJDWPConnection.ClosedException.html" target="_top"><B>FRAMES</B></A>
<A HREF="JDWPConnection.ClosedException.html" target="_top"><B>NO FRAMES</B></A>
<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>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>com.sun.squawk.debugger.JDWPConnection.ClosedException</B></H2>
</CENTER>
No usage of com.sun.squawk.debugger.JDWPConnection.ClosedException
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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="navbar_bottom_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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/sun/squawk/debugger/JDWPConnection.ClosedException.html" title="class in com.sun.squawk.debugger"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
"<p style=\"background-color:${javadoc.bgcolor}; color:${javadoc.fgcolor}; padding:4px 5px 2px 3px; margin-top:-1px\"><b>2013 FRC Java API</b></p>"</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/sun/squawk/debugger/\class-useJDWPConnection.ClosedException.html" target="_top"><B>FRAMES</B></A>
<A HREF="JDWPConnection.ClosedException.html" target="_top"><B>NO FRAMES</B></A>
<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>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
"<center><i><font size=\"-1\">For updated information see the <a href=\"http://www.usfirst.org/roboticsprograms/frc/\">Java FRC site</a></font></i></center>"
</BODY>
</HTML>
| {
"content_hash": "91312fb4139145e8baf35981b289a7fd",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 234,
"avg_line_length": 46.701388888888886,
"alnum_prop": 0.6123420074349443,
"repo_name": "arithehun/frc",
"id": "c597c6265161e4335d98639e5c51784f2e22212d",
"size": "6725",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/2013/com/sun/squawk/debugger/class-use/JDWPConnection.ClosedException.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "48011"
},
{
"name": "CSS",
"bytes": "192075"
},
{
"name": "JavaScript",
"bytes": "47369283"
},
{
"name": "Opa",
"bytes": "126616"
},
{
"name": "PHP",
"bytes": "52603"
},
{
"name": "Shell",
"bytes": "518"
},
{
"name": "TypeScript",
"bytes": "24280"
}
],
"symlink_target": ""
} |
package aerospike
import (
"bytes"
"fmt"
"io"
"math"
"reflect"
"strconv"
"strings"
// . "github.com/aerospike/aerospike-client-go/logger"
. "github.com/aerospike/aerospike-client-go/types"
ParticleType "github.com/aerospike/aerospike-client-go/types/particle_type"
Buffer "github.com/aerospike/aerospike-client-go/utils/buffer"
)
// Value interface is used to efficiently serialize objects into the wire protocol.
type Value interface {
// Calculate number of vl.bytes necessary to serialize the value in the wire protocol.
estimateSize() int
// Serialize the value in the wire protocol.
write(buffer []byte, offset int) (int, error)
// Serialize the value using MessagePack.
pack(packer *packer) error
// GetType returns wire protocol value type.
GetType() int
// GetObject returns original value as an interface{}.
GetObject() interface{}
// String implements Stringer interface.
String() string
// Return value as an Object.
// GetLuaValue() LuaValue
reader() io.Reader
}
// AerospikeBlob defines an interface to automatically
// encode an object to a []byte.
type AerospikeBlob interface {
// EncodeBlob returns a byte slice representing the encoding of the
// receiver for transmission to a Decoder, usually of the same
// concrete type.
EncodeBlob() ([]byte, error)
}
// NewValue generates a new Value object based on the type.
// If the type is not supported, NewValue will panic.
func NewValue(v interface{}) Value {
switch val := v.(type) {
case nil:
return &NullValue{}
case int:
return NewIntegerValue(val)
case int64:
return NewLongValue(val)
case string:
return NewStringValue(val)
case []Value:
return NewValueArray(val)
case []byte:
return NewBytesValue(val)
case int8:
return NewIntegerValue(int(val))
case int16:
return NewIntegerValue(int(val))
case int32:
return NewIntegerValue(int(val))
case uint8: // byte supported here
return NewIntegerValue(int(val))
case uint16:
return NewIntegerValue(int(val))
case uint32:
return NewIntegerValue(int(val))
case uint:
if !Buffer.Arch64Bits || (val <= math.MaxInt64) {
return NewLongValue(int64(val))
}
case []interface{}:
return NewListValue(val)
case map[interface{}]interface{}:
return NewMapValue(val)
case Value:
return val
case AerospikeBlob:
return NewBlobValue(val)
}
// check for array and map
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Array, reflect.Slice:
l := rv.Len()
arr := make([]interface{}, l)
for i := 0; i < l; i++ {
arr[i] = rv.Index(i).Interface()
}
return NewListValue(arr)
case reflect.Map:
l := rv.Len()
amap := make(map[interface{}]interface{}, l)
for _, i := range rv.MapKeys() {
amap[i.Interface()] = rv.MapIndex(i).Interface()
}
return NewMapValue(amap)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return NewLongValue(reflect.ValueOf(v).Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
return NewLongValue(int64(reflect.ValueOf(v).Uint()))
case reflect.String:
return NewStringValue(rv.String())
}
// panic for anything that is not supported.
panic(NewAerospikeError(TYPE_NOT_SUPPORTED, "Value type '"+reflect.TypeOf(v).Name()+"' not supported"))
}
// NullValue is an empty value.
type NullValue struct{}
var nullValue NullValue
// NewNullValue generates a NullValue instance.
func NewNullValue() NullValue {
return nullValue
}
func (vl NullValue) estimateSize() int {
return 0
}
func (vl NullValue) write(buffer []byte, offset int) (int, error) {
return 0, nil
}
func (vl NullValue) pack(packer *packer) error {
packer.PackNil()
return nil
}
// GetType returns wire protocol value type.
func (vl NullValue) GetType() int {
return ParticleType.NULL
}
// GetObject returns original value as an interface{}.
func (vl NullValue) GetObject() interface{} {
return nil
}
// func (vl NullValue) GetLuaValue() LuaValue {
// return LuaNil.NIL
// }
func (vl NullValue) reader() io.Reader {
return nil
}
// String implements Stringer interface.
func (vl NullValue) String() string {
return ""
}
///////////////////////////////////////////////////////////////////////////////
// BytesValue encapsulates an array of bytes.
type BytesValue []byte
// NewBytesValue generates a ByteValue instance.
func NewBytesValue(bytes []byte) BytesValue {
return BytesValue(bytes)
}
// NewBlobValue accepts an AerospikeBlob interface, and automatically
// converts it to a BytesValue.
// If Encode returns an err, it will panic.
func NewBlobValue(object AerospikeBlob) BytesValue {
buf, err := object.EncodeBlob()
if err != nil {
panic(err)
}
return NewBytesValue(buf)
}
func (vl BytesValue) estimateSize() int {
return len(vl)
}
func (vl BytesValue) write(buffer []byte, offset int) (int, error) {
len := copy(buffer[offset:], vl)
return len, nil
}
func (vl BytesValue) pack(packer *packer) error {
packer.PackBytes(vl)
return nil
}
// GetType returns wire protocol value type.
func (vl BytesValue) GetType() int {
return ParticleType.BLOB
}
// GetObject returns original value as an interface{}.
func (vl BytesValue) GetObject() interface{} {
return []byte(vl)
}
// func (vl BytesValue) GetLuaValue() LuaValue {
// return LuaString.valueOf(vl.bytes)
// }
func (vl BytesValue) reader() io.Reader {
return bytes.NewReader(vl)
}
// String implements Stringer interface.
func (vl BytesValue) String() string {
return Buffer.BytesToHexString(vl)
}
///////////////////////////////////////////////////////////////////////////////
// StringValue encapsulates a string value.
type StringValue string
// NewStringValue generates a StringValue instance.
func NewStringValue(value string) StringValue {
return StringValue(value)
}
func (vl StringValue) estimateSize() int {
return len(vl)
}
func (vl StringValue) write(buffer []byte, offset int) (int, error) {
return copy(buffer[offset:], vl), nil
}
func (vl StringValue) pack(packer *packer) error {
packer.PackString(string(vl))
return nil
}
// GetType returns wire protocol value type.
func (vl StringValue) GetType() int {
return ParticleType.STRING
}
// GetObject returns original value as an interface{}.
func (vl StringValue) GetObject() interface{} {
return string(vl)
}
// func (vl StringValue) GetLuaValue() LuaValue {
// return LuaString.valueOf(vl)
// }
func (vl StringValue) reader() io.Reader {
return strings.NewReader(string(vl))
}
// String implements Stringer interface.
func (vl StringValue) String() string {
return string(vl)
}
///////////////////////////////////////////////////////////////////////////////
// IntegerValue encapsulates an integer value.
type IntegerValue int
// NewIntegerValue generates an IntegerValue instance.
func NewIntegerValue(value int) IntegerValue {
return IntegerValue(value)
}
func (vl IntegerValue) estimateSize() int {
return 8
}
func (vl IntegerValue) write(buffer []byte, offset int) (int, error) {
Buffer.Int64ToBytes(int64(vl), buffer, offset)
return 8, nil
}
func (vl IntegerValue) pack(packer *packer) error {
if Buffer.SizeOfInt == Buffer.SizeOfInt32 {
packer.PackAInt(int(vl))
} else {
packer.PackALong(int64(vl))
}
return nil
}
// GetType returns wire protocol value type.
func (vl IntegerValue) GetType() int {
return ParticleType.INTEGER
}
// GetObject returns original value as an interface{}.
func (vl IntegerValue) GetObject() interface{} {
return int(vl)
}
// func (vl IntegerValue) GetLuaValue() LuaValue {
// return LuaInteger.valueOf(vl)
// }
func (vl IntegerValue) reader() io.Reader {
return bytes.NewReader(Buffer.Int64ToBytes(int64(vl), nil, 0))
}
// String implements Stringer interface.
func (vl IntegerValue) String() string {
return strconv.Itoa(int(vl))
}
///////////////////////////////////////////////////////////////////////////////
// LongValue encapsulates an int64 value.
type LongValue int64
// NewLongValue generates a LongValue instance.
func NewLongValue(value int64) LongValue {
return LongValue(value)
}
func (vl LongValue) estimateSize() int {
return 8
}
func (vl LongValue) write(buffer []byte, offset int) (int, error) {
Buffer.Int64ToBytes(int64(vl), buffer, offset)
return 8, nil
}
func (vl LongValue) pack(packer *packer) error {
packer.PackALong(int64(vl))
return nil
}
// GetType returns wire protocol value type.
func (vl LongValue) GetType() int {
return ParticleType.INTEGER
}
// GetObject returns original value as an interface{}.
func (vl LongValue) GetObject() interface{} {
return int64(vl)
}
// func (vl LongValue) GetLuaValue() LuaValue {
// return LuaInteger.valueOf(vl)
// }
func (vl LongValue) reader() io.Reader {
return bytes.NewReader(Buffer.Int64ToBytes(int64(vl), nil, 0))
}
// String implements Stringer interface.
func (vl LongValue) String() string {
return strconv.Itoa(int(vl))
}
///////////////////////////////////////////////////////////////////////////////
// ValueArray encapsulates an array of Value.
// Supported by Aerospike 3 servers only.
type ValueArray struct {
array []Value
bytes []byte
}
// ToValueArray converts a []interface{} to []Value.
// It will panic if any of array element types are not supported.
func ToValueArray(array []interface{}) *ValueArray {
res := make([]Value, 0, len(array))
for i := range array {
res = append(res, NewValue(array[i]))
}
return NewValueArray(res)
}
// NewValueArray generates a ValueArray instance.
func NewValueArray(array []Value) *ValueArray {
res := &ValueArray{
array: array,
}
res.bytes, _ = packValueArray(array)
return res
}
func (vl *ValueArray) estimateSize() int {
return len(vl.bytes)
}
func (vl *ValueArray) write(buffer []byte, offset int) (int, error) {
res := copy(buffer[offset:], vl.bytes)
return res, nil
}
func (vl *ValueArray) pack(packer *packer) error {
return packer.packValueArray(vl.array)
}
// GetType returns wire protocol value type.
func (vl *ValueArray) GetType() int {
return ParticleType.LIST
}
// GetObject returns original value as an interface{}.
func (vl *ValueArray) GetObject() interface{} {
return vl.array
}
// func (vl *ValueArray) GetLuaValue() LuaValue {
// return nil
// }
func (vl *ValueArray) reader() io.Reader {
return bytes.NewReader(vl.bytes)
}
// String implements Stringer interface.
func (vl *ValueArray) String() string {
return fmt.Sprintf("%v", vl.array)
}
///////////////////////////////////////////////////////////////////////////////
// ListValue encapsulates any arbitray array.
// Supported by Aerospike 3 servers only.
type ListValue struct {
list []interface{}
bytes []byte
}
// NewListValue generates a ListValue instance.
func NewListValue(list []interface{}) *ListValue {
res := &ListValue{
list: list,
}
res.bytes, _ = packAnyArray(list)
return res
}
func (vl *ListValue) estimateSize() int {
return len(vl.bytes)
}
func (vl *ListValue) write(buffer []byte, offset int) (int, error) {
l := copy(buffer[offset:], vl.bytes)
return l, nil
}
func (vl *ListValue) pack(packer *packer) error {
// return packer.PackList(vl.list)
_, err := packer.buffer.Write(vl.bytes)
return err
}
// GetType returns wire protocol value type.
func (vl *ListValue) GetType() int {
return ParticleType.LIST
}
// GetObject returns original value as an interface{}.
func (vl *ListValue) GetObject() interface{} {
return vl.list
}
// func (vl *ListValue) GetLuaValue() LuaValue {
// return nil
// }
func (vl *ListValue) reader() io.Reader {
return bytes.NewReader(vl.bytes)
}
// String implements Stringer interface.
func (vl *ListValue) String() string {
return fmt.Sprintf("%v", vl.list)
}
///////////////////////////////////////////////////////////////////////////////
// MapValue encapsulates an arbitray map.
// Supported by Aerospike 3 servers only.
type MapValue struct {
vmap map[interface{}]interface{}
bytes []byte
}
// NewMapValue generates a MapValue instance.
func NewMapValue(vmap map[interface{}]interface{}) *MapValue {
res := &MapValue{
vmap: vmap,
}
res.bytes, _ = packAnyMap(vmap)
return res
}
func (vl *MapValue) estimateSize() int {
return len(vl.bytes)
}
func (vl *MapValue) write(buffer []byte, offset int) (int, error) {
return copy(buffer[offset:], vl.bytes), nil
}
func (vl *MapValue) pack(packer *packer) error {
// return packer.PackMap(vl.vmap)
_, err := packer.buffer.Write(vl.bytes)
return err
}
// GetType returns wire protocol value type.
func (vl *MapValue) GetType() int {
return ParticleType.MAP
}
// GetObject returns original value as an interface{}.
func (vl *MapValue) GetObject() interface{} {
return vl.vmap
}
// func (vl *MapValue) GetLuaValue() LuaValue {
// return nil
// }
func (vl *MapValue) reader() io.Reader {
return bytes.NewReader(vl.bytes)
}
// String implements Stringer interface.
func (vl *MapValue) String() string {
return fmt.Sprintf("%v", vl.vmap)
}
//////////////////////////////////////////////////////////////////////////////
func bytesToParticle(ptype int, buf []byte, offset int, length int) (interface{}, error) {
switch ptype {
case ParticleType.INTEGER:
return Buffer.BytesToNumber(buf, offset, length), nil
case ParticleType.STRING:
return string(buf[offset : offset+length]), nil
case ParticleType.BLOB:
newObj := make([]byte, length)
copy(newObj, buf[offset:offset+length])
return newObj, nil
case ParticleType.LIST:
return newUnpacker(buf, offset, length).UnpackList()
case ParticleType.MAP:
return newUnpacker(buf, offset, length).UnpackMap()
}
return nil, nil
}
func bytesToKeyValue(pType int, buf []byte, offset int, len int) (Value, error) {
switch pType {
case ParticleType.STRING:
return NewStringValue(string(buf[offset : offset+len])), nil
case ParticleType.INTEGER:
return NewLongValue(Buffer.VarBytesToInt64(buf, offset, len)), nil
case ParticleType.BLOB:
bytes := make([]byte, len, len)
copy(bytes, buf[offset:offset+len])
return NewBytesValue(bytes), nil
default:
return nil, nil
}
}
| {
"content_hash": "017a9f146338929b969fb2c057777289",
"timestamp": "",
"source": "github",
"line_count": 600,
"max_line_length": 104,
"avg_line_length": 23.303333333333335,
"alnum_prop": 0.6845944786153626,
"repo_name": "matematik7/aerospike-client-go",
"id": "7f67026100212e2883fb545641103e0f1527e8e8",
"size": "14576",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "value.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "517951"
},
{
"name": "Shell",
"bytes": "177"
}
],
"symlink_target": ""
} |
wn.module_page["Website"] = [
{
title: wn._("Web Content"),
icon: "icon-copy",
top: true,
items: [
{
label: wn._("Web Page"),
description: wn._("Content web page."),
doctype:"Web Page"
},
{
label: wn._("Blog Post"),
description: wn._("Single Post (article)."),
doctype:"Blog Post"
},
]
},
{
title: wn._("Documents"),
icon: "icon-edit",
items: [
{
label: wn._("Website Slideshow"),
description: wn._("Embed image slideshows in website pages."),
doctype:"Website Slideshow"
},
{
label: wn._("Blogger"),
description: wn._("Profile of a blog writer."),
doctype:"Blogger"
},
{
label: wn._("Blog Category"),
description: wn._("Categorize blog posts."),
doctype:"Blog Category"
},
{
label: wn._("Blog Settings"),
description: wn._("Write titles and introductions to your blog."),
doctype:"Blog Settings",
route: "Form/Blog Settings"
},
]
},
{
title: wn._("Website Overall Settings"),
icon: "icon-wrench",
right: true,
items: [
{
"route":"Form/Website Settings",
"label":wn._("Website Settings"),
"description":wn._("Setup of top navigation bar, footer and logo."),
doctype:"Website Settings"
},
{
"route":"Form/Style Settings",
"label":wn._("Style Settings"),
"description":wn._("Setup of fonts and background."),
doctype:"Style Settings"
},
]
},
{
title: wn._("Special Page Settings"),
icon: "icon-wrench",
right: true,
items: [
{
"route":"Form/About Us Settings",
"label":wn._("About Us Settings"),
"description":wn._("Settings for About Us Page."),
doctype:"About Us Settings"
},
{
"route":"Form/Contact Us Settings",
"label":wn._("Contact Us Settings"),
"description":wn._("Settings for Contact Us Page."),
doctype:"Contact Us Settings"
},
]
},
{
title: wn._("Advanced Scripting"),
icon: "icon-wrench",
right: true,
items: [
{
"route":"Form/Website Script",
"label":wn._("Website Script"),
"description":wn._("Javascript to append to the head section of the page."),
doctype:"Website Script"
},
]
}
]
pscript['onload_website-home'] = function(wrapper) {
wn.views.moduleview.make(wrapper, "Website");
} | {
"content_hash": "5ed6bb557b7ceca0ec2871e58f70627a",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 80,
"avg_line_length": 22.362745098039216,
"alnum_prop": 0.5817623849188952,
"repo_name": "rohitw1991/innoworth-lib",
"id": "a48ca07055d0a8e9123510e7862b63a2eba09c44",
"size": "2371",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "website/page/website_home/website_home.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "102097"
},
{
"name": "JavaScript",
"bytes": "1442740"
},
{
"name": "Python",
"bytes": "576012"
}
],
"symlink_target": ""
} |
[](https://ci.appveyor.com/project/sguzunov/codeit)
[](https://coveralls.io/github/sguzunov/CodeIt)
# Main functionality
- Users can solve programming challenge
- Users can check their results
- Users can select from different categories in different tracks
- Admins can create new challenges
- Admins can repear broken challenge
# Technologies
- ASP.NET MVC
- Razor views
- jQuery
- SQL Server 2016
- Entity Framework 6
- Ninject (DI Container)
- Automapper
# Screenshots
| | |
| ----------------------------------- |:--------------------------------------------:|
|  |  |
|  | |
| 
| {
"content_hash": "2825dffbb52744fd145a564cfeb75c67",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 137,
"avg_line_length": 39.7037037037037,
"alnum_prop": 0.605410447761194,
"repo_name": "sguzunov/CodeIt",
"id": "94721e1306bc4e16eee7c32782616a11a0fa209f",
"size": "1082",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "104"
},
{
"name": "C#",
"bytes": "274798"
},
{
"name": "CSS",
"bytes": "1905"
},
{
"name": "JavaScript",
"bytes": "217963"
}
],
"symlink_target": ""
} |
package org.elasticsearch.tribe;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.discovery.MasterNotDiscoveredException;
import org.elasticsearch.discovery.zen.ping.unicast.UnicastZenPing;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.SettingsSource;
import org.elasticsearch.test.TestCluster;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
/**
* Note, when talking to tribe client, no need to set the local flag on master read operations, it
* does it by default.
*/
@LuceneTestCase.SuppressFileSystems("ExtrasFS") // doesn't work with potential multi data path from test cluster yet
public class TribeIT extends ESIntegTestCase {
public static final String SECOND_CLUSTER_NODE_PREFIX = "node_tribe2";
private static InternalTestCluster cluster2;
private Node tribeNode;
private Client tribeClient;
@BeforeClass
public static void setupSecondCluster() throws Exception {
ESIntegTestCase.beforeClass();
cluster2 = new InternalTestCluster(InternalTestCluster.configuredNodeMode(), randomLong(), createTempDir(), 2, 2,
Strings.randomBase64UUID(getRandom()), SettingsSource.EMPTY, 0, false, SECOND_CLUSTER_NODE_PREFIX);
cluster2.beforeTest(getRandom(), 0.1);
cluster2.ensureAtLeastNumDataNodes(2);
}
@AfterClass
public static void tearDownSecondCluster() {
if (cluster2 != null) {
try {
cluster2.close();
} finally {
cluster2 = null;
}
}
}
@After
public void tearDownTribeNode() throws IOException {
if (cluster2 != null) {
try {
cluster2.wipe();
} finally {
cluster2.afterTest();
}
}
if (tribeNode != null) {
tribeNode.close();
tribeNode = null;
}
}
private void setupTribeNode(Settings settings) {
ImmutableMap<String,String> asMap = internalCluster().getDefaultSettings().getAsMap();
Settings.Builder tribe1Defaults = Settings.builder();
Settings.Builder tribe2Defaults = Settings.builder();
for (Map.Entry<String, String> entry : asMap.entrySet()) {
tribe1Defaults.put("tribe.t1." + entry.getKey(), entry.getValue());
tribe2Defaults.put("tribe.t2." + entry.getKey(), entry.getValue());
}
// give each tribe it's unicast hosts to connect to
tribe1Defaults.putArray("tribe.t1." + UnicastZenPing.DISCOVERY_ZEN_PING_UNICAST_HOSTS, getUnicastHosts(internalCluster().client()));
tribe1Defaults.putArray("tribe.t2." + UnicastZenPing.DISCOVERY_ZEN_PING_UNICAST_HOSTS, getUnicastHosts(cluster2.client()));
Settings merged = Settings.builder()
.put("tribe.t1.cluster.name", internalCluster().getClusterName())
.put("tribe.t2.cluster.name", cluster2.getClusterName())
.put("tribe.blocks.write", false)
.put("tribe.blocks.read", false)
.put(settings)
.put(tribe1Defaults.build())
.put(tribe2Defaults.build())
.put(internalCluster().getDefaultSettings())
.put("node.name", "tribe_node") // make sure we can identify threads from this node
.build();
tribeNode = NodeBuilder.nodeBuilder()
.settings(merged)
.node();
tribeClient = tribeNode.client();
}
@Test
public void testGlobalReadWriteBlocks() throws Exception {
logger.info("create 2 indices, test1 on t1, and test2 on t2");
internalCluster().client().admin().indices().prepareCreate("test1").get();
assertAcked(cluster2.client().admin().indices().prepareCreate("test2"));
setupTribeNode(Settings.builder()
.put("tribe.blocks.write", true)
.put("tribe.blocks.metadata", true)
.build());
logger.info("wait till tribe has the same nodes as the 2 clusters");
awaitSameNodeCounts();
// wait till the tribe node connected to the cluster, by checking if the index exists in the cluster state
logger.info("wait till test1 and test2 exists in the tribe node state");
awaitIndicesInClusterState("test1", "test2");
try {
tribeClient.prepareIndex("test1", "type1", "1").setSource("field1", "value1").execute().actionGet();
fail("cluster block should be thrown");
} catch (ClusterBlockException e) {
// all is well!
}
try {
tribeClient.admin().indices().prepareOptimize("test1").execute().actionGet();
fail("cluster block should be thrown");
} catch (ClusterBlockException e) {
// all is well!
}
try {
tribeClient.admin().indices().prepareOptimize("test2").execute().actionGet();
fail("cluster block should be thrown");
} catch (ClusterBlockException e) {
// all is well!
}
}
@Test
public void testIndexWriteBlocks() throws Exception {
logger.info("create 2 indices, test1 on t1, and test2 on t2");
assertAcked(internalCluster().client().admin().indices().prepareCreate("test1"));
assertAcked(internalCluster().client().admin().indices().prepareCreate("block_test1"));
assertAcked(cluster2.client().admin().indices().prepareCreate("test2"));
assertAcked(cluster2.client().admin().indices().prepareCreate("block_test2"));
setupTribeNode(Settings.builder()
.put("tribe.blocks.write.indices", "block_*")
.build());
logger.info("wait till tribe has the same nodes as the 2 clusters");
awaitSameNodeCounts();
// wait till the tribe node connected to the cluster, by checking if the index exists in the cluster state
logger.info("wait till test1 and test2 exists in the tribe node state");
awaitIndicesInClusterState("test1", "test2", "block_test1", "block_test2");
tribeClient.prepareIndex("test1", "type1", "1").setSource("field1", "value1").get();
try {
tribeClient.prepareIndex("block_test1", "type1", "1").setSource("field1", "value1").get();
fail("cluster block should be thrown");
} catch (ClusterBlockException e) {
// all is well!
}
tribeClient.prepareIndex("test2", "type1", "1").setSource("field1", "value1").get();
try {
tribeClient.prepareIndex("block_test2", "type1", "1").setSource("field1", "value1").get();
fail("cluster block should be thrown");
} catch (ClusterBlockException e) {
// all is well!
}
}
@Test
public void testOnConflictDrop() throws Exception {
logger.info("create 2 indices, test1 on t1, and test2 on t2");
assertAcked(cluster().client().admin().indices().prepareCreate("conflict"));
assertAcked(cluster2.client().admin().indices().prepareCreate("conflict"));
assertAcked(cluster().client().admin().indices().prepareCreate("test1"));
assertAcked(cluster2.client().admin().indices().prepareCreate("test2"));
setupTribeNode(Settings.builder()
.put("tribe.on_conflict", "drop")
.build());
logger.info("wait till tribe has the same nodes as the 2 clusters");
awaitSameNodeCounts();
// wait till the tribe node connected to the cluster, by checking if the index exists in the cluster state
logger.info("wait till test1 and test2 exists in the tribe node state");
awaitIndicesInClusterState("test1", "test2");
assertThat(tribeClient.admin().cluster().prepareState().get().getState().getMetaData().index("test1").getSettings().get(TribeService.TRIBE_NAME), equalTo("t1"));
assertThat(tribeClient.admin().cluster().prepareState().get().getState().getMetaData().index("test2").getSettings().get(TribeService.TRIBE_NAME), equalTo("t2"));
assertThat(tribeClient.admin().cluster().prepareState().get().getState().getMetaData().hasIndex("conflict"), equalTo(false));
}
@Test
public void testOnConflictPrefer() throws Exception {
testOnConflictPrefer(randomBoolean() ? "t1" : "t2");
}
private void testOnConflictPrefer(String tribe) throws Exception {
logger.info("testing preference for tribe {}", tribe);
logger.info("create 2 indices, test1 on t1, and test2 on t2");
assertAcked(internalCluster().client().admin().indices().prepareCreate("conflict"));
assertAcked(cluster2.client().admin().indices().prepareCreate("conflict"));
assertAcked(internalCluster().client().admin().indices().prepareCreate("test1"));
assertAcked(cluster2.client().admin().indices().prepareCreate("test2"));
setupTribeNode(Settings.builder()
.put("tribe.on_conflict", "prefer_" + tribe)
.build());
logger.info("wait till tribe has the same nodes as the 2 clusters");
awaitSameNodeCounts();
// wait till the tribe node connected to the cluster, by checking if the index exists in the cluster state
logger.info("wait till test1 and test2 exists in the tribe node state");
awaitIndicesInClusterState("test1", "test2", "conflict");
assertThat(tribeClient.admin().cluster().prepareState().get().getState().getMetaData().index("test1").getSettings().get(TribeService.TRIBE_NAME), equalTo("t1"));
assertThat(tribeClient.admin().cluster().prepareState().get().getState().getMetaData().index("test2").getSettings().get(TribeService.TRIBE_NAME), equalTo("t2"));
assertThat(tribeClient.admin().cluster().prepareState().get().getState().getMetaData().index("conflict").getSettings().get(TribeService.TRIBE_NAME), equalTo(tribe));
}
@Test
public void testTribeOnOneCluster() throws Exception {
setupTribeNode(Settings.EMPTY);
logger.info("create 2 indices, test1 on t1, and test2 on t2");
assertAcked(internalCluster().client().admin().indices().prepareCreate("test1"));
assertAcked(cluster2.client().admin().indices().prepareCreate("test2"));
// wait till the tribe node connected to the cluster, by checking if the index exists in the cluster state
logger.info("wait till test1 and test2 exists in the tribe node state");
awaitIndicesInClusterState("test1", "test2");
logger.info("wait till tribe has the same nodes as the 2 clusters");
awaitSameNodeCounts();
assertThat(tribeClient.admin().cluster().prepareHealth().setWaitForGreenStatus().get().getStatus(), equalTo(ClusterHealthStatus.GREEN));
logger.info("create 2 docs through the tribe node");
tribeClient.prepareIndex("test1", "type1", "1").setSource("field1", "value1").get();
tribeClient.prepareIndex("test2", "type1", "1").setSource("field1", "value1").get();
tribeClient.admin().indices().prepareRefresh().get();
logger.info("verify they are there");
assertHitCount(tribeClient.prepareCount().get(), 2l);
assertHitCount(tribeClient.prepareSearch().get(), 2l);
assertBusy(new Runnable() {
@Override
public void run() {
ClusterState tribeState = tribeNode.client().admin().cluster().prepareState().get().getState();
assertThat(tribeState.getMetaData().index("test1").mapping("type1"), notNullValue());
assertThat(tribeState.getMetaData().index("test2").mapping("type1"), notNullValue());
}
});
logger.info("write to another type");
tribeClient.prepareIndex("test1", "type2", "1").setSource("field1", "value1").get();
tribeClient.prepareIndex("test2", "type2", "1").setSource("field1", "value1").get();
assertNoFailures(tribeClient.admin().indices().prepareRefresh().get());
logger.info("verify they are there");
assertHitCount(tribeClient.prepareCount().get(), 4l);
assertHitCount(tribeClient.prepareSearch().get(), 4l);
assertBusy(new Runnable() {
@Override
public void run() {
ClusterState tribeState = tribeNode.client().admin().cluster().prepareState().get().getState();
assertThat(tribeState.getMetaData().index("test1").mapping("type1"), notNullValue());
assertThat(tribeState.getMetaData().index("test1").mapping("type2"), notNullValue());
assertThat(tribeState.getMetaData().index("test2").mapping("type1"), notNullValue());
assertThat(tribeState.getMetaData().index("test2").mapping("type2"), notNullValue());
}
});
logger.info("make sure master level write operations fail... (we don't really have a master)");
try {
tribeClient.admin().indices().prepareCreate("tribe_index").setMasterNodeTimeout("10ms").get();
fail();
} catch (MasterNotDiscoveredException e) {
// all is well!
}
logger.info("delete an index, and make sure its reflected");
cluster2.client().admin().indices().prepareDelete("test2").get();
awaitIndicesNotInClusterState("test2");
try {
logger.info("stop a node, make sure its reflected");
cluster2.stopRandomDataNode();
awaitSameNodeCounts();
} finally {
cluster2.startNode();
awaitSameNodeCounts();
}
}
@Test
public void testCloseAndOpenIndex() throws Exception {
//create an index and close it even before starting the tribe node
assertAcked(internalCluster().client().admin().indices().prepareCreate("test1"));
ensureGreen(internalCluster());
assertAcked(internalCluster().client().admin().indices().prepareClose("test1"));
setupTribeNode(Settings.EMPTY);
awaitSameNodeCounts();
//the closed index is not part of the tribe node cluster state
ClusterState tribeState = tribeNode.client().admin().cluster().prepareState().get().getState();
assertThat(tribeState.getMetaData().hasIndex("test1"), equalTo(false));
//open the index, it becomes part of the tribe node cluster state
assertAcked(internalCluster().client().admin().indices().prepareOpen("test1"));
awaitIndicesInClusterState("test1");
ensureGreen(internalCluster());
//create a second index, wait till it is seen from within the tribe node
assertAcked(cluster2.client().admin().indices().prepareCreate("test2"));
awaitIndicesInClusterState("test1", "test2");
ensureGreen(cluster2);
//close the second index, wait till it gets removed from the tribe node cluster state
assertAcked(cluster2.client().admin().indices().prepareClose("test2"));
awaitIndicesNotInClusterState("test2");
//open the second index, wait till it gets added back to the tribe node cluster state
assertAcked(cluster2.client().admin().indices().prepareOpen("test2"));
awaitIndicesInClusterState("test1", "test2");
ensureGreen(cluster2);
}
private void awaitIndicesInClusterState(final String... indices) throws Exception {
assertBusy(new Runnable() {
@Override
public void run() {
ClusterState tribeState = tribeNode.client().admin().cluster().prepareState().get().getState();
for (String index : indices) {
assertTrue(tribeState.getMetaData().hasIndex(index));
assertTrue(tribeState.getRoutingTable().hasIndex(index));
}
}
});
}
private void awaitIndicesNotInClusterState(final String... indices) throws Exception {
assertBusy(new Runnable() {
@Override
public void run() {
ClusterState tribeState = tribeNode.client().admin().cluster().prepareState().get().getState();
for (String index : indices) {
assertFalse(tribeState.getMetaData().hasIndex(index));
assertFalse(tribeState.getRoutingTable().hasIndex(index));
}
}
});
}
private void ensureGreen(TestCluster testCluster) {
ClusterHealthResponse actionGet = testCluster.client().admin().cluster()
.health(Requests.clusterHealthRequest().waitForGreenStatus().waitForEvents(Priority.LANGUID).waitForRelocatingShards(0)).actionGet();
if (actionGet.isTimedOut()) {
logger.info("ensureGreen timed out, cluster state:\n{}\n{}", testCluster.client().admin().cluster().prepareState().get().getState().prettyPrint(), testCluster.client().admin().cluster().preparePendingClusterTasks().get().prettyPrint());
assertThat("timed out waiting for green state", actionGet.isTimedOut(), equalTo(false));
}
assertThat(actionGet.getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
private void awaitSameNodeCounts() throws Exception {
assertBusy(new Runnable() {
@Override
public void run() {
DiscoveryNodes tribeNodes = tribeNode.client().admin().cluster().prepareState().get().getState().getNodes();
assertThat(countDataNodesForTribe("t1", tribeNodes), equalTo(internalCluster().client().admin().cluster().prepareState().get().getState().getNodes().dataNodes().size()));
assertThat(countDataNodesForTribe("t2", tribeNodes), equalTo(cluster2.client().admin().cluster().prepareState().get().getState().getNodes().dataNodes().size()));
}
});
}
private int countDataNodesForTribe(String tribeName, DiscoveryNodes nodes) {
int count = 0;
for (DiscoveryNode node : nodes) {
if (!node.dataNode()) {
continue;
}
if (tribeName.equals(node.getAttributes().get(TribeService.TRIBE_NAME))) {
count++;
}
}
return count;
}
public String[] getUnicastHosts(Client client) {
ArrayList<String> unicastHosts = new ArrayList<>();
NodesInfoResponse nodeInfos = client.admin().cluster().prepareNodesInfo().clear().setTransport(true).get();
for (NodeInfo info : nodeInfos.getNodes()) {
TransportAddress address = info.getTransport().getAddress().publishAddress();
unicastHosts.add(address.getAddress() + ":" + address.getPort());
}
return unicastHosts.toArray(new String[unicastHosts.size()]);
}
} | {
"content_hash": "7fd73fb9949e41f58a90563e77ca0c2d",
"timestamp": "",
"source": "github",
"line_count": 429,
"max_line_length": 248,
"avg_line_length": 47.21678321678322,
"alnum_prop": 0.6491409952606635,
"repo_name": "jimhooker2002/elasticsearch",
"id": "9a633e4ae3de5fa9591de9c2dc9bada811503a71",
"size": "21044",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/org/elasticsearch/tribe/TribeIT.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10878"
},
{
"name": "Groovy",
"bytes": "451"
},
{
"name": "HTML",
"bytes": "1427"
},
{
"name": "Java",
"bytes": "29223932"
},
{
"name": "Perl",
"bytes": "264364"
},
{
"name": "Perl6",
"bytes": "103207"
},
{
"name": "Python",
"bytes": "79156"
},
{
"name": "Ruby",
"bytes": "17776"
},
{
"name": "Shell",
"bytes": "87409"
}
],
"symlink_target": ""
} |
module Tests.Move (tests) where
import Test.QuickCheck
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck.Property (Property(..))
import Utilities ()
import Control.Monad (replicateM)
import Control.Monad.ST (runST)
import Data.List (sort,permutations)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector as V
import qualified Data.Vector.Primitive as P
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Unboxed as U
basicMove :: G.Vector v a => v a -> Int -> Int -> Int -> v a
basicMove v dstOff srcOff len
| len > 0 = G.modify (\ mv -> G.copy (M.slice dstOff len mv) (G.slice srcOff len v)) v
| otherwise = v
testMove :: (G.Vector v a, Show (v a), Eq (v a)) => v a -> Property
testMove v = G.length v > 0 ==> (MkProperty $ do
dstOff <- choose (0, G.length v - 1)
srcOff <- choose (0, G.length v - 1)
len <- choose (1, G.length v - max dstOff srcOff)
expected <- return $ basicMove v dstOff srcOff len
actual <- return $ G.modify (\ mv -> M.move (M.slice dstOff len mv) (M.slice srcOff len mv)) v
unProperty $ counterexample ("Move: " ++ show (v, dstOff, srcOff, len)) (expected == actual))
checkPermutations :: Int -> Bool
checkPermutations n = runST $ do
vec <- U.thaw (U.fromList [1..n])
res <- replicateM (product [1..n]) $ M.nextPermutation vec >> U.freeze vec >>= return . U.toList
return $! ([1..n] : res) == sort (permutations [1..n]) ++ [[n,n-1..1]]
testPermutations :: Bool
testPermutations = all checkPermutations [1..7]
tests =
[testProperty "Data.Vector.Mutable (Move)" (testMove :: V.Vector Int -> Property),
testProperty "Data.Vector.Primitive.Mutable (Move)" (testMove :: P.Vector Int -> Property),
testProperty "Data.Vector.Unboxed.Mutable (Move)" (testMove :: U.Vector Int -> Property),
testProperty "Data.Vector.Storable.Mutable (Move)" (testMove :: S.Vector Int -> Property),
testProperty "Data.Vector.Generic.Mutable (nextPermutation)" testPermutations]
| {
"content_hash": "056e90cbaa01b55ca0805de0cefb15b3",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 100,
"avg_line_length": 41.755102040816325,
"alnum_prop": 0.6891495601173021,
"repo_name": "dolio/vector",
"id": "60ea8d334600cef136ce1ba6d77918a20ea15a17",
"size": "2046",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/Tests/Move.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "620"
},
{
"name": "Haskell",
"bytes": "609431"
}
],
"symlink_target": ""
} |
layout: media
title: "Ukulele and bikes"
excerpt: "PaperFaces portrait commission drawn with Paper by 53 on an iPad."
image:
feature: paperfaces-ukulele-bikes-lg.jpg
teaser: paperfaces-ukulele-bikes-teaser.jpg
thumb: paperfaces-ukulele-bikes-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53, beard]
---
PaperFaces portrait commission.
{% include paperfaces-boilerplate-2.html %}
<figure class="third">
<a href="{{ site.url }}/images/paperfaces-ukulele-bikes-process-1-lg.jpg"><img src="{{ site.url }}/images/paperfaces-ukulele-bikes-process-1-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-ukulele-bikes-process-2-lg.jpg"><img src="{{ site.url }}/images/paperfaces-ukulele-bikes-process-2-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-ukulele-bikes-process-3-lg.jpg"><img src="{{ site.url }}/images/paperfaces-ukulele-bikes-process-3-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-ukulele-bikes-process-4-lg.jpg"><img src="{{ site.url }}/images/paperfaces-ukulele-bikes-process-4-600.jpg" alt="Work in process screenshot"></a>
<figcaption>Work in progress screen captures Made with Paper.</figcaption>
</figure> | {
"content_hash": "a8d8eeacc2d11afc86fb1a85ce779485",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 189,
"avg_line_length": 58.04545454545455,
"alnum_prop": 0.7368833202819107,
"repo_name": "U-MH/U-MH.github.io",
"id": "12c00ee78cd782d5f0c0124564b0e5a8a73018a4",
"size": "1281",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "_posts/paperfaces/2014-06-04-ukulele-bikes-portrait.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "126757"
},
{
"name": "HTML",
"bytes": "71359"
},
{
"name": "JavaScript",
"bytes": "82451"
},
{
"name": "PHP",
"bytes": "535"
},
{
"name": "Ruby",
"bytes": "4652"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Pacman TLV 999</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/lib/jqtouch/jqtouch.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="/scripts/dsl.common.js"></script>
<script type="text/javascript" src="/scripts/lib/stringbuilder/dsl.stringbuilder.js"></script>
<script type="text/javascript" src="/scripts/lib/jhashtable/jshashtable-2.1.js"></script>
<script type="text/javascript" src="/scripts/tlvivi.pacman.gamemanager.js"></script>
<script type="text/javascript" src="/scripts/tlvivi.pacman.map.js"></script>
<script type="text/javascript" src="/scripts/ui/tlvivi.pacman.ui.makeplayerslist.js"></script>
<script type="text/javascript" src="/scripts/pages/default.html.js"></script>
<link rel="stylesheet" href="/styles/jqtouch.min.css" />
<link rel="stylesheet" href="/styles/theme.min.css" />
<link rel="stylesheet" href="/styles/screen.css" />
</head>
<body>
<!-- HOME SCREEN -->
<div id="home" class="current">
<div class="toolbar">
<h1>Pacman TLV</h1>
</div>
<br />
<img src="/images/pacmanTlv.jpg" />
<ul class="rounded">
<li><a href="#newGameScreen">New Game</a></li>
<li><span class="listItem" onclick="initGameSelectionScreen()">Join Game</span></li>
<li><a href="#">About Us</a></li>
</ul>
</div>
<!-- NEW GAME SCREEN -->
<div id="newGameScreen" class="form">
<div class="toolbar">
<h1>Start a New Game</h1>
<a class="back" href="#">Back</a>
</div>
<ul>
<li>
<span>Name: </span><input type="text" id="txtGameName" name="txtGameName" value="" placeholder="Enter game name" />
</li>
</ul>
<a href="#" class="whiteButton subButton" onclick="createNewGame()">Create Game</a>
</div>
<!-- GAME SELECTION SCREEN-->
<div id="gameSelectionScreen">
<div class="toolbar">
<h1>Join A Game</h1>
</div>
<h2>Current Games To Join</h2>
<ul class="rounded">
</ul>
</div>
<!-- JOIN GAME SCREEN -->
<div id="joinGameScreen" class="form">
<div class="toolbar">
<h1>Join a Game</h1>
<a class="back" href="#">Back</a>
</div>
<ul class="rounded">
<li>
<span>Name: </span><input type="text" id="txtPlayerName" name="txtPlayerName" value="" placeholder="Enter your name" />
</li>
<li>
<span>Role: </span>
<select id="ddlPlayerRole">
<option value="1">Pacman</option>
<option value="2">Monster</option>
</select>
</li>
</ul>
<a style="margin:0 10px;color:rgba(0,0,0,.9)" href="#" class="whiteButton subButton" onclick="joinGame()">Join Game</a>
</div>
<!-- GAME INTRO SCREEN IS SHOWN WHEN YOU JOIN A GAME THAT IS NOT STARTED YET-->
<div id="gameIntroScreen">
<div class="toolbar">
<h1></h1>
</div>
<h2>Players Currently Registered In The Game</h2>
<ul class="rounded">
</ul>
<a style="margin:0 10px;color:rgba(0,0,0,.9)" href="#gameBoard" class="submit whiteButton cube hidden" onclick="startGame()">Start Game</a>
</div>
<!-- GAME BOARD SCREEN -->
<div id="gameBoard" style="width:100%; height:100%">
<div class="toolbar">
<h1>Game On</h1>
<a class="button flip" href="#gameOptionsScreen">Options</a>
</div>
<div id="mapCanvas" style="width:100%; height:100%"></div>
<div id="messagesPanel" class="info">
<h2 id="messageBody"></h2>
</div>
</div>
<!-- SEND MESSAGE SCREEN -->
<div id="sendMessageScreen" class="form">
<div class="toolbar">
<h1>Send Message</h1>
<a class="back" href="#">Back</a>
</div>
<ul>
<li>
<textarea id="txtSendMessage" rows="5" cols="30"></textarea>
</li>
</ul>
<a href='#gameBoard' class="whiteButton swap subButton" onclick="sendMessage()">Send Message</a>
</div>
<!-- GAME OPTIONS SCREEN -->
<div id="gameOptionsScreen" class="form">
<div class="toolbar">
<h1>Game Options</h1>
<a class="back" href="#">Back</a>
</div>
<ul>
<li><a href="#gameStateScreen" onclick="initGameStateScreen()">View Game State</a></li>
<li><a href="#sendMessageScreen">Send Message</a></li>
<li>
<span class="toggle">
<input id="enableSound" type="checkbox" />
</span>
</li>
</ul>
</div>
<!-- GAME STATE SCREEN -->
<div id="gameStateScreen" class="form">
<div class="toolbar">
<h1>Game Options</h1>
<a class="back" href="#">Back</a>
</div>
<ul>
</ul>
</div>
</body>
</html> | {
"content_hash": "bfa53ff612e5ab418496c769cb36b4d6",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 147,
"avg_line_length": 35.13548387096774,
"alnum_prop": 0.5525156077855307,
"repo_name": "QuickUnit/PacmanTlv",
"id": "b7e0d7e9df2eabe93e22af7e4f37030779bad5ec",
"size": "5446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Site/default.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "2693"
},
{
"name": "C#",
"bytes": "276432"
},
{
"name": "CSS",
"bytes": "55360"
},
{
"name": "JavaScript",
"bytes": "51597"
}
],
"symlink_target": ""
} |
onmessage = function(event) {
const url = event.data;
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send();
const refText = xhr.responseText;
function getResponse(type) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
if (type !== undefined) {
xhr.responseType = type;
}
xhr.send();
return xhr.response;
}
if (getResponse() != refText) {
throw new Error("unset responseType failed");
}
if (getResponse("") != refText) {
throw new Error("'' responseType failed");
}
if (getResponse("text") != refText) {
throw new Error("'text' responseType failed");
}
var array = new Uint8Array(getResponse("arraybuffer"));
if (String.fromCharCode.apply(String, array) != refText) {
throw new Error("'arraybuffer' responseType failed");
}
var blob = getResponse("blob");
if (new FileReaderSync().readAsText(blob) != refText) {
throw new Error("'blob' responseType failed");
}
// Make sure that we get invalid state exceptions when getting the wrong
// property.
function testResponseTextException(type) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.responseType = type;
xhr.send();
var exception;
try {
xhr.responseText;
}
catch(e) {
exception = e;
}
if (!exception) {
throw new Error("Failed to throw when getting responseText on '" + type +
"' type");
}
if (exception.name != "InvalidStateError") {
throw new Error("Unexpected error when getting responseText on '" + type +
"' type");
}
if (exception.code != DOMException.INVALID_STATE_ERR) {
throw new Error("Unexpected error code when getting responseText on '" + type +
"' type");
}
}
testResponseTextException("arraybuffer");
testResponseTextException("blob");
// Make sure "document" works, but returns text.
xhr = new XMLHttpRequest();
if (xhr.responseType != "text") {
throw new Error("Default value for responseType is wrong!");
}
xhr.open("GET", url, false);
xhr.responseType = "document";
xhr.send();
if (xhr.responseText != refText) {
throw new Error("'document' type not working correctly");
}
// Make sure setting responseType before open or after send fails.
var exception;
xhr = new XMLHttpRequest();
try {
xhr.responseType = "arraybuffer";
}
catch(e) {
exception = e;
}
if (!exception) {
throw new Error("Failed to throw when setting responseType before " +
"calling open()");
}
if (exception.name != "InvalidStateError") {
throw new Error("Unexpected error when setting responseType before " +
"calling open()");
}
if (exception.code != DOMException.INVALID_STATE_ERR) {
throw new Error("Unexpected error code when setting responseType before " +
"calling open()");
}
xhr.open("GET", url);
xhr.responseType = "text";
xhr.onload = function(event) {
if (event.target.response != refText) {
throw new Error("Bad response!");
}
xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "moz-chunked-text";
var lastIndex = 0;
xhr.onprogress = function(event) {
if (refText.substr(lastIndex, xhr.response.length) != xhr.response) {
throw new Error("Bad chunk!");
}
lastIndex += xhr.response.length;
};
xhr.onload = function(event) {
if (lastIndex != refText.length) {
throw new Error("Didn't see all the data!");
}
setTimeout(function() {
if (xhr.response !== null) {
throw new Error("Should have gotten null response outside of event!");
}
postMessage("done");
}, 0);
}
xhr.send(null);
};
xhr.send();
exception = null;
try {
xhr.responseType = "arraybuffer";
}
catch(e) {
exception = e;
}
if (!exception) {
throw new Error("Failed to throw when setting responseType after " +
"calling send()");
}
if (exception.name != "InvalidStateError") {
throw new Error("Unexpected error when setting responseType after " +
"calling send()");
}
if (exception.code != DOMException.INVALID_STATE_ERR) {
throw new Error("Unexpected error code when setting responseType after " +
"calling send()");
}
}
| {
"content_hash": "736b87b3d3ba0e93eb5161903e4bf4dd",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 85,
"avg_line_length": 24.62087912087912,
"alnum_prop": 0.6005355947333184,
"repo_name": "sergecodd/FireFox-OS",
"id": "18924a15a4e4b5c6ed0e9cb2aad9e532cce93489",
"size": "4593",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "B2G/gecko/dom/workers/test/xhr2_worker.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "443"
},
{
"name": "ApacheConf",
"bytes": "85"
},
{
"name": "Assembly",
"bytes": "5123438"
},
{
"name": "Awk",
"bytes": "46481"
},
{
"name": "Batchfile",
"bytes": "56250"
},
{
"name": "C",
"bytes": "101720951"
},
{
"name": "C#",
"bytes": "38531"
},
{
"name": "C++",
"bytes": "148896543"
},
{
"name": "CMake",
"bytes": "23541"
},
{
"name": "CSS",
"bytes": "2758664"
},
{
"name": "DIGITAL Command Language",
"bytes": "56757"
},
{
"name": "Emacs Lisp",
"bytes": "12694"
},
{
"name": "Erlang",
"bytes": "889"
},
{
"name": "FLUX",
"bytes": "34449"
},
{
"name": "GLSL",
"bytes": "26344"
},
{
"name": "Gnuplot",
"bytes": "710"
},
{
"name": "Groff",
"bytes": "447012"
},
{
"name": "HTML",
"bytes": "43343468"
},
{
"name": "IDL",
"bytes": "1455122"
},
{
"name": "Java",
"bytes": "43261012"
},
{
"name": "JavaScript",
"bytes": "46646658"
},
{
"name": "Lex",
"bytes": "38358"
},
{
"name": "Logos",
"bytes": "21054"
},
{
"name": "Makefile",
"bytes": "2733844"
},
{
"name": "Matlab",
"bytes": "67316"
},
{
"name": "Max",
"bytes": "3698"
},
{
"name": "NSIS",
"bytes": "421625"
},
{
"name": "Objective-C",
"bytes": "877657"
},
{
"name": "Objective-C++",
"bytes": "737713"
},
{
"name": "PHP",
"bytes": "17415"
},
{
"name": "Pascal",
"bytes": "6780"
},
{
"name": "Perl",
"bytes": "1153180"
},
{
"name": "Perl6",
"bytes": "1255"
},
{
"name": "PostScript",
"bytes": "1139"
},
{
"name": "PowerShell",
"bytes": "8252"
},
{
"name": "Protocol Buffer",
"bytes": "26553"
},
{
"name": "Python",
"bytes": "8453201"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3481"
},
{
"name": "Ruby",
"bytes": "5116"
},
{
"name": "Scilab",
"bytes": "7"
},
{
"name": "Shell",
"bytes": "3383832"
},
{
"name": "SourcePawn",
"bytes": "23661"
},
{
"name": "TeX",
"bytes": "879606"
},
{
"name": "WebIDL",
"bytes": "1902"
},
{
"name": "XSLT",
"bytes": "13134"
},
{
"name": "Yacc",
"bytes": "112744"
}
],
"symlink_target": ""
} |
struct nlmsg {
struct nlmsghdr hdr;
union {
struct ifinfomsg ifi;
struct nlmsgerr err;
} msg;
};
#define NLMSG_TAIL(nmsg) \
((struct rtattr *) (((char *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
#define NLMSG_GOOD_SIZE (sizeof(struct nlmsg) * 256)
int nl_open(void);
void nl_send(int sock, struct nlmsg *nlmsg);
void nl_recv(int sock, struct nlmsg *nlmsg);
void rtattr_append(struct nlmsg *nlmsg, int attr, void *d, size_t len);
struct rtattr *rtattr_start_nested(struct nlmsg *nlmsg, int attr);
void rtattr_end_nested(struct nlmsg *nlmsg, struct rtattr *rtattr);
| {
"content_hash": "76ef731d2470efd48e4e2d931e3f8fd2",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 73,
"avg_line_length": 26.217391304347824,
"alnum_prop": 0.6749585406301825,
"repo_name": "ghedo/pflask",
"id": "d953d6a045657a6c57fc6e556ad376ff36f66852",
"size": "2033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/nl.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "156991"
},
{
"name": "Python",
"bytes": "7020"
}
],
"symlink_target": ""
} |
<!--$Id: delete.html 63573 2008-05-23 21:43:21Z trent.nelson $-->
<!--Copyright (c) 1997,2008 Oracle. All rights reserved.-->
<!--See the file LICENSE for redistribution information.-->
<html>
<head>
<title>Berkeley DB Reference Guide: Deleting records</title>
<meta name="description" content="Berkeley DB: An embedded database programmatic toolkit.">
<meta name="keywords" content="embedded,database,programmatic,toolkit,btree,hash,hashing,transaction,transactions,locking,logging,access method,access methods,Java,C,C++">
</head>
<body bgcolor=white>
<a name="2"><!--meow--></a>
<table width="100%"><tr valign=top>
<td><b><dl><dt>Berkeley DB Reference Guide:<dd>Access Methods</dl></b></td>
<td align=right><a href="../am/put.html"><img src="../../images/prev.gif" alt="Prev"></a><a href="../toc.html"><img src="../../images/ref.gif" alt="Ref"></a><a href="../am/stat.html"><img src="../../images/next.gif" alt="Next"></a>
</td></tr></table>
<p align=center><b>Deleting records</b></p>
<p>The <a href="../../api_c/db_del.html">DB->del</a> method deletes records from the database. In general,
<a href="../../api_c/db_del.html">DB->del</a> takes a key and deletes the data item associated with
it from the database.</p>
<p>If the database has been configured to support duplicate records, the
<a href="../../api_c/db_del.html">DB->del</a> method will remove all of the duplicate records. To remove
individual duplicate records, you must use a Berkeley DB cursor interface.</p>
<table width="100%"><tr><td><br></td><td align=right><a href="../am/put.html"><img src="../../images/prev.gif" alt="Prev"></a><a href="../toc.html"><img src="../../images/ref.gif" alt="Ref"></a><a href="../am/stat.html"><img src="../../images/next.gif" alt="Next"></a>
</td></tr></table>
<p><font size=1>Copyright (c) 1996,2008 Oracle. All rights reserved.</font>
</body>
</html>
| {
"content_hash": "ae2824c6b4c96b6e12af8e35dfedac13",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 268,
"avg_line_length": 69.33333333333333,
"alnum_prop": 0.6736111111111112,
"repo_name": "nzavagli/UnrealPy",
"id": "0e8aa67000eb0c371b230563c24710b08095dc35",
"size": "1872",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/db-4.7.25.0/docs/ref/am/delete.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "APL",
"bytes": "587"
},
{
"name": "ASP",
"bytes": "2753"
},
{
"name": "ActionScript",
"bytes": "5686"
},
{
"name": "Ada",
"bytes": "94225"
},
{
"name": "Agda",
"bytes": "3154"
},
{
"name": "Alloy",
"bytes": "6579"
},
{
"name": "ApacheConf",
"bytes": "12482"
},
{
"name": "AppleScript",
"bytes": "421"
},
{
"name": "Assembly",
"bytes": "1093261"
},
{
"name": "AutoHotkey",
"bytes": "3733"
},
{
"name": "AutoIt",
"bytes": "667"
},
{
"name": "Awk",
"bytes": "63276"
},
{
"name": "Batchfile",
"bytes": "147828"
},
{
"name": "BlitzBasic",
"bytes": "185102"
},
{
"name": "BlitzMax",
"bytes": "2387"
},
{
"name": "Boo",
"bytes": "1111"
},
{
"name": "Bro",
"bytes": "7337"
},
{
"name": "C",
"bytes": "108397183"
},
{
"name": "C#",
"bytes": "156749"
},
{
"name": "C++",
"bytes": "13535833"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CMake",
"bytes": "12441"
},
{
"name": "COBOL",
"bytes": "114812"
},
{
"name": "CSS",
"bytes": "430375"
},
{
"name": "Ceylon",
"bytes": "1387"
},
{
"name": "Chapel",
"bytes": "4366"
},
{
"name": "Cirru",
"bytes": "2574"
},
{
"name": "Clean",
"bytes": "9679"
},
{
"name": "Clojure",
"bytes": "23871"
},
{
"name": "CoffeeScript",
"bytes": "20149"
},
{
"name": "ColdFusion",
"bytes": "9006"
},
{
"name": "Common Lisp",
"bytes": "49017"
},
{
"name": "Coq",
"bytes": "66"
},
{
"name": "Cucumber",
"bytes": "390"
},
{
"name": "Cuda",
"bytes": "776"
},
{
"name": "D",
"bytes": "7556"
},
{
"name": "DIGITAL Command Language",
"bytes": "425938"
},
{
"name": "DTrace",
"bytes": "6706"
},
{
"name": "Dart",
"bytes": "591"
},
{
"name": "Dylan",
"bytes": "6343"
},
{
"name": "Ecl",
"bytes": "2599"
},
{
"name": "Eiffel",
"bytes": "2145"
},
{
"name": "Elixir",
"bytes": "4340"
},
{
"name": "Emacs Lisp",
"bytes": "18303"
},
{
"name": "Erlang",
"bytes": "5746"
},
{
"name": "F#",
"bytes": "19156"
},
{
"name": "FORTRAN",
"bytes": "38458"
},
{
"name": "Factor",
"bytes": "10194"
},
{
"name": "Fancy",
"bytes": "2581"
},
{
"name": "Fantom",
"bytes": "25331"
},
{
"name": "GAP",
"bytes": "29880"
},
{
"name": "GLSL",
"bytes": "450"
},
{
"name": "Gnuplot",
"bytes": "11501"
},
{
"name": "Go",
"bytes": "5444"
},
{
"name": "Golo",
"bytes": "1649"
},
{
"name": "Gosu",
"bytes": "2853"
},
{
"name": "Groff",
"bytes": "3458639"
},
{
"name": "Groovy",
"bytes": "2586"
},
{
"name": "HTML",
"bytes": "92126540"
},
{
"name": "Haskell",
"bytes": "49593"
},
{
"name": "Haxe",
"bytes": "16812"
},
{
"name": "Hy",
"bytes": "7237"
},
{
"name": "IDL",
"bytes": "2098"
},
{
"name": "Idris",
"bytes": "2771"
},
{
"name": "Inform 7",
"bytes": "1944"
},
{
"name": "Inno Setup",
"bytes": "18796"
},
{
"name": "Ioke",
"bytes": "469"
},
{
"name": "Isabelle",
"bytes": "21392"
},
{
"name": "Jasmin",
"bytes": "9428"
},
{
"name": "Java",
"bytes": "4040623"
},
{
"name": "JavaScript",
"bytes": "223927"
},
{
"name": "Julia",
"bytes": "27687"
},
{
"name": "KiCad",
"bytes": "475"
},
{
"name": "Kotlin",
"bytes": "971"
},
{
"name": "LSL",
"bytes": "160"
},
{
"name": "Lasso",
"bytes": "18650"
},
{
"name": "Lean",
"bytes": "6921"
},
{
"name": "Limbo",
"bytes": "9891"
},
{
"name": "Liquid",
"bytes": "862"
},
{
"name": "LiveScript",
"bytes": "972"
},
{
"name": "Logos",
"bytes": "19509"
},
{
"name": "Logtalk",
"bytes": "7260"
},
{
"name": "Lua",
"bytes": "8677"
},
{
"name": "Makefile",
"bytes": "2053844"
},
{
"name": "Mask",
"bytes": "815"
},
{
"name": "Mathematica",
"bytes": "191"
},
{
"name": "Max",
"bytes": "296"
},
{
"name": "Modelica",
"bytes": "6213"
},
{
"name": "Modula-2",
"bytes": "23838"
},
{
"name": "Module Management System",
"bytes": "14798"
},
{
"name": "Monkey",
"bytes": "2587"
},
{
"name": "Moocode",
"bytes": "3343"
},
{
"name": "MoonScript",
"bytes": "14862"
},
{
"name": "Myghty",
"bytes": "3939"
},
{
"name": "NSIS",
"bytes": "7663"
},
{
"name": "Nemerle",
"bytes": "1517"
},
{
"name": "NewLisp",
"bytes": "42726"
},
{
"name": "Nimrod",
"bytes": "37191"
},
{
"name": "Nit",
"bytes": "55581"
},
{
"name": "Nix",
"bytes": "2448"
},
{
"name": "OCaml",
"bytes": "42416"
},
{
"name": "Objective-C",
"bytes": "104883"
},
{
"name": "Objective-J",
"bytes": "15340"
},
{
"name": "Opa",
"bytes": "172"
},
{
"name": "OpenEdge ABL",
"bytes": "49943"
},
{
"name": "PAWN",
"bytes": "6555"
},
{
"name": "PHP",
"bytes": "68611"
},
{
"name": "PLSQL",
"bytes": "45772"
},
{
"name": "Pan",
"bytes": "1241"
},
{
"name": "Pascal",
"bytes": "349743"
},
{
"name": "Perl",
"bytes": "5931502"
},
{
"name": "Perl6",
"bytes": "113623"
},
{
"name": "PigLatin",
"bytes": "6657"
},
{
"name": "Pike",
"bytes": "8479"
},
{
"name": "PostScript",
"bytes": "18216"
},
{
"name": "PowerShell",
"bytes": "14236"
},
{
"name": "Prolog",
"bytes": "43750"
},
{
"name": "Protocol Buffer",
"bytes": "3401"
},
{
"name": "Puppet",
"bytes": "130"
},
{
"name": "Python",
"bytes": "122886156"
},
{
"name": "QML",
"bytes": "3912"
},
{
"name": "R",
"bytes": "49247"
},
{
"name": "Racket",
"bytes": "11341"
},
{
"name": "Rebol",
"bytes": "17708"
},
{
"name": "Red",
"bytes": "10536"
},
{
"name": "Redcode",
"bytes": "830"
},
{
"name": "Ruby",
"bytes": "91403"
},
{
"name": "Rust",
"bytes": "6788"
},
{
"name": "SAS",
"bytes": "15603"
},
{
"name": "SaltStack",
"bytes": "1040"
},
{
"name": "Scala",
"bytes": "730"
},
{
"name": "Scheme",
"bytes": "50346"
},
{
"name": "Scilab",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "2925097"
},
{
"name": "ShellSession",
"bytes": "320"
},
{
"name": "Smali",
"bytes": "832"
},
{
"name": "Smalltalk",
"bytes": "158636"
},
{
"name": "Smarty",
"bytes": "523"
},
{
"name": "SourcePawn",
"bytes": "130"
},
{
"name": "Standard ML",
"bytes": "36869"
},
{
"name": "Swift",
"bytes": "2035"
},
{
"name": "SystemVerilog",
"bytes": "265"
},
{
"name": "Tcl",
"bytes": "6077233"
},
{
"name": "TeX",
"bytes": "487999"
},
{
"name": "Tea",
"bytes": "391"
},
{
"name": "TypeScript",
"bytes": "535"
},
{
"name": "VHDL",
"bytes": "4446"
},
{
"name": "VimL",
"bytes": "32053"
},
{
"name": "Visual Basic",
"bytes": "19441"
},
{
"name": "XQuery",
"bytes": "4289"
},
{
"name": "XS",
"bytes": "178055"
},
{
"name": "XSLT",
"bytes": "1995174"
},
{
"name": "Xtend",
"bytes": "727"
},
{
"name": "Yacc",
"bytes": "25665"
},
{
"name": "Zephir",
"bytes": "485"
},
{
"name": "eC",
"bytes": "31545"
},
{
"name": "mupad",
"bytes": "2442"
},
{
"name": "nesC",
"bytes": "23697"
},
{
"name": "xBase",
"bytes": "3349"
}
],
"symlink_target": ""
} |
@interface IRLongPressGestureRecognizerDescriptor : IRTapGestureRecognizerDescriptor
@property (nonatomic) CFTimeInterval minimumPressDuration; // Default is 0.5. Time in seconds the fingers must be held down for the gesture to be recognized
@property (nonatomic) CGFloat allowableMovement; // Default is 10. Maximum movement in pixels allowed before the gesture fails. Once recognized (after minimumPressDuration) there is no limit on finger movement for the remainder of the touch tracking
- (id) initDescriptorWithDictionary:(NSDictionary *)aDictionary;
@end | {
"content_hash": "489ae9c928be3dab22615b2730cbb3cb",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 259,
"avg_line_length": 71.75,
"alnum_prop": 0.8118466898954704,
"repo_name": "infrared-io/infrared_ios",
"id": "d51fe3aa7c48d6a3049188cd801647c3b65951d8",
"size": "761",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "infrared_ios/Library/Components/Views/_GestureRecognizers/LongPressGestureRecognizer/IRLongPressGestureRecognizerDescriptor.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "198928"
},
{
"name": "JavaScript",
"bytes": "54906"
},
{
"name": "Objective-C",
"bytes": "1425231"
},
{
"name": "Ruby",
"bytes": "10742"
}
],
"symlink_target": ""
} |
command -v tox > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo 'This script requires "tox" to run.'
echo 'You can install it with "pip install tox".'
exit 1;
fi
tox -evenv -- $@
| {
"content_hash": "1d920f58fea483a2a93de5a322d3e287",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 53,
"avg_line_length": 23.375,
"alnum_prop": 0.5882352941176471,
"repo_name": "fzhaw/python-monascaclient",
"id": "7633f03b6c88681aa269dfecda4f1aebc93c53b7",
"size": "200",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tools/with_venv.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "194694"
},
{
"name": "Shell",
"bytes": "3386"
}
],
"symlink_target": ""
} |
#include "mbed-drivers/mbed_assert.h"
#include "device.h"
#if DEVICE_STDIO_MESSAGES
#include <stdio.h>
#endif
#include <stdlib.h>
#include "mbed-drivers/mbed_interface.h"
void mbed_assert_internal(const char *expr, const char *file, int line)
{
#if DEVICE_STDIO_MESSAGES
fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line);
#endif
mbed_die();
}
| {
"content_hash": "f529c7f0d7be938d7140e40a743bebd1",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 91,
"avg_line_length": 21.77777777777778,
"alnum_prop": 0.6989795918367347,
"repo_name": "Hydrogencyanide1/hackathon",
"id": "e8aeebb49dc65a8eba8caa9e255294959cb4f1d4",
"size": "1024",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "BLE_ItCounts/yotta_modules/mbed-drivers/source/assert.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "23189"
},
{
"name": "C",
"bytes": "2634884"
},
{
"name": "C++",
"bytes": "1050194"
},
{
"name": "CMake",
"bytes": "268196"
},
{
"name": "CSS",
"bytes": "34286"
},
{
"name": "HTML",
"bytes": "6692"
},
{
"name": "JavaScript",
"bytes": "178720"
},
{
"name": "Python",
"bytes": "4818"
},
{
"name": "Shell",
"bytes": "1993"
}
],
"symlink_target": ""
} |
"use strict";
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _css = _interopRequireDefault(require("../StyleSheet/css"));
var _pick = _interopRequireDefault(require("../../modules/pick"));
var _useElementLayout = _interopRequireDefault(require("../../hooks/useElementLayout"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRequireDefault(require("../../hooks/usePlatformMethods"));
var _useResponderEvents = _interopRequireDefault(require("../../hooks/useResponderEvents"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TextAncestorContext = _interopRequireDefault(require("./TextAncestorContext"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var forwardPropsList = {
accessibilityLabel: true,
accessibilityLiveRegion: true,
accessibilityRole: true,
accessibilityState: true,
accessibilityValue: true,
accessible: true,
children: true,
classList: true,
dir: true,
importantForAccessibility: true,
lang: true,
nativeID: true,
onBlur: true,
onClick: true,
onClickCapture: true,
onContextMenu: true,
onFocus: true,
onKeyDown: true,
onKeyUp: true,
onTouchCancel: true,
onTouchCancelCapture: true,
onTouchEnd: true,
onTouchEndCapture: true,
onTouchMove: true,
onTouchMoveCapture: true,
onTouchStart: true,
onTouchStartCapture: true,
pointerEvents: true,
ref: true,
style: true,
testID: true,
// unstable
dataSet: true,
onMouseDown: true,
onMouseEnter: true,
onMouseLeave: true,
onMouseMove: true,
onMouseOver: true,
onMouseOut: true,
onMouseUp: true,
onScroll: true,
onWheel: true,
href: true,
rel: true,
target: true
};
var pickProps = function pickProps(props) {
return (0, _pick.default)(props, forwardPropsList);
};
var Text = (0, React.forwardRef)(function (props, forwardedRef) {
var dir = props.dir,
numberOfLines = props.numberOfLines,
onClick = props.onClick,
onLayout = props.onLayout,
onPress = props.onPress,
onMoveShouldSetResponder = props.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture,
onResponderEnd = props.onResponderEnd,
onResponderGrant = props.onResponderGrant,
onResponderMove = props.onResponderMove,
onResponderReject = props.onResponderReject,
onResponderRelease = props.onResponderRelease,
onResponderStart = props.onResponderStart,
onResponderTerminate = props.onResponderTerminate,
onResponderTerminationRequest = props.onResponderTerminationRequest,
onScrollShouldSetResponder = props.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = props.onStartShouldSetResponder,
onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture,
selectable = props.selectable;
var hasTextAncestor = (0, React.useContext)(_TextAncestorContext.default);
var hostRef = (0, React.useRef)(null);
var setRef = (0, _useMergeRefs.default)(forwardedRef, hostRef);
var classList = [classes.text, hasTextAncestor === true && classes.textHasAncestor, numberOfLines === 1 && classes.textOneLine, numberOfLines != null && numberOfLines > 1 && classes.textMultiLine];
var style = [props.style, numberOfLines != null && numberOfLines > 1 && {
WebkitLineClamp: numberOfLines
}, selectable === false && styles.notSelectable, onPress && styles.pressable];
(0, _useElementLayout.default)(hostRef, onLayout);
(0, _useResponderEvents.default)(hostRef, {
onMoveShouldSetResponder: onMoveShouldSetResponder,
onMoveShouldSetResponderCapture: onMoveShouldSetResponderCapture,
onResponderEnd: onResponderEnd,
onResponderGrant: onResponderGrant,
onResponderMove: onResponderMove,
onResponderReject: onResponderReject,
onResponderRelease: onResponderRelease,
onResponderStart: onResponderStart,
onResponderTerminate: onResponderTerminate,
onResponderTerminationRequest: onResponderTerminationRequest,
onScrollShouldSetResponder: onScrollShouldSetResponder,
onScrollShouldSetResponderCapture: onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder: onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture: onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder: onStartShouldSetResponder,
onStartShouldSetResponderCapture: onStartShouldSetResponderCapture
});
function handleClick(e) {
if (onClick != null) {
onClick(e);
}
if (onClick == null && onPress != null) {
e.stopPropagation();
onPress(e);
}
}
var component = hasTextAncestor ? 'span' : 'div';
var supportedProps = pickProps(props);
supportedProps.classList = classList;
supportedProps.dir = dir; // 'auto' by default allows browsers to infer writing direction (root elements only)
if (!hasTextAncestor) {
supportedProps.dir = dir != null ? dir : 'auto';
}
supportedProps.onClick = handleClick;
supportedProps.ref = setRef;
supportedProps.style = style;
(0, _usePlatformMethods.default)(hostRef, supportedProps);
var element = (0, _createElement.default)(component, supportedProps);
return hasTextAncestor ? element : React.createElement(_TextAncestorContext.default.Provider, {
value: true
}, element);
});
Text.displayName = 'Text';
var classes = _css.default.create({
text: {
border: '0 solid black',
boxSizing: 'border-box',
color: 'black',
display: 'inline',
font: '14px System',
margin: 0,
padding: 0,
whiteSpace: 'pre-wrap',
wordWrap: 'break-word'
},
textHasAncestor: {
color: 'inherit',
font: 'inherit',
whiteSpace: 'inherit'
},
textOneLine: {
maxWidth: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
},
// See #13
textMultiLine: {
display: '-webkit-box',
maxWidth: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
WebkitBoxOrient: 'vertical'
}
});
var styles = _StyleSheet.default.create({
notSelectable: {
userSelect: 'none'
},
pressable: {
cursor: 'pointer'
}
});
var _default = Text;
exports.default = _default;
module.exports = exports.default; | {
"content_hash": "7dd83624aa75877ef25592efefe17a76",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 743,
"avg_line_length": 36.542857142857144,
"alnum_prop": 0.7268699504821475,
"repo_name": "cdnjs/cdnjs",
"id": "1156f63710c3ebd33b1b8be3fd99941de55ae136",
"size": "7905",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ajax/libs/react-native-web/0.0.0-20f889ecc/cjs/exports/Text/index.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
/// \dir
/// !Purpose
///
/// Definition and functions for using AT91SAM9XE-related features, such
/// has PIO pins, memories, etc.
///
/// !Usage
/// -# The code for booting the board is provided by board_cstartup.S and
/// board_lowlevel.c.
/// -# For using board PIOs, board characteristics (clock, etc.) and external
/// components, see board.h.
/// -# For manipulating memories (remapping, SDRAM, etc.), see board_memories.h.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// \unit
/// !Purpose
///
/// Definition of AT91SAM9XE-EK characteristics, AT91SAM9XE-dependant PIOs and
/// external components interfacing.
///
/// !Usage
/// -# For operating frequency information, see "SAM9XE-EK - Operating frequencies".
/// -# For using portable PIO definitions, see "SAM9XE-EK - PIO definitions".
/// -# Several USB definitions are included here (see "SAM9XE-EK - USB device").
/// -# For external components definitions, see "SAM79260-EK - External components".
/// -# For memory-related definitions, see "SAM79260-EK - Memories".
//------------------------------------------------------------------------------
#ifndef BOARD_H
#define BOARD_H
//------------------------------------------------------------------------------
// Headers
//------------------------------------------------------------------------------
#if defined(at91sam9xe128)
#include "at91sam9xe128/AT91SAM9XE128.h"
#elif defined(at91sam9xe256)
#include "at91sam9xe256/AT91SAM9XE256.h"
#elif defined(at91sam9xe512)
#include "at91sam9xe512/AT91SAM9XE512.h"
#else
#error Board does not support the specified chip.
#endif
//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// \page "SAM9XE-EK - Board Description"
/// This page lists several definition related to the board description.
///
/// !Definitions
/// - BOARD_NAME
/// Name of the board.
#define BOARD_NAME "AT91SAM9XE-EK"
/// Board definition.
#define at91sam9xeek
/// Family definition.
#define at91sam9xe
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// \page "SAM9XE-EK - Operating frequencies"
/// This page lists several definition related to the board operating frequency
/// (when using the initialization done by board_lowlevel.c).
///
/// !Definitions
/// - BOARD_MAINOSC
/// - BOARD_MCK
/// Frequency of the board main oscillator.
#define BOARD_MAINOSC 18432000
/// Master clock frequency (when using board_lowlevel.c).
#define BOARD_MCK ((18432000 * 97 / 9) / 2)
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// \page "SAM9XE-EK - USB device"
/// This page lists constants describing several characteristics (controller
/// type, D+ pull-up type, etc.) of the USB device controller of the chip/board.
///
/// !Constants
/// - BOARD_USB_UDP
/// - BOARD_USB_PULLUP_INTERNAL
/// - BOARD_USB_NUMENDPOINTS
/// - BOARD_USB_ENDPOINTS_MAXPACKETSIZE
/// - BOARD_USB_ENDPOINTS_BANKS
/// - BOARD_USB_BMATTRIBUTES
/// Chip has a UDP controller.
#define BOARD_USB_UDP
/// Indicates the D+ pull-up is internal to the USB controller.
#define BOARD_USB_PULLUP_INTERNAL
/// Number of endpoints in the USB controller.
#define BOARD_USB_NUMENDPOINTS 6
/// Returns the maximum packet size of the given endpoint.
#define BOARD_USB_ENDPOINTS_MAXPACKETSIZE(i) ((i >= 4) ? 512 : 64)
#define BOARD_USB_ENDPOINTS_MAXPACKETSIZE_FS 64
/// Returns the number of FIFO banks for the given endpoint.
#define BOARD_USB_ENDPOINTS_BANKS(i) (((i == 0) || (i == 3)) ? 1 : 2)
/// USB attributes configuration descriptor (bus or self powered, remote wakeup)
#define BOARD_USB_BMATTRIBUTES USBConfigurationDescriptor_SELFPOWERED_NORWAKEUP
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// \page "SAM9XE-EK - PIO definitions"
/// This pages lists all the pio definitions contained in board.h. The constants
/// are named using the following convention: PIN_* for a constant which defines
/// a single Pin instance (but may include several PIOs sharing the same
/// controller), and PINS_* for a list of Pin instances.
///
/// !DBGU
/// - PINS_DBGU
///
/// !LEDs
/// - PIN_LED_0
/// - PIN_LED_1
/// - PINS_LEDS
/// - LED_POWER
/// - LED_DS1
///
/// !Push buttons
/// - PIN_PUSHBUTTON_1
/// - PIN_PUSHBUTTON_2
/// - PINS_PUSHBUTTONS
/// - PUSHBUTTON_BP1
/// - PUSHBUTTON_BP2
///
/// !USART0
/// - PIN_USART0_RXD
/// - PIN_USART0_TXD
/// - PIN_USART0_SCK
///
/// !SPI0
/// - PIN_SPI0_MISO
/// - PIN_SPI0_MOSI
/// - PIN_SPI0_SPCK
/// - PINS_SPI0
/// - PIN_SPI0_NPCS0
/// - PIN_SPI0_NPCS1
///
/// !SSC
/// - PINS_SSC_TX
///
/// !USB
/// - PIN_USB_VBUS
///
/// !MCI
/// - PINS_MCI
///
/// !TWI0
/// - PINS_TWI0
/// List of all DBGU pin definitions.
#define PINS_DBGU {(1<<14) | (1<<15), AT91C_BASE_PIOB, AT91C_ID_PIOB, PIO_PERIPH_A, PIO_DEFAULT}
/// LED #0 pin definition.
#define PIN_LED_0 {1 << 9, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_OUTPUT_0, PIO_DEFAULT}
/// LED #1 pin definition.
#define PIN_LED_1 {1 << 6, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_OUTPUT_1, PIO_DEFAULT}
/// List of all LED definitions.
#define PINS_LEDS PIN_LED_0, PIN_LED_1
/// Power LED index.
#define LED_POWER 0
/// DS1 LED index.
#define LED_DS1 1
/// Push button #1 pin definition.
#define PIN_PUSHBUTTON_1 {1 << 30, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_INPUT, PIO_PULLUP}
/// Pusb button #2 pin definition.
#define PIN_PUSHBUTTON_2 {1UL << 31, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_INPUT, PIO_PULLUP}
/// List of all pushbutton pin definitions.
#define PINS_PUSHBUTTONS PIN_PUSHBUTTON_1, PIN_PUSHBUTTON_2
/// Push button #1 index.
#define PUSHBUTTON_BP1 0
/// Push button #2 index.
#define PUSHBUTTON_BP2 1
/// USART0 TXD pin definition.
#define PIN_USART0_TXD {1 << 4, AT91C_BASE_PIOB, AT91C_ID_PIOB, PIO_PERIPH_A, PIO_DEFAULT}
/// USART0 RXD pin definition.
#define PIN_USART0_RXD {1 << 5, AT91C_BASE_PIOB, AT91C_ID_PIOB, PIO_PERIPH_A, PIO_DEFAULT}
/// USART0 RTS pin definition.
#define PIN_USART0_RTS {1 << 26, AT91C_BASE_PIOB, AT91C_ID_PIOB, PIO_PERIPH_A, PIO_DEFAULT}
/// USART0 CTS pin definition.
#define PIN_USART0_CTS {1 << 27, AT91C_BASE_PIOB, AT91C_ID_PIOB, PIO_PERIPH_A, PIO_DEFAULT}
/// USART0 SCK pin definition.
#define PIN_USART0_SCK {1UL << 31, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
/// SPI0 MISO pin definition.
#define PIN_SPI0_MISO {1 << 0, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_PULLUP}
/// SPI0 MOSI pin definition.
#define PIN_SPI0_MOSI {1 << 1, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
/// SPI0 SPCK pin definition.
#define PIN_SPI0_SPCK {1 << 2, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
/// List of SPI0 pin definitions (MISO, MOSI & SPCK).
#define PINS_SPI0 PIN_SPI0_MISO, PIN_SPI0_MOSI, PIN_SPI0_SPCK
/// SPI0 chip select 0 pin definition.
#define PIN_SPI0_NPCS0 {AT91C_PA3_SPI0_NPCS0, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
/// SPI0 chip select 1 pin definition.
#define PIN_SPI0_NPCS1 {AT91C_PC11_SPI0_NPCS1, AT91C_BASE_PIOC, AT91C_ID_PIOC, PIO_PERIPH_B, PIO_DEFAULT}
/// SSC transmitter pins definition.
#define PINS_SSC_TX {0x00038000, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
/// USB VBus monitoring pin definition.
#define PIN_USB_VBUS {1 << 5, AT91C_BASE_PIOC, AT91C_ID_PIOC, PIO_INPUT, PIO_DEFAULT}
/// List of MCI pins definitions.
#define PINS_MCI {0x0000003B, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_B, PIO_DEFAULT}, \
{1 << 8, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
/// TWI0 pins definition.
#define PINS_TWI0 {0x01800000, AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// \page "SAM9XE-EK - External components"
/// This page lists the definitions related to external on-board components
/// located in the board.h file for the AT91SAM9XE-EK.
///
/// !AT45 Dataflash Card (A)
/// - BOARD_AT45_A_SPI_BASE
/// - BOARD_AT45_A_SPI_ID
/// - BOARD_AT45_A_SPI_PINS
/// - BOARD_AT45_A_SPI
/// - BOARD_AT45_A_NPCS
/// - BOARD_AT45_A_NPCS_PIN
///
/// !AT45 Dataflash (B)
/// - BOARD_AT45_B_SPI_BASE
/// - BOARD_AT45_B_SPI_ID
/// - BOARD_AT45_B_SPI_PINS
/// - BOARD_AT45_B_SPI
/// - BOARD_AT45_B_NPCS
/// - BOARD_AT45_B_NPCS_PIN
///
/// !SD Card
/// - BOARD_SD_MCI_BASE
/// - BOARD_SD_MCI_ID
/// - BOARD_SD_PINS
/// - BOARD_SD_SLOT
///
///
/// !EMAC
/// - AT91C_BASE_EMAC
/// - BOARD_EMAC_POWER_ALWAYS_ON
/// - BOARD_EMAC_MODE_RMII
/// - BOARD_EMAC_PINS
/// - BOARD_EMAC_PIN_TEST
/// - BOARD_EMAC_PIN_RPTR
/// - BOARD_EMAC_RST_PINS
/// - BOARD_EMAC_RUN_PINS
/// Base address of SPI peripheral connected to the dataflash.
#define BOARD_AT45_A_SPI_BASE AT91C_BASE_SPI0
/// Identifier of SPI peripheral connected to the dataflash.
#define BOARD_AT45_A_SPI_ID AT91C_ID_SPI0
/// Pins of the SPI peripheral connected to the dataflash.
#define BOARD_AT45_A_SPI_PINS PINS_SPI0
/// Dataflahs SPI number.
#define BOARD_AT45_A_SPI 0
/// Chip select connected to the dataflash.
#define BOARD_AT45_A_NPCS 0
/// Chip select pin connected to the dataflash.
#define BOARD_AT45_A_NPCS_PIN PIN_SPI0_NPCS0
/// Base address of SPI peripheral connected to the dataflash.
#define BOARD_AT45_B_SPI_BASE AT91C_BASE_SPI0
/// Identifier of SPI peripheral connected to the dataflash.
#define BOARD_AT45_B_SPI_ID AT91C_ID_SPI0
/// Pins of the SPI peripheral connected to the dataflash.
#define BOARD_AT45_B_SPI_PINS PINS_SPI0
/// Dataflahs SPI number.
#define BOARD_AT45_B_SPI 0
/// Chip select connected to the dataflash.
#define BOARD_AT45_B_NPCS 1
/// Chip select pin connected to the dataflash.
#define BOARD_AT45_B_NPCS_PIN PIN_SPI0_NPCS1
/// Base address of SPI peripheral connected to the serialflash.
#define BOARD_AT26_A_SPI_BASE AT91C_BASE_SPI0
/// Identifier of SPI peripheral connected to the dataflash.
#define BOARD_AT26_A_SPI_ID AT91C_ID_SPI0
/// Pins of the SPI peripheral connected to the dataflash.
#define BOARD_AT26_A_SPI_PINS PINS_SPI0
/// Dataflahs SPI number.
#define BOARD_AT26_A_SPI 0
/// Chip select connected to the dataflash.
#define BOARD_AT26_A_NPCS 0
/// Chip select pin connected to the dataflash.
#define BOARD_AT26_A_NPCS_PIN PIN_SPI0_NPCS0
/// Base address of the MCI peripheral connected to the SD card.
#define BOARD_SD_MCI_BASE AT91C_BASE_MCI
/// Peripheral identifier of the MCI connected to the SD card.
#define BOARD_SD_MCI_ID AT91C_ID_MCI
/// MCI pins that shall be configured to access the SD card.
#define BOARD_SD_PINS PINS_MCI
/// MCI slot to which the SD card is connected to.
#define BOARD_SD_SLOT MCI_SD_SLOTB
/// Board EMAC base address
#if !defined(AT91C_BASE_EMAC) && defined(AT91C_BASE_EMACB)
#define AT91C_BASE_EMAC AT91C_BASE_EMACB
#endif
/// Board EMAC power control - ALWAYS ON
#define BOARD_EMAC_POWER_ALWAYS_ON
/// Board EMAC work mode - RMII/MII ( 1 / 0 )
#define BOARD_EMAC_MODE_RMII 1
/// The PIN list of PIO for EMAC
#define BOARD_EMAC_PINS { ((1<<19)|(1<<13)|(1<<12)|(1<<16)|(1<<15)|(1<<14)\
|(1<<17)|(1<<18)|(1<<20)|(1<<21)|(1<<7)),\
AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT},\
{ ((1<<11)|(1<<10)|(1<<26)|(1<<25)|(1<<27)|(1<<22)\
|(1<<29)|(1<<28)),\
AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_PERIPH_B, PIO_DEFAULT}
/// The power up reset latch PIO for PHY
#define BOARD_EMAC_PIN_TEST {(1<<17), AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_OUTPUT_0, PIO_DEFAULT}
//#define BOARD_EMAC_PIN_RMII : connected to 3v3 (RMII)
// We force the address
// (1<<14) PHY address 0, (1<<15) PHY address 1 (PIO A, perih A)
// (1<<25) PHY address 2, (1<<26) PHY address 3 (PIO A, perih B)
#define BOARD_EMAC_PINS_PHYAD { ((1<<14)|(1<<15)),\
AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_OUTPUT_0, PIO_DEFAULT},\
{ ((1<<25)|(1<<26)),\
AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_OUTPUT_1, PIO_DEFAULT}
//#define BOARD_EMAC_PIN_10BT : not connected
#define BOARD_EMAC_PIN_RPTR {(1<<27), AT91C_BASE_PIOA, AT91C_ID_PIOA, PIO_OUTPUT_0, PIO_DEFAULT}
/// The PIN Configure list for EMAC on power up reset
#define BOARD_EMAC_RST_PINS BOARD_EMAC_PINS_PHYAD,\
BOARD_EMAC_PIN_TEST,\
BOARD_EMAC_PIN_RPTR
/// The runtime pin configure list for EMAC
#define BOARD_EMAC_RUN_PINS BOARD_EMAC_PINS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// \page "SAM9XE-EK - Memories"
/// This page lists definitions related to external on-board memories.
///
/// !Embedded Flash
/// - BOARD_FLASH_EEFC
///
/// !SDRAM
/// - BOARD_SDRAM_SIZE
/// - PINS_SDRAM
///
/// !Nandflash
/// - PINS_NANDFLASH
/// - BOARD_NF_COMMAND_ADDR
/// - BOARD_NF_ADDRESS_ADDR
/// - BOARD_NF_DATA_ADDR
/// - BOARD_NF_CE_PIN
/// - BOARD_NF_RB_PIN
/// Indicates chip has an Enhanced EFC.
#define BOARD_FLASH_EEFC
/// Address of the IAP function in ROM.
#define BOARD_FLASH_IAP_ADDRESS 0x100008
/// Board SDRAM size
#define BOARD_SDRAM_SIZE 0x02000000
/// List of all SDRAM pins definitions.
#define PINS_SDRAM {0xFFFF0000, AT91C_BASE_PIOC, AT91C_ID_PIOC, PIO_PERIPH_A, PIO_DEFAULT}
/// Nandflash controller peripheral pins definition.
#define PINS_NANDFLASH BOARD_NF_CE_PIN, BOARD_NF_RB_PIN
/// Nandflash chip enable pin definition.
#define BOARD_NF_CE_PIN {1 << 14, AT91C_BASE_PIOC, AT91C_ID_PIOC, PIO_OUTPUT_1, PIO_DEFAULT}
/// Nandflash ready/busy pin definition.
#define BOARD_NF_RB_PIN {1 << 13, AT91C_BASE_PIOC, AT91C_ID_PIOC, PIO_INPUT, PIO_PULLUP}
/// Address for transferring command bytes to the nandflash.
#define BOARD_NF_COMMAND_ADDR 0x40400000
/// Address for transferring address bytes to the nandflash.
#define BOARD_NF_ADDRESS_ADDR 0x40200000
/// Address for transferring data bytes to the nandflash.
#define BOARD_NF_DATA_ADDR 0x40000000
/// Address for transferring command bytes to the norflash.
#define BOARD_NORFLASH_ADDR 0x10000000
//------------------------------------------------------------------------------
#endif //#ifndef BOARD_H
| {
"content_hash": "f59faae25f8ffe11beabf2e5697e9341",
"timestamp": "",
"source": "github",
"line_count": 401,
"max_line_length": 105,
"avg_line_length": 38.18952618453865,
"alnum_prop": 0.5899830220713073,
"repo_name": "Beck-Sisyphus/EE472",
"id": "572286eb681f5a1ca071cdc193a80275dd655699",
"size": "16853",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "Lab5/Demo/Common/drivers/Atmel/at91lib/boards/at91sam9xe-ek/board.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "147529"
},
{
"name": "Batchfile",
"bytes": "13560"
},
{
"name": "C",
"bytes": "12896789"
},
{
"name": "C++",
"bytes": "3456953"
},
{
"name": "CSS",
"bytes": "6540"
},
{
"name": "HTML",
"bytes": "232939"
},
{
"name": "Makefile",
"bytes": "1003"
},
{
"name": "Objective-C",
"bytes": "38040"
},
{
"name": "Perl",
"bytes": "9735"
},
{
"name": "PureBasic",
"bytes": "10708"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.google.storage.unit;
import java.io.File;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.google.storage.GoogleCloudStorageConstants;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ConsumerDownloadLocalTest extends GoogleCloudStorageBaseTest {
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@EndpointInject("mock:consumedObjects")
private MockEndpoint consumedObjects;
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
String endpoint = "google-storage://myCamelBucket?autoCreateBucket=true";
from("direct:putObject")
.startupOrder(1)
.to(endpoint)
.to("mock:result");
from("google-storage://myCamelBucket?"
+ "moveAfterRead=true"
+ "&destinationBucket=camelDestinationBucket"
+ "&autoCreateBucket=true"
+ "&deleteAfterRead=true"
+ "&includeBody=true"
+ "&downloadFileName=target")
.startupOrder(2)
//.log("consuming: ${header.CamelGoogleCloudStorageBucketName}/${header.CamelGoogleCloudStorageObjectName}, body=${body}")
.to("mock:consumedObjects");
}
};
}
@Test
public void sendIn() throws Exception {
final int numberOfFiles = 3;
result.expectedMessageCount(numberOfFiles);
consumedObjects.expectedMessageCount(numberOfFiles);
for (int i = 0; i < numberOfFiles; i++) {
final String filename = String.format("file_%s.txt", i);
final String body = String.format("body_%s", i);
//upload a file
template.send("direct:putObject", exchange -> {
exchange.getIn().setHeader(GoogleCloudStorageConstants.OBJECT_NAME, filename);
exchange.getIn().setBody(body);
});
}
assertMockEndpointsSatisfied();
context.stop();
// there should be downloaded files
Assertions.assertTrue(new File("target/file_0.txt").exists());
Assertions.assertTrue(new File("target/file_1.txt").exists());
Assertions.assertTrue(new File("target/file_2.txt").exists());
}
}
| {
"content_hash": "d25eccb8a69a48c11b6b44303cc21ba0",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 151,
"avg_line_length": 34.333333333333336,
"alnum_prop": 0.6098525710176196,
"repo_name": "pax95/camel",
"id": "d3343eab2d22daa23c9e7e05a25256ecc52927fe",
"size": "3583",
"binary": false,
"copies": "1",
"ref": "refs/heads/CAMEL-17322",
"path": "components/camel-google/camel-google-storage/src/test/java/org/apache/camel/component/google/storage/unit/ConsumerDownloadLocalTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1518"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "54390"
},
{
"name": "HTML",
"bytes": "190919"
},
{
"name": "Java",
"bytes": "68575773"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "PLSQL",
"bytes": "1419"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323702"
},
{
"name": "Shell",
"bytes": "17107"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "284638"
}
],
"symlink_target": ""
} |
**WARNING:** Currently unmaintained because of lack of interest, activity and resources
React component for the expanding and collapsing of the blocks.
Supports both vertical and horizontal mode.
## Usage
```javascript
<Title onClick={toggle} />
<AnimakitExpander expanded={this.state.expanded}>
<Text />
</AnimakitExpander>
```
## [Demo](https://animakit.github.io/#/expander)
## Installation
```
npm install animakit-expander
```
## Properties
| Property | Required | Type | Default Value | Available Values | Description |
| ----- | ----- | ----- | ----- | ----- | ----- |
| expanded | true | bool | `false` | `true`, `false` | State of the component: expanded or collapsed |
| horizontal | false | bool | `false` | `true`, `false` | If true, component will expand in horizontal direction |
| align | false | string | | `top`, `bottom` for the default direction or `left`, `right` for the horizontal direction | Align of the content during the animation |
| duration | false | number | `500` | Any integer number | Duration of animation |
| durationPerPx | false | number | `0` | Any integer number | Duration of animation per pixel. Use it if you want the duration depended on the size and calculated dynamically. |
| easing | false | string | `ease-out` | Any [easing function](http://easings.net/) | Easing function of animation |
## Origin
Part of Animakit.
See https://animakit.github.io for more details.
<a href="https://evilmartians.com/?utm_source=animakit">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="Sponsored by Evil Martians" width="236" height="54">
</a>
| {
"content_hash": "ed54ab1318cf046e8d60a2d2b5d5b480",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 177,
"avg_line_length": 37.15909090909091,
"alnum_prop": 0.691743119266055,
"repo_name": "animakit/animakit-expander",
"id": "5f291d849636d3f3e54eb010eafa4087d2c93365",
"size": "1655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "8351"
}
],
"symlink_target": ""
} |
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "{{%irb_research_type}}".
*
* @property integer $id
* @property string $abbr
* @property string $name
* @property string $status
*/
class ResearchType extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%irb_research_type}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['status'], 'string'],
[['abbr'], 'string', 'max' => 100],
[['name'], 'string', 'max' => 256]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'abbr' => Yii::t('app', 'Abbr'),
'name' => Yii::t('app', 'Name'),
'status' => Yii::t('app', 'Status'),
];
}
/**
* @inheritdoc
* @return \common\models\query\ResearchTypeQuery the active query used by this AR class.
*/
public static function find()
{
return new \common\models\query\ResearchTypeQuery(get_called_class());
}
}
| {
"content_hash": "bca17ff8917be4ea6791ab822aa29ed4",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 93,
"avg_line_length": 20.43103448275862,
"alnum_prop": 0.49957805907173,
"repo_name": "khonkaen-hospital/KIRB",
"id": "6ae765f7a5751fb8662c246af60e62d6f35d93bf",
"size": "1185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/models/ResearchType.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "387"
},
{
"name": "Batchfile",
"bytes": "2069"
},
{
"name": "CSS",
"bytes": "708234"
},
{
"name": "HTML",
"bytes": "69220"
},
{
"name": "JavaScript",
"bytes": "1626675"
},
{
"name": "PHP",
"bytes": "609247"
},
{
"name": "Shell",
"bytes": "2683"
}
],
"symlink_target": ""
} |
package arun.hadoop.wordcount;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
// Record Reader for reading PDF file one file at a time
public class PDFRecordReader extends RecordReader<LongWritable, Text>{
private PDDocument pdfDoc;
private PDFTextStripper pdfStripper;
private int totalPages;
private int currentPage;
private LongWritable key;
private Text value;
private InputStream in;
@Override
public void initialize(InputSplit input, TaskAttemptContext context) throws IOException, InterruptedException {
// Open InputStream from input split
FileSplit split = (FileSplit) input;
Configuration job = context.getConfiguration();
final Path file = split.getPath();
final FileSystem fs = file.getFileSystem(job);
in = fs.open(file);
// Create PDF Doc from input stream
this.pdfStripper = new PDFTextStripper();
this.pdfDoc = PDDocument.load(in);
this.totalPages = pdfDoc.getNumberOfPages();
if(this.totalPages>-1)
this.currentPage = 0;
else
this.currentPage = -1;
}
// read next page from PDF and assign it to next (Key,Value) pair
private boolean readNextPage() {
try
{
System.out.println("Reading Page: " + this.currentPage);
// If pages exist and not last page
if(this.currentPage>-1 && this.currentPage<this.totalPages)
{
pdfStripper.setStartPage(this.currentPage);
pdfStripper.setEndPage(this.currentPage);
String parsedText = pdfStripper.getText(this.pdfDoc);
key = new LongWritable(this.currentPage);
value = new Text(parsedText);
this.currentPage++;
return true;
}
else // no more pages exists
{
key = null;
value = null;
return false;
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
return false;
}
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
return readNextPage();
}
@Override
public LongWritable getCurrentKey() throws IOException, InterruptedException {
return key;
}
@Override
public Text getCurrentValue() throws IOException, InterruptedException {
return value;
}
@Override
public float getProgress() throws IOException, InterruptedException {
return (this.currentPage/this.totalPages);
}
@Override
public void close() throws IOException {
this.pdfDoc.close();
this.in.close();
}
}
| {
"content_hash": "80e2a41e4ae2eac04e378ccffa7be20d",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 112,
"avg_line_length": 26.216216216216218,
"alnum_prop": 0.7254295532646048,
"repo_name": "arun-amalolbhavan/Hadoop-WordCount-PDF",
"id": "6e044b8be851cd35cd53f0d895e71339d5665237",
"size": "2910",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/arun/hadoop/wordcount/PDFRecordReader.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "6941"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<config>
<modules>
<Dabio_SingleShipping>
<version>1.0.0</version>
</Dabio_SingleShipping>
</modules>
<global>
<blocks>
<dabio_singleshipping>
<class>Dabio_SingleShipping_Block</class>
</dabio_singleshipping>
</blocks>
<helpers>
<dabio_singleshipping>
<class>Dabio_SingleShipping_Helper</class>
</dabio_singleshipping>
</helpers>
<models>
<dabio_singleshipping>
<class>Dabio_SingleShipping_Model</class>
</dabio_singleshipping>
</models>
</global>
<frontend>
<events>
<checkout_cart_save_before>
<observers>
<dabio_singleshipping_model_observer>
<type>singleton</type>
<class>Dabio_SingleShipping_Model_Observer</class>
<method>applySingleShippingMethod</method>
</dabio_singleshipping_model_observer>
</observers>
</checkout_cart_save_before>
</events>
<layout>
<updates>
<dabio_singleshipping>
<file>dabio_singleshipping.xml</file>
</dabio_singleshipping>
</updates>
</layout>
</frontend>
<adminhtml>
<translate>
<modules>
<Dabio_SingleShipping>
<files>
<default>Dabio_SingleShipping.csv</default>
</files>
</Dabio_SingleShipping>
</modules>
</translate>
</adminhtml>
<default>
<shipping>
<singleshipping>
<hide_shipping>0</hide_shipping>
</singleshipping>
</shipping>
</default>
</config>
| {
"content_hash": "bba1a13e54fbe7dbb0b7269719672c37",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 74,
"avg_line_length": 30.444444444444443,
"alnum_prop": 0.4801876955161627,
"repo_name": "dabio/magento-singleshipping",
"id": "bda3c3f4e1c2a5fa87f0bee6d42805cf36347c9d",
"size": "1918",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/code/community/Dabio/SingleShipping/etc/config.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "2087"
}
],
"symlink_target": ""
} |
<?php
// great
if ($expr1) {
// if body
} elseif ($expr2) {
// elseif body
} else {
// else body;
}
// terrific
foreach ($iterable as $key => $value) {
// foreach body
}
// superb
switch ($expr) {
case 0:
echo 'First case, with a break';
break;
case 1:
echo 'Second case, which falls through';
// no break
case 2:
case 3:
case 4:
echo 'Third case, return instead of break';
return;
default:
echo 'Default case';
break;
}
| {
"content_hash": "9b71b7d0a111f870323d53103daf4160",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 47,
"avg_line_length": 14.029411764705882,
"alnum_prop": 0.5681341719077568,
"repo_name": "PixelUnion/code-guide",
"id": "7c433de1796ad7c0ab5837b8ad2139f03e9f7864",
"size": "477",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_includes/php-apps/control-structures.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13331"
},
{
"name": "CoffeeScript",
"bytes": "1803"
},
{
"name": "HTML",
"bytes": "85808"
},
{
"name": "JavaScript",
"bytes": "11850"
},
{
"name": "Liquid",
"bytes": "1198"
},
{
"name": "PHP",
"bytes": "4632"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arbor.view;
import arbor.util.ArborVector;
/**
*
* @author Alexander Ramsay-Baggs
*/
public class Camera {
public static Camera main = new Camera();
private Camera() {
};
private ArborVector position = new ArborVector();
private float scale = 1f;
public ArborVector getPosition(){
return position;
}
public void setPosition(ArborVector newPosition) {
position = newPosition;
}
public void translate(ArborVector translate) {
position.x += translate.x;
position.y += translate.y;
}
public void setScale(float newScale) {
scale = newScale;
}
public void shiftScale(float scaleShift) {
scale += scaleShift;
}
public float getScale() {
return scale;
}
}
| {
"content_hash": "f167f9f15408352063a9f3a27d6dbd76",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 79,
"avg_line_length": 20.583333333333332,
"alnum_prop": 0.6376518218623481,
"repo_name": "ArborGames/Arbortechture",
"id": "019495951eca15eb626a85709e9a6253d9a2ed8d",
"size": "988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "view/Camera.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "25682"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CharacterBehaviour : PlayerBase{
[SerializeField] private GameObject AreaCheckHitBox;
[SerializeField] private HitboxElement AttackHitbox;
void Update()
{
if (Alive() == true)
{
if (attack() == "Light")
{
animator.PlayAnimation("Punch");
Hit(0.5f, 10, HitPosition.TOP);
}
else if (attack() == "Heavy")
{
animator.PlayAnimation("Kick");
Hit(0.5f, 10, HitPosition.TOP);
}
LookAtOpponent();
BasicMovement();
}
}
void Hit(float Lifetime,float Damage,HitPosition HitArea)
{
AttackHitbox.hitboxClass.hitArea = HitArea;
AttackHitbox.hitboxClass.damage = Damage;
AttackHitbox.hitboxClass.lifetime = Lifetime;
AttackHitbox.objectGameObject.SetActive(true);
}
}
| {
"content_hash": "6d25a81f811fc3eb461b217fb3e41454",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 61,
"avg_line_length": 27.243243243243242,
"alnum_prop": 0.5674603174603174,
"repo_name": "Chanisco/BeatThemUp",
"id": "ca734e6f32c128829e0b315a0f3ac80d5a0e63e9",
"size": "1010",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/Character/CharacterBehaviour.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "892174"
},
{
"name": "GLSL",
"bytes": "153275"
}
],
"symlink_target": ""
} |
var mtd = require('mt-downloader');
var fs = require('fs');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Download = function() {
EventEmitter.call(this);
this._reset();
this.url = '';
this.filePath = '';
this.options = {};
this.meta = {};
this._retryOptions = {
_nbRetries: 0,
maxRetries: 5,
retryInterval: 5000
};
};
util.inherits(Download, EventEmitter);
Download.prototype._reset = function(first_argument) {
this.status = 0; // -3 = destroyed, -2 = stopped, -1 = error, 0 = not started, 1 = started (downloading), 2 = error, retrying, 3 = finished
this.error = '';
this.stats = {
time: {
start: 0,
end: 0
},
total: {
size: 0,
downloaded: 0,
completed: 0
},
past: {
downloaded: 0
},
present: {
downloaded: 0,
time: 0,
speed: 0
},
future: {
remaining: 0,
eta: 0
},
threadStatus: {
idle: 0,
open: 0,
closed: 0,
failed: 0
}
};
};
Download.prototype.setUrl = function(url) {
this.url = url;
return this;
};
Download.prototype.setFilePath = function(filePath) {
this.filePath = filePath;
return this;
};
Download.prototype.setOptions = function(options) {
if(!options || options == {}) {
return this.options = {};
}
// The "options" object will be directly passed to mt-downloader, so we need to conform to his format
//To set the total number of download threads
this.options.count = options.threadsCount || options.count || 2;
//HTTP method
this.options.method = options.method || 'GET';
//HTTP port
this.options.port = options.port || 80;
//If no data is received the download times out. It is measured in seconds.
this.options.timeout = options.timeout/1000 || 5;
//Control the part of file that needs to be downloaded.
this.options.range = options.range || '0-100';
// Support customized header fields
this.options.headers = options.headers || {};
return this;
};
Download.prototype.setRetryOptions = function(options) {
this._retryOptions.maxRetries = options.maxRetries || 5;
this._retryOptions.retryInterval = options.retryInterval || 2000;
return this;
};
Download.prototype.setMeta = function(meta) {
this.meta = meta;
return this;
};
Download.prototype.setStatus = function(status) {
this.status = status;
return this;
};
Download.prototype.setError = function(error) {
this.error = error;
return this;
};
Download.prototype._computeDownloaded = function() {
if(!this.meta.threads) { return 0; }
var downloaded = 0;
this.meta.threads.forEach(function(thread) {
downloaded += thread.position - thread.start;
});
return downloaded;
};
// Should be called on start, set the start timestamp (in seconds)
Download.prototype._computeStartTime = function() {
this.stats.time.start = Math.floor(Date.now() / 1000);
};
// Should be called on end, set the end timestamp (in seconds)
Download.prototype._computeEndTime = function() {
this.stats.time.end = Math.floor(Date.now() / 1000);
};
// Should be called on start, count size already downloaded (eg. resumed download)
Download.prototype._computePastDownloaded = function() {
this.stats.past.downloaded = this._computeDownloaded();
};
// Should be called on start compute total size
Download.prototype._computeTotalSize = function() {
var threads = this.meta.threads;
if(!threads) { return 0; }
this.stats.total.size = threads[threads.length-1].end - threads[0].start;
};
Download.prototype._computeStats = function() {
this._computeTotalSize();
this._computeTotalDownloaded();
this._computePresentDownloaded();
this._computeTotalCompleted();
this._computeFutureRemaining();
// Only compute those stats when downloading
if(this.status == 1) {
this._computePresentTime();
this._computePresentSpeed();
this._computeFutureEta();
this._computeThreadStatus();
}
};
Download.prototype._computePresentTime = function() {
this.stats.present.time = Math.floor(Date.now() / 1000) - this.stats.time.start;
};
Download.prototype._computeTotalDownloaded = function() {
this.stats.total.downloaded = this._computeDownloaded();
};
Download.prototype._computePresentDownloaded = function() {
this.stats.present.downloaded = this.stats.total.downloaded - this.stats.past.downloaded;
};
Download.prototype._computeTotalCompleted = function() {
this.stats.total.completed = Math.floor((this.stats.total.downloaded) * 1000 / this.stats.total.size) / 10;
};
Download.prototype._computeFutureRemaining = function() {
this.stats.future.remaining = this.stats.total.size - this.stats.total.downloaded;
};
Download.prototype._computePresentSpeed = function() {
this.stats.present.speed = this.stats.present.downloaded / this.stats.present.time;
};
Download.prototype._computeFutureEta = function() {
this.stats.future.eta = this.stats.future.remaining / this.stats.present.speed;
};
Download.prototype._computeThreadStatus = function() {
var self = this;
this.stats.threadStatus = {
idle: 0,
open: 0,
closed: 0,
failed: 0
};
this.meta.threads.forEach(function(thread) {
self.stats.threadStatus[thread.connection]++;
});
};
Download.prototype.getStats = function() {
if(!this.meta.threads) {
return this.stats;
}
this._computeStats();
return this.stats;
};
Download.prototype._destroyThreads = function() {
if(this.meta.threads) {
this.meta.threads.forEach(function(i){
if(i.destroy) {
i.destroy();
}
});
}
};
Download.prototype.stop = function() {
this.setStatus(-2);
this._destroyThreads();
this.emit('stopped', this);
};
Download.prototype.destroy = function() {
var self = this;
this._destroyThreads();
this.setStatus(-3);
var filePath = this.filePath;
var tmpFilePath = filePath;
if (!filePath.match(/\.mtd$/)) {
tmpFilePath += '.mtd';
} else {
filePath = filePath.replace(new RegExp('(.mtd)*$', 'g'), '');
}
fs.unlink(filePath, function() {
fs.unlink(tmpFilePath, function() {
self.emit('destroyed', this);
});
});
};
Download.prototype.start = function() {
var self = this;
self._reset();
self._retryOptions._nbRetries = 0;
this.options.onStart = function(meta) {
self.setStatus(1);
self.setMeta(meta);
self.setUrl(meta.url);
self._computeStartTime();
self._computePastDownloaded();
self._computeTotalSize();
self.emit('start', self);
};
this.options.onEnd = function(err, result) {
// If stopped or destroyed, do nothing
if(self.status == -2 || self.status == -3) {
return;
}
// If we encountered an error and it's not an "Invalid file path" error, we try to resume download "maxRetries" times
if(err && (''+err).indexOf('Invalid file path') == -1 && self._retryOptions._nbRetries < self._retryOptions.maxRetries) {
self.setStatus(2);
self._retryOptions._nbRetries++;
setTimeout(function() {
self.resume();
self.emit('retry', self);
}, self._retryOptions.retryInterval);
// "Invalid file path" or maxRetries reached, emit error
} else if(err) {
self._computeEndTime();
self.setError(err);
self.setStatus(-1);
self.emit('error', self);
// No error, download ended successfully
} else {
self._computeEndTime();
self.setStatus(3);
self.emit('end', self);
}
};
this._downloader = new mtd(this.filePath, this.url, this.options);
this._downloader.start();
return this;
};
Download.prototype.resume = function() {
this._reset();
var filePath = this.filePath;
if (!filePath.match(/\.mtd$/)) {
filePath += '.mtd';
}
this._downloader = new mtd(filePath, null, this.options);
this._downloader.start();
return this;
};
// For backward compatibility, will be removed in next releases
Download.prototype.restart = util.deprecate(function() {
return this.resume();
}, 'Download `restart()` is deprecated, please use `resume()` instead.');
module.exports = Download; | {
"content_hash": "7d48767cdd414b036372f7b37d1d0204",
"timestamp": "",
"source": "github",
"line_count": 349,
"max_line_length": 143,
"avg_line_length": 24.856733524355302,
"alnum_prop": 0.6170605187319885,
"repo_name": "leeroybrun/node-mt-files-downloader",
"id": "d0105a99588083ed56aa939527eaea11bb994bb6",
"size": "8675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Download.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "12432"
}
],
"symlink_target": ""
} |
local sutil= require("lj2procfs.string-util")
local function environ(path)
-- open the file
-- return full contents as a string
local f = io.open(path)
if not f then return nil end
local str = f:read("*a")
local tbl = {}
local eqpatt = "(%g+)=(.*)"
-- The environment variables are separated by a null
-- terminator, so the outer iterator is over that
for _, elem in sutil.mstrziter(str) do
-- Each individual environment variable is a
-- key=value pair, so we split those apart.
local key, value = elem:match(eqpatt);
tbl[key] = value;
end
return tbl;
end
return {
decoder = environ;
} | {
"content_hash": "3f9745804ebdc975d8a951a2b2af2573",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 53,
"avg_line_length": 21.20689655172414,
"alnum_prop": 0.6813008130081301,
"repo_name": "LuaDist2/lj2procfs",
"id": "c980621cb44799a2d7ec0782e7069a3ed15b161c",
"size": "615",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lj2procfs/codecs/process/environ.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "83126"
}
],
"symlink_target": ""
} |
<?php
namespace Concrete\Core\Page\Controller;
use Concrete\Controller\Element\Dashboard\Express\Entries\Header;
use Concrete\Core\Entity\Express\Entry;
use Concrete\Core\Express\Event\Event;
use Concrete\Core\Express\Form\Context\DashboardFormContext;
use Concrete\Core\Express\Form\Control\SaveHandler\SaveHandlerInterface;
use Concrete\Core\Express\Form\OwnedEntityForm;
use Concrete\Core\Express\Form\Renderer;
use Concrete\Core\Form\Context\ContextFactory;
use Concrete\Core\Tree\Node\Node;
use Concrete\Core\Tree\Node\Type\Category;
use Concrete\Core\Tree\Type\ExpressEntryResults;
abstract class DashboardExpressEntityPageController extends DashboardExpressEntriesPageController
{
protected function getEntity(\Concrete\Core\Tree\Node\Type\ExpressEntryResults $parent = null)
{
if (!method_exists($this, 'getEntityName')) {
throw new \RuntimeException(t('Unless you override getEntity() you must define a method named getEntityName'));
} else {
return $this->entityManager->getRepository('Concrete\Core\Entity\Express\Entity')
->findOneByName($this->getEntityName());
}
}
protected function getResultsTreeNodeObject()
{
return Node::getByID($this->getEntity()->getEntityResultsNodeId());
}
public function view($folder = null)
{
$permissions = new \Permissions($this->getEntity());
if ($permissions->canAddExpressEntries()) {
$header = new Header($this->getEntity(), $this->getPageObject());
$this->set('headerMenu', $header);
}
$this->renderList($folder);
}
public function create_entry($id = null, $owner_entry_id = null)
{
$r = $this->entityManager->getRepository('\Concrete\Core\Entity\Express\Entity');
$entity = $r->findOneById($id);
if (!is_object($entity)) {
$this->redirect('/dashboard/express/entries');
}
if ($owner_entry_id) {
$r = $this->entityManager->getRepository('\Concrete\Core\Entity\Express\Entry');
$entry = $r->findOneById($owner_entry_id);
}
$permissions = new \Permissions($entity);
if (!$permissions->canAddExpressEntries()) {
throw new \Exception(t('You do not have access to add entries of this entity type.'));
}
$this->set('entity', $entity);
$form = $entity->getDefaultEditForm();
if (is_object($entry) && $entry->getEntity() == $entity->getOwnedBy()) {
$form = new OwnedEntityForm($form, $entry);
$this->set('backURL', $this->getViewEntryURL($entry));
} else {
$this->set('backURL', $this->getBackURL($entity));
}
$express = \Core::make('express');
$controller = $express->getEntityController($entity);
$factory = new ContextFactory($controller);
$context = $factory->getContext(new DashboardFormContext());
$renderer = new Renderer(
$context,
$form
);
$this->set('renderer', $renderer);
$this->set('pageTitle', t('Add %s', $entity->getName()));
$this->render('/dashboard/express/entries/create', false);
}
}
| {
"content_hash": "cc5d2e4a639126f1ce082a4301caf3dd",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 123,
"avg_line_length": 39.31707317073171,
"alnum_prop": 0.6377171215880894,
"repo_name": "a3020/concrete5",
"id": "9ee2ac699c9ef75cf8c4df00f7ff16052ee4b5da",
"size": "3224",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "concrete/src/Page/Controller/DashboardExpressEntityPageController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "37"
},
{
"name": "CSS",
"bytes": "495051"
},
{
"name": "Hack",
"bytes": "45"
},
{
"name": "JavaScript",
"bytes": "963634"
},
{
"name": "PHP",
"bytes": "10700471"
},
{
"name": "Vue",
"bytes": "2153"
}
],
"symlink_target": ""
} |
layout: post
microblog: true
audio:
photo:
date: 2009-03-05 18:00:00 -0600
guid: http://craigmcclellan.micro.blog/2009/03/06/t1287971330.html
---
Cruel irony. Forgot my iPod, have my iPhone. No headphones that fit the iPhone. Blah!
| {
"content_hash": "35e7132c7edd37bf284fa0d7f9dbcd29",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 85,
"avg_line_length": 29.25,
"alnum_prop": 0.7478632478632479,
"repo_name": "craigwmcclellan/craigwmcclellan.github.io",
"id": "9b4287582040c89cb6123d321c26b6d73a3f52bb",
"size": "238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2009-03-06-t1287971330.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27257"
},
{
"name": "HTML",
"bytes": "34777166"
},
{
"name": "Ruby",
"bytes": "13054"
}
],
"symlink_target": ""
} |
currentMenu: symfony_integration
---
Coming soon. | {
"content_hash": "fa0f6215f0da84f7fc7f6f23cb739db7",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 32,
"avg_line_length": 12.5,
"alnum_prop": 0.78,
"repo_name": "borNfreee/tactician-domain-events",
"id": "337e821dc27706d6a13551e80355526683644e10",
"size": "54",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/symfony_integration.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "12563"
}
],
"symlink_target": ""
} |
Ext.define('App.controller.ccontrabon',{
extend: 'Ext.app.Controller',
views: ['App.view.contrabon.vcontrabon'],
models:['App.model.contrabon.mcontrabon'],
stores:['App.store.contrabon.scontrabon'],
init: function(){
log('Controller ccontrabon Loaded');
}
});
| {
"content_hash": "2b85f0bd40033e1f46334cc25d791201",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 43,
"avg_line_length": 22.583333333333332,
"alnum_prop": 0.7084870848708487,
"repo_name": "emayk/ics",
"id": "f76b8797be652b2d2b2d659251ef8ad257ccd9a1",
"size": "1014",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/frontend/app/controller/ccontrabon.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16862"
},
{
"name": "JavaScript",
"bytes": "1830361"
},
{
"name": "PHP",
"bytes": "1775873"
},
{
"name": "Shell",
"bytes": "190"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<title>ImportWizardPageJDBC (ARX GUI Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ImportWizardPageJDBC (ARX GUI Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ImportWizardPageJDBC.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageExcel.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPagePreview.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageJDBC.html" target="_top">Frames</a></li>
<li><a href="ImportWizardPageJDBC.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.deidentifier.arx.gui.view.impl.wizard</div>
<h2 title="Class ImportWizardPageJDBC" class="title">Class ImportWizardPageJDBC</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.eclipse.jface.dialogs.DialogPage</li>
<li>
<ul class="inheritance">
<li>org.eclipse.jface.wizard.WizardPage</li>
<li>
<ul class="inheritance">
<li>org.deidentifier.arx.gui.view.impl.wizard.ImportWizardPageJDBC</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>org.eclipse.jface.dialogs.IDialogPage, org.eclipse.jface.dialogs.IMessageProvider, org.eclipse.jface.wizard.IWizardPage</dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">ImportWizardPageJDBC</span>
extends org.eclipse.jface.wizard.WizardPage</pre>
<div class="block">JDBC page
This page offers means to specify connection details for a database. For
now MS SQL, MySQL, PostgreSQL and SQLite is supported. In case of remote database
types (i.e. MS SQL, MySQL and PostgreSQL) the user is asked for the server and a
username and password. In case of SQLite the user can select any *.db file.
After ther user specified the details a connection is established and
passed on to <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardModel.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><code>ImportWizardModel</code></a>.
This includes:
<ul>
<li>{@link ImportWizardModel#setJdbcConnection(Connection)<li>
<li>{@link ImportWizardModel#setJdbcTables(List)<li>
</ul></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.eclipse.jface.dialogs.IMessageProvider">
<!-- -->
</a>
<h3>Fields inherited from interface org.eclipse.jface.dialogs.IMessageProvider</h3>
<code>ERROR, INFORMATION, NONE, WARNING</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageJDBC.html#ImportWizardPageJDBC(org.deidentifier.arx.gui.view.impl.wizard.ImportWizard)">ImportWizardPageJDBC</a></strong>(<a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizard.html" title="class in org.deidentifier.arx.gui.view.impl.wizard">ImportWizard</a> wizardImport)</code>
<div class="block">Creates a new instance of this page and sets its title and description.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageJDBC.html#connect()">connect</a></strong>()</code>
<div class="block">Connects to the database
This tries to establish an JDBC connection.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageJDBC.html#createControl(org.eclipse.swt.widgets.Composite)">createControl</a></strong>(org.eclipse.swt.widgets.Composite parent)</code>
<div class="block">Creates the design of this page
This adds all the controls to the page along with their listeners.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageJDBC.html#readTables()">readTables</a></strong>()</code>
<div class="block">Reads in the tables
If successful, the page is marked as complete and a list of tables is
assigned to <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardModel.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><code>ImportWizardModel</code></a>.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.eclipse.jface.wizard.WizardPage">
<!-- -->
</a>
<h3>Methods inherited from class org.eclipse.jface.wizard.WizardPage</h3>
<code>canFlipToNextPage, getContainer, getDialogSettings, getImage, getName, getNextPage, getPreviousPage, getShell, getWizard, isCurrentPage, isPageComplete, setDescription, setErrorMessage, setImageDescriptor, setMessage, setPageComplete, setPreviousPage, setTitle, setWizard, toString</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.eclipse.jface.dialogs.DialogPage">
<!-- -->
</a>
<h3>Methods inherited from class org.eclipse.jface.dialogs.DialogPage</h3>
<code>convertHeightInCharsToPixels, convertHorizontalDLUsToPixels, convertVerticalDLUsToPixels, convertWidthInCharsToPixels, dispose, getControl, getDescription, getDialogFontName, getErrorMessage, getFont, getMessage, getMessageType, getTitle, getToolTipText, initializeDialogUnits, isControlCreated, performHelp, setButtonLayoutData, setControl, setMessage, setVisible</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.eclipse.jface.dialogs.IDialogPage">
<!-- -->
</a>
<h3>Methods inherited from interface org.eclipse.jface.dialogs.IDialogPage</h3>
<code>dispose, getControl, getDescription, getErrorMessage, getMessage, getTitle, performHelp, setVisible</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ImportWizardPageJDBC(org.deidentifier.arx.gui.view.impl.wizard.ImportWizard)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ImportWizardPageJDBC</h4>
<pre>public ImportWizardPageJDBC(<a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizard.html" title="class in org.deidentifier.arx.gui.view.impl.wizard">ImportWizard</a> wizardImport)</pre>
<div class="block">Creates a new instance of this page and sets its title and description.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>wizardImport</code> - Reference to wizard containing this page</dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="createControl(org.eclipse.swt.widgets.Composite)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>createControl</h4>
<pre>public void createControl(org.eclipse.swt.widgets.Composite parent)</pre>
<div class="block">Creates the design of this page
This adds all the controls to the page along with their listeners.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>parent</code> - </dd></dl>
</li>
</ul>
<a name="connect()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>connect</h4>
<pre>protected boolean connect()</pre>
<div class="block">Connects to the database
This tries to establish an JDBC connection. In case of an error
appropriate error messages are set. Otherwise the connection is passed
on to <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardModel.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><code>ImportWizardModel</code></a>. The return value indicates whether a
connection has been established.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>True if successfully connected, false otherwise</dd><dt><span class="strong">See Also:</span></dt><dd><code>ImportWizardModel#setJdbcConnection(Connection)}</code></dd></dl>
</li>
</ul>
<a name="readTables()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>readTables</h4>
<pre>protected void readTables()</pre>
<div class="block">Reads in the tables
If successful, the page is marked as complete and a list of tables is
assigned to <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardModel.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><code>ImportWizardModel</code></a>. Otherwise an appropriate error messages
is set.</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><code>ImportWizardModel#setJdbcTables(List)}</code></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ImportWizardPageJDBC.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageExcel.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPagePreview.html" title="class in org.deidentifier.arx.gui.view.impl.wizard"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageJDBC.html" target="_top">Frames</a></li>
<li><a href="ImportWizardPageJDBC.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "4d801a4479d21467515046f08685bdae",
"timestamp": "",
"source": "github",
"line_count": 380,
"max_line_length": 435,
"avg_line_length": 41.88421052631579,
"alnum_prop": 0.6597134958532295,
"repo_name": "bitraten/arx",
"id": "7d36d5758191e42aedbcb6cf2179dd82f326355a",
"size": "15916",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/gui/org/deidentifier/arx/gui/view/impl/wizard/ImportWizardPageJDBC.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "37206"
},
{
"name": "Java",
"bytes": "4436239"
}
],
"symlink_target": ""
} |
<?php
namespace ZF\Doctrine\QueryBuilder\OrderBy\Service;
use Doctrine\ORM\QueryBuilder;
use Zend\ServiceManager\AbstractPluginManager;
use Zend\ServiceManager\Exception;
use ZF\Doctrine\QueryBuilder\OrderBy\OrderByInterface;
class ORMOrderByManager extends AbstractPluginManager
{
/**
* @param QueryBuilder $queryBuilder
* @param mixed $metadata
* @param array $options
* @return void
*/
public function orderBy(QueryBuilder $queryBuilder, $metadata, $options)
{
foreach ($options as $option) {
if (!isset($option['type']) || false == $option['type']) {
// @codeCoverageIgnoreStart
throw new Exception\RuntimeException('Array element "type" is required for all orderBy directives');
}
// @codeCoverageIgnoreEnd
/** @var OrderByInterface $orderByHandler */
$orderByHandler = $this->get(strtolower($option['type']), [$this]);
$orderByHandler->orderBy($queryBuilder, $option);
}
}
/**
* Validate the plugin
*
* Checks that the filter loaded is either a valid callback or an instance
* of FilterInterface.
*
* @param mixed $plugin
* @return void
* @throws Exception\RuntimeException if invalid
*/
public function validatePlugin($plugin)
{
if ($plugin instanceof OrderByInterface) {
return;
}
// @codeCoverageIgnoreStart
throw new Exception\RuntimeException(sprintf(
'Plugin of type %s is invalid; must implement %s\Plugin\PluginInterface',
(is_object($plugin) ? get_class($plugin) : gettype($plugin)),
__NAMESPACE__
));
// @codeCoverageIgnoreEnd
}
} | {
"content_hash": "769b673cac5b4a0e7ce05355e496c721",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 116,
"avg_line_length": 30.551724137931036,
"alnum_prop": 0.6202031602708804,
"repo_name": "jguittard/zf-doctrine-mapping",
"id": "5d1698c87196c69176126ffe3e2e0c1c9aa43b14",
"size": "2269",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/QueryBuilder/OrderBy/Service/ORMOrderByManager.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "86920"
}
],
"symlink_target": ""
} |
package com.ctrip.xpipe.redis.proxy.monitor.stats;
import com.ctrip.xpipe.concurrent.AbstractExceptionLogTask;
import com.ctrip.xpipe.lifecycle.AbstractStartStoppable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* @author chen.zhu
* <p>
* Oct 31, 2018
*/
public abstract class AbstractStats extends AbstractStartStoppable {
private ScheduledFuture future;
private ScheduledExecutorService scheduled;
private static final int ONE_SEC = 1000;
public AbstractStats(ScheduledExecutorService scheduled) {
this.scheduled = scheduled;
}
@Override
protected void doStart() {
future = scheduled.scheduleWithFixedDelay(new AbstractExceptionLogTask() {
@Override
protected void doRun() {
doTask();
}
}, getCheckIntervalMilli(), getCheckIntervalMilli(), TimeUnit.MILLISECONDS);
}
@Override
protected void doStop() {
if(future != null) {
future.cancel(true);
}
}
protected ScheduledFuture getFuture() {
return future;
}
protected ScheduledExecutorService getScheduled() {
return scheduled;
}
protected int getCheckIntervalMilli() {
return ONE_SEC;
}
protected abstract void doTask();
}
| {
"content_hash": "af1707cc6368693f6313ec4670440119",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 84,
"avg_line_length": 24.333333333333332,
"alnum_prop": 0.6770007209805335,
"repo_name": "ctripcorp/x-pipe",
"id": "f9f5da99c65df95fa4b66b65987ca8d8f53cbb50",
"size": "1387",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "redis/redis-proxy/src/main/java/com/ctrip/xpipe/redis/proxy/monitor/stats/AbstractStats.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1933"
},
{
"name": "Dockerfile",
"bytes": "1061"
},
{
"name": "HTML",
"bytes": "182469"
},
{
"name": "Java",
"bytes": "9045838"
},
{
"name": "JavaScript",
"bytes": "1615"
},
{
"name": "Python",
"bytes": "10427"
},
{
"name": "Shell",
"bytes": "73728"
},
{
"name": "TypeScript",
"bytes": "235225"
}
],
"symlink_target": ""
} |
// Need the following side-effect import because in actual production code,
// Fast Fetch impls are always loaded via an AmpAd tag, which means AmpAd is
// always available for them. However, when we test an impl in isolation,
// AmpAd is not loaded already, so we need to load it separately.
import '../../../amp-ad/0.1/amp-ad';
import {AmpAdNetworkDoubleclickImpl} from '../amp-ad-network-doubleclick-impl';
import {SafeframeHostApi, removeSafeframeListener} from '../safeframe-host';
import {createElementWithAttributes} from '../../../../src/dom';
import {utf8Encode} from '../../../../src/utils/bytes';
/**
* We're allowing external resources because otherwise using realWin causes
* strange behavior with iframes, as it doesn't load resources that we
* normally load in prod.
* We're turning on ampAdCss because using realWin means that we don't
* inherit that CSS from the parent page anymore.
*/
const realWinConfig = {
amp: {
extensions: ['amp-ad-network-doubleclick-impl'],
},
ampAdCss: true,
allowExternalResources: true,
};
const rawCreative = `
<script>
parent./*OK*/postMessage(
JSON.stringify(/** @type {!JsonObject} */ ({
e: 'sentinel',
c: '1234',
})), '*');
parent./*OK*/postMessage(
JSON.stringify(/** @type {!JsonObject} */ ({
s: 'creative_geometry_update',
p: '{"width":"1px","height":"250px","sentinel":"sentinel"}',
})), '*');
</script>`;
const mockPromise = {
then: (callback) => {
callback();
return {
catch: () => {},
};
},
};
/**
* Sets up the necessary mocks and stubs to render a fake fluid creative in unit
* tests.
* @param {!AmpAdNetworkDoubleclickImpl} impl
* @param {!Object} sandbox Sinon sandbox to mock out properties.
* @param {boolean=} resize Whether resize is permitted.
*/
function createScaffoldingForFluidRendering(impl, sandbox, resize = true) {
impl.getVsync = () => {
return {
run: (runArgs) => {
runArgs.mutate();
},
};
};
impl.buildCallback();
impl.attemptChangeHeight = resize
? () => Promise.resolve()
: () => Promise.reject('Creative in viewport');
sandbox.stub(impl, 'sendXhrRequest').returns(
Promise.resolve({
arrayBuffer: () => Promise.resolve(utf8Encode(rawCreative)),
headers: {has: () => false, get: () => undefined},
})
);
impl.sentinel = 'sentinel';
impl.initiateAdRequest();
impl.safeframeApi_ = new SafeframeHostApi(impl, true, impl.creativeSize_);
sandbox./*OK*/ stub(impl.safeframeApi_, 'setupGeom_');
}
describes.realWin('DoubleClick Fast Fetch Fluid', realWinConfig, (env) => {
let impl;
let multiSizeImpl;
let element;
let multiSizeElement;
const initialSize = {width: 0, height: 0};
beforeEach(() => {
env.win.__AMP_MODE.test = true;
const doc = env.win.document;
// TODO(a4a-cam@): This is necessary in the short term, until A4A is
// smarter about host document styling. The issue is that it needs to
// inherit the AMP runtime style element in order for shadow DOM-enclosed
// elements to behave properly. So we have to set up a minimal one here.
const ampStyle = doc.createElement('style');
ampStyle.setAttribute('amp-runtime', 'scratch-fortesting');
doc.head.appendChild(ampStyle);
doc.body.appendChild(
createElementWithAttributes(env.win.document, 'div', {
'style': 'width: 1px; height: 1000px;',
})
);
element = createElementWithAttributes(env.win.document, 'amp-ad', {
'height': 'fluid',
'type': 'doubleclick',
});
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element, env.win.document, env.win);
multiSizeElement = createElementWithAttributes(env.win.document, 'amp-ad', {
'height': 'fluid',
'type': 'doubleclick',
'data-multi-size': '300x200,150x50',
});
doc.body.appendChild(multiSizeElement);
multiSizeImpl = new AmpAdNetworkDoubleclickImpl(
multiSizeElement,
env.win.document,
env.win
);
const getLayout = () => 'fluid';
impl.getLayout = getLayout;
impl.isLayoutSupported('fluid');
impl.experimentalNonAmpCreativeRenderMethod_ = 'safeframe';
multiSizeImpl.getLayout = getLayout;
multiSizeImpl.isLayoutSupported('fluid');
multiSizeImpl.experimentalNonAmpCreativeRenderMethod_ = 'safeframe';
});
afterEach(() => {
removeSafeframeListener();
impl.cleanupAfterTest();
impl = null;
});
it('should start with height 0', () => {
impl.buildCallback();
expect(element.getAttribute('style')).to.match(/height: 0px/);
});
it('should be fluid enabled', () => {
expect(impl.isFluidRequest()).to.be.true;
});
it('should have a supported layout', () => {
expect(impl.isLayoutSupported('fluid')).to.be.true;
});
it('should NOT load delayed impression amp-pixels', () => {
const fireDelayedImpressionsSpy = env.sandbox.spy(
impl,
'fireDelayedImpressions'
);
const size = impl.extractSize({
get(name) {
switch (name) {
case 'X-AmpImps':
return 'https://a.com?a=b,https://b.com?c=d';
case 'X-AmpRSImps':
return 'https://c.com?e=f,https://d.com?g=h';
default:
return undefined;
}
},
has(name) {
return !!this.get(name);
},
});
expect(size.width).to.equal(initialSize.width);
expect(size.height).to.equal(initialSize.height);
expect(fireDelayedImpressionsSpy).to.not.be.calledOnce;
});
it('should contain sz=320x50 in ad request by default', () => {
impl.initiateAdRequest();
return impl.adPromise_.then(() => {
expect(impl.adUrl_).to.be.ok;
expect(impl.adUrl_).to.match(/[&?]sz=320x50/);
});
});
it('should contain mulitple sizes in ad request', () => {
multiSizeImpl.initiateAdRequest();
return multiSizeImpl.adPromise_.then(() => {
expect(multiSizeImpl.adUrl_).to.be.ok;
expect(multiSizeImpl.adUrl_).to.match(/[&?]sz=320x50%7C300x200%7C150x50/);
});
});
it('should style iframe/slot correctly on multi-size creative', () => {
multiSizeImpl.buildCallback();
multiSizeImpl.sentinel = 'sentinel';
multiSizeImpl.adPromise_ = Promise.resolve();
multiSizeImpl.creativeBody_ = utf8Encode('foo');
multiSizeImpl.returnedSize_ = {width: 250, height: 100};
return multiSizeImpl.layoutCallback().then(() => {
const iframeStyleString = multiSizeImpl.iframe.getAttribute('style');
const slotStyleString = multiSizeImpl.element.getAttribute('style');
expect(slotStyleString).to.match(/width: 250px/);
expect(iframeStyleString).to.match(/position: relative/);
expect(multiSizeImpl.element.getAttribute('height')).to.be.null;
});
});
it('should have an iframe child with initial size 0x0', () => {
impl.buildCallback();
impl.sentinel = 'sentinel';
impl.adPromise_ = Promise.resolve();
impl.creativeBody_ = utf8Encode('foo');
return impl.layoutCallback().then(() => {
const styleString = impl.iframe.getAttribute('style');
expect(styleString).to.match(/width: 0px/);
expect(styleString).to.match(/height: 0px/);
});
});
it('should fire delayed impression ping', () => {
createScaffoldingForFluidRendering(impl, env.sandbox);
const connectMessagingChannelSpy = env.sandbox./*OK*/ spy(
impl.safeframeApi_,
'connectMessagingChannel'
);
const onFluidResizeSpy = env.sandbox./*OK*/ spy(
impl.safeframeApi_,
'onFluidResize_'
);
return impl.adPromise_.then(() => {
return impl.layoutCallback().then(() => {
expect(connectMessagingChannelSpy).to.be.calledOnce;
expect(onFluidResizeSpy).to.be.calledOnce;
});
});
});
it('should fire delayed impression ping, if creative partly visible', () => {
createScaffoldingForFluidRendering(impl, env.sandbox, false);
const connectMessagingChannelSpy = env.sandbox./*OK*/ spy(
impl.safeframeApi_,
'connectMessagingChannel'
);
const onFluidResizeSpy = env.sandbox./*OK*/ spy(
impl.safeframeApi_,
'onFluidResize_'
);
// Size must be non-zero to fire impression.
impl.element.setAttribute('height', 1);
impl.element.setAttribute('width', 1);
return impl.adPromise_.then(() => {
return impl.layoutCallback().then(() => {
expect(connectMessagingChannelSpy).to.be.calledOnce;
expect(onFluidResizeSpy).to.be.calledOnce;
});
});
});
it('should set height on iframe', () => {
createScaffoldingForFluidRendering(impl, env.sandbox);
return impl.adPromise_.then(() => {
return impl.layoutCallback().then(() => {
expect(impl.iframe.style.height).to.equal('250px');
});
});
});
it('should fire impression for AMP fluid creative', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
env.sandbox.stub(impl, 'setCssPosition_').returns(mockPromise);
env.sandbox.stub(impl, 'attemptChangeHeight').returns(mockPromise);
const delayedImpressionSpy = env.sandbox.spy(
impl,
'fireDelayedImpressions'
);
impl.buildCallback();
impl.isFluidRequest_ = true;
impl.isVerifiedAmpCreative_ = true;
impl.fluidImpressionUrl_ = 'http://www.foo.co.uk';
impl.onCreativeRender(null, mockPromise);
expect(delayedImpressionSpy.withArgs('http://www.foo.co.uk')).to.be
.calledOnce;
});
it('should fire impression for AMP fluid creative, if partly visible', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
env.sandbox.stub(impl, 'setCssPosition_').returns(Promise.resolve());
env.sandbox.stub(impl, 'attemptChangeHeight').returns(Promise.reject());
const delayedImpressionSpy = env.sandbox.spy(
impl,
'fireDelayedImpressions'
);
impl.buildCallback();
impl.isFluidRequest_ = true;
impl.isVerifiedAmpCreative_ = true;
impl.fluidImpressionUrl_ = 'http://www.foo.co.uk';
// Size must be non-zero to fire impression.
impl.element.setAttribute('height', 1);
impl.element.setAttribute('width', 1);
return impl.expandFluidCreative_().then(() => {
expect(delayedImpressionSpy.withArgs('http://www.foo.co.uk')).to.be
.calledOnce;
});
});
it('should not fire impression for AMP fluid creative', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
env.sandbox.stub(impl, 'setCssPosition_').returns(Promise.resolve());
env.sandbox.stub(impl, 'attemptChangeHeight').returns(Promise.reject());
const delayedImpressionSpy = env.sandbox.spy(
impl,
'fireDelayedImpressions'
);
impl.buildCallback();
impl.isFluidRequest_ = true;
impl.isVerifiedAmpCreative_ = true;
return impl.expandFluidCreative_().then(() => {
expect(delayedImpressionSpy.withArgs('http://www.foo.co.uk')).to.not.be
.calledOnce;
});
});
it('should set expansion re-attempt flag after initial failure', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
const attemptChangeHeightStub = env.sandbox.stub(
impl,
'attemptChangeHeight'
);
attemptChangeHeightStub.returns(Promise.reject());
env.sandbox.stub(impl, 'setCssPosition_').returns(Promise.resolve());
env.sandbox
.stub(impl, 'attemptToRenderCreative')
.returns(Promise.resolve());
impl.buildCallback();
impl.isFluidRequest_ = true;
impl.isVerifiedAmpCreative_ = true;
return impl.expandFluidCreative_().then(() => {
expect(attemptChangeHeightStub).to.be.calledOnce;
expect(impl.reattemptToExpandFluidCreative_).to.be.true;
});
});
it('should re-attempt expansion after initial failure', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
const attemptChangeHeightStub = env.sandbox.stub(
impl,
'attemptChangeHeight'
);
attemptChangeHeightStub.returns(Promise.resolve());
env.sandbox
.stub(impl, 'attemptToRenderCreative')
.returns(Promise.resolve());
env.sandbox.stub(impl, 'setCssPosition_').returns(mockPromise);
impl.buildCallback();
impl.isFluidRequest_ = true;
impl.isVerifiedAmpCreative_ = true;
impl.reattemptToExpandFluidCreative_ = true;
// Should do nothing
impl.viewportCallback(true);
expect(attemptChangeHeightStub).to.not.be.called;
impl.viewportCallback(false);
expect(attemptChangeHeightStub).to.be.calledOnce;
});
it('should set position: static when measuring height on AMP fluid', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
const attemptChangeHeightStub = env.sandbox.stub(
impl,
'attemptChangeHeight'
);
const mutateElementStub = env.sandbox.stub(impl, 'mutateElement');
attemptChangeHeightStub.returns(Promise.resolve());
mutateElementStub.returns(Promise.resolve());
env.sandbox
.stub(impl, 'attemptToRenderCreative')
.returns(Promise.resolve());
impl.buildCallback();
impl.isFluidRequest_ = true;
impl.isVerifiedAmpCreative_ = true;
const setCssPositionSpy = env.sandbox.spy(impl, 'setCssPosition_');
return impl.expandFluidCreative_().then(() => {
expect(attemptChangeHeightStub).to.be.calledOnce;
expect(setCssPositionSpy.withArgs('static')).to.be.calledOnce;
expect(setCssPositionSpy.withArgs('absolute')).to.not.be.called;
});
});
it('should set position: absoltute back when resizing fails', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
const attemptChangeHeightStub = env.sandbox.stub(
impl,
'attemptChangeHeight'
);
const mutateElementStub = env.sandbox.stub(impl, 'mutateElement');
attemptChangeHeightStub.returns(Promise.reject());
mutateElementStub.returns(Promise.resolve());
env.sandbox
.stub(impl, 'attemptToRenderCreative')
.returns(Promise.resolve());
impl.buildCallback();
impl.isFluidRequest_ = true;
impl.isVerifiedAmpCreative_ = true;
const setCssPositionSpy = env.sandbox.spy(impl, 'setCssPosition_');
return impl.expandFluidCreative_().then(() => {
expect(attemptChangeHeightStub).to.be.calledOnce;
expect(setCssPositionSpy.withArgs('static')).to.be.calledOnce;
expect(setCssPositionSpy.withArgs('absolute')).to.be.calledOnce;
});
});
});
| {
"content_hash": "ddef52ac4da8705268e14af1270aba90",
"timestamp": "",
"source": "github",
"line_count": 416,
"max_line_length": 80,
"avg_line_length": 35.59855769230769,
"alnum_prop": 0.6623674792356,
"repo_name": "adup-tech/amphtml",
"id": "0b1ba859729494b64decbe03fc3303c9b4f224f1",
"size": "15436",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "extensions/amp-ad-network-doubleclick-impl/0.1/test/test-doubleclick-fluid.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "71752"
},
{
"name": "Go",
"bytes": "7459"
},
{
"name": "HTML",
"bytes": "506690"
},
{
"name": "Java",
"bytes": "36355"
},
{
"name": "JavaScript",
"bytes": "5661528"
},
{
"name": "Protocol Buffer",
"bytes": "25410"
},
{
"name": "Python",
"bytes": "68440"
},
{
"name": "Shell",
"bytes": "4731"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Ustilago shastense Zundel
### Remarks
null | {
"content_hash": "ba9487c0f3124aa5cddab6189f048631",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 25,
"avg_line_length": 9.923076923076923,
"alnum_prop": 0.7131782945736435,
"repo_name": "mdoering/backbone",
"id": "efc1937b057fe76208bd4e66387eac41c75db3eb",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Microbotryomycetes/Microbotryales/Microbotryaceae/Microbotryum/Microbotryum shastense/ Syn. Ustilago shastense/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package net.segner.poc.wlltw.aspect;
import net.segner.poc.wlltw.service.HelloService;
import net.segner.poc.wlltw.view.DemoViewController;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kubek2k.springockito.annotations.ReplaceWithMock;
import org.kubek2k.springockito.annotations.SpringockitoContextLoader;
import org.mockito.Mockito;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ui.Model;
import static org.hamcrest.CoreMatchers.is;
/**
* Integration test demonstrating one way of verifying aspect pointcuts
*
* @author asegner
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = SpringockitoContextLoader.class,
locations = {
"classpath:spring/shared-services.xml",
"classpath:spring/appone-context.xml",
"classpath:spring/appone-view-context.xml"
})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class DemoViewControllerAspectIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private DemoCounter demoCounter;
@Autowired
@ReplaceWithMock
private HelloService helloService;
private Model model;
/**
* NOTE:
* Placing a weaved class as a field in the test will cause the class to load before the weaver and it will not be weaved
* Alternatively, load the bean method-local using the beanFactory
*/
// private DemoViewController demoViewController;
@Autowired
private BeanFactory beanFactory;
@Before
public void setup() {
model = Mockito.mock(Model.class);
}
@Test
public void testAspectAroundHelloRequest() {
DemoViewController demoViewController = beanFactory.getBean(DemoViewController.class);
demoViewController.helloWorld(model);
//verification
Assert.assertThat("Check counter to verify around advice was called", demoCounter.getAroundAdvise(), is(1));
Assert.assertThat("Check counter to verify throw advice was not called", demoCounter.getThrowAdvise(), is(0));
}
@Test
public void testAspectExceptionInHelloRequest() {
//setup
DemoViewController demoViewController = beanFactory.getBean(DemoViewController.class);
Mockito.when(helloService.getHello()).thenThrow(new RuntimeException());
boolean firedExceptionFlag = false;
//test
try {
demoViewController.helloWorld(model);
} catch (Exception e) {
firedExceptionFlag = true;
}
//verification
Assert.assertTrue(firedExceptionFlag);
Assert.assertThat("Check counter to verify around advice was called", demoCounter.getAroundAdvise(), is(1));
Assert.assertThat("Check counter to verify throw advice was called", demoCounter.getThrowAdvise(), is(1));
}
} | {
"content_hash": "d2d634692e8d800e18c6b1048e60f8cd",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 125,
"avg_line_length": 36.96629213483146,
"alnum_prop": 0.7355623100303952,
"repo_name": "asegner/spring-ltw-weblogic",
"id": "91382d8678d309706b96ee85c2d0b54714a653c6",
"size": "3290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/warone/src/test/java/net/segner/poc/wlltw/aspect/DemoViewControllerAspectIntegrationTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "12227"
}
],
"symlink_target": ""
} |
module tf.graph.scene {
const svgNamespace = 'http://www.w3.org/2000/svg';
/** Enums element class of objects in the scene */
export let Class = {
Node: {
// <g> element that contains nodes.
CONTAINER: 'nodes',
// <g> element that contains detail about a node.
GROUP: 'node',
// <g> element that contains visual elements (like rect, ellipse).
SHAPE: 'nodeshape',
// <*> element(s) under SHAPE that should receive color updates.
COLOR_TARGET: 'nodecolortarget',
// <text> element showing the node's label.
LABEL: 'nodelabel',
// <g> element that contains all visuals for the expand/collapse
// button for expandable group nodes.
BUTTON_CONTAINER: 'buttoncontainer',
// <circle> element that surrounds expand/collapse buttons.
BUTTON_CIRCLE: 'buttoncircle',
// <path> element of the expand button.
EXPAND_BUTTON: 'expandbutton',
// <path> element of the collapse button.
COLLAPSE_BUTTON: 'collapsebutton'
},
Edge: {
CONTAINER: 'edges',
GROUP: 'edge',
LINE: 'edgeline',
REF_LINE: 'refline',
STRUCTURAL: 'structural'
},
Annotation: {
OUTBOX: 'out-annotations',
INBOX: 'in-annotations',
GROUP: 'annotation',
NODE: 'annotation-node',
EDGE: 'annotation-edge',
CONTROL_EDGE: 'annotation-control-edge',
LABEL: 'annotation-label',
ELLIPSIS: 'annotation-ellipsis'
},
Scene: {
GROUP: 'scene',
CORE: 'core',
INEXTRACT: 'in-extract',
OUTEXTRACT: 'out-extract'
},
Subscene: {GROUP: 'subscene'},
OPNODE: 'op',
METANODE: 'meta',
SERIESNODE: 'series',
BRIDGENODE: 'bridge',
ELLIPSISNODE: 'ellipsis'
};
/**
* A health pill encapsulates an overview of tensor element values. The value
* field is a list of 12 numbers that shed light on the status of the tensor.
* Visualized in health pills are the 3rd through 8th (inclusive) numbers of
* health pill values. Those 6 numbers are counts of tensor elements that fall
* under -Inf, negative, 0, positive, +Inf, NaN (in that order).
*
* Please keep this interface consistent with HealthPillDatum within
* backend.ts.
*/
export interface HealthPill {
node_name: string;
output_slot: number;
value: number[];
wall_time: number;
step: number;
}
;
/**
* Encapsulates how to render a single entry in a health pill. Each entry
* corresponds to a category of tensor element values.
*/
interface HealthPillEntry {
background_color: string;
text_color: string;
label: string;
}
;
const _healthPillEntries: HealthPillEntry[] = [
{
background_color: '#762a83',
text_color: '#fff',
label: '-∞',
},
{
background_color: '#af8dc3',
text_color: '#000',
label: '-',
},
{
background_color: '#f7da0b',
text_color: '#000',
label: '0',
},
{
background_color: '#a2c96f',
text_color: '#000',
label: '+',
},
{
background_color: '#1f8926',
text_color: '#fff',
label: '+∞',
},
{
background_color: '#0909c6',
text_color: '#fff',
label: 'NaN',
},
];
/**
* Helper method for fitting the graph in the svg view.
*
* @param svg The main svg.
* @param zoomG The svg group used for panning and zooming.
* @param d3zoom The zoom behavior.
* @param callback Called when the fitting is done.
*/
export function fit(svg, zoomG, d3zoom, callback) {
let svgRect = svg.getBoundingClientRect();
let sceneSize = null;
try {
sceneSize = zoomG.getBBox();
if (sceneSize.width === 0) {
// There is no scene anymore. We have been detached from the dom.
return;
}
} catch (e) {
// Firefox produced NS_ERROR_FAILURE if we have been
// detached from the dom.
return;
}
let scale = 0.9 *
Math.min(
svgRect.width / sceneSize.width, svgRect.height / sceneSize.height,
2);
let params = layout.PARAMS.graph;
let zoomEvent =
d3zoom.scale(scale)
.on('zoomend.fitted',
() => {
// Remove the listener for the zoomend event,
// so we don't get called at the end of regular zoom events,
// just those that fit the graph to screen.
d3zoom.on('zoomend.fitted', null);
callback();
})
.translate([params.padding.paddingLeft, params.padding.paddingTop])
.event;
d3.select(zoomG).transition().duration(500).call(zoomEvent);
};
/**
* Helper method for panning the graph to center on the provided node,
* if the node is currently off-screen.
*
* @param nodeName The node to center the graph on
* @param svg The root SVG element for the graph
* @param zoomG The svg group used for panning and zooming.
* @param d3zoom The zoom behavior.
* @return True if the graph had to be panned to display the
* provided node.
*/
export function panToNode(nodeName: String, svg, zoomG, d3zoom): boolean {
let node = <SVGAElement>d3
.select('[data-name="' + nodeName + '"].' + Class.Node.GROUP)
.node();
if (!node) {
return false;
}
let translate = d3zoom.translate();
// Check if the selected node is off-screen in either
// X or Y dimension in either direction.
let nodeBox = node.getBBox();
let nodeCtm = node.getScreenCTM();
let pointTL = svg.createSVGPoint();
let pointBR = svg.createSVGPoint();
pointTL.x = nodeBox.x;
pointTL.y = nodeBox.y;
pointBR.x = nodeBox.x + nodeBox.width;
pointBR.y = nodeBox.y + nodeBox.height;
pointTL = pointTL.matrixTransform(nodeCtm);
pointBR = pointBR.matrixTransform(nodeCtm);
let isOutsideOfBounds = (start, end, bound) => {
return end < 0 || start > bound;
};
let svgRect = svg.getBoundingClientRect();
if (isOutsideOfBounds(pointTL.x, pointBR.x, svgRect.width) ||
isOutsideOfBounds(pointTL.y, pointBR.y, svgRect.height)) {
// Determine the amount to transform the graph in both X and Y
// dimensions in order to center the selected node. This takes into
// acount the position of the node, the size of the svg scene, the
// amount the scene has been scaled by through zooming, and any previous
// transform already performed by this logic.
let centerX = (pointTL.x + pointBR.x) / 2;
let centerY = (pointTL.y + pointBR.y) / 2;
let dx = ((svgRect.width / 2) - centerX);
let dy = ((svgRect.height / 2) - centerY);
let zoomEvent = d3zoom.translate([translate[0] + dx, translate[1] + dy])
.event;
d3.select(zoomG).transition().duration(500).call(zoomEvent);
return true;
}
return false;
};
/**
* Given a container d3 selection, select a child svg element of a given tag
* and class if exists or append / insert one otherwise. If multiple children
* matches the tag and class name, returns only the first one.
*
* @param container
* @param tagName tag name.
* @param className (optional) Class name or a list of class names.
* @param before (optional) reference DOM node for insertion.
* @return selection of the element
*/
export function selectOrCreateChild(
container, tagName: string, className?: string | string[], before?) {
let child = selectChild(container, tagName, className);
if (!child.empty()) {
return child;
}
let newElement =
document.createElementNS('http://www.w3.org/2000/svg', tagName);
if (className instanceof Array) {
for (let i = 0; i < className.length; i++) {
newElement.classList.add(className[i]);
}
} else {
newElement.classList.add(className);
}
if (before) { // if before exists, insert
container.node().insertBefore(newElement, before);
} else { // otherwise, append
container.node().appendChild(newElement);
}
return d3.select(newElement)
// need to bind data to emulate d3_selection.append
.datum(container.datum());
};
/**
* Given a container d3 selection, select a child element of a given tag and
* class. If multiple children matches the tag and class name, returns only
* the first one.
*
* @param container
* @param tagName tag name.
* @param className (optional) Class name or list of class names.
* @return selection of the element, or an empty selection
*/
export function selectChild(
container, tagName: string, className?: string | string[]) {
let children = container.node().childNodes;
for (let i = 0; i < children.length; i++) {
let child = children[i];
if (child.tagName === tagName) {
if (className instanceof Array) {
let hasAllClasses = true;
for (let j = 0; j < className.length; j++) {
hasAllClasses =
hasAllClasses && child.classList.contains(className[j]);
}
if (hasAllClasses) {
return d3.select(child);
}
} else if ((!className || child.classList.contains(className))) {
return d3.select(child);
}
}
}
return d3.select(null);
};
/**
* Select or create a sceneGroup and build/update its nodes and edges.
*
* Structure Pattern:
*
* <g class='scene'>
* <g class='core'>
* <g class='edges'>
* ... stuff from tf.graph.scene.edges.build ...
* </g>
* <g class='nodes'>
* ... stuff from tf.graph.scene.nodes.build ...
* </g>
* </g>
* <g class='in-extract'>
* <g class='nodes'>
* ... stuff from tf.graph.scene.nodes.build ...
* </g>
* </g>
* <g class='out-extract'>
* <g class='nodes'>
* ... stuff from tf.graph.scene.nodes.build ...
* </g>
* </g>
* </g>
*
* @param container D3 selection of the parent.
* @param renderNode render node of a metanode or series node.
* @param sceneElement <tf-graph-scene> polymer element.
* @param sceneClass class attribute of the scene (default='scene').
*/
export function buildGroup(container,
renderNode: render.RenderGroupNodeInfo,
sceneElement,
sceneClass: string) {
sceneClass = sceneClass || Class.Scene.GROUP;
let isNewSceneGroup = selectChild(container, 'g', sceneClass).empty();
let sceneGroup = selectOrCreateChild(container, 'g', sceneClass);
// core
let coreGroup = selectOrCreateChild(sceneGroup, 'g', Class.Scene.CORE);
let coreNodes = _.reduce(renderNode.coreGraph.nodes(), (nodes, name) => {
let node = renderNode.coreGraph.node(name);
if (!node.excluded) {
nodes.push(node);
}
return nodes;
}, []);
if (renderNode.node.type === NodeType.SERIES) {
// For series, we want the first item on top, so reverse the array so
// the first item in the series becomes last item in the top, and thus
// is rendered on the top.
coreNodes.reverse();
}
// Create the layer of edges for this scene (paths).
edge.buildGroup(coreGroup, renderNode.coreGraph, sceneElement);
// Create the layer of nodes for this scene (ellipses, rects etc).
node.buildGroup(coreGroup, coreNodes, sceneElement);
// In-extract
if (renderNode.isolatedInExtract.length > 0) {
let inExtractGroup =
selectOrCreateChild(sceneGroup, 'g', Class.Scene.INEXTRACT);
node.buildGroup(inExtractGroup, renderNode.isolatedInExtract,
sceneElement);
} else {
selectChild(sceneGroup, 'g', Class.Scene.INEXTRACT).remove();
}
// Out-extract
if (renderNode.isolatedOutExtract.length > 0) {
let outExtractGroup =
selectOrCreateChild(sceneGroup, 'g', Class.Scene.OUTEXTRACT);
node.buildGroup(outExtractGroup, renderNode.isolatedOutExtract,
sceneElement);
} else {
selectChild(sceneGroup, 'g', Class.Scene.OUTEXTRACT).remove();
}
position(sceneGroup, renderNode);
// Fade in the scene group if it didn't already exist.
if (isNewSceneGroup) {
sceneGroup.attr('opacity', 0).transition().attr('opacity', 1);
}
return sceneGroup;
};
/**
* Given a scene's svg group, set g.in-extract, g.coreGraph, g.out-extract svg
* groups' position relative to the scene.
*
* @param sceneGroup
* @param renderNode render node of a metanode or series node.
*/
function position(sceneGroup, renderNode: render.RenderGroupNodeInfo) {
// Translate scenes down by the label height so that when showing graphs in
// expanded metanodes, the graphs are below the labels. Do not shift them
// down for series nodes as series nodes don't have labels inside of their
// bounding boxes.
let yTranslate = renderNode.node.type === NodeType.SERIES ?
0 : layout.PARAMS.subscene.meta.labelHeight;
// core
translate(selectChild(sceneGroup, 'g', Class.Scene.CORE), 0, yTranslate);
// in-extract
let hasInExtract = renderNode.isolatedInExtract.length > 0;
let hasOutExtract = renderNode.isolatedOutExtract.length > 0;
if (hasInExtract) {
let offset = layout.PARAMS.subscene.meta.extractXOffset;
let inExtractX = renderNode.coreBox.width -
renderNode.inExtractBox.width / 2 - renderNode.outExtractBox.width -
(hasOutExtract ? offset : 0);
translate(
selectChild(sceneGroup, 'g', Class.Scene.INEXTRACT), inExtractX,
yTranslate);
}
// out-extract
if (hasOutExtract) {
let outExtractX = renderNode.coreBox.width -
renderNode.outExtractBox.width / 2;
translate(
selectChild(sceneGroup, 'g', Class.Scene.OUTEXTRACT), outExtractX,
yTranslate);
}
};
/** Adds a click listener to a group that fires a graph-select event */
export function addGraphClickListener(graphGroup, sceneElement) {
d3.select(graphGroup).on('click', () => {
sceneElement.fire('graph-select');
});
};
/** Helper for adding transform: translate(x0, y0) */
export function translate(selection, x0: number, y0: number) {
// If it is already placed on the screen, make it a transition.
if (selection.attr('transform') != null) {
selection = selection.transition('position');
}
selection.attr('transform', 'translate(' + x0 + ',' + y0 + ')');
};
/**
* Helper for setting position of a svg rect
* @param rect rect to set position of.
* @param cx Center x.
* @param cy Center x.
* @param width Width to set.
* @param height Height to set.
*/
export function positionRect(rect, cx: number, cy: number, width: number,
height: number) {
rect.transition().attr({
x: cx - width / 2,
y: cy - height / 2,
width: width,
height: height
});
};
/**
* Helper for setting position of a svg expand/collapse button
* @param button container group
* @param renderNode the render node of the group node to position
* the button on.
*/
export function positionButton(button, renderNode: render.RenderNodeInfo) {
let cx = layout.computeCXPositionOfNodeShape(renderNode);
// Position the button in the top-right corner of the group node,
// with space given the draw the button inside of the corner.
let width = renderNode.expanded ?
renderNode.width : renderNode.coreBox.width;
let height = renderNode.expanded ?
renderNode.height : renderNode.coreBox.height;
let x = cx + width / 2 - 6;
let y = renderNode.y - height / 2 + 6;
// For unexpanded series nodes, the button has special placement due
// to the unique visuals of this group node.
if (renderNode.node.type === NodeType.SERIES && !renderNode.expanded) {
x += 10;
y -= 2;
}
let translateStr = 'translate(' + x + ',' + y + ')';
button.selectAll('path').transition().attr('transform', translateStr);
button.select('circle').transition().attr(
{cx: x, cy: y, r: layout.PARAMS.nodeSize.meta.expandButtonRadius});
};
/**
* Helper for setting position of a svg ellipse
* @param ellipse ellipse to set position of.
* @param cx Center x.
* @param cy Center x.
* @param width Width to set.
* @param height Height to set.
*/
export function positionEllipse(ellipse, cx: number, cy: number,
width: number, height: number) {
ellipse.transition().attr({
cx: cx,
cy: cy,
rx: width / 2,
ry: height / 2
});
};
/**
* Renders a health pill for an op atop a node.
*/
function _addHealthPill(
nodeGroupElement: SVGElement, healthPill: HealthPill,
nodeInfo: render.RenderGroupNodeInfo) {
// Check if text already exists at location.
d3.select(nodeGroupElement.parentNode)
.selectAll('.health-pill-group')
.remove();
if (!nodeInfo || !healthPill) {
return;
}
let lastHealthPillData = healthPill.value;
// For now, we only visualize the 6 values that summarize counts of tensor
// elements of various categories: -Inf, negative, 0, positive, Inf, and NaN.
let lastHealthPillOverview = lastHealthPillData.slice(2, 8);
let healthPillWidth = 60;
let healthPillHeight = 10;
let healthPillSvg = document.createElementNS(svgNamespace, 'svg');
healthPillSvg.classList.add('health-pill-group');
healthPillSvg.setAttribute('width', String(healthPillWidth));
healthPillSvg.setAttribute('height', String(healthPillHeight));
let svgDefs = document.createElementNS(svgNamespace, 'defs');
healthPillSvg.appendChild(svgDefs);
let clipPath = document.createElementNS(svgNamespace, 'clipPath');
clipPath.setAttribute('id', 'health-pill-clip-path');
svgDefs.appendChild(clipPath);
let clipRect = document.createElementNS(svgNamespace, 'rect');
clipRect.setAttribute('height', String(healthPillHeight));
clipRect.setAttribute('width', String(healthPillWidth));
clipRect.setAttribute('rx', '2');
clipRect.setAttribute('ry', '2');
clipPath.appendChild(clipRect);
let rectGroup = document.createElementNS(svgNamespace, 'g');
rectGroup.setAttribute('clip-path', 'url(#health-pill-clip-path)');
healthPillSvg.appendChild(rectGroup);
let totalCount = lastHealthPillData[1];
// Create 1 rectangle for each category.
let totalCountSoFar = 0;
let totalWidthDividedByTotalCount = healthPillWidth / totalCount;
let titleOnHoverTextEntries = [];
for (let i = 0; i < lastHealthPillOverview.length; i++) {
if (!lastHealthPillOverview[i]) {
// Do not render empty rectangles.
continue;
}
let rect = document.createElementNS(svgNamespace, 'rect');
rect.setAttribute('height', String(healthPillHeight));
let rectWidth = totalWidthDividedByTotalCount * lastHealthPillOverview[i];
rect.setAttribute('width', String(rectWidth));
let rectX = totalWidthDividedByTotalCount * totalCountSoFar;
rect.setAttribute('x', String(rectX));
rect.setAttribute('fill', _healthPillEntries[i].background_color);
totalCountSoFar += lastHealthPillOverview[i];
rectGroup.appendChild(rect);
// Append a label.
let textSvg = document.createElementNS(svgNamespace, 'text');
textSvg.setAttribute('font-size', '8');
textSvg.setAttribute('font-family', 'arial');
rectGroup.appendChild(textSvg);
textSvg.appendChild(document.createTextNode(_healthPillEntries[i].label));
textSvg.setAttribute('x', String(rectX + rectWidth / 2));
textSvg.setAttribute('y', String(7.5));
textSvg.setAttribute('text-anchor', 'middle');
textSvg.setAttribute('fill', _healthPillEntries[i].text_color);
// Include this number in the title that appears on hover.
titleOnHoverTextEntries.push(
_healthPillEntries[i].label + ': ' + lastHealthPillOverview[i]);
}
// Show a title with specific counts on hover.
let titleSvg = document.createElementNS(svgNamespace, 'title');
titleSvg.textContent = titleOnHoverTextEntries.join(', ');
healthPillSvg.appendChild(titleSvg);
// Center this health pill just right above the node for the op.
healthPillSvg.setAttribute(
'x', String(nodeInfo.x - healthPillWidth + nodeInfo.width / 2));
healthPillSvg.setAttribute(
'y',
String(nodeInfo.y - healthPillHeight - nodeInfo.coreBox.height / 2 - 2));
Polymer.dom(nodeGroupElement.parentNode).appendChild(healthPillSvg);
}
/**
* Adds health pills (which visualize tensor summaries) to a graph group.
* @param svgRoot The root SVG element of the graph to add heath pills to.
* @param nodeNamesToHealthPills An object mapping node name to health pill.
* @param colors A list of colors to use.
*/
export function addHealthPills(
svgRoot: SVGElement, nodeNamesToHealthPill: {[key: string]: HealthPill}) {
if (!nodeNamesToHealthPill) {
// No health pill information available.
return;
}
let svgRootSelection = d3.select(svgRoot);
svgRootSelection.selectAll('g.nodeshape')
.each(function(nodeInfo: render.RenderGroupNodeInfo) {
// The element is the first item of a d3 selection.
_addHealthPill(
this, nodeNamesToHealthPill[nodeInfo.node.name], nodeInfo);
});
};
} // close module
| {
"content_hash": "f6ebf433d7ec78f682c87de6f52180ee",
"timestamp": "",
"source": "github",
"line_count": 617,
"max_line_length": 80,
"avg_line_length": 33.90437601296596,
"alnum_prop": 0.6572971939385248,
"repo_name": "eerwitt/tensorflow",
"id": "ad584451cb32af521d865e38811912648e2baf85",
"size": "21591",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tensorflow/tensorboard/components/tf_graph_common/lib/scene/scene.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2967"
},
{
"name": "C",
"bytes": "94360"
},
{
"name": "C++",
"bytes": "13836767"
},
{
"name": "CMake",
"bytes": "93933"
},
{
"name": "CSS",
"bytes": "774"
},
{
"name": "Go",
"bytes": "85550"
},
{
"name": "HTML",
"bytes": "525038"
},
{
"name": "Java",
"bytes": "56007"
},
{
"name": "JavaScript",
"bytes": "12235"
},
{
"name": "Jupyter Notebook",
"bytes": "1833475"
},
{
"name": "Makefile",
"bytes": "23468"
},
{
"name": "Objective-C",
"bytes": "7056"
},
{
"name": "Objective-C++",
"bytes": "64592"
},
{
"name": "Protocol Buffer",
"bytes": "142519"
},
{
"name": "Python",
"bytes": "13166441"
},
{
"name": "Shell",
"bytes": "262797"
},
{
"name": "TypeScript",
"bytes": "726452"
}
],
"symlink_target": ""
} |
import new_product from './new_product'
export default {
new_product
};
| {
"content_hash": "c952baae81aec0672d0718c842259f81",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 39,
"avg_line_length": 15,
"alnum_prop": 0.7066666666666667,
"repo_name": "newswim/mantra-react-toolbox",
"id": "f7a308ff2b2b8ce9cad356e5813943096be4d833",
"size": "75",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/modules/new_product/actions/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10420"
},
{
"name": "JavaScript",
"bytes": "101217"
}
],
"symlink_target": ""
} |
require 'ip'
require 'ruby-wmi' if ::RightScale::Platform.windows?
module RightScale
class WindowsNetworkConfigurator < NetworkConfigurator
def self.supported?
::RightScale::Platform.windows?
end
# converts CIDR to ip/netmask
#
# === Parameters
# cidr_range(String):: target range in CIDR notation
# === Return
# result(Array):: array which contains ip address and netmask
#
def cidr_to_netmask(cidr_range)
cidr = IP::CIDR.new(cidr_range)
return cidr.ip.ip_address, cidr.long_netmask.ip_address
end
def configure_network
super
rename_devices
set_default_gateway
# setting administrator password setting (not yet supported)
end
def set_default_gateway
default_gw = ENV.keys.grep(/RS_IP\d_GATEWAY/).first
if default_gw
default_gw_device_name = shell_escape_if_necessary(ENV[default_gw.sub('GATEWAY', 'NAME')])
runshell("netsh interface ipv4 set interface #{default_gw_device_name} METRIC=0")
end
end
def route_regex(network, nat_server_ip)
network, mask = cidr_to_netmask(network)
/#{network}.*#{mask}.*#{nat_server_ip}/
end
def routes_show
runshell("route print")
end
# For Windows 2008R2/Windows 7 and earlier its Local Area Connection
# For Windows 8/2012 and later its Ethernet
def network_device_name
return @network_device_name if @network_device_name
major, minor, build = ::RightScale::Platform.release.split(".").map(&:to_i)
@network_device_name = (major == 6 && minor <= 1) ? "Local Area Connection" : "Ethernet" # http://msdn.microsoft.com/en-us/library/ms724834%28VS.85%29.aspx
end
def os_net_devices
@net_devices ||= (1..10).map { |i| "#{network_device_name} #{i}".sub(/ 1$/, "") }
end
def network_adapters
WMI::Win32_NetworkAdapter.all
end
def network_devices
@network_devices ||= network_adapters.delete_if { |dev| dev.MACAddress.nil? || dev.NetConnectionID.nil? }
.sort_by { |dev| os_net_devices.index(dev.NetConnectionID) }
.reverse
end
def device_name_from_mac(mac)
network_devices.detect { |dev| dev.macaddress.casecmp(mac) == 0 }.NetConnectionID
end
def rename_device(old_name, new_name)
old_name = shell_escape_if_necessary(old_name)
new_name = shell_escape_if_necessary(new_name)
runshell("netsh interface set interface #{old_name} newname=#{new_name}")
end
def name_from_mac(mac)
key = ENV.select { |k,v| k =~ /RS_IP\d_MAC/ && v == mac }.keys.first || ''
key = key.sub('MAC', 'NAME')
ENV[key] || os_net_devices.pop
end
def rename_devices_to_temp_name
network_devices.each do |device|
rename_device(device.NetConnectionID, safe_name(device.MACAddress))
end
end
def safe_name(name)
name.tr('<>:"/\\|?*', '.')
end
def rename_devices
return if ENV.keys.grep(/RS_IP\d_NAME/).empty?
rename_devices_to_temp_name
ENV.keys.grep(/RS_IP\d_MAC/).each do |mac|
n = mac[/\d/].to_i
temp_name = safe_name(ENV[mac])
device_name = safe_name(ENV["RS_IP#{n}_NAME"] || os_net_devices.shift)
rename_device(temp_name, device_name)
end
end
def network_route_add(network, nat_server_ip)
super
if network_route_exists?(network, nat_server_ip)
logger.debug "Route already exists to #{network} via #{nat_server_ip}"
else
network, mask = cidr_to_netmask(network)
runshell("route -p ADD #{network} MASK #{mask} #{nat_server_ip}")
end
true
end
# Shows network configuration for specified device
#
# === Parameters
# device(String):: target device name
#
# === Return
# result(String):: current config for specified device
#
def device_config_show(device)
runshell("netsh interface ipv4 show addresses #{device}")
end
# Gets IP address for specified device
#
# === Parameters
# device(String):: target device name
#
# === Return
# result(String):: current IP for specified device or nil
#
def get_device_ip(device)
ip_addr = device_config_show(device).lines("\n").grep(/IP Address/).shift
return nil unless ip_addr
ip_addr.strip.split.last
end
# Waits until device configuration applies i.e.
# until device IP == specified IP
#
def wait_for_configuration_appliance(device, ip)
sleep(2) while ip != get_device_ip(device)
end
def configure_network_adaptor(device, ip, netmask, gateway, nameservers = [])
super
cmd = "netsh interface ip set address name=#{device} source=static addr=#{ip} mask=#{netmask} gateway="
cmd += gateway ? "#{gateway} gwmetric=1" : "none"
runshell(cmd)
wait_for_configuration_appliance(device, ip)
if nameservers && nameservers.length > 0
unless all_nameservers_match?(device, nameservers)
nameservers.each_with_index do |n, i|
add_nameserver_to_device(device, n, i + 1)
end
end
end
# return the IP address assigned
ip
end
def add_nameserver_to_device(device, nameserver_ip, index)
cmd = "netsh interface ipv4 add dnsserver name=#{device} addr=#{nameserver_ip} index=#{index} validate=no"
primary = (index == 1)
cmd = "netsh interface ipv4 set dnsserver name=#{device} source=static addr=#{nameserver_ip} register=primary validate=no" if primary
runshell(cmd)
true
end
def configured_nameservers(device)
# show only nameservers configured staticly i.e. not through DHCP
runshell("netsh interface ip show dns #{device}").lines.reject { |l| l =~ /DHCP/ }.join
end
def all_nameservers_match?(device, nameservers)
configured = configured_nameservers(device)
nameservers.all? { |n| configured.include?(n) }
end
def null_device
"NUL"
end
end
end
| {
"content_hash": "0c794eda3f649ab4522834a0f662b58f",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 161,
"avg_line_length": 31.533678756476682,
"alnum_prop": 0.6233979625369701,
"repo_name": "rightscale/right_link",
"id": "4ade7fd932ee3a331a51a05e07f71c6337795e7b",
"size": "6086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/instance/network_configurator/windows_network_configurator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4118"
},
{
"name": "C#",
"bytes": "132130"
},
{
"name": "PowerShell",
"bytes": "6732"
},
{
"name": "Ruby",
"bytes": "1507482"
}
],
"symlink_target": ""
} |
@implementation LogisticsInfo
-(instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+(instancetype)logisticsWithDict:(NSDictionary *)dict
{
return [[self alloc]initWithDict:dict];
}
@end
| {
"content_hash": "01a8edc4f09939134853031313fdb089",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 53,
"avg_line_length": 18.6875,
"alnum_prop": 0.6989966555183946,
"repo_name": "lifei321/MyDemo",
"id": "d548ef58049b9074bff9187db5308c914abe01b2",
"size": "462",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MyDemo/ChildController/wuliu(物流轴线)/Model/LogisticsInfo.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1217789"
},
{
"name": "Ruby",
"bytes": "137"
}
],
"symlink_target": ""
} |
package edu.asu.scrapbook.digital.test;
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.SaveException;
import com.googlecode.objectify.VoidWork;
import edu.asu.scrapbook.digital.dao.UserDAO;
import edu.asu.scrapbook.digital.dao.UserDAOFactory;
import edu.asu.scrapbook.digital.model.ProfileSettings;
import edu.asu.scrapbook.digital.model.User;
public class DatastoreUserTest {
@Test
public void createUserTest() throws Exception {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
User testUser = new User();
ProfileSettings ps = new ProfileSettings();
ps.setFirstName("John");
ps.setLastName("Doe");
testUser.setUsername("testID");
testUser.setSettings(ps);
UserDAO dao = UserDAOFactory.getInstance();
User resultUser = null;
try {
resultUser = dao.create(testUser);
} catch (Exception e) {
fail("User could not be created: " + e.getMessage());
}
assertEquals("Created user differs from returned user", testUser, resultUser);
helper.tearDown();
}
});
}
@Test
public void failToCreateUserTest() {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
UserDAO dao = UserDAOFactory.getInstance();
User testUser = new User();
try {
dao.create(testUser);
fail("Test must fail");
} catch (SaveException se) {
// Successful test
} catch (Exception e) {
fail("Emergency failure. Threw an unknown exception");
}
helper.tearDown();
}
});
}
@Test
public void foundUserTest() throws Exception {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
User testUser = new User();
ProfileSettings ps = new ProfileSettings();
ps.setFirstName("John");
ps.setLastName("Doe");
testUser.setUsername("testID");
testUser.setSettings(ps);
UserDAO dao = UserDAOFactory.getInstance();
User resultUser = new User();
try {
dao.create(testUser);
resultUser = dao.findById("testID");
} catch (Exception e) {
fail("User was not found: " + e.getMessage());
}
assertEquals("User was not found", testUser, resultUser);
helper.tearDown();
}
});
}
@Test
public void userWithIdNotFoundTest() {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
UserDAO dao = UserDAOFactory.getInstance();
User testUser = new User();
try {
testUser = dao.findById("testID");
} catch (Exception e) {
fail("Exception was thrown. It shouldn't have done that.");
}
assertNull("Object was not null", testUser);
helper.tearDown();
}
});
}
@Test
public void findByIdEmptyStringTest() {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
UserDAO dao = UserDAOFactory.getInstance();
try {
dao.findById("");
fail("Test must fail");
} catch (IllegalArgumentException iae) {
// Successful test
} catch (Exception e) {
fail("Emergency failure. Threw an unexpected exception");
}
helper.tearDown();
}
});
}
@Test
public void updateUserTest() throws Exception {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
User controlUser = new User();
User testUser = new User();
ProfileSettings cps = new ProfileSettings();
ProfileSettings ps = new ProfileSettings();
cps.setFirstName("Jane");
cps.setLastName("Doe");
controlUser.setUsername("otherID");
controlUser.setSettings(cps);
ps.setFirstName("John");
ps.setLastName("Doe");
testUser.setUsername("testID");
testUser.setSettings(ps);
UserDAO dao = UserDAOFactory.getInstance();
User resultUser = null;
User updateTestUser = null;
try {
dao.create(controlUser);
resultUser = dao.create(testUser);
resultUser.getSettings().setFirstName("Jane");
updateTestUser = dao.update(resultUser);
} catch (Exception e) {
fail("User was not updated " + e.getMessage());
}
assertEquals("User was not updated. First name differs.", controlUser.getSettings().getFirstName(), updateTestUser.getSettings().getFirstName());
helper.tearDown();
}
});
}
@Test
public void failToUpdateUserTest() throws Exception {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
User testUser = new User();
ProfileSettings ps = new ProfileSettings();
ps.setFirstName("Jane");
ps.setLastName("Doe");
testUser.setUsername("");
testUser.setSettings(ps);
UserDAO dao = UserDAOFactory.getInstance();
try {
dao.update(testUser);
fail("Test must fail");
} catch (IllegalArgumentException iae) {
// Successful test
} catch (Exception e) {
fail("Emergency failure. Threw an unexpected exception");
}
helper.tearDown();
}
});
}
@Test
public void deleteUserTest() throws Exception {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
User testUser = new User();
ProfileSettings ps = new ProfileSettings();
ps.setFirstName("John");
ps.setLastName("Doe");
testUser.setUsername("testID");
testUser.setSettings(ps);
UserDAO dao = UserDAOFactory.getInstance();
User resultUser = null;
try {
dao.create(testUser);
dao.delete(testUser.getUsername());
resultUser = dao.findById(testUser.getUsername());
} catch (Exception e) {
System.out.println("Something went very wrong");
}
assertNull("User was found when they should have been deleted", resultUser);
helper.tearDown();
}
});
}
@Test
public void failToDeleteUserTest() throws Exception {
ObjectifyService.run(new VoidWork() {
public void vrun() {
LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
User testUser = new User();
ProfileSettings ps = new ProfileSettings();
ps.setFirstName("John");
ps.setLastName("Doe");
testUser.setUsername("testID");
testUser.setSettings(ps);
UserDAO dao = UserDAOFactory.getInstance();
try {
dao.create(testUser);
dao.delete("");
} catch (IllegalArgumentException iae) {
// Successful test
} catch (Exception e) {
fail("Emergency failure. Threw an unexpected exception");
}
helper.tearDown();
}
});
}
}
| {
"content_hash": "1a6cba47a2313f3da0b01ce1449ca1e3",
"timestamp": "",
"source": "github",
"line_count": 273,
"max_line_length": 149,
"avg_line_length": 28.296703296703296,
"alnum_prop": 0.666537216828479,
"repo_name": "mcmathews/CSE-360-Digital-Scrapbook",
"id": "cf92797145bdaa8c82424d5eb3b14f148de249e9",
"size": "7725",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/edu/asu/scrapbook/digital/test/DatastoreUserTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7089"
},
{
"name": "Java",
"bytes": "53927"
},
{
"name": "JavaScript",
"bytes": "3638"
}
],
"symlink_target": ""
} |
package org.tensorflow.lite.support.image;
import com.google.android.odml.image.BitmapExtractor;
import com.google.android.odml.image.ByteBufferExtractor;
import com.google.android.odml.image.MediaImageExtractor;
import com.google.android.odml.image.MlImage;
import com.google.android.odml.image.MlImage.ImageFormat;
import com.google.auto.value.AutoValue;
import java.nio.ByteBuffer;
/** Converts {@code MlImage} to {@link TensorImage} and vice versa. */
public class MlImageAdapter {
/** Proxies an {@link ImageFormat} and its equivalent {@link ColorSpaceType}. */
@AutoValue
abstract static class ImageFormatProxy {
abstract ColorSpaceType getColorSpaceType();
@ImageFormat
abstract int getImageFormat();
static ImageFormatProxy createFromImageFormat(@ImageFormat int format) {
switch (format) {
case MlImage.IMAGE_FORMAT_RGB:
return new AutoValue_MlImageAdapter_ImageFormatProxy(ColorSpaceType.RGB, format);
case MlImage.IMAGE_FORMAT_NV12:
return new AutoValue_MlImageAdapter_ImageFormatProxy(ColorSpaceType.NV12, format);
case MlImage.IMAGE_FORMAT_NV21:
return new AutoValue_MlImageAdapter_ImageFormatProxy(ColorSpaceType.NV21, format);
case MlImage.IMAGE_FORMAT_YV12:
return new AutoValue_MlImageAdapter_ImageFormatProxy(ColorSpaceType.YV12, format);
case MlImage.IMAGE_FORMAT_YV21:
return new AutoValue_MlImageAdapter_ImageFormatProxy(ColorSpaceType.YV21, format);
case MlImage.IMAGE_FORMAT_YUV_420_888:
return new AutoValue_MlImageAdapter_ImageFormatProxy(ColorSpaceType.YUV_420_888, format);
case MlImage.IMAGE_FORMAT_ALPHA:
return new AutoValue_MlImageAdapter_ImageFormatProxy(ColorSpaceType.GRAYSCALE, format);
case MlImage.IMAGE_FORMAT_RGBA:
case MlImage.IMAGE_FORMAT_JPEG:
case MlImage.IMAGE_FORMAT_UNKNOWN:
throw new IllegalArgumentException(
"Cannot create ColorSpaceType from MlImage format: " + format);
default:
throw new AssertionError("Illegal @ImageFormat: " + format);
}
}
}
/**
* Creates a {@link TensorImage} from an {@link MlImage}.
*
* <p>IMPORTANT: The returned {@link TensorImage} shares storage with {@code mlImage}, so do not
* modify the contained object in the {@link TensorImage}, as {@code MlImage} expects its
* contained data are immutable. Also, callers should use {@code MlImage#getInternal()#acquire()}
* and {@code MlImage#release()} to avoid the {@code mlImage} being released unexpectedly.
*
* @throws IllegalArgumentException if the {@code mlImage} is built from an unsupported container.
*/
public static TensorImage createTensorImageFrom(MlImage mlImage) {
// TODO(b/190670174): Choose the best storage from multiple containers.
com.google.android.odml.image.ImageProperties mlImageProperties =
mlImage.getContainedImageProperties().get(0);
switch (mlImageProperties.getStorageType()) {
case MlImage.STORAGE_TYPE_BITMAP:
return TensorImage.fromBitmap(BitmapExtractor.extract(mlImage));
case MlImage.STORAGE_TYPE_MEDIA_IMAGE:
TensorImage mediaTensorImage = new TensorImage();
mediaTensorImage.load(MediaImageExtractor.extract(mlImage));
return mediaTensorImage;
case MlImage.STORAGE_TYPE_BYTEBUFFER:
ByteBuffer buffer = ByteBufferExtractor.extract(mlImage);
ImageFormatProxy formatProxy =
ImageFormatProxy.createFromImageFormat(mlImageProperties.getImageFormat());
TensorImage byteBufferTensorImage = new TensorImage();
ImageProperties properties =
ImageProperties.builder()
.setColorSpaceType(formatProxy.getColorSpaceType())
.setHeight(mlImage.getHeight())
.setWidth(mlImage.getWidth())
.build();
byteBufferTensorImage.load(buffer, properties);
return byteBufferTensorImage;
default:
throw new IllegalArgumentException(
"Illegal storage type: " + mlImageProperties.getStorageType());
}
}
/** Creatas a {@link ColorSpaceType} from {@code MlImage.ImageFormat}. */
public static ColorSpaceType createColorSpaceTypeFrom(@ImageFormat int imageFormat) {
return ImageFormatProxy.createFromImageFormat(imageFormat).getColorSpaceType();
}
private MlImageAdapter() {}
}
| {
"content_hash": "dc69733d81465cd249e516aad3e6e282",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 100,
"avg_line_length": 45.204081632653065,
"alnum_prop": 0.718510158013544,
"repo_name": "tensorflow/tflite-support",
"id": "ed066e5308fb9fa2cda79c05e27b2dcb59e0d551",
"size": "5098",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tensorflow_lite_support/java/src/java/org/tensorflow/lite/support/image/MlImageAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1152"
},
{
"name": "C",
"bytes": "108226"
},
{
"name": "C++",
"bytes": "2067530"
},
{
"name": "Java",
"bytes": "845682"
},
{
"name": "Jupyter Notebook",
"bytes": "59660"
},
{
"name": "Makefile",
"bytes": "2420"
},
{
"name": "Objective-C",
"bytes": "338606"
},
{
"name": "Objective-C++",
"bytes": "30976"
},
{
"name": "Python",
"bytes": "631212"
},
{
"name": "Shell",
"bytes": "33741"
},
{
"name": "Starlark",
"bytes": "433326"
},
{
"name": "Swift",
"bytes": "33812"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "04c0aa6aab5dff0da44bbfa0754369f9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "2db403b9f244e1d016b99d63e4c3c6a4c736de0f",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Papaveraceae/Capnoides/Capnoides engelmannii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Use std::move on rvalue refs, std::foarward on universal
========================================================
Base material
-------------
Rvalue references bind only to objects that are candidates for
moving; if you have an rvalue reference parameter, you *know* that
the object it's bound to may be moved.
A universal reference *might* be bound to an object that's eligible
for moving; universal references should be cast to rvalues only if
they were initialized with rvalues.
- rvalue references should be *uncoditionally cast* to rvalues
(via std::move) when forwarding them to other functions,
because they're *always* bound to rvalues;
- universal references should be *conditionally cast* to rvalues
(via std::forward) when forwarding them,
because they're only *sometimes* bound to rvalues.
You should avoid using *std::forward* with rvalue references
you should avoid using *std::move* with universal references,
because that can have the effect of unexpectedly modifying lvalues
(e.g., local variables).
You can overload function for const lvalues and for rvalues, but
- you must mantain two functions instead of a single template
(and if you have n parameters, you must mantina pow(2,n) functions,
and if you have unlimited count of parameters the problem
can't be resolved);
- this approach is less efficient than using universal references.
If you want to use the object bound to an rvalue reference or a
universal reference more that once in a single function, and you
want to make sure that it's not moved from until you are otherwise
done with it, you must apply *std::move* (for rvalue references)
or *std::forward* (for universal references) to only the *final use*
of the reference.
If you're in a function that returns by value, and you're returning
an object bound to an rvalue reference or a universal reference,
you can apply std::move or std::forward when you return the reference.
Copy elision
------------
Compilers may elide the copying (or moving) of a local object in
a function that returns by value if
- the type of the local object is the same as that returned by
the function;
- the local objects is what's being returned.
Summary
-------
- apply std::move to rvalue references and std::forward to universal
references the last time each is used;
- do the same thing for rvalue references and universal references
being returned from functions that return by value;
- never apply std::move or std::forward to local objects if they would
otherwise be eligible for the return value optimization.
| {
"content_hash": "0528165ae68f14524b9a8bf822f93abd",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 70,
"avg_line_length": 41.3125,
"alnum_prop": 0.7299546142208775,
"repo_name": "ordinary-developer/book_effective_modern_c_plus_plus_s_meyers",
"id": "6ecbd7a9551b34d0fb89dd870c43626b9315fdcf",
"size": "2644",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "synopses/ch_5-RVALUE_REFERENCES/item_25-use_move_on_rvalue_refs_and_forward_on_universal/synopsis.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "120710"
}
],
"symlink_target": ""
} |
package org.apache.sling.validation.impl.util;
import java.util.Collection;
import javax.annotation.Nonnull;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.validation.Validator;
import org.apache.sling.validation.exceptions.SlingValidationException;
import org.apache.sling.validation.impl.util.examplevalidators.DerivedStringValidator;
import org.apache.sling.validation.impl.util.examplevalidators.ExtendedStringValidator;
import org.apache.sling.validation.impl.util.examplevalidators.GenericTypeParameterBaseClass;
import org.apache.sling.validation.impl.util.examplevalidators.IntegerValidator;
import org.apache.sling.validation.impl.util.examplevalidators.StringArrayValidator;
import org.apache.sling.validation.impl.util.examplevalidators.StringValidator;
import org.apache.sling.validation.impl.validators.RegexValidator;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
public class ValidatorTypeUtilTest {
@SuppressWarnings("unchecked")
@Test
public void testGetValidatorTypeOfDirectImplementations() {
Assert.assertThat((Class<String>)ValidatorTypeUtil.getValidatorType(new RegexValidator()), Matchers.equalTo(String.class));
Assert.assertThat((Class<String>)ValidatorTypeUtil.getValidatorType(new StringValidator()), Matchers.equalTo(String.class));
Assert.assertThat((Class<Integer>)ValidatorTypeUtil.getValidatorType(new IntegerValidator()), Matchers.equalTo(Integer.class));
}
@Test
@SuppressWarnings("unchecked")
public void testGetValidatorTypeOfDerivedImplementations() {
Assert.assertThat((Class<String>)ValidatorTypeUtil.getValidatorType(new DerivedStringValidator()), Matchers.equalTo(String.class));
}
@Test
@SuppressWarnings("unchecked")
public void testGetValidatorTypeWithAdditionalTypeParameters() {
Assert.assertThat((Class<String>)ValidatorTypeUtil.getValidatorType(new ExtendedStringValidator()), Matchers.equalTo(String.class));
}
private class InnerStringValidator implements Validator<String> {
@Override
public String validate(@Nonnull String data, @Nonnull ValueMap valueMap, Resource resource, @Nonnull ValueMap arguments)
throws SlingValidationException {
return null;
}
}
@Test
@SuppressWarnings("unchecked")
public void testGetValidatorTypeWithInnerClass() {
Assert.assertThat((Class<String>)ValidatorTypeUtil.getValidatorType(new InnerStringValidator()), Matchers.equalTo(String.class));
}
@Test
@SuppressWarnings("unchecked")
public void testGetValidatorTypeWithAnonymousClass() {
Assert.assertThat((Class<String>)ValidatorTypeUtil.getValidatorType(new Validator<String>() {
@Override
public String validate(@Nonnull String data, @Nonnull ValueMap valueMap, Resource resource, @Nonnull ValueMap arguments)
throws SlingValidationException {
return null;
}
}), Matchers.equalTo(String.class));
}
@Test
@SuppressWarnings("unchecked")
public void testGetValidatorTypeWithArrayType() {
Assert.assertThat((Class<String[]>)ValidatorTypeUtil.getValidatorType(new StringArrayValidator()), Matchers.equalTo(String[].class));
}
@Test(expected=IllegalArgumentException.class)
public void testGetValidatorTypeWithCollectionType() {
ValidatorTypeUtil.getValidatorType(new Validator<Collection<String>>() {
@Override
public String validate(@Nonnull Collection<String> data, @Nonnull ValueMap valueMap, Resource resource, @Nonnull ValueMap arguments)
throws SlingValidationException {
return null;
}
});
}
private class InnerStringValidatorWithAdditionalBaseClass extends GenericTypeParameterBaseClass<Integer> implements Validator<String> {
@Override
public String validate(@Nonnull String data, @Nonnull ValueMap valueMap, Resource resource, @Nonnull ValueMap arguments)
throws SlingValidationException {
return null;
}
}
@Test
public void testGetValidatorTypeWithUnrelatedSuperClass() {
// http://stackoverflow.com/questions/24093000/how-do-i-match-a-class-against-a-specific-class-instance-in-a-hamcrest-matche
Assert.assertThat((Class<?>)ValidatorTypeUtil.getValidatorType(new InnerStringValidatorWithAdditionalBaseClass()), Matchers.is(CoreMatchers.<Class<?>>equalTo(String.class)));
}
}
| {
"content_hash": "f6327ba60bdfc5525d7e4ac0dde44c3f",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 182,
"avg_line_length": 45.25961538461539,
"alnum_prop": 0.7384746122795836,
"repo_name": "gutsy/sling",
"id": "4eada1450d4ea8e3863872c26ff99c571d2fc676",
"size": "5512",
"binary": false,
"copies": "6",
"ref": "refs/heads/trunk",
"path": "bundles/extensions/validation/core/src/test/java/org/apache/sling/validation/impl/util/ValidatorTypeUtilTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "7690"
},
{
"name": "Batchfile",
"bytes": "194"
},
{
"name": "CSS",
"bytes": "80802"
},
{
"name": "Groovy",
"bytes": "7745"
},
{
"name": "HTML",
"bytes": "106611"
},
{
"name": "Java",
"bytes": "22026804"
},
{
"name": "JavaScript",
"bytes": "331950"
},
{
"name": "Makefile",
"bytes": "1519"
},
{
"name": "Python",
"bytes": "2586"
},
{
"name": "Ruby",
"bytes": "4896"
},
{
"name": "Scala",
"bytes": "127988"
},
{
"name": "Shell",
"bytes": "24834"
},
{
"name": "XProc",
"bytes": "2290"
},
{
"name": "XSLT",
"bytes": "8575"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GM-Angular</title>
<link type="text/css" rel="stylesheet" href="/angular-1.x.css"/>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script src="/angular-1.x.js"></script>
</head>
<body ng-app="myApp" ng-controller="AppController as vm">
<div class="search-area">
<div class="sa-ele">
<label class="se-title">名称:</label>
<input class="se-con" ng-model="searchForm.title"/>
</div>
<div class="sa-ele">
<label class="se-title">内容:</label>
<input class="se-con" ng-model="searchForm.content"/>
</div>
<div class="sa-ele">
<button class="search-action" ng-click="onSearch()">搜索</button>
<button class="reset-action" ng-click="onReset()">重置</button>
<button ng-click="onAddCol()">新增列: ID</button>
<button ng-click="onRemoveCol()">删除列: 博文分类</button>
</div>
</div>
<div class="grid-main">
<div ng-if="!destroyDisabled" style="height: 100%;">
<grid-manager option="option" callback="callback(query)"></grid-manager>
</div>
</div>
<div class="bottom-bar">
<button ng-click="onInit()">init</button>
<button ng-click="onDestroy()">destroy</button>
<a href="https://github.com/baukh789/GridManager-Angular-1.x" target="_blank">查看源码</a>
</div>
</body>
</html>
| {
"content_hash": "0b4038059ca51db56ba47b03b7394164",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 94,
"avg_line_length": 35.41463414634146,
"alnum_prop": 0.5757575757575758,
"repo_name": "baukh789/GridManager",
"id": "7471254d968e3ed6cd72d432c45d696f7938eef7",
"size": "1496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/framework/angular-1.x/demo/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6906"
},
{
"name": "HTML",
"bytes": "172011"
},
{
"name": "JavaScript",
"bytes": "457433"
},
{
"name": "Less",
"bytes": "38834"
},
{
"name": "TypeScript",
"bytes": "358249"
}
],
"symlink_target": ""
} |
<?php
require_once('abstractModule.php');
class AdminModule extends abstractModule{
//Service module
private $head = "<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>LODSPeaKr Admin Menu</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta name='description' content=''>
<meta name='author' content=''>
<link href='../css/bootstrap.min.css' rel='stylesheet' type='text/css' media='screen' />
<link href='codemirror/lib/codemirror.css' rel='stylesheet' type='text/css' media='screen' />
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
.CodeMirror {border: 1px solid black;}
.cm-mustache {color: #0ca;}
.wait{
background-image:url('img/wait.gif');
background-repeat:no-repeat;
padding-right:20px;
background-position: right;
}
.strong{font-weight: 900; font-size:120%}
.cheat-sheet{
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border-radius: 15px;
min-height: 200px;
background:lightgray;
width:400px;
padding:5px;
position:absolute;
border:1px solid black;
right:-370px;
top:120px;
opacity:0.9
}
.cheat-title{
writing-mode:tb-rl;
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
-o-transform: rotate(90deg);
white-space:nowrap;
display:block;
width:20px;
height:40px;
font-size:24px;
font-weight:normal;
text-shadow: 0px 0px 1px #333;
}
.first-editor{
top:120px;
}
.second-editor{
top:540px;
}
/* Base class */
.bs-docs-template {
position: relative;
margin: 0px 0;
padding: 39px 19px 14px;
*padding-top: 19px;
background-color: #fff;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.cheat-list{
margin-left:60px;
margin-top:-30px;
}
.sparql-list{
margin-left:60px;
margin-top:-40px;
}
/* Echo out a label for the example */
.bs-docs-template:after {
content: 'Template';
position: absolute;
top: -1px;
left: -1px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
background-color: #f5f5f5;
border: 1px solid #ddd;
color: #9da0a4;
-webkit-border-radius: 4px 0 4px 0;
-moz-border-radius: 4px 0 4px 0;
border-radius: 4px 0 4px 0;
}
.bs-docs-query {
position: relative;
margin: 0px 0;
padding: 39px 19px 14px;
*padding-top: 19px;
background-color: #fff;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
/* Echo out a label for the example */
.bs-docs-query:after {
content: 'Query';
position: absolute;
top: -1px;
left: -1px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
background-color: #f5f5f5;
border: 1px solid #ddd;
color: #9da0a4;
-webkit-border-radius: 4px 0 4px 0;
-moz-border-radius: 4px 0 4px 0;
border-radius: 4px 0 4px 0;
}
.cheat-example{
background:#ccc;
font-family:monaco;
font-size:11px;
}
.embed-code{
font-family:Monaco;
}
</style>
<link href='../css/bootstrap-responsive.min.css' rel='stylesheet' type='text/css' media='screen' />
<script type='text/javascript' src='../js/jquery.js'></script>
<script type='text/javascript' src='../js/bootstrap.min.js'></script>
</head>
<body>
<div class='navbar navbar-fixed-top'>
<div class='navbar-inner'>
<div class='container'>
<a class='btn btn-navbar' data-toggle='collapse' data-target='.nav-collapse'>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</a>
<a class='brand' href='../admin'>LODSPeaKr menu</a>
<div class='nav-collapse'>
<ul class='nav'>
<!--li class='dropdown'>
<a class='dropdown-toggle' data-toggle='dropdown' href='#'>SPARQL Endpoint<b class='caret'></b></a>
<ul class='dropdown-menu'>
<li><a href='../admin/start'>Start endpoint</a></li>
<li><a href='../admin/stop'>Stop endpoint</a></li>
<!--li><a href='../admin/load'>Add RDF</a></li>
<li><a href='../admin/remove'>Remove RDF</a></li>
</ul>
</li-->
<li>
<a class='dropdown-toggle' data-toggle='dropdown' href='../admin/namespaces'>Namespaces<b class='caret'></b></a>
</li>
<li>
<a class='dropdown-toggle' data-toggle='dropdown' href='../admin/endpoints'>Endpoints<b class='caret'></b></a>
</li>
<li>
<a class='dropdown-toggle' data-toggle='dropdown' href='../admin/components'>Component Editor<b class='caret'></b></a>
</li>
<li>
<a href='../'><i class='icon-share icon-white'></i> Go to main site</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class='container'>
<img src='../img/lodspeakr_logotype.png' style='opacity: 0.1; position: absolute; right:0px; top:60%'/>
";
private $foot =" <div id='embed-box' class='modal hide fade'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h3>Embed this code</h3>
</div>
<div class='modal-body'>
<form class='form-inline'><fieldset><label>Width:</label> <input type='text' class='input-small embed-size' id='embed-width' value='600px'/> <label>Height:</label> <input type='text' class='input-small embed-size' id='embed-height' value='400px'/></fieldset></form>
<div id='embed-body' class='embed-code'>
</div>
<hr/>
<span id='tweet-span'></span>
<div class='fb-like' data-href='http://google.com' data-send='true' data-layout='button_count' data-width='450' data-show-faces='true' data-action='recommend'></div><div id='fb-root'></div>
<div class='modal-footer'>
<a href='#' class='btn' data-dismiss='modal'>Close</a>
</div>
</div></div>
</body>
</html>
";
public function match($uri){
global $localUri;
global $conf;
//URLs used by this component. Other URLs starting with admin/* won't be considered by this module
$operations = array("menu", /*"load", "remove",*/ "endpoints", "namespaces", "components", "");
$q = preg_replace('|^'.$conf['basedir'].'|', '', $localUri);
$qArr = explode('/', $q);
if(sizeof($qArr)==0){
return FALSE;
}
if($qArr[0] == "admin" && array_search($qArr[1], $operations) !== FALSE){
if($conf['admin']['pass'] !== FALSE && !$this->auth()){
HTTPStatus::send401("Forbidden\n");
exit(0);
}
return $qArr;
}
return FALSE;
}
public function execute($params){
global $conf;
global $localUri;
global $uri;
global $acceptContentType;
global $endpoints;
global $lodspk;
global $firstResults;
if(sizeof($params) == 1){
header( 'Location: admin/menu' ) ;
exit(0);
}
if($params[1] == ""){
header( 'Location: menu' ) ;
exit(0);
}
switch($params[1]){
case "menu":
$this->homeMenu();
break;
/*case "start":
$this->startEndpoint();
break;
case "stop":
$this->stopEndpoint();
break;*/
/*case "load":
$this->loadRDF();
break;
case "remove":
$this->deleteRDF();
break;*/
case "namespaces":
$this->editNamespaces();
break;
case "endpoints":
$this->editEndpoints();
break;
case "components":
if(sizeof($params) == 2){
$this->componentEditor();
}else{
$this->componentEditorApi(array_slice($params, 2));
}
break;
default:
HTTPStatus::send404($params[1]);
}
exit(0);
}
protected function loadRDF(){
global $conf;
if(!isset($conf['updateendpoint']['local'])){
echo $this->head."
<div class='fluid-row'>
<div class='span8'>
<div class='alert alert-error'><strong>Error:</strong> No SPARQL/UPDATE server found. Please include it in <code>\$conf['updateendpoint']['local']</code> at <strong>settings.inc.php</strong></div>
</div>
</div>
".$this->foot;
}else{
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo $this->head."
<div class='fluid-row'>
<div class='span5'>
<form action='load' method='post'
enctype='multipart/form-data'>
<legend>Load RDF into the endpoint</legend>
<div class='alert alert-info'><span class='label label-info'>Important</span> If you load data into an existing Named graph, the content will be overwritten!</div>
<label for='file'>RDF file</label>
<input type='file' name='file' id='file' />
<span class='help-block'>LODSPeaKr accepts RDF/XML, Turtle and N-Triples files</span>
<label for='file'>Named graph</label>
<input type='text' name='namedgraph' id='namedgraph' value='default'/>
<span class='help-block'>The named graph where the RDF will be stored (optional).</span>
<br />
<button type='submit' class='btn btn-large'>Submit</button>
</form>
</div>
<div class='span6'>
<legend>Named Graphs</legend>
<div id='ng'></div>
</div>
</div>
<script type='text/javascript' src='".$conf['basedir']."js/jquery.js'></script>
<script type='text/javascript' src='".$conf['basedir']."js/namedgraphs.js'></script>
".$this->foot;
}elseif($_SERVER['REQUEST_METHOD'] == 'POST'){
if ($_FILES["file"]["error"] > 0){
HTTPStatus::send409("No file was included in the request");
}else{
$ng = (isset($_POST['namedgraph']))?$_POST['namedgraph']:'default';
require_once($conf['home'].'lib/arc2/ARC2.php');
$parser = ARC2::getRDFParser();
$parser->parse($_FILES["file"]["tmp_name"]);
$triples = $parser->getTriples();
if(sizeof($triples) > 0){
$c = curl_init();
$body = $parser->toTurtle($triples);
$fp = fopen('php://temp/maxmemory:256000', 'w');
if (!$fp) {
die('could not open temp memory data');
}
fwrite($fp, $body);
fseek($fp, 0);
curl_setopt($c, CURLOPT_URL, $conf['updateendpoint']['local']."?graph=".$ng);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($c, CURLOPT_PUT, 1);
curl_setopt($c, CURLOPT_BINARYTRANSFER, true);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT',"Content-Type: text/turtle"));
curl_setopt($c, CURLOPT_USERAGENT, "LODSPeaKr version ".$conf['version']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($c, CURLOPT_INFILESIZE, strlen($body));
curl_exec($c); // execute the curl command
$http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
if(intval($http_status)>=200 && intval($http_status) <300){
echo $this->head."<h2>Success!!</h2><div class='alert alert-success'>The file ".$_FILES["file"]["name"]." (".$_FILES["file"]["size"]." bytes, ".sizeof($triples)." triples) was stored successfully on $ng.</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}else{
HTTPStatus::send502($this->head."<h2>Error!!</h2><div class='alert alert-success'>The file ".$_FILES["file"]["name"]." couldn't be loaded into the triples store. The server was acting as a gateway or proxy and received an invalid response (".$http_status.") from the upstream server</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot);
}
curl_close($c);
fclose($fp);
}else{
HTTPStatus::send409($this->head."<h2>Error!!</h2><div class='alert alert-error'>The file was not a valid RDF document.</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot);
}
}
}else{
HTTPStatus::send405($_SERVER['REQUEST_METHOD']);
}
exit(0);
}
}
protected function deleteRDF(){
global $conf;
if(!isset($conf['updateendpoint']['local'])){
echo $this->head."
<div class='fluid-row'>
<div class='span8'>
<div class='alert alert-error'><strong>Error:</strong> No SPARQL/UPDATE server found. Please include it in <code>\$conf['updateendpoint']['local']</code> at <strong>settings.inc.php</strong></div>
</div>
</div>
".$this->foot;
}else{
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo $this->head."
<div class='fluid-row'>
<div class='span5'>
<form action='remove' method='post'
enctype='multipart/form-data'>
<legend>Remove a Named Graph containing RDF</legend>
<label for='file'>Named graph</label>
<input type='text' name='namedgraph' id='namedgraph' />
<span class='help-block'>The named graph where the RDF is stored.</span>
<br />
<button type='submit' class='btn'>Submit</button></form>
</div>
<div class='span6'>
<legend>Named Graphs</legend>
<div id='ng'></div>
</div>
</div>
<script type='text/javascript' src='".$conf['basedir']."js/jquery.js'></script>
<script type='text/javascript' src='".$conf['basedir']."js/namedgraphs.js'></script>
".$this->foot;
}elseif($_SERVER['REQUEST_METHOD'] == 'POST'){
$ng = (isset($_POST['namedgraph']))?$_POST['namedgraph']:'default';
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $conf['updateendpoint']['local']."?graph=".$ng);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($c, CURLOPT_BINARYTRANSFER, true);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_USERAGENT, "LODSPeaKr version ".$conf['version']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_exec($c); // execute the curl command
$http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
if(intval($http_status)>=200 && intval($http_status) <300){
echo $this->head."<h2>Success!!</h2><div class='alert alert-success'>The named graph $ng was removed successfully</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}else{
HTTPStatus::send502($this->head."<h2>Error!!</h2><div class='alert alert-error'>The named graph $ng couldn't be removed from the endpoint. The server was acting as a gateway or proxy and received an invalid response (".$http_status.") from the upstream server</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot);
}
curl_close($c);
}else{
HTTPStatus::send405($_SERVER['REQUEST_METHOD']);
}
}
exit(0);
}
protected function editNamespaces(){
global $conf;
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$nstable = "";
foreach($conf['ns'] as $k=>$v){
$nstable .= "<tr><td>".$k."</td><td id='$k'>".$v."</td><td><button class='button btn edit-button' data-prefix='$k' data-ns='$v'>Edit</button></tr>";
}
echo $this->head."
<div class='fluid-row'>
<div class='span7'>
<form action='namespaces' method='post'
enctype='multipart/form-data'>
<legend>Edit main namespace</legend>
<label for='file'>Prefix</label>
<input type='text' name='prefix' id='prefix' value='local'/>
<span class='help-block'>The prefix to describe this namespace ('local' is the one used to mirror URIs of the data in this server)</span>
<label for='file'>Namespace</label>
<input type='text' name='namespace' id='namespace' value='".$conf['ns']['local']."'/>
<span class='help-block'>The namespace of the data being served</span>
<br />
<button type='submit' class='btn'>Submit</button></form>
</div>
<div class='span4 well'>
<legend>Edit local namespace</legend>
<p>'local' namespace defines which types of URI will be mirrored in this server. Thus, it is possible to serve data about <code>http://example.org/myresource</code> by dereferencing <code>".$conf['ns']['local']."myresource</code></p>
<legend>Add a new namespace</legend>
<p>To add a new namespace, simply change the prefix from 'local' to the new one you want to add and include the namespaces in the following box.</p>
<legend>Edit other namespace</legend>
<p>Click on 'edit' in the proper row in the following table and modify the values in the form.</p>
</div>
</div>
<script type='text/javascript' src='".$conf['basedir']."js/jquery.js'></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function(){
$('.edit-button').on('click', function(target){
$('#prefix').val($(this).attr('data-prefix'));
$('#namespace').val($(this).attr('data-ns'));
$('html, body').stop().animate({
scrollTop: $('body').offset().top
}, 1000);
})
});
//]]>
</script>
<div class='fluid-row'>
<div class='span8'>
<legend>Edit other namespaces</legend>
<table class='table table-striped'>
<thead><td>Prefix</td><td>Namespace</td><td>Edit</td></thead>$nstable</table>
".$this->foot;
}elseif($_SERVER['REQUEST_METHOD'] == 'POST'){
$ns = (isset($_POST['namespace']))?$_POST['namespace']:'http://'.$_SERVER['SERVER_NAME'].'/';
$prefix = (isset($_POST['prefix']))?$_POST['prefix']:'local';
$return_var = 0;
exec ("php utils/modules/remove-namespace.php ".$prefix, $output, $return_var);
exec ("php utils/modules/add-namespace.php ".$prefix." ".$ns, $output, $return_var);
if($return_var == 0){
echo $this->head ."<div class='alert alert-success'>Your main namespace was updated successfully to $ns</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}else{
echo $this->head ."<div class='alert alert-error'>Error: Update did not finished successfullt. Please check setting.inc.php located at ".$conf['home'].".</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}
}
}
protected function editEndpoints(){
global $conf;
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$nstable = "";
foreach($conf['endpoint'] as $k=>$v){
$nstable .= "<tr><td>".$k."</td><td id='$k'>".$v."</td><td><button class='button btn edit-button' data-prefix='$k' data-ns='$v'>Edit</button></tr>";
}
echo $this->head."
<div class='fluid-row'>
<div class='span7'>
<form action='endpoints' method='post'
enctype='multipart/form-data'>
<legend>Edit Endpoints</legend>
<label for='file'>Shortname</label>
<input type='text' name='prefix' id='prefix' value='local'/>
<span class='help-block'>The prefix to describe this namespace ('local' is the one used to mirror URIs of the data in this server)</span>
<label for='file'>Endpoint</label>
<input type='text' name='endpoint' id='endpoint' value='".$conf['endpoint']['local']."'/>
<span class='help-block'>The endpoint URL</span>
<br />
<button type='submit' class='btn'>Submit</button></form>
</div>
<div class='span4 well'>
<legend>Add or edit an endpoint</legend>
<p>To add a new endpoint, simply add a new prefix, the SPARQL endpoint URL and click on Submit.</p>
<p>To edit an endpoint, click on 'edit' in the proper row in the following table and modify the values in the form.</p>
</div>
</div>
<script type='text/javascript' src='".$conf['basedir']."js/jquery.js'></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function(){
$('.edit-button').on('click', function(target){
$('#prefix').val($(this).attr('data-prefix'));
$('#endpoint').val($(this).attr('data-ns'));
$('html, body').stop().animate({
scrollTop: $('body').offset().top
}, 1000);
})
});
//]]>
</script>
<div class='fluid-row'>
<div class='span8'>
<legend>Edit other namespaces</legend>
<table class='table table-striped'>
<thead><td>Prefix</td><td>Namespace</td><td>Edit</td></thead>$nstable</table>
".$this->foot;
}elseif($_SERVER['REQUEST_METHOD'] == 'POST'){
$ns = (isset($_POST['endpoint']))?$_POST['endpoint']:'http://'.$_SERVER['SERVER_NAME'].'/';
$prefix = (isset($_POST['prefix']))?$_POST['prefix']:'local';
$return_var = 0;
exec ("php utils/modules/remove-endpoint.php ".$prefix, $output, $return_var);
exec ("php utils/modules/add-endpoint.php ".$prefix." ".$ns, $output, $return_var);
if($return_var == 0){
echo $this->head ."<div class='alert alert-success'>Your endpoint was updated successfully to $ns</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}else{
echo $this->head ."<div class='alert alert-error'>Error: Update did not finished successfully. Please check setting.inc.php located at ".$conf['home'].".</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}
}
}
protected function startEndpoint(){
$return_var = 0;
exec ("utils/modules/start-endpoint.sh", $output, $return_var);
if($return_var == 0){
echo $this->head ."<div class='alert alert-success'>Endpoint starter successfully</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}else{
echo $this->head ."<div class='alert alert-error'>Error: /tmp/fusekiPid already exists. This probably means Fuseki is already running. You could also try to <a href='stop'>stop</a> the endpoint first.</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}
}
protected function componentEditor(){
global $lodspk;
global $conf;
exec ("utils/lodspk.sh list components", $output, $return_var);
$menu = "";
$endpointOptions = "";
foreach($conf['endpoint'] as $k => $v){
$selected = "";
if($k == "local")
$selected = 'selected';
$endpointOptions .= "<option $selected value='$k'>$k ($v)</option>";
}
$namespaces = "var ns = ".json_encode($conf['ns']);
$lastComponentType="";
$onlyService = false;
foreach($output as $line){
if($line == ""){
$menu .= "</ul>\n";
}else{
if(preg_match("/^\w/", $line) ){
$lastComponentType = trim($line);
$singleLastComponentType = preg_replace('/(.*)s$/', '\1', $lastComponentType);
$menu .= "<ul class='nav nav-list'>
<li class='nav-header'>".$lastComponentType." <button class='btn btn-mini btn-info new-button' style='float:right' data-type='$singleLastComponentType'>new</button></li>\n";
}else{
$componentName = trim($line);
$menu .= "<li class='component-li'> <button type='button' class='close hide lodspk-delete-component' data-component-type='$singleLastComponentType' data-component-name='$componentName' style='align:left'>x</button>
<a href='#$componentName' class='lodspk-component' data-component-type='$lastComponentType' data-component-name='$componentName'>".$componentName."</a></li>\n";
}
}
}
echo $this->head ."
<script type='application/javascript'>
var home='".$conf['basedir']."';
$namespaces
</script>
<div class='row-fluid'>
<div class='span3 well'>$menu<div id='component-msg' class='alert hide'></div></div>
<div class='bs-docs-template span9'>
<textarea class='field span12' rows='8' cols='25' id='template-editor' name='template-editor'></textarea>
<button class='btn btn-info disabled' id='template-save-button' data-url=''>Save</button>
<div class='alert alert-success hide' id='template-msg'></div>
</div>
</div>
<div class='row-fluid'>
<div class='span3'>
<div class='container'>
<div class='row-fluid'>
<div class='span3 well'>
<legend>Views <!-- button class='btn btn-mini btn-info new-file-button hide new-file-button-view' data-component=''>new</button --></legend>
<ul class='nav nav-list' id='template-list'>
</ul>
</div>
</div>
<div class='row-fluid'>
<div class='span3 well'>
<legend>Models <button class='btn btn-mini btn-info new-file-button hide new-file-button-model' data-component=''>new</button></legend>
<ul class='nav nav-list' id='query-list'>
</ul>
</div>
</div>
<div class='row-fluid'>
<div class='span3'>
<p><a href='#' id='preview-button' class='hide'><button class='btn btn-success btn-large'>View component</button></a></p>
<p><button id='embed-button' class='btn btn-success btn-large hide'>Share component</button></p>
</div>
</div>
</div>
</div>
<div class='span9 bs-docs-query'>
<textarea class='field span12' rows='8' cols='25' id='query-editor'></textarea>
<button class='btn btn-info disabled' id='query-save-button' data-url=''>Save</button>
<select style='float:right' id='endpoint-list'>$endpointOptions</select>
<button class='btn btn-success' style='float:right; margin-right:20px' id='query-test-button'>Test this query against</button>
<div class='alert alert-success hide' id='query-msg'></div>
</div>
</div>
<div class='row-fluid'>
<div class='span12'>
<h2>Query results preview</h2>
<span class='alert alert-error hide' id='results-msg'></span>
<table class='table' id='results'></table>
<div style='height:300px'></div>
</div>
</div>
</div>
</div>
</div>
<script src='".$conf['basedir'] ."admin/codemirror/lib/codemirror.js'></script>
<script src='".$conf['basedir'] ."admin/codemirror/lib/util/overlay.js'></script>
<script src='".$conf['basedir'] ."admin/codemirror/mode/xml/xml.js'></script>
<script src='".$conf['basedir'] ."admin/codemirror/mode/sparql/sparql.js'></script>
<script src='".$conf['basedir'] ."admin/js/editor.js'></script>
".$this->foot;
}
protected function componentEditorApi($params){
switch($params[0]){
case "details":
$this->getComponentDetails(array_slice($params, 1));
break;
case "save":
if(sizeof($params) > 2){
$this->saveComponent($params);
}else{
HTTPStatus::send404($params[1]);
}
break;
case "create":
if(sizeof($params) > 2){
$this->createComponent($params);
}else{
HTTPStatus::send404($params[1]);
}
break;
case "delete":
if(sizeof($params) > 2){
$this->deleteComponent($params);
}else{
HTTPStatus::send404($params[1]);
}
break;
case "add":
if(sizeof($params) > 2){
$this->addFile($params);
}else{
HTTPStatus::send404($params[1]);
}
break;
case "remove":
if(sizeof($params) > 2){
$this->deleteFile($params);
}else{
HTTPStatus::send404($params[1]);
}
break;
case "query":
$this->queryEndpoint($_POST);
break;
default:
HTTPStatus::send404($params[1]);
}
}
protected function queryEndpoint($data){
global $endpoints;
global $conf;
$query = $data['query'];
$endpoint = $data['endpoint'];
if(isset($endpoint) && isset($conf['endpoint'][$endpoint])){
if(!isset($endpoints[$endpoint])){
$e = new Endpoint($conf['endpoint'][$endpoint], $conf['endpoint']['config']);
}else{
$e = $endpoints[$endpoint];
}
$aux = $e->query($query, Utils::getResultsType($query));
header("Content-type: ".$data['format']);
$jaux = json_encode($aux);
if(isset($jaux)){
echo $jaux;
}else{
echo $aux;
HTTPStatus::send404($params[1]);
}
}else{
echo "no endpoint";
HTTPStatus::send404($params[1]);
}
}
protected function getComponentDetails($params){
$componentType = $params[0];
$componentName = $params[1];
if(!isset($componentType) || !isset($componentName)){
HTTPStatus::send404();
exit(0);
}
$return_var = 0;
exec ("utils/modules/detail-component.sh $componentType $componentName", $output, $return_var);
if($return_var == 0){
$comps = array();
$lastKey = "";
foreach($output as $line){
if($line == ""){
$menu .= "</ul>\n";
}else{
if(preg_match("/^\w/", $line) ){
$lastKey = trim($line);
$comps[$lastKey] = array();
}else{
array_push($comps[$lastKey], trim($line));
}
}
}
header("Content-type: application/json");
echo json_encode($comps);
}else{
HTTPStatus::send500();
exit(0);
}
}
protected function saveComponent($params){
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$path = implode("/", array_slice($params, 1));
if(file_exists("components/".$path)){
$result = file_put_contents("components/".$path,$_POST['content'] );
if($result === FALSE){
HTTPStatus::send500();
}else{
echo json_encode(array('success' => true, 'size' => $result));
}
}else{
HTTPStatus::send500();
exit(0);
}
}
}
protected function createComponent($params){
$path = implode("/", array_slice($params, 1));
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(sizeof($params) != 3){
HTTPStatus::send404();
exit(0);
}
$return_var = 0;
exec ("utils/lodspk.sh create ".$params[1]." ".$params[2], $output, $return_var);
//echo $return_var;exit(0);
if($return_var !== 0){
HTTPStatus::send500($params[0]." ".$params[1]);
}else{
echo json_encode(array('success' => true, 'size' => $result));
}
}else{
HTTPStatus::send406();
exit(0);
}
}
protected function deleteComponent($params){
$path = implode("/", array_slice($params, 1));
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(sizeof($params) != 3){
HTTPStatus::send404();
exit(0);
}
$return_var = 0;
exec ("utils/lodspk.sh delete ".$params[1]." ".$params[2], $output, $return_var);
if($return_var !== 0){
HTTPStatus::send500($params[0]." ".$params[1]);
}else{
echo json_encode(array('success' => true, 'size' => $result));
}
}else{
HTTPStatus::send406();
exit(0);
}
}
protected function deleteFile($params){
$path = "components/".implode("/", array_slice($params, 1));
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(sizeof($params) < 3){
HTTPStatus::send404();
exit(0);
}
$return_var = 0;
if(strpos($path, "components") === 0 && strpos($path, '..') === FALSE){
exec ("rm ".$path, $output, $return_var);
if($return_var !== 0){
echo json_encode(array('success' => false, path => $path));
}else{
echo json_encode(array('success' => true, path => $path));
}
}else{
HTTPStatus::send406();
exit(0);
}
}else{
echo json_encode(array('success' => false, path => $path));
}
}
protected function addFile($params){
$path = "components/".implode("/", array_slice($params, 1));
$basicContent = "SELECT * WHERE{
?s ?p ?o
}LIMIT 10";
if(strpos($path, ".template") !== FALSE){
//It is not a query, but a template
$basicContent = "<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
</head>
<body>
</body>
</html>";
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(sizeof($params) < 3){
HTTPStatus::send404();
exit(0);
}
$return_var = 0;
if(file_exists($path)){
echo json_encode(array('success' => false));
return;
}
$dirpath=$path;
$dirArray = explode("/", $path);
array_pop($dirArray);
$dirpath = implode("/", $dirArray);
if(!is_dir($dirpath)){
$oldumask = umask(0);
$return_var = mkdir($dirpath, 0755, true);
umask($oldumask);
if($return_var === FALSE){
HTTPStatus::send500("mkdir ".var_export($return_var, true)." ".$dirpath);
}
}
$return_var = file_put_contents($path, $basicContent );
//echo $return_var;exit(0);
if($return_var === FALSE){
HTTPStatus::send500("file_puts_content ".var_export($return_var, true)." ".$path);
}else{
echo json_encode(array('success' => true, 'return' => $return_var));
}
}else{
HTTPStatus::send406();
exit(0);
}
}
protected function stopEndpoint(){
$return_var = 0;
exec ("utils/modules/stop-endpoint.sh", $output, $return_var);
if($return_var == 0){
echo $this->head ."<div class='alert alert-success'>Endpoint stopped successfully</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}else{
echo $this->head ."<div class='alert alert-error'>Error: Something went wrong. Are you sure the endpoint is running?</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>".$this->foot;
}
}
protected function homeMenu(){
global $conf;
$output = array();
echo $this->head."
<div class='well span5'>
<h2>Components Editor</h2>
<p>You can create, remove and edit components (services types, etc) using the <a href='components'>editor</a></p>
<a href='components'><button class='btn btn-large btn-info'>Go to Editor</button></a>
</div>
<div class='span5 well'>
<h2>Options</h2>
<p>You can also:</p>
<ul>
<li>Add, remove or <a href='namespaces'>edit namespaces</a></li>
<li>Add, remove or <a href='endpoints'>edit endpoints</a></li>
</ul>
</div>
".$this->foot;
}
protected function auth(){
global $conf;
$realm = 'Restricted area';
//user => password
$users = array('admin' => $conf['admin']['pass']);
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Access to administration menu requires valid authentication');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = $this->http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
return FALSE;
//die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response)
return FALSE;
// die('Wrong Credentials!');
// ok, valid username & password
//echo 'You are logged in as: ' . $data['username'];
return TRUE;
}
// function to parse the http auth header
protected function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
}
?>
| {
"content_hash": "94d7ea902211ef2fb33a6af5ba49bb5d",
"timestamp": "",
"source": "github",
"line_count": 987,
"max_line_length": 397,
"avg_line_length": 37.69807497467072,
"alnum_prop": 0.5659266824338852,
"repo_name": "armandobs14/lodspeakr",
"id": "3f302a723b4ac8e2949c8d1d9cb22d5287a86275",
"size": "37208",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "classes/modules/adminModule.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "205"
},
{
"name": "HTML",
"bytes": "17314"
},
{
"name": "Makefile",
"bytes": "460"
},
{
"name": "PHP",
"bytes": "1133564"
},
{
"name": "Shell",
"bytes": "31210"
},
{
"name": "Smarty",
"bytes": "12466"
},
{
"name": "Yacc",
"bytes": "17086"
}
],
"symlink_target": ""
} |
import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
from pybullet_envs.bullet.kukaCamGymEnv import KukaCamGymEnv
import time
def main():
environment = KukaCamGymEnv(renders=True, isDiscrete=False)
motorsIds = []
#motorsIds.append(environment._p.addUserDebugParameter("posX",0.4,0.75,0.537))
#motorsIds.append(environment._p.addUserDebugParameter("posY",-.22,.3,0.0))
#motorsIds.append(environment._p.addUserDebugParameter("posZ",0.1,1,0.2))
#motorsIds.append(environment._p.addUserDebugParameter("yaw",-3.14,3.14,0))
#motorsIds.append(environment._p.addUserDebugParameter("fingerAngle",0,0.3,.3))
dv = 1
motorsIds.append(environment._p.addUserDebugParameter("posX", -dv, dv, 0))
motorsIds.append(environment._p.addUserDebugParameter("posY", -dv, dv, 0))
motorsIds.append(environment._p.addUserDebugParameter("posZ", -dv, dv, 0))
motorsIds.append(environment._p.addUserDebugParameter("yaw", -dv, dv, 0))
motorsIds.append(environment._p.addUserDebugParameter("fingerAngle", 0, 0.3, .3))
done = False
while (not done):
action = []
for motorId in motorsIds:
action.append(environment._p.readUserDebugParameter(motorId))
state, reward, done, info = environment.step(action)
obs = environment.getExtendedObservation()
if __name__ == "__main__":
main()
| {
"content_hash": "67b2e1b46023003c99a2fa2b3a32e057",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 86,
"avg_line_length": 36.375,
"alnum_prop": 0.7312714776632302,
"repo_name": "MTASZTAKI/ApertusVR",
"id": "6cf9909cb2953d0ab85fda760cf3ab617398ef8b",
"size": "1552",
"binary": false,
"copies": "3",
"ref": "refs/heads/0.9",
"path": "plugins/physics/bulletPhysics/3rdParty/bullet3/examples/pybullet/gym/pybullet_envs/examples/kukaCamGymEnvTest.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7599"
},
{
"name": "C++",
"bytes": "1207412"
},
{
"name": "CMake",
"bytes": "165066"
},
{
"name": "CSS",
"bytes": "1816"
},
{
"name": "GLSL",
"bytes": "223507"
},
{
"name": "HLSL",
"bytes": "141879"
},
{
"name": "HTML",
"bytes": "34827"
},
{
"name": "JavaScript",
"bytes": "140550"
},
{
"name": "Python",
"bytes": "1370"
}
],
"symlink_target": ""
} |
package analyzer
import (
"errors"
"flag"
"go/ast"
"go/types"
"strings"
"sync"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var (
ErrEmptyPattern = errors.New("pattern can't be empty")
)
type analyzer struct {
include PatternsList
exclude PatternsList
typesProcessCache map[types.Type]bool
typesProcessCacheMu sync.RWMutex
structFieldsCache map[types.Type]*StructFields
structFieldsCacheMu sync.RWMutex
}
// NewAnalyzer returns a go/analysis-compatible analyzer.
// -i arguments adds include patterns
// -e arguments adds exclude patterns
func NewAnalyzer(include []string, exclude []string) (*analysis.Analyzer, error) {
a := analyzer{ //nolint:exhaustruct
typesProcessCache: map[types.Type]bool{},
structFieldsCache: map[types.Type]*StructFields{},
}
var err error
a.include, err = newPatternsList(include)
if err != nil {
return nil, err
}
a.exclude, err = newPatternsList(exclude)
if err != nil {
return nil, err
}
return &analysis.Analyzer{ //nolint:exhaustruct
Name: "exhaustruct",
Doc: "Checks if all structure fields are initialized",
Run: a.run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
Flags: a.newFlagSet(),
}, nil
}
func (a *analyzer) newFlagSet() flag.FlagSet {
fs := flag.NewFlagSet("exhaustruct flags", flag.PanicOnError)
fs.Var(
&reListVar{values: &a.include},
"i",
"Regular expression to match struct packages and names, can receive multiple flags",
)
fs.Var(
&reListVar{values: &a.exclude},
"e",
"Regular expression to exclude struct packages and names, can receive multiple flags",
)
return *fs
}
func (a *analyzer) run(pass *analysis.Pass) (interface{}, error) {
insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) //nolint:forcetypeassert
nodeTypes := []ast.Node{
(*ast.CompositeLit)(nil),
(*ast.ReturnStmt)(nil),
}
insp.Preorder(nodeTypes, a.newVisitor(pass))
return nil, nil //nolint:nilnil
}
//nolint:cyclop
func (a *analyzer) newVisitor(pass *analysis.Pass) func(node ast.Node) {
var ret *ast.ReturnStmt
return func(node ast.Node) {
if retLit, ok := node.(*ast.ReturnStmt); ok {
// save return statement for future (to detect error-containing returns)
ret = retLit
return
}
lit, _ := node.(*ast.CompositeLit)
if lit.Type == nil {
// we're not interested in non-typed literals
return
}
typ := pass.TypesInfo.TypeOf(lit.Type)
if typ == nil {
return
}
strct, ok := typ.Underlying().(*types.Struct)
if !ok {
// we also not interested in non-structure literals
return
}
strctName := exprName(lit.Type)
if strctName == "" {
return
}
if !a.shouldProcessType(typ) {
return
}
if len(lit.Elts) == 0 && ret != nil {
if ret.End() < lit.Pos() {
// we're outside last return statement
ret = nil
} else if returnContainsLiteral(ret, lit) && returnContainsError(ret, pass) {
// we're okay with empty literals in return statements with non-nil errors, like
// `return my.Struct{}, fmt.Errorf("non-nil error!")`
return
}
}
missingFields := a.structMissingFields(lit, strct, strings.HasPrefix(typ.String(), pass.Pkg.Path()+"."))
if len(missingFields) == 1 {
pass.Reportf(node.Pos(), "%s is missing in %s", missingFields[0], strctName)
} else if len(missingFields) > 1 {
pass.Reportf(node.Pos(), "%s are missing in %s", strings.Join(missingFields, ", "), strctName)
}
}
}
func (a *analyzer) shouldProcessType(typ types.Type) bool {
if len(a.include) == 0 && len(a.exclude) == 0 {
// skip whole part with cache, since we have no restrictions and have to check everything
return true
}
a.typesProcessCacheMu.RLock()
v, ok := a.typesProcessCache[typ]
a.typesProcessCacheMu.RUnlock()
if !ok {
a.typesProcessCacheMu.Lock()
defer a.typesProcessCacheMu.Unlock()
v = true
typStr := typ.String()
if len(a.include) > 0 && !a.include.MatchesAny(typStr) {
v = false
}
if v && a.exclude.MatchesAny(typStr) {
v = false
}
a.typesProcessCache[typ] = v
}
return v
}
func (a *analyzer) structMissingFields(lit *ast.CompositeLit, strct *types.Struct, private bool) []string {
keys, unnamed := literalKeys(lit)
fields := a.structFields(strct)
var fieldNames []string
if private {
// we're in same package and should match private fields
fieldNames = fields.All
} else {
fieldNames = fields.Public
}
if unnamed {
return fieldNames[len(keys):]
}
return difference(fieldNames, keys)
}
func (a *analyzer) structFields(strct *types.Struct) *StructFields {
typ := strct.Underlying()
a.structFieldsCacheMu.RLock()
fields, ok := a.structFieldsCache[typ]
a.structFieldsCacheMu.RUnlock()
if !ok {
a.structFieldsCacheMu.Lock()
defer a.structFieldsCacheMu.Unlock()
fields = NewStructFields(strct)
a.structFieldsCache[typ] = fields
}
return fields
}
func returnContainsLiteral(ret *ast.ReturnStmt, lit *ast.CompositeLit) bool {
for _, result := range ret.Results {
if l, ok := result.(*ast.CompositeLit); ok {
if lit == l {
return true
}
}
}
return false
}
func returnContainsError(ret *ast.ReturnStmt, pass *analysis.Pass) bool {
for _, result := range ret.Results {
if pass.TypesInfo.TypeOf(result).String() == "error" {
return true
}
}
return false
}
func literalKeys(lit *ast.CompositeLit) (keys []string, unnamed bool) {
for _, elt := range lit.Elts {
if k, ok := elt.(*ast.KeyValueExpr); ok {
if ident, ok := k.Key.(*ast.Ident); ok {
keys = append(keys, ident.Name)
}
continue
}
// in case we deal with unnamed initialization - no need to iterate over all
// elements - simply create slice with proper size
unnamed = true
keys = make([]string, len(lit.Elts))
return
}
return
}
// difference returns elements that are in `a` and not in `b`.
func difference(a, b []string) (diff []string) {
mb := make(map[string]struct{}, len(b))
for _, x := range b {
mb[x] = struct{}{}
}
for _, x := range a {
if _, found := mb[x]; !found {
diff = append(diff, x)
}
}
return diff
}
func exprName(expr ast.Expr) string {
if i, ok := expr.(*ast.Ident); ok {
return i.Name
}
s, ok := expr.(*ast.SelectorExpr)
if !ok {
return ""
}
return s.Sel.Name
}
| {
"content_hash": "ccf2e7191a4016e85337e8f1cae83a17",
"timestamp": "",
"source": "github",
"line_count": 290,
"max_line_length": 107,
"avg_line_length": 21.817241379310346,
"alnum_prop": 0.6707760391970918,
"repo_name": "nalind/buildah-1",
"id": "4da988426b1b00976a6462aed52011c3ce23a271",
"size": "6327",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "tests/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/analyzer.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "512"
},
{
"name": "Dockerfile",
"bytes": "13995"
},
{
"name": "Go",
"bytes": "1275228"
},
{
"name": "Makefile",
"bytes": "8990"
},
{
"name": "Nix",
"bytes": "5882"
},
{
"name": "Perl",
"bytes": "10721"
},
{
"name": "Roff",
"bytes": "1045"
},
{
"name": "Shell",
"bytes": "572659"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02.Count of Negative Elements")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.Count of Negative Elements")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3dc5ae22-0862-44cc-8063-188dfad32a03")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "0c9a7b348c5e57724fae6517a3867692",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.75,
"alnum_prop": 0.7456324248777079,
"repo_name": "dgeshev/-Programming-Fundamentals",
"id": "0d22d4db75eb87b7bb72dd51ede57dd755d6b3f8",
"size": "1434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Extended mode/06.Arrays-Exercises/02.Count of Negative Elements/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "236657"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>gdp</artifactId>
<groupId>com.paouke</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>com.paouke.gdp.youdaoTranslate</artifactId>
<dependencies>
<dependency>
<groupId>com.paouke</groupId>
<artifactId>com.paouke.gdp.common</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<archive>
<manifest>
<mainClass>com.paouke.gdp.youdaoTranslate.main.YoudaoTranslateMain</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project> | {
"content_hash": "87369b759430b28eadd14f9d6cbfa144",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 108,
"avg_line_length": 32.31111111111111,
"alnum_prop": 0.53232462173315,
"repo_name": "NinthCode/gdp",
"id": "631ebe5b805126cf79d8962444b02e138bc2495f",
"size": "1454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com.paouke.gdp.youdaoTranslate/pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "28498"
},
{
"name": "Java",
"bytes": "103403"
}
],
"symlink_target": ""
} |
package graphdriver
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/containers/storage/pkg/archive"
"github.com/containers/storage/pkg/directory"
"github.com/containers/storage/pkg/idtools"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
"github.com/vbatts/tar-split/tar/storage"
)
// FsMagic unsigned id of the filesystem in use.
type FsMagic uint32
const (
// FsMagicUnsupported is a predefined constant value other than a valid filesystem id.
FsMagicUnsupported = FsMagic(0x00000000)
)
var (
// All registered drivers
drivers map[string]InitFunc
// ErrNotSupported returned when driver is not supported.
ErrNotSupported = errors.New("driver not supported")
// ErrPrerequisites returned when driver does not meet prerequisites.
ErrPrerequisites = errors.New("prerequisites for driver not satisfied (wrong filesystem?)")
// ErrIncompatibleFS returned when file system is not supported.
ErrIncompatibleFS = errors.New("backing file system is unsupported for this graph driver")
// ErrLayerUnknown returned when the specified layer is unknown by the driver.
ErrLayerUnknown = errors.New("unknown layer")
)
// CreateOpts contains optional arguments for Create() and CreateReadWrite()
// methods.
type CreateOpts struct {
MountLabel string
StorageOpt map[string]string
*idtools.IDMappings
ignoreChownErrors bool
}
// MountOpts contains optional arguments for Driver.Get() methods.
type MountOpts struct {
// Mount label is the MAC Labels to assign to mount point (SELINUX)
MountLabel string
// UidMaps & GidMaps are the User Namespace mappings to be assigned to content in the mount point
UidMaps []idtools.IDMap //nolint: golint,revive
GidMaps []idtools.IDMap //nolint: golint
Options []string
// Volatile specifies whether the container storage can be optimized
// at the cost of not syncing all the dirty files in memory.
Volatile bool
// DisableShifting forces the driver to not do any ID shifting at runtime.
DisableShifting bool
}
// ApplyDiffOpts contains optional arguments for ApplyDiff methods.
type ApplyDiffOpts struct {
Diff io.Reader
Mappings *idtools.IDMappings
MountLabel string
IgnoreChownErrors bool
ForceMask *os.FileMode
}
// InitFunc initializes the storage driver.
type InitFunc func(homedir string, options Options) (Driver, error)
// ProtoDriver defines the basic capabilities of a driver.
// This interface exists solely to be a minimum set of methods
// for client code which choose not to implement the entire Driver
// interface and use the NaiveDiffDriver wrapper constructor.
//
// Use of ProtoDriver directly by client code is not recommended.
type ProtoDriver interface {
// String returns a string representation of this driver.
String() string
// CreateReadWrite creates a new, empty filesystem layer that is ready
// to be used as the storage for a container. Additional options can
// be passed in opts. parent may be "" and opts may be nil.
CreateReadWrite(id, parent string, opts *CreateOpts) error
// Create creates a new, empty, filesystem layer with the
// specified id and parent and options passed in opts. Parent
// may be "" and opts may be nil.
Create(id, parent string, opts *CreateOpts) error
// CreateFromTemplate creates a new filesystem layer with the specified id
// and parent, with contents identical to the specified template layer.
CreateFromTemplate(id, template string, templateIDMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, opts *CreateOpts, readWrite bool) error
// Remove attempts to remove the filesystem layer with this id.
Remove(id string) error
// Get returns the mountpoint for the layered filesystem referred
// to by this id. You can optionally specify a mountLabel or "".
// Optionally it gets the mappings used to create the layer.
// Returns the absolute path to the mounted layered filesystem.
Get(id string, options MountOpts) (dir string, err error)
// Put releases the system resources for the specified id,
// e.g, unmounting layered filesystem.
Put(id string) error
// Exists returns whether a filesystem layer with the specified
// ID exists on this driver.
Exists(id string) bool
// Status returns a set of key-value pairs which give low
// level diagnostic status about this driver.
Status() [][2]string
// Returns a set of key-value pairs which give low level information
// about the image/container driver is managing.
Metadata(id string) (map[string]string, error)
// ReadWriteDiskUsage returns the disk usage of the writable directory for the specified ID.
ReadWriteDiskUsage(id string) (*directory.DiskUsage, error)
// Cleanup performs necessary tasks to release resources
// held by the driver, e.g., unmounting all layered filesystems
// known to this driver.
Cleanup() error
// AdditionalImageStores returns additional image stores supported by the driver
// This API is experimental and can be changed without bumping the major version number.
AdditionalImageStores() []string
}
// DiffDriver is the interface to use to implement graph diffs
type DiffDriver interface {
// Diff produces an archive of the changes between the specified
// layer and its parent layer which may be "".
Diff(id string, idMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, mountLabel string) (io.ReadCloser, error)
// Changes produces a list of changes between the specified layer
// and its parent layer. If parent is "", then all changes will be ADD changes.
Changes(id string, idMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, mountLabel string) ([]archive.Change, error)
// ApplyDiff extracts the changeset from the given diff into the
// layer with the specified id and parent, returning the size of the
// new layer in bytes.
// The io.Reader must be an uncompressed stream.
ApplyDiff(id string, parent string, options ApplyDiffOpts) (size int64, err error)
// DiffSize calculates the changes between the specified id
// and its parent and returns the size in bytes of the changes
// relative to its base filesystem directory.
DiffSize(id string, idMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, mountLabel string) (size int64, err error)
}
// LayerIDMapUpdater is the interface that implements ID map changes for layers.
type LayerIDMapUpdater interface {
// UpdateLayerIDMap walks the layer's filesystem tree, changing the ownership
// information using the toContainer and toHost mappings, using them to replace
// on-disk owner UIDs and GIDs which are "host" values in the first map with
// UIDs and GIDs for "host" values from the second map which correspond to the
// same "container" IDs. This method should only be called after a layer is
// first created and populated, and before it is mounted, as other changes made
// relative to a parent layer, but before this method is called, may be discarded
// by Diff().
UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMappings, mountLabel string) error
// SupportsShifting tells whether the driver support shifting of the UIDs/GIDs in a
// image and it is not required to Chown the files when running in an user namespace.
SupportsShifting() bool
}
// Driver is the interface for layered/snapshot file system drivers.
type Driver interface {
ProtoDriver
DiffDriver
LayerIDMapUpdater
}
// DriverWithDifferOutput is the result of ApplyDiffWithDiffer
// This API is experimental and can be changed without bumping the major version number.
type DriverWithDifferOutput struct {
Differ Differ
Target string
Size int64
UIDs []uint32
GIDs []uint32
UncompressedDigest digest.Digest
Metadata string
BigData map[string][]byte
}
// Differ defines the interface for using a custom differ.
// This API is experimental and can be changed without bumping the major version number.
type Differ interface {
ApplyDiff(dest string, options *archive.TarOptions) (DriverWithDifferOutput, error)
}
// DriverWithDiffer is the interface for direct diff access.
// This API is experimental and can be changed without bumping the major version number.
type DriverWithDiffer interface {
Driver
// ApplyDiffWithDiffer applies the changes using the callback function.
// If id is empty, then a staging directory is created. The staging directory is guaranteed to be usable with ApplyDiffFromStagingDirectory.
ApplyDiffWithDiffer(id, parent string, options *ApplyDiffOpts, differ Differ) (output DriverWithDifferOutput, err error)
// ApplyDiffFromStagingDirectory applies the changes using the specified staging directory.
ApplyDiffFromStagingDirectory(id, parent, stagingDirectory string, diffOutput *DriverWithDifferOutput, options *ApplyDiffOpts) error
// CleanupStagingDirectory cleanups the staging directory. It can be used to cleanup the staging directory on errors
CleanupStagingDirectory(stagingDirectory string) error
// DifferTarget gets the location where files are stored for the layer.
DifferTarget(id string) (string, error)
}
// Capabilities defines a list of capabilities a driver may implement.
// These capabilities are not required; however, they do determine how a
// graphdriver can be used.
type Capabilities struct {
// Flags that this driver is capable of reproducing exactly equivalent
// diffs for read-only layers. If set, clients can rely on the driver
// for consistent tar streams, and avoid extra processing to account
// for potential differences (eg: the layer store's use of tar-split).
ReproducesExactDiffs bool
}
// CapabilityDriver is the interface for layered file system drivers that
// can report on their Capabilities.
type CapabilityDriver interface {
Capabilities() Capabilities
}
// AdditionalLayer reprents a layer that is stored in the additional layer store
// This API is experimental and can be changed without bumping the major version number.
type AdditionalLayer interface {
// CreateAs creates a new layer from this additional layer
CreateAs(id, parent string) error
// Info returns arbitrary information stored along with this layer (i.e. `info` file)
Info() (io.ReadCloser, error)
// Blob returns a reader of the raw contents of this layer.
Blob() (io.ReadCloser, error)
// Release tells the additional layer store that we don't use this handler.
Release()
}
// AdditionalLayerStoreDriver is the interface for driver that supports
// additional layer store functionality.
// This API is experimental and can be changed without bumping the major version number.
type AdditionalLayerStoreDriver interface {
Driver
// LookupAdditionalLayer looks up additional layer store by the specified
// digest and ref and returns an object representing that layer.
LookupAdditionalLayer(d digest.Digest, ref string) (AdditionalLayer, error)
// LookupAdditionalLayer looks up additional layer store by the specified
// ID and returns an object representing that layer.
LookupAdditionalLayerByID(id string) (AdditionalLayer, error)
}
// DiffGetterDriver is the interface for layered file system drivers that
// provide a specialized function for getting file contents for tar-split.
type DiffGetterDriver interface {
Driver
// DiffGetter returns an interface to efficiently retrieve the contents
// of files in a layer.
DiffGetter(id string) (FileGetCloser, error)
}
// FileGetCloser extends the storage.FileGetter interface with a Close method
// for cleaning up.
type FileGetCloser interface {
storage.FileGetter
// Close cleans up any resources associated with the FileGetCloser.
Close() error
}
// Checker makes checks on specified filesystems.
type Checker interface {
// IsMounted returns true if the provided path is mounted for the specific checker
IsMounted(path string) bool
}
func init() {
drivers = make(map[string]InitFunc)
}
// MustRegister registers an InitFunc for the driver, or panics.
// It is suitable for package’s init() sections.
func MustRegister(name string, initFunc InitFunc) {
if err := Register(name, initFunc); err != nil {
panic(fmt.Sprintf("failed to register containers/storage graph driver %q: %v", name, err))
}
}
// Register registers an InitFunc for the driver.
func Register(name string, initFunc InitFunc) error {
if _, exists := drivers[name]; exists {
return fmt.Errorf("name already registered %s", name)
}
drivers[name] = initFunc
return nil
}
// GetDriver initializes and returns the registered driver
func GetDriver(name string, config Options) (Driver, error) {
if initFunc, exists := drivers[name]; exists {
return initFunc(filepath.Join(config.Root, name), config)
}
logrus.Errorf("Failed to GetDriver graph %s %s", name, config.Root)
return nil, fmt.Errorf("failed to GetDriver graph %s %s: %w", name, config.Root, ErrNotSupported)
}
// getBuiltinDriver initializes and returns the registered driver, but does not try to load from plugins
func getBuiltinDriver(name, home string, options Options) (Driver, error) {
if initFunc, exists := drivers[name]; exists {
return initFunc(filepath.Join(home, name), options)
}
logrus.Errorf("Failed to built-in GetDriver graph %s %s", name, home)
return nil, fmt.Errorf("failed to built-in GetDriver graph %s %s: %w", name, home, ErrNotSupported)
}
// Options is used to initialize a graphdriver
type Options struct {
Root string
RunRoot string
DriverOptions []string
UIDMaps []idtools.IDMap
GIDMaps []idtools.IDMap
ExperimentalEnabled bool
}
// New creates the driver and initializes it at the specified root.
func New(name string, config Options) (Driver, error) {
if name != "" {
logrus.Debugf("[graphdriver] trying provided driver %q", name) // so the logs show specified driver
return GetDriver(name, config)
}
// Guess for prior driver
driversMap := scanPriorDrivers(config.Root)
for _, name := range priority {
if name == "vfs" {
// don't use vfs even if there is state present.
continue
}
if _, prior := driversMap[name]; prior {
// of the state found from prior drivers, check in order of our priority
// which we would prefer
driver, err := getBuiltinDriver(name, config.Root, config)
if err != nil {
// unlike below, we will return error here, because there is prior
// state, and now it is no longer supported/prereq/compatible, so
// something changed and needs attention. Otherwise the daemon's
// images would just "disappear".
logrus.Errorf("[graphdriver] prior storage driver %s failed: %s", name, err)
return nil, err
}
// abort starting when there are other prior configured drivers
// to ensure the user explicitly selects the driver to load
if len(driversMap)-1 > 0 {
var driversSlice []string
for name := range driversMap {
driversSlice = append(driversSlice, name)
}
return nil, fmt.Errorf("%s contains several valid graphdrivers: %s; Please cleanup or explicitly choose storage driver (-s <DRIVER>)", config.Root, strings.Join(driversSlice, ", "))
}
logrus.Infof("[graphdriver] using prior storage driver: %s", name)
return driver, nil
}
}
// Check for priority drivers first
for _, name := range priority {
driver, err := getBuiltinDriver(name, config.Root, config)
if err != nil {
if isDriverNotSupported(err) {
continue
}
return nil, err
}
return driver, nil
}
// Check all registered drivers if no priority driver is found
for name, initFunc := range drivers {
driver, err := initFunc(filepath.Join(config.Root, name), config)
if err != nil {
if isDriverNotSupported(err) {
continue
}
return nil, err
}
return driver, nil
}
return nil, fmt.Errorf("no supported storage backend found")
}
// isDriverNotSupported returns true if the error initializing
// the graph driver is a non-supported error.
func isDriverNotSupported(err error) bool {
return errors.Is(err, ErrNotSupported) || errors.Is(err, ErrPrerequisites) || errors.Is(err, ErrIncompatibleFS)
}
// scanPriorDrivers returns an un-ordered scan of directories of prior storage drivers
func scanPriorDrivers(root string) map[string]bool {
driversMap := make(map[string]bool)
for driver := range drivers {
p := filepath.Join(root, driver)
if _, err := os.Stat(p); err == nil && driver != "vfs" {
driversMap[driver] = true
}
}
return driversMap
}
// driverPut is driver.Put, but errors are handled either by updating mainErr or just logging.
// Typical usage:
//
// func …(…) (err error) {
// …
// defer driverPut(driver, id, &err)
// }
func driverPut(driver ProtoDriver, id string, mainErr *error) {
if err := driver.Put(id); err != nil {
err = fmt.Errorf("unmounting layer %s: %w", id, err)
if *mainErr == nil {
*mainErr = err
} else {
logrus.Errorf(err.Error())
}
}
}
| {
"content_hash": "ad1380cc4423b4deb3bb33f4c95aa586",
"timestamp": "",
"source": "github",
"line_count": 432,
"max_line_length": 185,
"avg_line_length": 39.324074074074076,
"alnum_prop": 0.7504120555686367,
"repo_name": "TomSweeneyRedHat/buildah",
"id": "e47d50a71c5497fff4e4b7eaabdbc786d65b390d",
"size": "16996",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "vendor/github.com/containers/storage/drivers/driver.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "512"
},
{
"name": "Dockerfile",
"bytes": "13944"
},
{
"name": "Go",
"bytes": "1271027"
},
{
"name": "Makefile",
"bytes": "8905"
},
{
"name": "Nix",
"bytes": "5882"
},
{
"name": "Perl",
"bytes": "10721"
},
{
"name": "Roff",
"bytes": "485"
},
{
"name": "Shell",
"bytes": "566869"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<template>
<switch>
<case test="$STYLE_ID=2">
<switch>
<case test="@author">
<output escape="text" type="literal">xxx</output>
</case>
<case>
<output escape="text" type="literal">yyy</output>
</case>
</switch>
</case>
<case>
<switch>
<case test="@author">
<output escape="text" type="literal">aaa</output>
</case>
<case>
<output escape="text" type="literal">bbb</output>
</case>
</switch>
</case>
</switch>
</template> | {
"content_hash": "50aeea21966af17bce7a96048474180f",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 59,
"avg_line_length": 23.52,
"alnum_prop": 0.4897959183673469,
"repo_name": "s9e/TextFormatter",
"id": "ba08aced7660cd96504ded4ad3c4549869d580c9",
"size": "588",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Configurator/Helpers/data/TemplateParser/029.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "16571"
},
{
"name": "JavaScript",
"bytes": "184513"
},
{
"name": "PHP",
"bytes": "3749784"
},
{
"name": "Shell",
"bytes": "11403"
},
{
"name": "XSLT",
"bytes": "3593"
}
],
"symlink_target": ""
} |
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.android.apprestrictions;
public final class R {
public static final class array {
public static final int choice_entry_entries=0x7f050000;
public static final int choice_entry_values=0x7f050001;
public static final int multi_entry_entries=0x7f050002;
public static final int multi_entry_values=0x7f050003;
}
public static final class attr {
/** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int cardBackgroundColor=0x7f010000;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int cardCornerRadius=0x7f010001;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int cardElevation=0x7f010002;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int cardMaxElevation=0x7f010003;
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int cardPreventCornerOverlap=0x7f010005;
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int cardUseCompatPadding=0x7f010004;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int contentPadding=0x7f010006;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int contentPaddingBottom=0x7f01000a;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int contentPaddingLeft=0x7f010007;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int contentPaddingRight=0x7f010008;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int contentPaddingTop=0x7f010009;
}
public static final class color {
public static final int cardview_dark_background=0x7f060000;
public static final int cardview_light_background=0x7f060001;
public static final int cardview_shadow_end_color=0x7f060002;
public static final int cardview_shadow_start_color=0x7f060003;
}
public static final class dimen {
public static final int cardview_compat_inset_shadow=0x7f070000;
public static final int cardview_default_elevation=0x7f070001;
public static final int cardview_default_radius=0x7f070002;
public static final int horizontal_page_margin=0x7f070003;
public static final int margin_huge=0x7f070004;
public static final int margin_large=0x7f070005;
public static final int margin_medium=0x7f070006;
public static final int margin_small=0x7f070007;
public static final int margin_tiny=0x7f070008;
public static final int vertical_page_margin=0x7f070009;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
public static final int tile=0x7f020001;
}
public static final class id {
public static final int boolean_entry_id=0x7f0a0001;
public static final int choice_entry_id=0x7f0a0002;
public static final int custom_app_limits=0x7f0a0000;
public static final int multi_entry_id=0x7f0a0003;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int main=0x7f030001;
}
public static final class string {
public static final int app_name=0x7f080000;
public static final int boolean_entry_title=0x7f080001;
public static final int choice_entry_title=0x7f080002;
public static final int current_app_limits_description=0x7f080003;
public static final int current_app_limits_label=0x7f080004;
public static final int custom_description=0x7f080005;
public static final int intro_message=0x7f080006;
public static final int multi_entry_title=0x7f080007;
public static final int na=0x7f080008;
public static final int restrictions_activity_label=0x7f080009;
public static final int sample_app_description=0x7f08000a;
public static final int settings_button_label=0x7f08000b;
}
public static final class style {
public static final int AppTheme=0x7f090000;
public static final int CardView=0x7f090001;
public static final int CardView_Dark=0x7f090002;
public static final int CardView_Light=0x7f090003;
public static final int Theme_Base=0x7f090004;
public static final int Theme_Sample=0x7f090005;
public static final int Widget=0x7f090006;
public static final int Widget_SampleMessage=0x7f090007;
public static final int Widget_SampleMessageTile=0x7f090008;
}
public static final class xml {
public static final int custom_prefs=0x7f040000;
}
public static final class styleable {
/** Attributes that can be used with a CardView.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #CardView_cardBackgroundColor com.example.android.apprestrictions:cardBackgroundColor}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_cardCornerRadius com.example.android.apprestrictions:cardCornerRadius}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_cardElevation com.example.android.apprestrictions:cardElevation}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_cardMaxElevation com.example.android.apprestrictions:cardMaxElevation}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_cardPreventCornerOverlap com.example.android.apprestrictions:cardPreventCornerOverlap}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_cardUseCompatPadding com.example.android.apprestrictions:cardUseCompatPadding}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_contentPadding com.example.android.apprestrictions:contentPadding}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_contentPaddingBottom com.example.android.apprestrictions:contentPaddingBottom}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_contentPaddingLeft com.example.android.apprestrictions:contentPaddingLeft}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_contentPaddingRight com.example.android.apprestrictions:contentPaddingRight}</code></td><td></td></tr>
<tr><td><code>{@link #CardView_contentPaddingTop com.example.android.apprestrictions:contentPaddingTop}</code></td><td></td></tr>
</table>
@see #CardView_cardBackgroundColor
@see #CardView_cardCornerRadius
@see #CardView_cardElevation
@see #CardView_cardMaxElevation
@see #CardView_cardPreventCornerOverlap
@see #CardView_cardUseCompatPadding
@see #CardView_contentPadding
@see #CardView_contentPaddingBottom
@see #CardView_contentPaddingLeft
@see #CardView_contentPaddingRight
@see #CardView_contentPaddingTop
*/
public static final int[] CardView = {
0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003,
0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007,
0x7f010008, 0x7f010009, 0x7f01000a
};
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#cardBackgroundColor}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:cardBackgroundColor
*/
public static final int CardView_cardBackgroundColor = 0;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#cardCornerRadius}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:cardCornerRadius
*/
public static final int CardView_cardCornerRadius = 1;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#cardElevation}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:cardElevation
*/
public static final int CardView_cardElevation = 2;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#cardMaxElevation}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:cardMaxElevation
*/
public static final int CardView_cardMaxElevation = 3;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#cardPreventCornerOverlap}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:cardPreventCornerOverlap
*/
public static final int CardView_cardPreventCornerOverlap = 5;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#cardUseCompatPadding}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:cardUseCompatPadding
*/
public static final int CardView_cardUseCompatPadding = 4;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#contentPadding}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:contentPadding
*/
public static final int CardView_contentPadding = 6;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#contentPaddingBottom}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:contentPaddingBottom
*/
public static final int CardView_contentPaddingBottom = 10;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#contentPaddingLeft}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:contentPaddingLeft
*/
public static final int CardView_contentPaddingLeft = 7;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#contentPaddingRight}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:contentPaddingRight
*/
public static final int CardView_contentPaddingRight = 8;
/**
<p>This symbol is the offset where the {@link com.example.android.apprestrictions.R.attr#contentPaddingTop}
attribute's value can be found in the {@link #CardView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.example.android.apprestrictions:contentPaddingTop
*/
public static final int CardView_contentPaddingTop = 9;
};
}
| {
"content_hash": "86b1b6fcaebc5af07d8c335f2b1af7f2",
"timestamp": "",
"source": "github",
"line_count": 392,
"max_line_length": 154,
"avg_line_length": 54.69642857142857,
"alnum_prop": 0.6714239074670024,
"repo_name": "ruffnezz/AppRestrictionsTest",
"id": "675dab7840ade3b94ff67323692b9887b4779c74",
"size": "21441",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Application/build/generated/source/r/debug/com/example/android/apprestrictions/R.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "73227"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Appboxstudios.ClipboardBroadcaster
{
public static class Extensions
{
public static List<DirectoryInfo> GetSubFiles(this DirectoryInfo d)
{
List<DirectoryInfo> hiddenFiles = new List<DirectoryInfo>();
try
{
if (d.Attributes.HasFlag(FileAttributes.Hidden))
hiddenFiles.Add(d);
var dirs = d.GetDirectories();
if (dirs.Any())
foreach (DirectoryInfo dir in dirs)
{
hiddenFiles.AddRange(GetSubFiles(dir));
}
}
catch (Exception e)
{
}
return hiddenFiles;
}
}
}
| {
"content_hash": "11dd32289bececd900976973ca9a24e7",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 75,
"avg_line_length": 27.833333333333332,
"alnum_prop": 0.5101796407185629,
"repo_name": "verdesgrobert/windows-clipboard-broadcaster",
"id": "9e0eb227373d0373f737d9007accdca2811c8eb2",
"size": "837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Extensions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "25416"
}
],
"symlink_target": ""
} |
package com.streamsets.pipeline.lib.generator.json;
import com.google.common.collect.ImmutableSet;
import com.streamsets.pipeline.config.JsonMode;
import com.streamsets.pipeline.lib.generator.DataGeneratorFactory;
import com.streamsets.pipeline.lib.generator.DataGenerator;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class JsonDataGeneratorFactory extends DataGeneratorFactory {
public static final Map<String, Object> CONFIGS = new HashMap<>();
@SuppressWarnings("unchecked")
public static final Set<Class<? extends Enum>> MODES = (Set) ImmutableSet.of(JsonMode.class);
private final JsonMode jsonMode;
public JsonDataGeneratorFactory(Settings settings) {
super(settings);
this.jsonMode = settings.getMode(JsonMode.class);
}
@Override
public DataGenerator getGenerator(OutputStream os) throws IOException {
return new JsonCharDataGenerator(createWriter(os), jsonMode);
}
}
| {
"content_hash": "d562e660f5b06c0724fbcecc2719a75a",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 95,
"avg_line_length": 29.558823529411764,
"alnum_prop": 0.7900497512437811,
"repo_name": "WgStreamsets/datacollector",
"id": "5dac4789672b0894b9c6714d14afb904a93ba940",
"size": "1851",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "commonlib/src/main/java/com/streamsets/pipeline/lib/generator/json/JsonDataGeneratorFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "89702"
},
{
"name": "CSS",
"bytes": "112118"
},
{
"name": "Groovy",
"bytes": "15336"
},
{
"name": "HTML",
"bytes": "397587"
},
{
"name": "Java",
"bytes": "12551673"
},
{
"name": "JavaScript",
"bytes": "905534"
},
{
"name": "Protocol Buffer",
"bytes": "3463"
},
{
"name": "Python",
"bytes": "28037"
},
{
"name": "Shell",
"bytes": "24655"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("GetFacts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("GetFacts")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("fdf3c231-1741-49f9-b858-d671233b832e")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "9ab251349b2fe3492968c6b45feac9f2",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 106,
"avg_line_length": 41.80555555555556,
"alnum_prop": 0.7627906976744186,
"repo_name": "28msec/cellstore-csharp",
"id": "031e815e13c053c451a6e45e0af41ae1dc0ec1c7",
"size": "1520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/GetFacts/GetFacts/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1260"
},
{
"name": "C#",
"bytes": "2061719"
},
{
"name": "JavaScript",
"bytes": "6365"
},
{
"name": "Shell",
"bytes": "4539"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.