text
stringlengths
2
1.04M
meta
dict
using System; using Microsoft.WindowsAzure.Mobile.Service; namespace BeerDrinkin.Service.DataObjects { public class BinaryItem : EntityData { public string ObjectId { get; set; } public string BinaryUrl { get; set; } public string BinaryType { get; set; } public string UserId { get; set; } } }
{ "content_hash": "cab28de1ccfc5f515128411b984f7bd6", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 46, "avg_line_length": 20.235294117647058, "alnum_prop": 0.6511627906976745, "repo_name": "ashwinkumar01/BeerDrinkin", "id": "b303f3dce66076730783d80d02d58b96d5295f52", "size": "346", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BeerDrinkingService/DataObjects/BinaryItem.cs", "mode": "33261", "license": "mit", "language": [ { "name": "ASP", "bytes": "113" }, { "name": "C#", "bytes": "241041" }, { "name": "CSS", "bytes": "37592" }, { "name": "HTML", "bytes": "76574" }, { "name": "JavaScript", "bytes": "3905" } ], "symlink_target": "" }
+++ pre = "<b>3.6.5. </b>" toc = true title = "性能测试" weight = 5 +++ ## 目标 对Sharding-JDBC,Sharding-Proxy及MySQL进行性能对比。从业务角度考虑,在基本应用场景(单路由,主从+脱敏+分库分表,全路由)下,INSERT+UPDATE+DELETE通常用作一个完整的关联操作,用于性能评估,而SELECT关注分片优化可用作性能评估的另一个操作;而主从模式下,可将INSERT+SELECT+DELETE作为一组评估性能的关联操作。 为了更好的观察效果,设计在一定数据量的基础上,使用jmeter 20并发线程持续压测半小时,进行增删改查性能测试,且每台机器部署一个MySQL实例,而对比MySQL场景为单机单实例部署。 ## 测试场景 #### 单路由 在1000数据量的基础上分库分表,根据`id`分为4个库,部署在同一台机器上,根据`k`分为1024个表,查询操作路由到单库单表; 作为对比,MySQL运行在1000数据量的基础上,使用INSERT+UPDATE+DELETE和单路由查询语句。 #### 主从 基本主从场景,设置一主库一从库,部署在两台不同的机器上,在10000数据量的基础上,观察读写性能; 作为对比,MySQL运行在10000数据量的基础上,使用INSERT+SELECT+DELETE语句。 #### 主从+脱敏+分库分表 在1000数据量的基础上,根据`id`分为4个库,部署在四台不同的机器上,根据`k`分为1024个表,`c`使用aes加密,`pad`使用md5加密,查询操作路由到单库单表; 作为对比,MySQL运行在1000数据量的基础上,使用INSERT+UPDATE+DELETE和单路由查询语句。 #### 全路由 在1000数据量的基础上,分库分表,根据`id`分为4个库,部署在四台不同的机器上,根据`k`分为1个表,查询操作使用全路由。 作为对比,MySQL运行在1000数据量的基础上,使用INSERT+UPDATE+DELETE和全路由查询语句。 ## 测试环境搭建 #### 数据库表结构 此处表结构参考sysbench的sbtest表 ```shell CREATE TABLE `tbl` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `k` int(11) NOT NULL DEFAULT 0, `c` char(120) NOT NULL DEFAULT '', `pad` char(60) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ); ``` #### 测试场景配置 Sharding-JDBC使用与Sharding-Proxy一致的配置,MySQL直连一个库用作性能对比,下面为四个场景的具体配置: ##### 单路由配置 ```yaml schemaName: sharding_db dataSources: ds_0: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 ds_1: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 ds_2: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 ds_3: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 shardingRule: tables: tbl: actualDataNodes: ds_${0..3}.tbl${0..1023} tableStrategy: inline: shardingColumn: k algorithmExpression: tbl${k % 1024} keyGenerator: type: SNOWFLAKE column: id defaultDatabaseStrategy: inline: shardingColumn: id algorithmExpression: ds_${id % 4} defaultTableStrategy: none: ``` ##### 主从配置 ```yaml schemaName: sharding_db dataSources: master_ds: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 slave_ds_0: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 masterSlaveRule: name: ms_ds masterDataSourceName: master_ds slaveDataSourceNames: - slave_ds_0 ``` ##### 主从+脱敏+分库分表配置 ```yaml schemaName: sharding_db dataSources: master_ds_0: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 slave_ds_0: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 master_ds_1: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 slave_ds_1: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 master_ds_2: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 slave_ds_2: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 master_ds_3: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 slave_ds_3: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 shardingRule: tables: tbl: actualDataNodes: ms_ds_${0..3}.tbl${0..1023} databaseStrategy: inline: shardingColumn: id algorithmExpression: ms_ds_${id % 4} tableStrategy: inline: shardingColumn: k algorithmExpression: tbl${k % 1024} keyGenerator: type: SNOWFLAKE column: id bindingTables: - tbl defaultDataSourceName: master_ds_1 defaultTableStrategy: none: masterSlaveRules: ms_ds_0: masterDataSourceName: master_ds_0 slaveDataSourceNames: - slave_ds_0 loadBalanceAlgorithmType: ROUND_ROBIN ms_ds_1: masterDataSourceName: master_ds_1 slaveDataSourceNames: - slave_ds_1 loadBalanceAlgorithmType: ROUND_ROBIN ms_ds_2: masterDataSourceName: master_ds_2 slaveDataSourceNames: - slave_ds_2 loadBalanceAlgorithmType: ROUND_ROBIN ms_ds_3: masterDataSourceName: master_ds_3 slaveDataSourceNames: - slave_ds_3 loadBalanceAlgorithmType: ROUND_ROBIN encryptRule: encryptors: encryptor_aes: type: aes props: aes.key.value: 123456abc encryptor_md5: type: md5 tables: sbtest: columns: c: plainColumn: c_plain cipherColumn: c_cipher encryptor: encryptor_aes pad: cipherColumn: pad_cipher encryptor: encryptor_md5 ``` ##### 全路由 ```yaml schemaName: sharding_db dataSources: ds_0: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 ds_1: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 ds_2: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 ds_3: url: jdbc:mysql://***.***.***.***:****/ds?serverTimezone=UTC&useSSL=false username: test password: connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 200 shardingRule: tables: tbl: actualDataNodes: ds_${0..3}.tbl1 tableStrategy: inline: shardingColumn: k algorithmExpression: tbl1 keyGenerator: type: SNOWFLAKE column: id defaultDatabaseStrategy: inline: shardingColumn: id algorithmExpression: ds_${id % 4} defaultTableStrategy: none: ``` ## 测试结果验证 #### 压测语句 ```shell INSERT+UPDATE+DELETE语句: INSERT INTO tbl(k, c, pad) VALUES(1, '###-###-###', '###-###'); UPDATE tbl SET c='####-####-####', pad='####-####' WHERE id=?; DELETE FROM tbl WHERE id=? 全路由查询语句: SELECT max(id) FROM tbl WHERE id%4=1 单路由查询语句: SELECT id, k FROM tbl ignore index(`PRIMARY`) WHERE id=1 AND k=1 INSERT+SELECT+DELETE语句: INSERT INTO tbl1(k, c, pad) VALUES(1, '###-###-###', '###-###'); SELECT count(id) FROM tbl1; SELECT max(id) FROM tbl1 ignore index(`PRIMARY`); DELETE FROM tbl1 WHERE id=? ``` #### 压测类 参考[shardingsphere-benchmark](https://github.com/apache/incubator-shardingsphere-benchmark/tree/master/shardingsphere-benchmark)实现,注意阅读其中的注释 #### 编译 ```shell git clone https://github.com/apache/incubator-shardingsphere-benchmark.git cd incubator-shardingsphere-benchmark/shardingsphere-benchmark mvn clean install ``` #### 压测执行 ```shell cp target/shardingsphere-benchmark-1.0-SNAPSHOT-jar-with-dependencies.jar apache-jmeter-4.0/lib/ext jmeter –n –t test_plan/test.jmx test.jmx参考https://github.com/apache/incubator-shardingsphere-benchmark/tree/master/report/script/test_plan/test.jmx ``` #### 压测结果处理 注意修改为上一步生成的result.jtl的位置。 ```shell sh shardingsphere-benchmark/report/script/gen_report.sh ``` #### 历史压测数据展示 [Benchmark性能平台](https://shardingsphere.apache.org/benchmark/#/overview)是数据以天粒度展示
{ "content_hash": "18af09ebe20c4778aa2c9d535256f4de", "timestamp": "", "source": "github", "line_count": 381, "max_line_length": 190, "avg_line_length": 25.829396325459317, "alnum_prop": 0.6739152525149883, "repo_name": "shardingjdbc/sharding-jdbc", "id": "0394f7c43eaf666bace4a17d4b9bf190216c1134", "size": "11233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/document/content/features/test-engine/performance-test.cn.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.accumulo.server.watcher; import static java.nio.charset.StandardCharsets.UTF_8; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.zookeeper.ZooUtil; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; import org.apache.log4j.Appender; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.helpers.FileWatchdog; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import com.google.common.net.HostAndPort; /** * Watcher that updates the monitor's log4j port from ZooKeeper in a system property */ public class MonitorLog4jWatcher extends FileWatchdog implements Watcher { private static final Logger log = Logger.getLogger(MonitorLog4jWatcher.class); private static final String HOST_PROPERTY_NAME = "org.apache.accumulo.core.host.log"; private static final String PORT_PROPERTY_NAME = "org.apache.accumulo.core.host.log.port"; private final Object lock; private final Log4jConfiguration logConfig; private boolean loggingDisabled = false; protected String path; public MonitorLog4jWatcher(String instance, String filename) { super(filename); this.path = ZooUtil.getRoot(instance) + Constants.ZMONITOR_LOG4J_ADDR; this.lock = new Object(); this.logConfig = new Log4jConfiguration(filename); doOnChange(); } boolean isUsingProperties() { return logConfig.isUsingProperties(); } String getPath() { return path; } @Override public void run() { try { // Initially set the logger if the Monitor's log4j advertisement node exists if (ZooReaderWriter.getInstance().exists(path, this)) updateMonitorLog4jLocation(); log.info("Set watch for Monitor Log4j watcher"); } catch (Exception e) { log.error("Unable to set watch for Monitor Log4j watcher on " + path); } super.run(); } @Override public void doOnChange() { // this method gets called in the parent class' constructor // I'm not sure of a better way to get around this. The final modifier helps though. if (null == lock) { return; } synchronized (lock) { // We might triggered by file-reloading or from ZK update. // Either way will result in log-forwarding being restarted loggingDisabled = false; log.info("Enabled log-forwarding"); logConfig.resetLogger(); } } @Override public void process(WatchedEvent event) { // We got an update, process the data in the node updateMonitorLog4jLocation(); if (event.getPath() != null) { try { ZooReaderWriter.getInstance().exists(event.getPath(), this); } catch (Exception ex) { log.error("Unable to reset watch for Monitor Log4j watcher", ex); } } } /** * Read the host and port information for the Monitor's log4j socket and update the system properties so that, on logger refresh, it sees the new information. */ protected void updateMonitorLog4jLocation() { try { String hostPortString = new String(ZooReaderWriter.getInstance().getData(path, null), UTF_8); HostAndPort hostAndPort = HostAndPort.fromString(hostPortString); System.setProperty(HOST_PROPERTY_NAME, hostAndPort.getHostText()); System.setProperty(PORT_PROPERTY_NAME, Integer.toString(hostAndPort.getPort())); log.info("Changing monitor log4j address to " + hostAndPort.toString()); doOnChange(); } catch (NoNodeException e) { // Not sure on the synchronization guarantees for Loggers and Appenders // on configuration reload synchronized (lock) { // Don't need to try to re-disable'ing it. if (loggingDisabled) { return; } Logger logger = LogManager.getLogger("org.apache.accumulo"); if (null != logger) { // TODO ACCUMULO-2343 Create a specific appender for log-forwarding to the monitor // that can replace the AsyncAppender+SocketAppender. Appender appender = logger.getAppender("ASYNC"); if (null != appender) { log.info("Closing log-forwarding appender"); appender.close(); log.info("Removing log-forwarding appender"); logger.removeAppender(appender); loggingDisabled = true; } } } } catch (IllegalArgumentException e) { log.error("Could not parse host and port information", e); } catch (Exception e) { log.error("Error reading zookeeper data for Monitor Log4j watcher", e); } } }
{ "content_hash": "96d4ad61dd96dfbe37c6d0be21a6a72c", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 160, "avg_line_length": 33.91240875912409, "alnum_prop": 0.690055962117951, "repo_name": "adamjshook/accumulo", "id": "103aefc552b343eddcad9492b65787822b2ca6a1", "size": "5447", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/base/src/main/java/org/apache/accumulo/server/watcher/MonitorLog4jWatcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2423" }, { "name": "C++", "bytes": "1414083" }, { "name": "CSS", "bytes": "5933" }, { "name": "Groovy", "bytes": "1385" }, { "name": "HTML", "bytes": "11698" }, { "name": "Java", "bytes": "20215877" }, { "name": "JavaScript", "bytes": "249594" }, { "name": "Makefile", "bytes": "2865" }, { "name": "Perl", "bytes": "28190" }, { "name": "Protocol Buffer", "bytes": "1325" }, { "name": "Python", "bytes": "729147" }, { "name": "Ruby", "bytes": "211593" }, { "name": "Shell", "bytes": "194340" }, { "name": "Thrift", "bytes": "55653" } ], "symlink_target": "" }
package com.ibgwy; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.ib.client.*; import com.ibgwy.events.OrderPending; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO: Add JavaDoc! */ public class OutboundImpl implements AdminCommands, ConnectionCommands, Outbound { /*-------------------------------------------- | C O N S T A N T S | ============================================*/ /*-------------------------------------------- | I N S T A N C E V A R I A B L E S | ============================================*/ private Logger logger = LoggerFactory.getLogger(OutboundImpl.class); private EClientSocket socket; private AnyWrapper api; private final String hostAddress; private final int port; private final int clientId; private boolean initialized; private boolean connected; private int numIds = 1; private IBApiHelper ibApiHelper; private InstrumentsCache instrumentsCache; /*-------------------------------------------- | C O N S T R U C T O R S | ============================================*/ public OutboundImpl(AnyWrapper api, String hostAddress, int port, int clientId, IBApiHelper ibApiHelper, InstrumentsCache instrumentsCache) { Preconditions.checkNotNull(api); Preconditions.checkArgument(!Strings.isNullOrEmpty(hostAddress)); Preconditions.checkNotNull(ibApiHelper); this.api = api; this.hostAddress = hostAddress; this.port = port; this.clientId = clientId; this.ibApiHelper = ibApiHelper; this.instrumentsCache = instrumentsCache; } /*-------------------------------------------- | M E T H O D S | ============================================*/ // ~ AdminCommands Methods ================== @Override public void startup() { if (!initialized) { logger.info("Initializing gateway"); socket = new EClientSocket(api); socket.reqIds(numIds); initialized = true; } else { } } @Override public void shutdown() { if (initialized) { logger.info("Shutting down gateway"); socket = null; initialized = false; } } protected void setSocket(EClientSocket socket) { this.socket = socket; } // ~ ConnectionCommands Methods ============== @Override public void connect() { if (!initialized) { startup(); } else { if (!connected) { try { socket.eConnect(hostAddress, port, clientId); connected = socket.isConnected(); } catch (Throwable t) { logger.error("Error connecting to :" + hostAddress + ":" + port); } } else { logger.info("Gateway already connected to " + hostAddress + ":" + port); } } } @Override public void disconnect() { if (connected) { logger.info("Disconnecting Gateway"); socket.eDisconnect(); String msg = EWrapperMsgGenerator.connectionClosed(); logger.info(msg); connected = false; } else { logger.info("Gateway not connected"); } } // ~ EClientSocket methods ================== /** * Asynchronous market data request call that calls-back on <code>IBApi</code>#tickPrice() * * @param mktDataReq */ @Override public void reqMktData(InstrumentUpdateRequest mktDataReq) { try { Contract contract = ibApiHelper.toContract(instrumentsCache.getInstrument(mktDataReq.getInstrumentId())); socket.reqMktData(mktDataReq.getId(), contract, " ", mktDataReq.isSnapshot()); } catch (Throwable t) { // TODO: Cancel event! logger.error("Error requesting market data request " + mktDataReq); } } @Override public void cancelHistoricalData(int tickerId) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void reqHistoricalData(int tickerId, Contract contract, String endDateTime, String durationStr, String barSizeSetting, String whatToShow, int useRTH, int formatDate) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void cancelMktData(int tickerId) { socket.cancelMktData(tickerId); } @Override public void placeOrder(OrderPending orderEvent) { Contract contract = ibApiHelper.toContract(orderEvent); Order order = ibApiHelper.toOrder(orderEvent, clientId); try { socket.placeOrder(orderEvent.getOrderId(), contract, order); } catch (Throwable t) { logger.error("Error placing order " + orderEvent); } } @Override public void cancelOrder(int id) { //To change body of implemented methods use File | Settings | File Templates. } }
{ "content_hash": "f318de89e187ef6341df0ae866879e25", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 111, "avg_line_length": 27.329545454545453, "alnum_prop": 0.598960498960499, "repo_name": "Vishal-Puri/IBGwy", "id": "53de274ca263e57d0a9de71bda2bea22fa29fbc3", "size": "4810", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/ibgwy/OutboundImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "253113" } ], "symlink_target": "" }
import 'reflect-metadata'; import { Controller, Get, RequestParam, } from 'inversify-express-utils'; import { injectable } from 'inversify'; import { IHttpResponse } from './../interfaces/IHttpResponse'; import { Success } from './../models/Success.model'; @Controller('/') @injectable() export class HomeController { @Get('/') public helloWorld(): IHttpResponse { return new Success(200, "Hello world !") } }
{ "content_hash": "03319eee40c18f3c60e0e33cae8f98d7", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 73, "avg_line_length": 27, "alnum_prop": 0.6782407407407407, "repo_name": "gjdass/whiteapi-express-ts", "id": "b8274a3b371fad615fb0433a4d682bd7af478db3", "size": "432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/controllers/Home.controller.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "922" }, { "name": "TypeScript", "bytes": "21104" } ], "symlink_target": "" }
class Stock include Mongoid::Document field :name, type: String field :country, type: String field :date, type: Time field :value, type: Float end
{ "content_hash": "e2dc0b9d3173737b307574b4f8e280c8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 30, "avg_line_length": 22.428571428571427, "alnum_prop": 0.7133757961783439, "repo_name": "jasper-fu/stock_monitoring", "id": "3e7b3f00c2fd208a1d2c916958f37f6abf0eaeb8", "size": "157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/stock.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2651" }, { "name": "CoffeeScript", "bytes": "1711" }, { "name": "JavaScript", "bytes": "769841" }, { "name": "Ruby", "bytes": "21805" } ], "symlink_target": "" }
.class Lcom/android/server/am/ActivityManagerService$12; .super Ljava/lang/Object; .source "ActivityManagerService.java" # interfaces .implements Landroid/os/IBinder$DeathRecipient; # annotations .annotation system Ldalvik/annotation/EnclosingMethod; value = Lcom/android/server/am/ActivityManagerService;->hang(Landroid/os/IBinder;Z)V .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic this$0:Lcom/android/server/am/ActivityManagerService; # direct methods .method constructor <init>(Lcom/android/server/am/ActivityManagerService;)V .locals 0 .prologue .line 11471 iput-object p1, p0, Lcom/android/server/am/ActivityManagerService$12;->this$0:Lcom/android/server/am/ActivityManagerService; invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public binderDied()V .locals 1 .prologue .line 11474 monitor-enter p0 .line 11475 :try_start_0 invoke-virtual {p0}, Ljava/lang/Object;->notifyAll()V .line 11476 monitor-exit p0 .line 11477 return-void .line 11476 :catchall_0 move-exception v0 monitor-exit p0 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v0 .end method
{ "content_hash": "29eebcdfa9395f3a4d7ce0b7bba68688", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 128, "avg_line_length": 20.96923076923077, "alnum_prop": 0.7197358767424799, "repo_name": "shumxin/FlymeOS_A5DUG", "id": "6a941b4fd5a1ff65592b0936dc432b93363c31ae", "size": "1363", "binary": false, "copies": "1", "ref": "refs/heads/lollipop-5.0", "path": "services.jar.out/smali/com/android/server/am/ActivityManagerService$12.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "1500" }, { "name": "HTML", "bytes": "96769" }, { "name": "Makefile", "bytes": "13678" }, { "name": "Shell", "bytes": "103420" }, { "name": "Smali", "bytes": "189389087" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Timers; using MonoMac.AppKit; using MonoMac.Foundation; using Outlander.Core; using Outlander.Core.Authentication; using Outlander.Core.Client; using Outlander.Core.Text; namespace Outlander.Mac.Beta { public partial class MainWindowController : MonoMac.AppKit.NSWindowController { private IServiceLocator _services; private Bootstrapper _bootStrapper; private IGameServer _gameServer; private CommandCache _commandCache; private IGameStream _gameStream; private GameStreamListener _gameStreamListener; private ICommandProcessor _commandProcessor; private IScriptLog _scriptLog; private ExpTracker _expTracker; private HighlightSettings _highlightSettings; private Timer _spellTimer; private string _spell; private int _count; private TextViewWrapper _mainTextViewWrapper; #region Constructors // Called when created from unmanaged code public MainWindowController(IntPtr handle) : base(handle) { Initialize(); } // Called when created directly from a XIB file [Export("initWithCoder:")] public MainWindowController(NSCoder coder) : base(coder) { Initialize(); } // Call to load from the XIB/NIB file public MainWindowController() : base("MainWindow") { Initialize(); } // Shared initialization code void Initialize() { _bootStrapper = new Bootstrapper(); _commandCache = new CommandCache(); _expTracker = new ExpTracker(); _spellTimer = new Timer(); _spellTimer.Interval = 1000; _spellTimer.Elapsed += (sender, e) => { _count++; _gameServer.GameState.Set(ComponentKeys.SpellTime, _count.ToString()); BeginInvokeOnMainThread(() => SpellLabel.StringValue = "S: ({0}) {1}".ToFormat(_count, _spell)); }; } #endregion public void SwitchProfile() { var profiles = _services.Get<IProfileLoader>().Profiles(); var ctrl = new ProfileSelectorController(); ctrl.Window.ParentWindow = Window; ctrl.InitWithProfiles( profiles, _services, _services.Get<AppSettings>(), _services.Get<IProfileLoader>(), _services.Get<IAppSettingsLoader>(), () => { NSApplication.SharedApplication.StopModal(); } ); NSApplication.SharedApplication.RunModalForWindow(ctrl.Window); } public void Connect() { var loader = _services.Get<IProfileLoader>(); var profile = loader.Load(_services.Get<AppSettings>().Profile); var ctrl = new LoginWindowController(); ctrl.ShowSheet( Window, ConnectModel.For(profile.Account, profile.Game, profile.Character), _services, (model) => { Connect(model); }, () => { } ); } private void InitializeVitalsAndRTBars() { HealthLabel.Label = "Health 100%"; HealthLabel.BackgroundColor = "#800000"; HealthLabel.Value = 0; ManaLabel.Label = "Mana 100%"; ManaLabel.Value = 0; ConcentrationLabel.BackgroundColor = "#009999"; ConcentrationLabel.Label = "Concentration 100%"; ConcentrationLabel.TextOffset = new PointF(55, 1); ConcentrationLabel.Value = 0; StaminaLabel.BackgroundColor = "#004000"; StaminaLabel.Label = "Stamina 100%"; StaminaLabel.Value = 0; SpiritLabel.BackgroundColor = "#400040"; SpiritLabel.Label = "Spirit 100%"; SpiritLabel.Value = 0; RTLabel.Label = string.Empty; RTLabel.Value = 0.0f; RTLabel.BackgroundColor = "#0000FF"; RTLabel.TextOffset = new PointF(6, 2); RTLabel.Font = NSFont.FromFontName("Geneva", 16); } private void UpdateImages() { var state = _gameServer.GameState; NSImage standing = null; if(state.Get(ComponentKeys.Standing) == "1") { standing = NSImage.ImageNamed("standing-s.png"); } if(state.Get(ComponentKeys.Kneeling) == "1") { standing = NSImage.ImageNamed("kneeling-s.png"); } if(state.Get(ComponentKeys.Sitting) == "1") { standing = NSImage.ImageNamed("sitting-s.png"); } if(state.Get(ComponentKeys.Prone) == "1") { standing = NSImage.ImageNamed("prone-s.png"); } StandingImage.Image = standing; NSImage health = null; if(state.Get(ComponentKeys.Bleeding) == "1") { health = NSImage.ImageNamed("bleeding.png"); } if(state.Get(ComponentKeys.Stunned) == "1") { health = NSImage.ImageNamed("stunned.png"); } if(state.Get(ComponentKeys.Dead) == "1") { health = NSImage.ImageNamed("dead.png"); } HealthImage.Image = health; NSImage hidden = null; if(state.Get(ComponentKeys.Hidden) == "1") { hidden = NSImage.ImageNamed("hidden.png"); } HiddenImage.Image = hidden; NSImage grouped = null; if(state.Get(ComponentKeys.Joined) == "1") { grouped = NSImage.ImageNamed("group.png"); } GroupedImage.Image = grouped; NSImage webbed = null; if(state.Get(ComponentKeys.Webbed) == "1") { webbed = NSImage.ImageNamed("web.png"); } WebbedImage.Image = webbed; NSImage invisible = null; if(state.Get(ComponentKeys.Invisible) == "1") { invisible = NSImage.ImageNamed("invisible.png"); } InvisibleImage.Image = invisible; } public override void AwakeFromNib() { base.AwakeFromNib(); InitializeVitalsAndRTBars(); Window.Title = "Outlander"; _gameServer = _bootStrapper.Build(); _services = _bootStrapper.ServiceLocator(); var appSettings = _services.Get<AppSettings>(); var homeDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Documents/Outlander"); appSettings.HomeDirectory = homeDir; _services.Get<IAppDirectoriesBuilder>().Build(); _services.Get<IAppSettingsLoader>().Load(); UpdateImages(); _commandProcessor = _services.Get<ICommandProcessor>(); _scriptLog = _services.Get<IScriptLog>(); _services.Get<IRoundtimeHandler>().Changed += (sender, e) => { SetRoundtime(e); }; _highlightSettings = _services.Get<HighlightSettings>(); _mainTextViewWrapper = new TextViewWrapper(MainTextView, _highlightSettings); _scriptLog.Info += (sender, e) => { string log; if(e.LineNumber > -1) { log = "[{0}({1})]: {2}\n".ToFormat(e.Name, e.LineNumber, e.Data); } else { log = "[{0}]: {1}\n".ToFormat(e.Name, e.Data); } BeginInvokeOnMainThread(()=> { var hasLineFeed = MainTextView.TextStorage.Value.EndsWith("\n"); if(!hasLineFeed) log = "\n" + log; var tag = TextTag.For(log, "#0066CC"); _mainTextViewWrapper.Append(tag); }); }; _scriptLog.NotifyStarted += (sender, e) => { var log = "[{0}]: {1} - script started\n".ToFormat(e.Name, e.Started.ToString("G")); BeginInvokeOnMainThread(()=> { var hasLineFeed = MainTextView.TextStorage.Value.EndsWith("\n"); if(!hasLineFeed) log = "\n" + log; var tag = TextTag.For(log, "ADFF2F"); _mainTextViewWrapper.Append(tag); }); }; _scriptLog.NotifyAborted += (sender, e) => { var log = "[{0}]: total runtime {1:hh\\:mm\\:ss} - {2} seconds\n".ToFormat(e.Name, e.Runtime, Math.Round(e.Runtime.TotalSeconds, 2)); BeginInvokeOnMainThread(()=> { var hasLineFeed = MainTextView.TextStorage.Value.EndsWith("\n"); if(!hasLineFeed) log = "\n" + log; var tag = TextTag.For(log, "ADFF2F"); _mainTextViewWrapper.Append(tag); }); }; var notifyLogger = new NotificationLogger(); notifyLogger.OnError = (err) => { BeginInvokeOnMainThread(()=> { LogSystem(err.Message + "\n\n"); }); }; var compositeLogger = _services.Get<ILog>().As<CompositeLog>(); compositeLogger.Add(notifyLogger); _gameServer.GameState.Tags = (tags) => { tags.Apply(t => { t.As<AppTag>().IfNotNull(appInfo => { BeginInvokeOnMainThread(() => { Window.Title = string.Format("{0}: {1} - {2}", appInfo.Game, appInfo.Character, "Outlander"); }); }); t.As<StreamTag>().IfNotNull(streamTag => { if(!string.IsNullOrWhiteSpace(streamTag.Id) && streamTag.Id.Equals("logons")) { var text = "[{0}]{1}".ToFormat(DateTime.Now.ToString("HH:mm"), streamTag.Text); var highlights = _services.Get<Highlights>().For(TextTag.For(text)); BeginInvokeOnMainThread(()=> { highlights.Apply(h => { h.Mono = true; Append(h, ArrivalsTextView); }); }); } if(!string.IsNullOrWhiteSpace(streamTag.Id) && streamTag.Id.Equals("thoughts")) { var text = "[{0}]: {1}".ToFormat(DateTime.Now.ToString("HH:mm"), streamTag.Text); var highlights = _services.Get<Highlights>().For(TextTag.For(text)); BeginInvokeOnMainThread(()=> { highlights.Apply(h => { Append(h, ThoughtsTextView); }); }); } if(!string.IsNullOrWhiteSpace(streamTag.Id) && streamTag.Id.Equals("death")) { var text = "[{0}]{1}".ToFormat(DateTime.Now.ToString("HH:mm"), streamTag.Text); var highlights = _services.Get<Highlights>().For(TextTag.For(text)); BeginInvokeOnMainThread(()=> { highlights.Apply(h => { Append(h, DeathsTextView); }); }); } }); t.As<SpellTag>().IfNotNull(s => { BeginInvokeOnMainThread(() => { _spell = s.Spell; _count = 0; SpellLabel.StringValue = "S: {0}".ToFormat(s.Spell); if(!string.Equals(_spell, "None")) { _gameServer.GameState.Set(ComponentKeys.SpellTime, "0"); _spellTimer.Start(); } else { _spellTimer.Stop(); _gameServer.GameState.Set(ComponentKeys.SpellTime, "0"); } }); }); t.As<VitalsTag>().IfNotNull(v => { UpdateVitals(); }); var ids = new string[] { ComponentKeys.RoomTitle, ComponentKeys.RoomDescription, ComponentKeys.RoomObjects, ComponentKeys.RoomPlayers, ComponentKeys.RoomExists }; t.As<ComponentTag>().IfNotNull(c => { if(!ids.Contains(c.Id)) return; var builder = new StringBuilder(); _gameServer.GameState.Get(ComponentKeys.RoomTitle).IfNotNullOrEmpty(s=>builder.AppendLine(s)); _gameServer.GameState.Get(ComponentKeys.RoomDescription).IfNotNullOrEmpty(s=>builder.AppendLine(s)); _gameServer.GameState.Get(ComponentKeys.RoomObjectsH).IfNotNullOrEmpty(s=>builder.AppendLine(s)); _gameServer.GameState.Get(ComponentKeys.RoomPlayers).IfNotNullOrEmpty(s=>builder.AppendLine(s)); _gameServer.GameState.Get(ComponentKeys.RoomExists).IfNotNullOrEmpty(s=>builder.AppendLine(s)); BeginInvokeOnMainThread(()=> { LogRoom(builder.ToString(), RoomTextView); }); }); BeginInvokeOnMainThread(()=> { UpdateImages(); LeftHandLabel.StringValue = string.Format("L: {0}", _gameServer.GameState.Get(ComponentKeys.LeftHand)); RightHandLabel.StringValue = string.Format("R: {0}", _gameServer.GameState.Get(ComponentKeys.RightHand)); }); _services.Get<IAppSettingsLoader>().SaveVariables(); }); }; _gameServer.GameState.Exp = (exp) => { _expTracker.Update(exp); var skills = _expTracker.SkillsWithExp().ToList(); var tags = skills .OrderBy(x => x.Name) .Select(x => { var color = x.IsNew ? _highlightSettings.Get(HighlightKeys.Whisper).Color : string.Empty; return TextTag.For(x.Display() + "\n", color, true); }).ToList(); var now = DateTime.Now; tags.Add(TextTag.For("Last updated: {0:hh\\:mm\\:ss tt}\n".ToFormat(now), string.Empty, true)); if(_expTracker.StartedTracking.HasValue) tags.Add(TextTag.For("Tracking for: {0:hh\\:mm\\:ss}\n".ToFormat(now - _expTracker.StartedTracking.Value), string.Empty, true)); BeginInvokeOnMainThread(()=> { ReplaceText(tags, ExpTextView); }); }; _gameStream = _services.Get<IGameStream>(); _gameStreamListener = new GameStreamListener(tag => { BeginInvokeOnMainThread(()=>{ if(tag.Filtered) return; Log(tag); }); }); _gameStreamListener.Subscribe(_gameStream); } private void Connect(ConnectModel model) { if(string.IsNullOrWhiteSpace(model.Game) || string.IsNullOrWhiteSpace(model.Account) || string.IsNullOrWhiteSpace(model.Password) || string.IsNullOrWhiteSpace(model.Character)) { LogSystem("Please enter all information\n"); return; } LogSystem("Authenticating...\n"); var token = _gameServer.Authenticate(model.Game, model.Account, model.Password, model.Character); if(token != null) { LogSystem("Authenticated...\n"); _gameServer.Connect(token); } else { LogSystem("Unable to authenticate.\n"); } } private void UpdateVitals() { BeginInvokeOnMainThread(()=> { HealthLabel.Value = _gameServer.GameState.Get(ComponentKeys.Health).AsFloat(); HealthLabel.Label = "Health {0}%".ToFormat(HealthLabel.Value); ManaLabel.Value = _gameServer.GameState.Get(ComponentKeys.Mana).AsFloat(); ManaLabel.Label = "Mana {0}%".ToFormat(ManaLabel.Value); StaminaLabel.Value = _gameServer.GameState.Get(ComponentKeys.Stamina).AsFloat(); StaminaLabel.Label = "Stamina {0}%".ToFormat(StaminaLabel.Value); ConcentrationLabel.Value = _gameServer.GameState.Get(ComponentKeys.Concentration).AsFloat(); ConcentrationLabel.Label = "Concentration {0}%".ToFormat(ConcentrationLabel.Value); SpiritLabel.Value = _gameServer.GameState.Get(ComponentKeys.Spirit).AsFloat(); SpiritLabel.Label = "Spirit {0}%".ToFormat(SpiritLabel.Value); }); } private void SendCommand(string command) { _commandCache.Add(command); if(!command.StartsWith("#")) { command = _commandProcessor.Eval(command); var prompt = _gameServer.GameState.Get(ComponentKeys.Prompt) + " " + command + "\n"; var hasLineFeed = _mainTextViewWrapper.EndsWithNewline(); if(!hasLineFeed) prompt = "\n" + prompt; Log(TextTag.For(prompt)); } _commandProcessor.Process(command, echo: false); } private void LogRoom(string text, NSTextView textView) { var defaultSettings = new DefaultSettings(); var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color; //textView.TextStorage.BeginEditing(); textView.TextStorage.SetString("".CreateString(defaultColor.ToNSColor(), defaultSettings.Font)); //textView.TextStorage.EndEditing(); var highlights = _services.Get<Highlights>(); highlights.For(TextTag.For(text)).Apply(t => Append(t, textView)); } private void Log(TextTag text) { var prompt = _gameServer.GameState.Get(ComponentKeys.Prompt); if (string.Equals(text.Text.Trim(), prompt) && _mainTextViewWrapper.EndsWith(prompt, true)) return; var highlights = _services.Get<Highlights>(); highlights.For(text).Apply(t => _mainTextViewWrapper.Append(t)); } private void LogSystem(string text) { LogSystem(text, "#ffbb00"); } private void LogSystem(string text, string color) { text = "[{0}]: {1}".ToFormat(DateTime.Now.ToString("HH:mm"), text); _mainTextViewWrapper.Append(TextTag.For(text, color, true)); } private void Append(TextTag tag, NSTextView textView) { var text = tag.Text.Replace("&lt;", "<").Replace("&gt;", ">"); var defaultSettings = new DefaultSettings(); var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color; var color = !string.IsNullOrWhiteSpace(tag.Color) ? tag.Color : defaultColor; var font = tag.Mono ? defaultSettings.MonoFont : defaultSettings.Font; var scroll = textView.EnclosingScrollView.VerticalScroller.FloatValue == 1.0f; //textView.TextStorage.BeginEditing(); textView.TextStorage.Append(text.CreateString(color.ToNSColor(), font)); //textView.TextStorage.EndEditing(); if(scroll) textView.ScrollRangeToVisible(new NSRange(textView.Value.Length, 0)); } private void ReplaceText(IEnumerable<TextTag> tags, NSTextView textView) { var defaultSettings = new DefaultSettings(); var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color; //textView.TextStorage.BeginEditing(); textView.TextStorage.SetString("".CreateString(defaultColor.ToNSColor())); tags.Apply(tag => { var color = !string.IsNullOrWhiteSpace(tag.Color) ? tag.Color : defaultColor; var font = tag.Mono ? defaultSettings.MonoFont : defaultSettings.Font; textView.TextStorage.Append(tag.Text.CreateString(color.ToNSColor(), font)); }); //textView.TextStorage.EndEditing(); } private long _rtMax = 0; private void SetRoundtime(RoundtimeArgs args) { if(args.Roundtime < 0) { args.Roundtime = 0; } if(args.Reset) _rtMax = args.Roundtime; BeginInvokeOnMainThread(() => { RTLabel.Value = ((float)args.Roundtime / (float)_rtMax) * 100.0f; RTLabel.Label = "{0}".ToFormat(args.Roundtime); if(args.Roundtime == 0) RTLabel.Label = string.Empty; if(args.Roundtime < 10) { RTLabel.TextOffset = new PointF(6, 2); } else { RTLabel.TextOffset = new PointF(12, 2); } }); } public override void KeyUp(NSEvent theEvent) { base.KeyUp(theEvent); var keys = KeyUtil.GetKeys(theEvent); if(keys == NSKey.Return && !string.IsNullOrWhiteSpace(CommandTextField.StringValue)) { var command = CommandTextField.StringValue; CommandTextField.StringValue = string.Empty; SendCommand(command); } if(keys == NSKey.UpArrow) { _commandCache.MovePrevious(); CommandTextField.StringValue = _commandCache.Current; } if(keys == NSKey.DownArrow) { _commandCache.MoveNext(); CommandTextField.StringValue = _commandCache.Current; } } //strongly typed window accessor public new MainWindow Window { get { return (MainWindow)base.Window; } } } public class TextViewWrapper { private readonly NSTextView _textView; private readonly HighlightSettings _highlightSettings; public TextViewWrapper(NSTextView textView, HighlightSettings highlightSettings) { _textView = textView; _highlightSettings = highlightSettings; } public bool EndsWithNewline() { return EndsWith("\n"); } public bool EndsWith(string value, bool trim = false) { var val = trim ? _textView.TextStorage.Value.Trim() : _textView.TextStorage.Value; return val.EndsWith(value); } public void Append(TextTag tag) { _textView.BeginInvokeOnMainThread(() => { var text = tag.Text.Replace("&lt;", "<").Replace("&gt;", ">"); var defaultSettings = new DefaultSettings(); var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color; var color = !string.IsNullOrWhiteSpace(tag.Color) ? tag.Color : defaultColor; var font = tag.Mono ? defaultSettings.MonoFont : defaultSettings.Font; var scroll = _textView.EnclosingScrollView.VerticalScroller.FloatValue == 1.0f; //textView.TextStorage.BeginEditing(); _textView.TextStorage.Append(text.CreateString(color.ToNSColor(), font)); //textView.TextStorage.EndEditing(); if(scroll) _textView.ScrollRangeToVisible(new NSRange(_textView.Value.Length, 0)); }); } public void ReplaceText(IEnumerable<TextTag> tags) { _textView.BeginInvokeOnMainThread(() => { var defaultSettings = new DefaultSettings(); var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color; //textView.TextStorage.BeginEditing(); _textView.TextStorage.SetString("".CreateString(defaultColor.ToNSColor())); tags.Apply(tag => { var color = !string.IsNullOrWhiteSpace(tag.Color) ? tag.Color : defaultColor; var font = tag.Mono ? defaultSettings.MonoFont : defaultSettings.Font; _textView.TextStorage.Append(tag.Text.CreateString(color.ToNSColor(), font)); }); //textView.TextStorage.EndEditing(); }); } } }
{ "content_hash": "fe127229737f35f0babed60e959ae309", "timestamp": "", "source": "github", "line_count": 687, "max_line_length": 137, "avg_line_length": 28.829694323144103, "alnum_prop": 0.6658588306573765, "repo_name": "joemcbride/outlander", "id": "a0fe384bbb42bd7a3889ad8c7422b2a266c1f0f2", "size": "19806", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Pathfinder.Mac.Beta/MainWindowController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "399564" }, { "name": "Shell", "bytes": "2581" } ], "symlink_target": "" }
@implementation NoHighlightsObject @end
{ "content_hash": "9a2fda5742829d38cc4e0c9b06ce1112", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 34, "avg_line_length": 13.666666666666666, "alnum_prop": 0.8536585365853658, "repo_name": "noahsw/highlight-hunter", "id": "0f06dccbedf261a02cfdcc18b34c446759c94715", "size": "248", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OdessaMacGUIApp/Source/ReviewHighlights/NoHighlightsViewItem/NoHighlightsObject.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "9319" }, { "name": "C", "bytes": "933806" }, { "name": "C#", "bytes": "874573" }, { "name": "C++", "bytes": "121328" }, { "name": "CSS", "bytes": "698807" }, { "name": "JavaScript", "bytes": "1295663" }, { "name": "Objective-C", "bytes": "1285018" }, { "name": "PHP", "bytes": "7668297" }, { "name": "Shell", "bytes": "6572" }, { "name": "XSLT", "bytes": "13169" } ], "symlink_target": "" }
package com.cloudnative.reference.events; import java.io.Serializable; public class OrderCreatedEvent implements Serializable { private String id; private String description; public OrderCreatedEvent() { } public OrderCreatedEvent(String id, String description) { this.id = id; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
{ "content_hash": "d845e8644c0a8c7952f01f1059c5d3fb", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 59, "avg_line_length": 17.114285714285714, "alnum_prop": 0.7011686143572621, "repo_name": "drm317/cloud-native-reference", "id": "30e8dd5c112f1c5e363cc353a75ee0288251e757", "size": "599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "order-service/src/main/java/com/cloudnative/reference/events/OrderCreatedEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "34756" }, { "name": "Shell", "bytes": "154" } ], "symlink_target": "" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gsd.iml.ast.expression; /** * * @author leonardo */ public class IsLoadedFunctionCallExpression extends UnaryFunctionCallExpression { public IsLoadedFunctionCallExpression(Expression argument) { super("is_loaded", argument) ; } }
{ "content_hash": "6b4ba3b26ea4e22a08b7a9775476646a", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 81, "avg_line_length": 21.11111111111111, "alnum_prop": 0.6815789473684211, "repo_name": "matachi/rangeFix", "id": "046dc5003d450d65abdcf816fccdf8ff1aded78c", "size": "380", "binary": false, "copies": "1", "ref": "refs/heads/scala-2.9", "path": "src/test/java/gsd/iml/ast/expression/IsLoadedFunctionCallExpression.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1148" }, { "name": "Java", "bytes": "370324" }, { "name": "Lex", "bytes": "29423" }, { "name": "Scala", "bytes": "720655" }, { "name": "Shell", "bytes": "2000" }, { "name": "Yacc", "bytes": "20952" } ], "symlink_target": "" }
/* Layout helpers ----------------------------------*/ .ui-helper-hidden { display: none; } .ui-helper-hidden-accessible { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } .ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; border-collapse: collapse; } .ui-helper-clearfix:after { clear: both; } .ui-helper-clearfix { min-height: 0; /* support: IE7 */ } .ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } .ui-front { z-index: 100; } /* Interaction Cues ----------------------------------*/ .ui-state-disabled { cursor: default !important; } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } /* Misc visuals ----------------------------------*/ /* Overlays */ .ui-widget-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; } .ui-accordion .ui-accordion-header { display: block; cursor: pointer; position: relative; margin-top: 2px; padding: .5em .5em .5em .7em; min-height: 0; /* support: IE7 */ } .ui-accordion .ui-accordion-icons { padding-left: 2.2em; } .ui-accordion .ui-accordion-noicons { padding-left: .7em; } .ui-accordion .ui-accordion-icons .ui-accordion-icons { padding-left: 2.2em; } .ui-accordion .ui-accordion-header .ui-accordion-header-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: auto; } .ui-autocomplete { position: absolute; top: 0; left: 0; cursor: default; } .ui-button { display: inline-block; position: relative; padding: 0; line-height: normal; margin-right: .1em; cursor: pointer; vertical-align: middle; text-align: center; overflow: visible; /* removes extra width in IE */ } .ui-button, .ui-button:link, .ui-button:visited, .ui-button:hover, .ui-button:active { text-decoration: none; } /* to make room for the icon, a width needs to be set here */ .ui-button-icon-only { width: 2.2em; } /* button elements seem to need a little more width */ button.ui-button-icon-only { width: 2.4em; } .ui-button-icons-only { width: 3.4em; } button.ui-button-icons-only { width: 3.7em; } /* button text element */ .ui-button .ui-button-text { display: block; line-height: normal; } .ui-button-text-only .ui-button-text { padding: .4em 1em; } .ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } .ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } .ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } .ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } /* no icon support for input elements, provide padding by default */ input.ui-button { padding: .4em 1em; } /* button icon element(s) */ .ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } .ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } .ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } .ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } /* button sets */ .ui-buttonset { margin-right: 7px; } .ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } /* workarounds */ /* reset extra padding in Firefox, see h5bp.com/l */ input.ui-button::-moz-focus-inner, button.ui-button::-moz-focus-inner { border: 0; padding: 0; } .ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } .ui-datepicker .ui-datepicker-header { position: relative; padding: .2em 0; } .ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position: absolute; top: 2px; width: 1.8em; height: 1.8em; } .ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } .ui-datepicker .ui-datepicker-prev { left: 2px; } .ui-datepicker .ui-datepicker-next { right: 2px; } .ui-datepicker .ui-datepicker-prev-hover { left: 1px; } .ui-datepicker .ui-datepicker-next-hover { right: 1px; } .ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } .ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } .ui-datepicker .ui-datepicker-title select { font-size: 1em; margin: 1px 0; } .ui-datepicker select.ui-datepicker-month-year { width: 100%; } .ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year { width: 49%; } .ui-datepicker table { width: 100%; font-size: .9em; border-collapse: collapse; margin: 0 0 .4em; } .ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } .ui-datepicker td { border: 0; padding: 1px; } .ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } .ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding: 0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } .ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width: auto; overflow: visible; } .ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float: left; } /* with multiple calendars */ .ui-datepicker.ui-datepicker-multi { width: auto; } .ui-datepicker-multi .ui-datepicker-group { float: left; } .ui-datepicker-multi .ui-datepicker-group table { width: 95%; margin: 0 auto .4em; } .ui-datepicker-multi-2 .ui-datepicker-group { width: 50%; } .ui-datepicker-multi-3 .ui-datepicker-group { width: 33.3%; } .ui-datepicker-multi-4 .ui-datepicker-group { width: 25%; } .ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, .ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width: 0; } .ui-datepicker-multi .ui-datepicker-buttonpane { clear: left; } .ui-datepicker-row-break { clear: both; width: 100%; font-size: 0; } /* RTL support */ .ui-datepicker-rtl { direction: rtl; } .ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } .ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } .ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } .ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } .ui-datepicker-rtl .ui-datepicker-buttonpane { clear: right; } .ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } .ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, .ui-datepicker-rtl .ui-datepicker-group { float: right; } .ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, .ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width: 0; border-left-width: 1px; } .ui-dialog { position: absolute; top: 0; left: 0; padding: .2em; outline: 0; } .ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } .ui-dialog .ui-dialog-title { float: left; margin: .1em 0; white-space: nowrap; width: 90%; overflow: hidden; text-overflow: ellipsis; } .ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 21px; margin: -10px 0 0 0; padding: 1px; height: 20px; } .ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; } .ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin-top: .5em; padding: .3em 1em .5em .4em; } .ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } .ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } .ui-dialog .ui-resizable-se { width: 12px; height: 12px; right: -5px; bottom: -5px; background-position: 16px 16px; } .ui-draggable .ui-dialog-titlebar { cursor: move; } .ui-menu { list-style: none; padding: 2px; margin: 0; display: block; outline: none; } .ui-menu .ui-menu { margin-top: -3px; position: absolute; } .ui-menu .ui-menu-item { margin: 0; padding: 0; width: 100%; /* support: IE10, see #8844 */ list-style-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7); } .ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; } .ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; min-height: 0; /* support: IE7 */ font-weight: normal; } .ui-menu .ui-menu-item a.ui-state-focus, .ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; } .ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; } .ui-menu .ui-state-disabled a { cursor: default; } /* icon support */ .ui-menu-icons { position: relative; } .ui-menu-icons .ui-menu-item a { position: relative; padding-left: 2em; } /* left-aligned */ .ui-menu .ui-icon { position: absolute; top: .2em; left: .2em; } /* right-aligned */ .ui-menu .ui-menu-icon { position: static; float: right; } .ui-progressbar { height: 2em; text-align: left; overflow: hidden; } .ui-progressbar .ui-progressbar-value { margin: -1px; height: 100%; } .ui-progressbar .ui-progressbar-overlay { background: url("images/animated-overlay.gif"); height: 100%; filter: alpha(opacity=25); opacity: 0.25; } .ui-progressbar-indeterminate .ui-progressbar-value { background-image: none; } .ui-resizable { position: relative; } .ui-resizable-handle { position: absolute; font-size: 0.1px; display: block; } .ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } .ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } .ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } .ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } .ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } .ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } .ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } .ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } .ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px; } .ui-selectable-helper { position: absolute; z-index: 100; border: 1px dotted black; } .ui-slider { position: relative; text-align: left; } .ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } /* For IE8 - See #6727 */ .ui-slider.ui-state-disabled .ui-slider-handle, .ui-slider.ui-state-disabled .ui-slider-range { filter: inherit; } .ui-slider-horizontal { height: .8em; } .ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } .ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } .ui-slider-horizontal .ui-slider-range-min { left: 0; } .ui-slider-horizontal .ui-slider-range-max { right: 0; } .ui-slider-vertical { width: .8em; height: 100px; } .ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } .ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } .ui-slider-vertical .ui-slider-range-min { bottom: 0; } .ui-slider-vertical .ui-slider-range-max { top: 0; } .ui-spinner { position: relative; display: inline-block; overflow: hidden; padding: 0; vertical-align: middle; } .ui-spinner-input { border: none; background: none; color: inherit; padding: 0; margin: .2em 0; vertical-align: middle; margin-left: .4em; margin-right: 22px; } .ui-spinner-button { width: 16px; height: 50%; font-size: .5em; padding: 0; margin: 0; text-align: center; position: absolute; cursor: default; display: block; overflow: hidden; right: 0; } /* more specificity required here to overide default borders */ .ui-spinner a.ui-spinner-button { border-top: none; border-bottom: none; border-right: none; } /* vertical centre icon */ .ui-spinner .ui-icon { position: absolute; margin-top: -8px; top: 50%; left: 0; } .ui-spinner-up { top: 0; } .ui-spinner-down { bottom: 0; } /* TR overrides */ .ui-spinner .ui-icon-triangle-1-s { /* need to fix icons sprite */ background-position: -65px -16px; } .ui-tabs { position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ padding: .2em; } .ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } .ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 0; margin: 1px .2em 0 0; border-bottom-width: 0; padding: 0; white-space: nowrap; } .ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } .ui-tabs .ui-tabs-nav li.ui-tabs-active { margin-bottom: -1px; padding-bottom: 1px; } .ui-tabs .ui-tabs-nav li.ui-tabs-active a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-tabs-loading a { cursor: text; } .ui-tabs .ui-tabs-nav li a, /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ .ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { cursor: pointer; } .ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } .ui-tooltip { padding: 8px; position: absolute; z-index: 9999; max-width: 300px; -webkit-box-shadow: 0 0 5px #aaa; box-shadow: 0 0 5px #aaa; } body .ui-tooltip { border-width: 2px; } /* Component containers ----------------------------------*/ .ui-widget { font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; font-size: 1.1em; } .ui-widget .ui-widget { font-size: 1em; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; font-size: 1em; } .ui-widget-content { border: 1px solid #72b42d; background: #285c00 url(images/ui-bg_inset-soft_10_285c00_1x100.png) 50% bottom repeat-x; color: #ffffff; } .ui-widget-content a { color: #ffffff; } .ui-widget-header { border: 1px solid #3f7506; background: #3a8104 url(images/ui-bg_highlight-soft_33_3a8104_1x100.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; } .ui-widget-header a { color: #ffffff; } /* Interaction states ----------------------------------*/ .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #45930b; background: #4ca20b url(images/ui-bg_highlight-soft_60_4ca20b_1x100.png) 50% 50% repeat-x; font-weight: normal; color: #ffffff; } .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #ffffff; text-decoration: none; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #8bd83b; background: #4eb305 url(images/ui-bg_highlight-soft_50_4eb305_1x100.png) 50% 50% repeat-x; font-weight: normal; color: #ffffff; } .ui-state-hover a, .ui-state-hover a:hover, .ui-state-hover a:link, .ui-state-hover a:visited { color: #ffffff; text-decoration: none; } .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #72b42d; background: #285c00 url(images/ui-bg_highlight-hard_30_285c00_1x100.png) 50% 50% repeat-x; font-weight: normal; color: #ffffff; } .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #ffffff; text-decoration: none; } /* Interaction Cues ----------------------------------*/ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #f9dd34; background: #fbf5d0 url(images/ui-bg_glass_55_fbf5d0_1x400.png) 50% 50% repeat-x; color: #363636; } .ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a { color: #363636; } .ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #fad000; background: #ffdc2e url(images/ui-bg_diagonals-thick_95_ffdc2e_40x40.png) 50% 50% repeat; color: #2b2b2b; } .ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #2b2b2b; } .ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #2b2b2b; } .ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } .ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } .ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } .ui-state-disabled .ui-icon { filter:Alpha(Opacity=35); /* For IE8 - See #6059 */ } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { width: 16px; height: 16px; } .ui-icon, .ui-widget-content .ui-icon { background-image: url(images/ui-icons_72b42d_256x240.png); } .ui-widget-header .ui-icon { background-image: url(images/ui-icons_ffffff_256x240.png); } .ui-state-default .ui-icon { background-image: url(images/ui-icons_ffffff_256x240.png); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { background-image: url(images/ui-icons_ffffff_256x240.png); } .ui-state-active .ui-icon { background-image: url(images/ui-icons_ffffff_256x240.png); } .ui-state-highlight .ui-icon { background-image: url(images/ui-icons_4eb305_256x240.png); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { background-image: url(images/ui-icons_cd0a0a_256x240.png); } /* positioning */ .ui-icon-blank { background-position: 16px 16px; } .ui-icon-carat-1-n { background-position: 0 0; } .ui-icon-carat-1-ne { background-position: -16px 0; } .ui-icon-carat-1-e { background-position: -32px 0; } .ui-icon-carat-1-se { background-position: -48px 0; } .ui-icon-carat-1-s { background-position: -64px 0; } .ui-icon-carat-1-sw { background-position: -80px 0; } .ui-icon-carat-1-w { background-position: -96px 0; } .ui-icon-carat-1-nw { background-position: -112px 0; } .ui-icon-carat-2-n-s { background-position: -128px 0; } .ui-icon-carat-2-e-w { background-position: -144px 0; } .ui-icon-triangle-1-n { background-position: 0 -16px; } .ui-icon-triangle-1-ne { background-position: -16px -16px; } .ui-icon-triangle-1-e { background-position: -32px -16px; } .ui-icon-triangle-1-se { background-position: -48px -16px; } .ui-icon-triangle-1-s { background-position: -64px -16px; } .ui-icon-triangle-1-sw { background-position: -80px -16px; } .ui-icon-triangle-1-w { background-position: -96px -16px; } .ui-icon-triangle-1-nw { background-position: -112px -16px; } .ui-icon-triangle-2-n-s { background-position: -128px -16px; } .ui-icon-triangle-2-e-w { background-position: -144px -16px; } .ui-icon-arrow-1-n { background-position: 0 -32px; } .ui-icon-arrow-1-ne { background-position: -16px -32px; } .ui-icon-arrow-1-e { background-position: -32px -32px; } .ui-icon-arrow-1-se { background-position: -48px -32px; } .ui-icon-arrow-1-s { background-position: -64px -32px; } .ui-icon-arrow-1-sw { background-position: -80px -32px; } .ui-icon-arrow-1-w { background-position: -96px -32px; } .ui-icon-arrow-1-nw { background-position: -112px -32px; } .ui-icon-arrow-2-n-s { background-position: -128px -32px; } .ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } .ui-icon-arrow-2-e-w { background-position: -160px -32px; } .ui-icon-arrow-2-se-nw { background-position: -176px -32px; } .ui-icon-arrowstop-1-n { background-position: -192px -32px; } .ui-icon-arrowstop-1-e { background-position: -208px -32px; } .ui-icon-arrowstop-1-s { background-position: -224px -32px; } .ui-icon-arrowstop-1-w { background-position: -240px -32px; } .ui-icon-arrowthick-1-n { background-position: 0 -48px; } .ui-icon-arrowthick-1-ne { background-position: -16px -48px; } .ui-icon-arrowthick-1-e { background-position: -32px -48px; } .ui-icon-arrowthick-1-se { background-position: -48px -48px; } .ui-icon-arrowthick-1-s { background-position: -64px -48px; } .ui-icon-arrowthick-1-sw { background-position: -80px -48px; } .ui-icon-arrowthick-1-w { background-position: -96px -48px; } .ui-icon-arrowthick-1-nw { background-position: -112px -48px; } .ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } .ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } .ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } .ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } .ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } .ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } .ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } .ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } .ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } .ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } .ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } .ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } .ui-icon-arrowreturn-1-w { background-position: -64px -64px; } .ui-icon-arrowreturn-1-n { background-position: -80px -64px; } .ui-icon-arrowreturn-1-e { background-position: -96px -64px; } .ui-icon-arrowreturn-1-s { background-position: -112px -64px; } .ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } .ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } .ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } .ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } .ui-icon-arrow-4 { background-position: 0 -80px; } .ui-icon-arrow-4-diag { background-position: -16px -80px; } .ui-icon-extlink { background-position: -32px -80px; } .ui-icon-newwin { background-position: -48px -80px; } .ui-icon-refresh { background-position: -64px -80px; } .ui-icon-shuffle { background-position: -80px -80px; } .ui-icon-transfer-e-w { background-position: -96px -80px; } .ui-icon-transferthick-e-w { background-position: -112px -80px; } .ui-icon-folder-collapsed { background-position: 0 -96px; } .ui-icon-folder-open { background-position: -16px -96px; } .ui-icon-document { background-position: -32px -96px; } .ui-icon-document-b { background-position: -48px -96px; } .ui-icon-note { background-position: -64px -96px; } .ui-icon-mail-closed { background-position: -80px -96px; } .ui-icon-mail-open { background-position: -96px -96px; } .ui-icon-suitcase { background-position: -112px -96px; } .ui-icon-comment { background-position: -128px -96px; } .ui-icon-person { background-position: -144px -96px; } .ui-icon-print { background-position: -160px -96px; } .ui-icon-trash { background-position: -176px -96px; } .ui-icon-locked { background-position: -192px -96px; } .ui-icon-unlocked { background-position: -208px -96px; } .ui-icon-bookmark { background-position: -224px -96px; } .ui-icon-tag { background-position: -240px -96px; } .ui-icon-home { background-position: 0 -112px; } .ui-icon-flag { background-position: -16px -112px; } .ui-icon-calendar { background-position: -32px -112px; } .ui-icon-cart { background-position: -48px -112px; } .ui-icon-pencil { background-position: -64px -112px; } .ui-icon-clock { background-position: -80px -112px; } .ui-icon-disk { background-position: -96px -112px; } .ui-icon-calculator { background-position: -112px -112px; } .ui-icon-zoomin { background-position: -128px -112px; } .ui-icon-zoomout { background-position: -144px -112px; } .ui-icon-search { background-position: -160px -112px; } .ui-icon-wrench { background-position: -176px -112px; } .ui-icon-gear { background-position: -192px -112px; } .ui-icon-heart { background-position: -208px -112px; } .ui-icon-star { background-position: -224px -112px; } .ui-icon-link { background-position: -240px -112px; } .ui-icon-cancel { background-position: 0 -128px; } .ui-icon-plus { background-position: -16px -128px; } .ui-icon-plusthick { background-position: -32px -128px; } .ui-icon-minus { background-position: -48px -128px; } .ui-icon-minusthick { background-position: -64px -128px; } .ui-icon-close { background-position: -80px -128px; } .ui-icon-closethick { background-position: -96px -128px; } .ui-icon-key { background-position: -112px -128px; } .ui-icon-lightbulb { background-position: -128px -128px; } .ui-icon-scissors { background-position: -144px -128px; } .ui-icon-clipboard { background-position: -160px -128px; } .ui-icon-copy { background-position: -176px -128px; } .ui-icon-contact { background-position: -192px -128px; } .ui-icon-image { background-position: -208px -128px; } .ui-icon-video { background-position: -224px -128px; } .ui-icon-script { background-position: -240px -128px; } .ui-icon-alert { background-position: 0 -144px; } .ui-icon-info { background-position: -16px -144px; } .ui-icon-notice { background-position: -32px -144px; } .ui-icon-help { background-position: -48px -144px; } .ui-icon-check { background-position: -64px -144px; } .ui-icon-bullet { background-position: -80px -144px; } .ui-icon-radio-on { background-position: -96px -144px; } .ui-icon-radio-off { background-position: -112px -144px; } .ui-icon-pin-w { background-position: -128px -144px; } .ui-icon-pin-s { background-position: -144px -144px; } .ui-icon-play { background-position: 0 -160px; } .ui-icon-pause { background-position: -16px -160px; } .ui-icon-seek-next { background-position: -32px -160px; } .ui-icon-seek-prev { background-position: -48px -160px; } .ui-icon-seek-end { background-position: -64px -160px; } .ui-icon-seek-start { background-position: -80px -160px; } /* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ .ui-icon-seek-first { background-position: -80px -160px; } .ui-icon-stop { background-position: -96px -160px; } .ui-icon-eject { background-position: -112px -160px; } .ui-icon-volume-off { background-position: -128px -160px; } .ui-icon-volume-on { background-position: -144px -160px; } .ui-icon-power { background-position: 0 -176px; } .ui-icon-signal-diag { background-position: -16px -176px; } .ui-icon-signal { background-position: -32px -176px; } .ui-icon-battery-0 { background-position: -48px -176px; } .ui-icon-battery-1 { background-position: -64px -176px; } .ui-icon-battery-2 { background-position: -80px -176px; } .ui-icon-battery-3 { background-position: -96px -176px; } .ui-icon-circle-plus { background-position: 0 -192px; } .ui-icon-circle-minus { background-position: -16px -192px; } .ui-icon-circle-close { background-position: -32px -192px; } .ui-icon-circle-triangle-e { background-position: -48px -192px; } .ui-icon-circle-triangle-s { background-position: -64px -192px; } .ui-icon-circle-triangle-w { background-position: -80px -192px; } .ui-icon-circle-triangle-n { background-position: -96px -192px; } .ui-icon-circle-arrow-e { background-position: -112px -192px; } .ui-icon-circle-arrow-s { background-position: -128px -192px; } .ui-icon-circle-arrow-w { background-position: -144px -192px; } .ui-icon-circle-arrow-n { background-position: -160px -192px; } .ui-icon-circle-zoomin { background-position: -176px -192px; } .ui-icon-circle-zoomout { background-position: -192px -192px; } .ui-icon-circle-check { background-position: -208px -192px; } .ui-icon-circlesmall-plus { background-position: 0 -208px; } .ui-icon-circlesmall-minus { background-position: -16px -208px; } .ui-icon-circlesmall-close { background-position: -32px -208px; } .ui-icon-squaresmall-plus { background-position: -48px -208px; } .ui-icon-squaresmall-minus { background-position: -64px -208px; } .ui-icon-squaresmall-close { background-position: -80px -208px; } .ui-icon-grip-dotted-vertical { background-position: 0 -224px; } .ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } .ui-icon-grip-solid-vertical { background-position: -32px -224px; } .ui-icon-grip-solid-horizontal { background-position: -48px -224px; } .ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } .ui-icon-grip-diagonal-se { background-position: -80px -224px; } /* Misc visuals ----------------------------------*/ /* Corner radius */ .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { border-top-left-radius: 10px; } .ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { border-top-right-radius: 10px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { border-bottom-left-radius: 10px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { border-bottom-right-radius: 10px; } /* Overlays */ .ui-widget-overlay { background: #444444 url(images/ui-bg_diagonals-thick_15_444444_40x40.png) 50% 50% repeat; opacity: .3; filter: Alpha(Opacity=30); } .ui-widget-shadow { margin: 4px 0 0 4px; padding: 0px; background: #aaaaaa url(images/ui-bg_diagonals-small_0_aaaaaa_40x40.png) 50% 50% repeat; opacity: .3; filter: Alpha(Opacity=30); border-radius: 4px; }
{ "content_hash": "4871cc1b6ab1e3d39dd802a1a05d323a", "timestamp": "", "source": "github", "line_count": 1173, "max_line_length": 165, "avg_line_length": 27.075873827791987, "alnum_prop": 0.6591309823677581, "repo_name": "austerus/av-decision", "id": "5243998d11579f20894891a14f0e03504fce300e", "size": "33661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Decision/DecisionBundle/Resources/public/css/le-frog/jquery-ui.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2218" }, { "name": "JavaScript", "bytes": "3157" }, { "name": "PHP", "bytes": "82743" } ], "symlink_target": "" }
#include "TextDescriptions.h" #include <media/stagefright/foundation/ByteUtils.h> #include <media/stagefright/MediaErrors.h> namespace android { TextDescriptions::TextDescriptions() { } status_t TextDescriptions::getParcelOfDescriptions( const uint8_t *data, ssize_t size, uint32_t flags, int timeMs, Parcel *parcel) { parcel->freeData(); if (flags & IN_BAND_TEXT_3GPP) { if (flags & GLOBAL_DESCRIPTIONS) { return extract3GPPGlobalDescriptions(data, size, parcel); } else if (flags & LOCAL_DESCRIPTIONS) { return extract3GPPLocalDescriptions(data, size, timeMs, parcel); } } else if (flags & OUT_OF_BAND_TEXT_SRT) { if (flags & LOCAL_DESCRIPTIONS) { return extractSRTLocalDescriptions(data, size, timeMs, parcel); } } return ERROR_UNSUPPORTED; } // Parse the SRT text sample, and store the timing and text sample in a Parcel. // The Parcel will be sent to MediaPlayer.java through event, and will be // parsed in TimedText.java. status_t TextDescriptions::extractSRTLocalDescriptions( const uint8_t *data, ssize_t size, int timeMs, Parcel *parcel) { parcel->writeInt32(KEY_LOCAL_SETTING); parcel->writeInt32(KEY_START_TIME); parcel->writeInt32(timeMs); parcel->writeInt32(KEY_STRUCT_TEXT); // write the size of the text sample parcel->writeInt32(size); // write the text sample as a byte array parcel->writeInt32(size); parcel->write(data, size); return OK; } // Extract the local 3GPP display descriptions. 3GPP local descriptions // are appended to the text sample if any. The descriptions could include // information such as text styles, highlights, karaoke and so on. They // are contained in different boxes, such as 'styl' box contains text // styles, and 'krok' box contains karaoke timing and positions. status_t TextDescriptions::extract3GPPLocalDescriptions( const uint8_t *data, ssize_t size, int timeMs, Parcel *parcel) { parcel->writeInt32(KEY_LOCAL_SETTING); // write start time to display this text sample parcel->writeInt32(KEY_START_TIME); parcel->writeInt32(timeMs); if (size < 2) { return OK; } ssize_t textLen = (*data) << 8 | (*(data + 1)); if (size < textLen + 2) { return OK; } // write text sample length and text sample itself parcel->writeInt32(KEY_STRUCT_TEXT); parcel->writeInt32(textLen); parcel->writeInt32(textLen); parcel->write(data + 2, textLen); if (size > textLen + 2) { data += (textLen + 2); size -= (textLen + 2); } else { return OK; } while (size >= 8) { const uint8_t *tmpData = data; ssize_t chunkSize = U32_AT(tmpData); // size includes size and type uint32_t chunkType = U32_AT(tmpData + 4); if (chunkSize <= 8 || chunkSize > size) { return OK; } size_t remaining = chunkSize - 8; tmpData += 8; switch(chunkType) { // 'styl' box specifies the style of the text. case FOURCC('s', 't', 'y', 'l'): { if (remaining < 2) { return OK; } size_t dataPos = parcel->dataPosition(); uint16_t count = U16_AT(tmpData); tmpData += 2; remaining -= 2; for (int i = 0; i < count; i++) { if (remaining < 12) { // roll back parcel->setDataPosition(dataPos); return OK; } parcel->writeInt32(KEY_STRUCT_STYLE_LIST); parcel->writeInt32(KEY_START_CHAR); parcel->writeInt32(U16_AT(tmpData)); parcel->writeInt32(KEY_END_CHAR); parcel->writeInt32(U16_AT(tmpData + 2)); parcel->writeInt32(KEY_FONT_ID); parcel->writeInt32(U16_AT(tmpData + 4)); parcel->writeInt32(KEY_STYLE_FLAGS); parcel->writeInt32(*(tmpData + 6)); parcel->writeInt32(KEY_FONT_SIZE); parcel->writeInt32(*(tmpData + 7)); parcel->writeInt32(KEY_TEXT_COLOR_RGBA); uint32_t rgba = *(tmpData + 8) << 24 | *(tmpData + 9) << 16 | *(tmpData + 10) << 8 | *(tmpData + 11); parcel->writeInt32(rgba); tmpData += 12; remaining -= 12; } break; } // 'krok' box. The number of highlight events is specified, and each // event is specified by a starting and ending char offset and an end // time for the event. case FOURCC('k', 'r', 'o', 'k'): { if (remaining < 6) { return OK; } size_t dataPos = parcel->dataPosition(); parcel->writeInt32(KEY_STRUCT_KARAOKE_LIST); int startTime = U32_AT(tmpData); uint16_t count = U16_AT(tmpData + 4); parcel->writeInt32(count); tmpData += 6; remaining -= 6; int lastEndTime = 0; for (int i = 0; i < count; i++) { if (remaining < 8) { // roll back parcel->setDataPosition(dataPos); return OK; } parcel->writeInt32(startTime + lastEndTime); lastEndTime = U32_AT(tmpData); parcel->writeInt32(lastEndTime); parcel->writeInt32(U16_AT(tmpData + 4)); parcel->writeInt32(U16_AT(tmpData + 6)); tmpData += 8; remaining -= 8; } break; } // 'hlit' box specifies highlighted text case FOURCC('h', 'l', 'i', 't'): { if (remaining < 4) { return OK; } parcel->writeInt32(KEY_STRUCT_HIGHLIGHT_LIST); // the start char offset to highlight parcel->writeInt32(U16_AT(tmpData)); // the last char offset to highlight parcel->writeInt32(U16_AT(tmpData + 2)); tmpData += 4; remaining -= 4; break; } // 'hclr' box specifies the RGBA color: 8 bits each of // red, green, blue, and an alpha(transparency) value case FOURCC('h', 'c', 'l', 'r'): { if (remaining < 4) { return OK; } parcel->writeInt32(KEY_HIGHLIGHT_COLOR_RGBA); uint32_t rgba = *(tmpData) << 24 | *(tmpData + 1) << 16 | *(tmpData + 2) << 8 | *(tmpData + 3); parcel->writeInt32(rgba); tmpData += 4; remaining -= 4; break; } // 'dlay' box specifies a delay after a scroll in and/or // before scroll out. case FOURCC('d', 'l', 'a', 'y'): { if (remaining < 4) { return OK; } parcel->writeInt32(KEY_SCROLL_DELAY); uint32_t delay = *(tmpData) << 24 | *(tmpData + 1) << 16 | *(tmpData + 2) << 8 | *(tmpData + 3); parcel->writeInt32(delay); tmpData += 4; remaining -= 4; break; } // 'href' box for hyper text link case FOURCC('h', 'r', 'e', 'f'): { if (remaining < 5) { return OK; } size_t dataPos = parcel->dataPosition(); parcel->writeInt32(KEY_STRUCT_HYPER_TEXT_LIST); // the start offset of the text to be linked parcel->writeInt32(U16_AT(tmpData)); // the end offset of the text parcel->writeInt32(U16_AT(tmpData + 2)); // the number of bytes in the following URL size_t len = *(tmpData + 4); parcel->writeInt32(len); remaining -= 5; if (remaining < len) { parcel->setDataPosition(dataPos); return OK; } // the linked-to URL parcel->writeInt32(len); parcel->write(tmpData + 5, len); tmpData += (5 + len); remaining -= len; if (remaining < 1) { parcel->setDataPosition(dataPos); return OK; } // the number of bytes in the following "alt" string len = *tmpData; parcel->writeInt32(len); tmpData += 1; remaining -= 1; if (remaining < len) { parcel->setDataPosition(dataPos); return OK; } // an "alt" string for user display parcel->writeInt32(len); parcel->write(tmpData, len); tmpData += 1; remaining -= 1; break; } // 'tbox' box to indicate the position of the text with values // of top, left, bottom and right case FOURCC('t', 'b', 'o', 'x'): { if (remaining < 8) { return OK; } parcel->writeInt32(KEY_STRUCT_TEXT_POS); parcel->writeInt32(U16_AT(tmpData)); parcel->writeInt32(U16_AT(tmpData + 2)); parcel->writeInt32(U16_AT(tmpData + 4)); parcel->writeInt32(U16_AT(tmpData + 6)); tmpData += 8; remaining -= 8; break; } // 'blnk' to specify the char range to be blinked case FOURCC('b', 'l', 'n', 'k'): { if (remaining < 4) { return OK; } parcel->writeInt32(KEY_STRUCT_BLINKING_TEXT_LIST); // start char offset parcel->writeInt32(U16_AT(tmpData)); // end char offset parcel->writeInt32(U16_AT(tmpData + 2)); tmpData += 4; remaining -= 4; break; } // 'twrp' box specifies text wrap behavior. If the value if 0x00, // then no wrap. If it's 0x01, then automatic 'soft' wrap is enabled. // 0x02-0xff are reserved. case FOURCC('t', 'w', 'r', 'p'): { if (remaining < 1) { return OK; } parcel->writeInt32(KEY_WRAP_TEXT); parcel->writeInt32(*tmpData); tmpData += 1; remaining -= 1; break; } default: { break; } } data += chunkSize; size -= chunkSize; } return OK; } // To extract box 'tx3g' defined in 3GPP TS 26.245, and store it in a Parcel status_t TextDescriptions::extract3GPPGlobalDescriptions( const uint8_t *data, ssize_t size, Parcel *parcel) { parcel->writeInt32(KEY_GLOBAL_SETTING); while (size >= 8) { ssize_t chunkSize = U32_AT(data); uint32_t chunkType = U32_AT(data + 4); const uint8_t *tmpData = data; tmpData += 8; size_t remaining = size - 8; if (chunkSize <= 8 || size < chunkSize) { return OK; } switch(chunkType) { case FOURCC('t', 'x', '3', 'g'): { if (remaining < 18) { // 8 just below, and another 10 a little further down return OK; } tmpData += 8; // skip the first 8 bytes remaining -=8; parcel->writeInt32(KEY_DISPLAY_FLAGS); parcel->writeInt32(U32_AT(tmpData)); parcel->writeInt32(KEY_STRUCT_JUSTIFICATION); parcel->writeInt32(tmpData[4]); parcel->writeInt32(tmpData[5]); parcel->writeInt32(KEY_BACKGROUND_COLOR_RGBA); uint32_t rgba = *(tmpData + 6) << 24 | *(tmpData + 7) << 16 | *(tmpData + 8) << 8 | *(tmpData + 9); parcel->writeInt32(rgba); tmpData += 10; remaining -= 10; if (remaining < 8) { return OK; } parcel->writeInt32(KEY_STRUCT_TEXT_POS); parcel->writeInt32(U16_AT(tmpData)); parcel->writeInt32(U16_AT(tmpData + 2)); parcel->writeInt32(U16_AT(tmpData + 4)); parcel->writeInt32(U16_AT(tmpData + 6)); tmpData += 8; remaining -= 8; if (remaining < 12) { return OK; } parcel->writeInt32(KEY_STRUCT_STYLE_LIST); parcel->writeInt32(KEY_START_CHAR); parcel->writeInt32(U16_AT(tmpData)); parcel->writeInt32(KEY_END_CHAR); parcel->writeInt32(U16_AT(tmpData + 2)); parcel->writeInt32(KEY_FONT_ID); parcel->writeInt32(U16_AT(tmpData + 4)); parcel->writeInt32(KEY_STYLE_FLAGS); parcel->writeInt32(*(tmpData + 6)); parcel->writeInt32(KEY_FONT_SIZE); parcel->writeInt32(*(tmpData + 7)); parcel->writeInt32(KEY_TEXT_COLOR_RGBA); rgba = *(tmpData + 8) << 24 | *(tmpData + 9) << 16 | *(tmpData + 10) << 8 | *(tmpData + 11); parcel->writeInt32(rgba); tmpData += 12; remaining -= 12; if (remaining < 2) { return OK; } size_t dataPos = parcel->dataPosition(); parcel->writeInt32(KEY_STRUCT_FONT_LIST); uint16_t count = U16_AT(tmpData); parcel->writeInt32(count); tmpData += 2; remaining -= 2; for (int i = 0; i < count; i++) { if (remaining < 3) { // roll back parcel->setDataPosition(dataPos); return OK; } // font ID parcel->writeInt32(U16_AT(tmpData)); // font name length parcel->writeInt32(*(tmpData + 2)); size_t len = *(tmpData + 2); tmpData += 3; remaining -= 3; if (remaining < len) { // roll back parcel->setDataPosition(dataPos); return OK; } parcel->write(tmpData, len); tmpData += len; remaining -= len; } // there is a "DisparityBox" after this according to the spec, but we ignore it break; } default: { break; } } data += chunkSize; size -= chunkSize; } return OK; } } // namespace android
{ "content_hash": "1ebee02b0dc3bc94696ec50d5276b51c", "timestamp": "", "source": "github", "line_count": 494, "max_line_length": 95, "avg_line_length": 32.23279352226721, "alnum_prop": 0.45380895559881934, "repo_name": "dAck2cC2/m3e", "id": "0dc7722f6f7dfdc348a6a8a974a8049a753c3fb6", "size": "16542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/frameworks/av/media/libstagefright/timedtext/TextDescriptions.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "10986" }, { "name": "Assembly", "bytes": "179243" }, { "name": "C", "bytes": "7339857" }, { "name": "C++", "bytes": "27763758" }, { "name": "CMake", "bytes": "277213" }, { "name": "HTML", "bytes": "47935" }, { "name": "Makefile", "bytes": "396212" }, { "name": "Objective-C++", "bytes": "2804" }, { "name": "Perl", "bytes": "3733" }, { "name": "Python", "bytes": "3628" }, { "name": "RenderScript", "bytes": "6664" }, { "name": "Shell", "bytes": "25112" } ], "symlink_target": "" }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.mobileParser = void 0; var _mobileDetect = _interopRequireDefault(require("mobile-detect")); var mobileParser = function mobileParser() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$headers = _ref.headers, headers = _ref$headers === void 0 ? {} : _ref$headers; var ua = headers['user-agent'] || headers['User-Agent']; var md = new _mobileDetect["default"](ua); return { phone: !!md.phone(), tablet: !!md.tablet(), mobile: !!md.mobile(), desktop: !md.mobile() }; }; exports.mobileParser = mobileParser; //# sourceMappingURL=parser.js.map
{ "content_hash": "97390e2aee002b48e974d3c2ff3efc09", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 85, "avg_line_length": 28.464285714285715, "alnum_prop": 0.6599749058971142, "repo_name": "modosc/react-responsive-redux", "id": "fcfb4d9774fd3f6173b908a595dbb9b63e205863", "size": "797", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/parser.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "24204" } ], "symlink_target": "" }
import os.path, subprocess from ..mesonlib import EnvironmentException, version_compare from .compilers import ( GCC_STANDARD, d_dmd_buildtype_args, d_gdc_buildtype_args, d_ldc_buildtype_args, get_gcc_soname_args, gnu_color_args, Compiler, CompilerArgs, ) d_feature_args = {'gcc': {'unittest': '-funittest', 'version': '-fversion', 'import_dir': '-J' }, 'llvm': {'unittest': '-unittest', 'version': '-d-version', 'import_dir': '-J' }, 'dmd': {'unittest': '-unittest', 'version': '-version', 'import_dir': '-J' } } class DCompiler(Compiler): def __init__(self, exelist, version, is_cross, **kwargs): self.language = 'd' super().__init__(exelist, version, **kwargs) self.id = 'unknown' self.is_cross = is_cross def sanity_check(self, work_dir, environment): source_name = os.path.join(work_dir, 'sanity.d') output_name = os.path.join(work_dir, 'dtest') with open(source_name, 'w') as ofile: ofile.write('''void main() { } ''') pc = subprocess.Popen(self.exelist + self.get_output_args(output_name) + [source_name], cwd=work_dir) pc.wait() if pc.returncode != 0: raise EnvironmentException('D compiler %s can not compile programs.' % self.name_string()) if subprocess.call(output_name) != 0: raise EnvironmentException('Executables created by D compiler %s are not runnable.' % self.name_string()) def needs_static_linker(self): return True def name_string(self): return ' '.join(self.exelist) def get_linker_exelist(self): return self.exelist[:] def get_preprocess_only_args(self): return ['-E'] def get_compile_only_args(self): return ['-c'] def depfile_for_object(self, objfile): return objfile + '.' + self.get_depfile_suffix() def get_depfile_suffix(self): return 'deps' def get_pic_args(self): return ['-fPIC'] def get_std_shared_lib_link_args(self): return ['-shared'] def get_soname_args(self, prefix, shlib_name, suffix, soversion, is_shared_module): # FIXME: Make this work for Windows, MacOS and cross-compiling return get_gcc_soname_args(GCC_STANDARD, prefix, shlib_name, suffix, soversion, is_shared_module) def get_feature_args(self, kwargs, build_to_src): res = [] if 'unittest' in kwargs: unittest = kwargs.pop('unittest') unittest_arg = d_feature_args[self.id]['unittest'] if not unittest_arg: raise EnvironmentException('D compiler %s does not support the "unittest" feature.' % self.name_string()) if unittest: res.append(unittest_arg) if 'versions' in kwargs: versions = kwargs.pop('versions') if not isinstance(versions, list): versions = [versions] version_arg = d_feature_args[self.id]['version'] if not version_arg: raise EnvironmentException('D compiler %s does not support the "feature versions" feature.' % self.name_string()) for v in versions: res.append('{0}={1}'.format(version_arg, v)) if 'import_dirs' in kwargs: import_dirs = kwargs.pop('import_dirs') if not isinstance(import_dirs, list): import_dirs = [import_dirs] import_dir_arg = d_feature_args[self.id]['import_dir'] if not import_dir_arg: raise EnvironmentException('D compiler %s does not support the "string import directories" feature.' % self.name_string()) for idir_obj in import_dirs: basedir = idir_obj.get_curdir() for idir in idir_obj.get_incdirs(): # Avoid superfluous '/.' at the end of paths when d is '.' if idir not in ('', '.'): expdir = os.path.join(basedir, idir) else: expdir = basedir srctreedir = os.path.join(build_to_src, expdir) res.append('{0}{1}'.format(import_dir_arg, srctreedir)) if kwargs: raise EnvironmentException('Unknown D compiler feature(s) selected: %s' % ', '.join(kwargs.keys())) return res def get_buildtype_linker_args(self, buildtype): return [] def get_std_exe_link_args(self): return [] def build_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath): # This method is to be used by LDC and DMD. # GDC can deal with the verbatim flags. if not rpath_paths and not install_rpath: return [] paths = ':'.join([os.path.join(build_dir, p) for p in rpath_paths]) if build_rpath != '': paths += ':' + build_rpath if len(paths) < len(install_rpath): padding = 'X' * (len(install_rpath) - len(paths)) if not paths: paths = padding else: paths = paths + ':' + padding return ['-L-rpath={}'.format(paths)] def _get_compiler_check_args(self, env, extra_args, dependencies, mode='compile'): if extra_args is None: extra_args = [] elif isinstance(extra_args, str): extra_args = [extra_args] if dependencies is None: dependencies = [] elif not isinstance(dependencies, list): dependencies = [dependencies] # Collect compiler arguments args = CompilerArgs(self) for d in dependencies: # Add compile flags needed by dependencies args += d.get_compile_args() if mode == 'link': # Add link flags needed to find dependencies args += d.get_link_args() if mode == 'compile': # Add DFLAGS from the env args += env.coredata.get_external_args(self.language) elif mode == 'link': # Add LDFLAGS from the env args += env.coredata.get_external_link_args(self.language) # extra_args must override all other arguments, so we add them last args += extra_args return args def compiles(self, code, env, extra_args=None, dependencies=None, mode='compile'): args = self._get_compiler_check_args(env, extra_args, dependencies, mode) with self.compile(code, args, mode) as p: return p.returncode == 0 def has_multi_arguments(self, args, env): return self.compiles('int i;\n', env, extra_args=args) @classmethod def translate_args_to_nongnu(cls, args): dcargs = [] # Translate common arguments to flags the LDC/DMD compilers # can understand. # The flags might have been added by pkg-config files, # and are therefore out of the user's control. for arg in args: if arg == '-pthread': continue if arg.startswith('-Wl,'): linkargs = arg[arg.index(',') + 1:].split(',') for la in linkargs: dcargs.append('-L' + la.strip()) continue elif arg.startswith('-link-defaultlib') or arg.startswith('-linker'): # these are special arguments to the LDC linker call, # arguments like "-link-defaultlib-shared" do *not* # denote a library to be linked, but change the default # Phobos/DRuntime linking behavior, while "-linker" sets the # default linker. dcargs.append(arg) continue elif arg.startswith('-l'): # translate library link flag dcargs.append('-L' + arg) continue elif arg.startswith('-L/') or arg.startswith('-L./'): # we need to handle cases where -L is set by e.g. a pkg-config # setting to select a linker search path. We can however not # unconditionally prefix '-L' with '-L' because the user might # have set this flag too to do what it is intended to for this # compiler (pass flag through to the linker) # Hence, we guess here whether the flag was intended to pass # a linker search path. dcargs.append('-L' + arg) continue dcargs.append(arg) return dcargs class GnuDCompiler(DCompiler): def __init__(self, exelist, version, is_cross, **kwargs): DCompiler.__init__(self, exelist, version, is_cross, **kwargs) self.id = 'gcc' default_warn_args = ['-Wall', '-Wdeprecated'] self.warn_args = {'1': default_warn_args, '2': default_warn_args + ['-Wextra'], '3': default_warn_args + ['-Wextra', '-Wpedantic']} self.base_options = ['b_colorout', 'b_sanitize', 'b_staticpic'] self._has_color_support = version_compare(self.version, '>=4.9') # dependencies were implemented before, but broken - support was fixed in GCC 7.1+ # (and some backported versions) self._has_deps_support = version_compare(self.version, '>=7.1') def get_colorout_args(self, colortype): if self._has_color_support: return gnu_color_args[colortype][:] return [] def get_dependency_gen_args(self, outtarget, outfile): if not self._has_deps_support: return [] return ['-MD', '-MQ', outtarget, '-MF', outfile] def get_output_args(self, target): return ['-o', target] def get_linker_output_args(self, target): return ['-o', target] def get_include_args(self, path, is_system): return ['-I' + path] def get_warn_args(self, level): return self.warn_args[level] def get_werror_args(self): return ['-Werror'] def get_linker_search_args(self, dirname): return ['-L' + dirname] def get_buildtype_args(self, buildtype): return d_gdc_buildtype_args[buildtype] def build_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath): return self.build_unix_rpath_args(build_dir, from_dir, rpath_paths, build_rpath, install_rpath) class LLVMDCompiler(DCompiler): def __init__(self, exelist, version, is_cross, **kwargs): DCompiler.__init__(self, exelist, version, is_cross, **kwargs) self.id = 'llvm' self.base_options = ['b_coverage', 'b_colorout'] def get_colorout_args(self, colortype): if colortype == 'always': return ['-enable-color'] return [] def get_dependency_gen_args(self, outtarget, outfile): # LDC using the -deps flag returns a non-Makefile dependency-info file, which # the backends can not use. So we disable this feature for now. return [] def get_output_args(self, target): return ['-of', target] def get_linker_output_args(self, target): return ['-of', target] def get_include_args(self, path, is_system): return ['-I' + path] def get_warn_args(self, level): if level == '2' or level == '3': return ['-wi', '-dw'] else: return ['-wi'] def get_werror_args(self): return ['-w'] def get_coverage_args(self): return ['-cov'] def get_buildtype_args(self, buildtype): return d_ldc_buildtype_args[buildtype] def get_pic_args(self): return ['-relocation-model=pic'] def get_linker_search_args(self, dirname): # -L is recognized as "add this to the search path" by the linker, # while the compiler recognizes it as "pass to linker". So, the first # -L is for the compiler, telling it to pass the second -L to the linker. return ['-L-L' + dirname] @classmethod def unix_args_to_native(cls, args): return cls.translate_args_to_nongnu(args) class DmdDCompiler(DCompiler): def __init__(self, exelist, version, is_cross, **kwargs): DCompiler.__init__(self, exelist, version, is_cross, **kwargs) self.id = 'dmd' self.base_options = ['b_coverage', 'b_colorout'] def get_colorout_args(self, colortype): if colortype == 'always': return ['-color=on'] return [] def get_dependency_gen_args(self, outtarget, outfile): # LDC using the -deps flag returns a non-Makefile dependency-info file, which # the backends can not use. So we disable this feature for now. return [] def get_output_args(self, target): return ['-of' + target] def get_werror_args(self): return ['-w'] def get_linker_output_args(self, target): return ['-of' + target] def get_include_args(self, path, is_system): return ['-I' + path] def get_warn_args(self, level): return ['-wi'] def get_coverage_args(self): return ['-cov'] def get_linker_search_args(self, dirname): # -L is recognized as "add this to the search path" by the linker, # while the compiler recognizes it as "pass to linker". So, the first # -L is for the compiler, telling it to pass the second -L to the linker. return ['-L-L' + dirname] def get_buildtype_args(self, buildtype): return d_dmd_buildtype_args[buildtype] def get_std_shared_lib_link_args(self): return ['-shared', '-defaultlib=libphobos2.so'] @classmethod def unix_args_to_native(cls, args): return cls.translate_args_to_nongnu(args)
{ "content_hash": "5319137ac07c6db2f8c7607f3e0310b5", "timestamp": "", "source": "github", "line_count": 380, "max_line_length": 138, "avg_line_length": 36.86842105263158, "alnum_prop": 0.5651677373304782, "repo_name": "thiblahute/meson", "id": "f0f3d54b0101c4769d318ec01b6d016562b03da2", "size": "14603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mesonbuild/compilers/d.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4190" }, { "name": "Batchfile", "bytes": "868" }, { "name": "C", "bytes": "142464" }, { "name": "C#", "bytes": "949" }, { "name": "C++", "bytes": "26871" }, { "name": "CMake", "bytes": "1780" }, { "name": "D", "bytes": "4111" }, { "name": "Dockerfile", "bytes": "694" }, { "name": "Emacs Lisp", "bytes": "919" }, { "name": "Fortran", "bytes": "4590" }, { "name": "Genie", "bytes": "341" }, { "name": "Inno Setup", "bytes": "372" }, { "name": "Java", "bytes": "2125" }, { "name": "JavaScript", "bytes": "136" }, { "name": "LLVM", "bytes": "75" }, { "name": "Lex", "bytes": "135" }, { "name": "Meson", "bytes": "316300" }, { "name": "Objective-C", "bytes": "1092" }, { "name": "Objective-C++", "bytes": "332" }, { "name": "Python", "bytes": "1817555" }, { "name": "Roff", "bytes": "301" }, { "name": "Rust", "bytes": "1079" }, { "name": "Shell", "bytes": "2083" }, { "name": "Swift", "bytes": "1152" }, { "name": "Vala", "bytes": "10025" }, { "name": "Verilog", "bytes": "709" }, { "name": "Vim script", "bytes": "9480" }, { "name": "Yacc", "bytes": "50" } ], "symlink_target": "" }
@interface EXScopedNotificationSchedulerModule () @property (nonatomic, strong) NSString *scopeKey; @end @implementation EXScopedNotificationSchedulerModule - (instancetype)initWithScopeKey:(NSString *)scopeKey { if (self = [super init]) { _scopeKey = scopeKey; } return self; } - (UNNotificationRequest *)buildNotificationRequestWithIdentifier:(NSString *)identifier content:(NSDictionary *)contentInput trigger:(NSDictionary *)triggerInput { NSString *scopedIdentifier = [EXScopedNotificationsUtils scopedIdentifierFromId:identifier forExperience:_scopeKey]; return [super buildNotificationRequestWithIdentifier:scopedIdentifier content:contentInput trigger:triggerInput]; } - (NSArray * _Nonnull)serializeNotificationRequests:(NSArray<UNNotificationRequest *> * _Nonnull) requests; { NSMutableArray *serializedRequests = [NSMutableArray new]; for (UNNotificationRequest *request in requests) { if ([EXScopedNotificationsUtils isId:request.identifier scopedByExperience:_scopeKey]) { [serializedRequests addObject:[EXScopedNotificationSerializer serializedNotificationRequest:request]]; } } return serializedRequests; } - (void)cancelNotification:(NSString *)identifier resolve:(EXPromiseResolveBlock)resolve rejecting:(EXPromiseRejectBlock)reject { NSString *scopedIdentifier = [EXScopedNotificationsUtils scopedIdentifierFromId:identifier forExperience:_scopeKey]; [super cancelNotification:scopedIdentifier resolve:resolve rejecting:reject]; } - (void)cancelAllNotificationsWithResolver:(EXPromiseResolveBlock)resolve rejecting:(EXPromiseRejectBlock)reject { __block NSString *scopeKey = _scopeKey; [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) { NSMutableArray<NSString *> *toRemove = [NSMutableArray new]; for (UNNotificationRequest *request in requests) { if ([EXScopedNotificationsUtils isId:request.identifier scopedByExperience:scopeKey]) { [toRemove addObject:request.identifier]; } } [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:toRemove]; resolve(nil); }]; } @end
{ "content_hash": "36d77c0ace4a086051b6f4e39abcd736", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 165, "avg_line_length": 41, "alnum_prop": 0.7205117952818872, "repo_name": "exponent/exponent", "id": "ef90971aa30b761d87eb64b27e5ca8063a23d2b3", "size": "2735", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ios/Exponent/Versioned/Core/UniversalModules/EXNotifications/EXScopedNotificationSchedulerModule.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "113276" }, { "name": "Batchfile", "bytes": "127" }, { "name": "C", "bytes": "1744836" }, { "name": "C++", "bytes": "1801159" }, { "name": "CSS", "bytes": "7854" }, { "name": "HTML", "bytes": "176329" }, { "name": "IDL", "bytes": "897" }, { "name": "Java", "bytes": "6251130" }, { "name": "JavaScript", "bytes": "4416558" }, { "name": "Makefile", "bytes": "18061" }, { "name": "Objective-C", "bytes": "13971362" }, { "name": "Objective-C++", "bytes": "725480" }, { "name": "Perl", "bytes": "5860" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "125673" }, { "name": "Ruby", "bytes": "61190" }, { "name": "Shell", "bytes": "4441" } ], "symlink_target": "" }
// Copyright 2015 The Bazel Authors. All rights reserved. // // 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.devtools.build.android; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.hash.Hashing; import com.google.devtools.build.android.AndroidResourceProcessor.AaptConfigOptions; import com.google.devtools.build.android.AndroidResourceProcessor.FlagAaptOptions; import com.google.devtools.build.android.Converters.DependencyAndroidDataListConverter; import com.google.devtools.build.android.Converters.PathConverter; import com.google.devtools.build.android.Converters.UnvalidatedAndroidDataConverter; import com.google.devtools.build.android.Converters.VariantConfigurationTypeConverter; import com.google.devtools.build.android.SplitConfigurationFilter.UnrecognizedSplitsException; import com.google.devtools.common.options.Converters.CommaSeparatedOptionListConverter; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionsBase; import com.google.devtools.common.options.OptionsParser; import com.google.devtools.common.options.TriState; import com.android.builder.core.VariantConfiguration; import com.android.builder.core.VariantConfiguration.Type; import com.android.ide.common.internal.AaptCruncher; import com.android.ide.common.internal.CommandLineRunner; import com.android.ide.common.internal.LoggedErrorException; import com.android.ide.common.internal.PngCruncher; import com.android.ide.common.res2.MergingException; import com.android.utils.StdLogger; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Provides an entry point for the resource processing using the AOSP build tools. * * <pre> * Example Usage: * java/com/google/build/android/AndroidResourceProcessingAction\ * --sdkRoot path/to/sdk\ * --aapt path/to/sdk/aapt\ * --annotationJar path/to/sdk/annotationJar\ * --adb path/to/sdk/adb\ * --zipAlign path/to/sdk/zipAlign\ * --androidJar path/to/sdk/androidJar\ * --manifest path/to/manifest\ * --primaryData path/to/resources:path/to/assets:path/to/manifest:path/to/R.txt * --data p/t/res1:p/t/assets1:p/t/1/AndroidManifest.xml:p/t/1/R.txt,\ * p/t/res2:p/t/assets2:p/t/2/AndroidManifest.xml:p/t/2/R.txt * --packagePath path/to/write/archive.ap_ * --srcJarOutput path/to/write/archive.srcjar * </pre> */ public class AndroidResourceProcessingAction { private static final StdLogger STD_LOGGER = new StdLogger(com.android.utils.StdLogger.Level.WARNING); private static final Logger LOGGER = Logger.getLogger(AndroidResourceProcessingAction.class.getName()); /** Flag specifications for this action. */ public static final class Options extends OptionsBase { @Option(name = "primaryData", defaultValue = "null", converter = UnvalidatedAndroidDataConverter.class, category = "input", help = "The directory containing the primary resource directory. The contents will override" + " the contents of any other resource directories during merging. The expected format" + " is resources[|resources]:assets[|assets]:manifest") public UnvalidatedAndroidData primaryData; @Option(name = "data", defaultValue = "", converter = DependencyAndroidDataListConverter.class, category = "input", help = "Transitive Data dependencies. These values will be used if not defined in the " + "primary resources. The expected format is " + "resources[#resources]:assets[#assets]:manifest:r.txt:symbols.bin" + "[,resources[#resources]:assets[#assets]:manifest:r.txt:symbols.bin]") public List<DependencyAndroidData> transitiveData; @Option(name = "directData", defaultValue = "", converter = DependencyAndroidDataListConverter.class, category = "input", help = "Direct Data dependencies. These values will be used if not defined in the " + "primary resources. The expected format is " + "resources[#resources]:assets[#assets]:manifest:r.txt:symbols.bin" + "[,resources[#resources]:assets[#assets]:manifest:r.txt:symbols.bin]") public List<DependencyAndroidData> directData; @Option(name = "rOutput", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path to where the R.txt should be written.") public Path rOutput; @Option(name = "symbolsTxtOut", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path to where the symbolsTxt should be written.") public Path symbolsTxtOut; @Option(name = "packagePath", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path to the write the archive.") public Path packagePath; @Option(name = "resourcesOutput", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path to the write merged resources archive.") public Path resourcesOutput; @Option(name = "proguardOutput", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path for the proguard file.") public Path proguardOutput; @Option(name = "mainDexProguardOutput", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path for the main dex proguard file.") public Path mainDexProguardOutput; @Option(name = "manifestOutput", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path for the modified manifest.") public Path manifestOutput; @Option(name = "srcJarOutput", defaultValue = "null", converter = PathConverter.class, category = "output", help = "Path for the generated java source jar.") public Path srcJarOutput; @Option(name = "packageType", defaultValue = "DEFAULT", converter = VariantConfigurationTypeConverter.class, category = "config", help = "Variant configuration type for packaging the resources." + " Acceptible values DEFAULT, LIBRARY, TEST") public VariantConfiguration.Type packageType; @Option(name = "densities", defaultValue = "", converter = CommaSeparatedOptionListConverter.class, category = "config", help = "A list of densities to filter the resource drawables by.") public List<String> densities; @Option(name = "packageForR", defaultValue = "null", category = "config", help = "Custom java package to generate the R symbols files.") public String packageForR; @Option(name = "applicationId", defaultValue = "null", category = "config", help = "Custom application id (package manifest) for the packaged manifest.") public String applicationId; @Option(name = "versionName", defaultValue = "null", category = "config", help = "Version name to stamp into the packaged manifest.") public String versionName; @Option(name = "versionCode", defaultValue = "-1", category = "config", help = "Version code to stamp into the packaged manifest.") public int versionCode; } private static AaptConfigOptions aaptConfigOptions; private static Options options; public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser( Options.class, AaptConfigOptions.class); optionsParser.parseAndExitUponError(args); aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class); options = optionsParser.getOptions(Options.class); FileSystem fileSystem = FileSystems.getDefault(); Path working = fileSystem.getPath("").toAbsolutePath(); final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(STD_LOGGER); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resources_tmp")) { final Path tmp = scopedTmp.getPath(); final Path expandedOut = tmp.resolve("tmp-expanded"); final Path deduplicatedOut = tmp.resolve("tmp-deduplicated"); final Path mergedAssets = tmp.resolve("merged_assets"); final Path mergedResources = tmp.resolve("merged_resources"); final Path filteredResources = tmp.resolve("resources-filtered"); final Path densityManifest = tmp.resolve("manifest-filtered/AndroidManifest.xml"); final Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml"); final Path dummyManifest = tmp.resolve("manifest-aapt-dummy/AndroidManifest.xml"); Path generatedSources = null; if (options.srcJarOutput != null || options.rOutput != null || options.symbolsTxtOut != null) { generatedSources = tmp.resolve("generated_resources"); } LOGGER.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); final ImmutableList<DirectoryModifier> modifiers = ImmutableList.of( new PackedResourceTarExpander(expandedOut, working), new FileDeDuplicator(Hashing.murmur3_128(), deduplicatedOut, working)); // Resources can appear in both the direct dependencies and transitive -- use a set to // ensure depeduplication. List<DependencyAndroidData> data = ImmutableSet.<DependencyAndroidData>builder() .addAll(options.directData) .addAll(options.transitiveData) .build() .asList(); final MergedAndroidData mergedData = resourceProcessor.mergeData( options.primaryData, data, mergedResources, mergedAssets, modifiers, selectPngCruncher(), true); LOGGER.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); final DensityFilteredAndroidData filteredData = mergedData.filter( new DensitySpecificResourceFilter(options.densities, filteredResources, mergedResources), new DensitySpecificManifestProcessor(options.densities, densityManifest)); LOGGER.fine(String.format("Density filtering finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); MergedAndroidData processedData = resourceProcessor.processManifest( options.packageType, options.packageForR, options.applicationId, options.versionCode, options.versionName, filteredData, processedManifest); // Write manifestOutput now before the dummy manifest is created. if (options.manifestOutput != null) { resourceProcessor.copyManifestToOutput(processedData, options.manifestOutput); } if (options.packageType == Type.LIBRARY) { Files.createDirectories(dummyManifest.getParent()); Files.write(dummyManifest, String.format( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"" + " package=\"%s\">" + "</manifest>", options.packageForR).getBytes(UTF_8)); processedData = new MergedAndroidData( processedData.getResourceDir(), processedData.getAssetDir(), dummyManifest); } resourceProcessor.processResources( aaptConfigOptions.aapt, aaptConfigOptions.androidJar, aaptConfigOptions.buildToolsVersion, options.packageType, aaptConfigOptions.debug, options.packageForR, new FlagAaptOptions(aaptConfigOptions), aaptConfigOptions.resourceConfigs, aaptConfigOptions.splits, processedData, data, generatedSources, options.packagePath, options.proguardOutput, options.mainDexProguardOutput, options.resourcesOutput != null ? processedData.getResourceDir().resolve("values").resolve("public.xml") : null); LOGGER.fine(String.format("aapt finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); if (options.srcJarOutput != null) { resourceProcessor.createSrcJar(generatedSources, options.srcJarOutput, VariantConfiguration.Type.LIBRARY == options.packageType); } if (options.rOutput != null) { resourceProcessor.copyRToOutput(generatedSources, options.rOutput, VariantConfiguration.Type.LIBRARY == options.packageType); } if (options.symbolsTxtOut != null) { resourceProcessor.copyRToOutput(generatedSources, options.symbolsTxtOut, VariantConfiguration.Type.LIBRARY == options.packageType); } if (options.resourcesOutput != null) { resourceProcessor.createResourcesZip(processedData.getResourceDir(), processedData.getAssetDir(), options.resourcesOutput); } LOGGER.fine(String.format("Packaging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } catch (MergingException e) { LOGGER.log(java.util.logging.Level.SEVERE, "Error during merging resources", e); throw e; } catch (IOException | InterruptedException | LoggedErrorException | UnrecognizedSplitsException e) { LOGGER.log(java.util.logging.Level.SEVERE, "Error during processing resources", e); throw e; } catch (Exception e) { LOGGER.log(java.util.logging.Level.SEVERE, "Unexpected", e); throw e; } finally { resourceProcessor.shutdown(); } LOGGER.fine(String.format("Resources processed in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } private static boolean usePngCruncher() { // If the value was set, use that. if (aaptConfigOptions.useAaptCruncher != TriState.AUTO) { return aaptConfigOptions.useAaptCruncher == TriState.YES; } // By default png cruncher shouldn't be invoked on a library -- the work is just thrown away. return options.packageType != VariantConfiguration.Type.LIBRARY; } private static PngCruncher selectPngCruncher() { // Use the full cruncher if asked to do so. if (usePngCruncher()) { return new AaptCruncher(aaptConfigOptions.aapt.toString(), new CommandLineRunner(STD_LOGGER)); } // Otherwise, if this is a binary, we need to at least process nine-patch PNGs. if (options.packageType != VariantConfiguration.Type.LIBRARY) { return new NinePatchOnlyCruncher( aaptConfigOptions.aapt.toString(), new CommandLineRunner(STD_LOGGER)); } return null; } }
{ "content_hash": "14c26697d2f23e4f43357175b3d4b1c8", "timestamp": "", "source": "github", "line_count": 380, "max_line_length": 100, "avg_line_length": 41.57105263157895, "alnum_prop": 0.6906374628093942, "repo_name": "abergmeier-dsfishlabs/bazel", "id": "17c4822cbebc414ae17def05b1e5dfd819f425c0", "size": "15797", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessingAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "78" }, { "name": "C", "bytes": "49306" }, { "name": "C++", "bytes": "358480" }, { "name": "HTML", "bytes": "17135" }, { "name": "Java", "bytes": "17824773" }, { "name": "Objective-C", "bytes": "6820" }, { "name": "Protocol Buffer", "bytes": "94374" }, { "name": "Python", "bytes": "237314" }, { "name": "Shell", "bytes": "491747" } ], "symlink_target": "" }
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var setTag = function(tag) { return tag.toLowerCase().trim(); }; var TagSchema = new Schema({ tag: { type: String, set: setTag, default: '' }, app_name: { type: String, default: '' } }); TagSchema.statics = { list: function(tagName, cb) { this.find({tag: tagName}).exec(cb); }, search: function(string, cb) { var regex = new RegExp(string, "i"); this.distinct('tag', { 'tag': regex }).exec(cb); } }; var tag = mongoose.model("Tag", TagSchema); module.exports = { Tag: tag };
{ "content_hash": "252ec9d8c5f5920b719946a825c97b56", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 52, "avg_line_length": 21.25925925925926, "alnum_prop": 0.6149825783972126, "repo_name": "pennlabs/MadeAtPenn", "id": "ad2af557a17f861e5769e292f63abf28bcf4390c", "size": "574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/tag.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "8512" }, { "name": "HTML", "bytes": "38260" }, { "name": "JavaScript", "bytes": "13907" } ], "symlink_target": "" }
FOUNDATION_EXPORT double UIColor_Hex_SwiftVersionNumber; FOUNDATION_EXPORT const unsigned char UIColor_Hex_SwiftVersionString[];
{ "content_hash": "bbe2f7d3c55974dfc7568ffcf988adef", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 71, "avg_line_length": 43.333333333333336, "alnum_prop": 0.8538461538461538, "repo_name": "niunaruto/DeDaoAppSwift", "id": "902388fc0dd38366419f69cfb60ebf14ff95702a", "size": "200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DeDaoSwift/Pods/Target Support Files/UIColor_Hex_Swift/UIColor_Hex_Swift-umbrella.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "362" }, { "name": "Ruby", "bytes": "2376" }, { "name": "Swift", "bytes": "109918" } ], "symlink_target": "" }
<?php /** * @namespace */ namespace Zend\Dojo\View\Helper; /** * Dojo TextBox dijit * * @uses \Zend\Dojo\View\Helper\Dijit * @package Zend_Dojo * @subpackage View * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class TextBox extends Dijit { /** * Dijit being used * @var string */ protected $_dijit = 'dijit.form.TextBox'; /** * HTML element type * @var string */ protected $_elementType = 'text'; /** * Dojo module to use * @var string */ protected $_module = 'dijit.form.TextBox'; /** * dijit.form.TextBox * * @param int $id * @param mixed $value * @param array $params Parameters to use for dijit creation * @param array $attribs HTML attributes * @return string */ public function direct($id = null, $value = null, array $params = array(), array $attribs = array()) { return $this->_createFormElement($id, $value, $params, $attribs); } }
{ "content_hash": "efdd4fa51dba57503e5ce2435136fef7", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 104, "avg_line_length": 22.058823529411764, "alnum_prop": 0.5804444444444444, "repo_name": "triggertoo/whatsup", "id": "51d82a8f9e56c9edf6af1f74ac62b809e61cd7e3", "size": "1815", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/vendor/zend/library/Zend/Dojo/View/Helper/TextBox.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
function[interval, start]=SONGetSampleInterval(fid,chan) % SONGETSAMPLEINTERVAL returns the sampling interval in microseconds % on a waveform data channel in a SON file, i.e. the reciprocal of the % sampling rate for the channel, together with the time of the first sample % % [INTERVAL{, START}]=SONGETSAMPLEINTERVAL(FID, CHAN) % FID is the matlab file handle and CHAN is the channel number (1-max) % The sampling INTERVAL and, if requested START time for the data are % returned in seconds. % % Note that, as of Version 2.2, the returned times are always in microseconds. % Uncomment the last line for backwards compatibility % % Malcolm Lidierth 02/02 % Updated 09/06 ML % Copyright © The Author & King's College London 2002-2006 FileH=SONFileHeader(fid); % File header Info=SONChannelInfo(fid,chan); % Channel header header=SONGetBlockHeaders(fid,chan); switch Info.kind % Disk block headers case {1,6,7,9} switch FileH.systemID case {1,2,3,4,5} % Before version 6 if (isfield(Info,'divide')) interval=Info.divide*FileH.usPerTime*FileH.timePerADC; start=header(2,1)*FileH.usPerTime*FileH.timePerADC; else warning('SONGetSampleInterval: ldivide not defined Channel #%d', chan); interval=[]; start=[]; end; otherwise % Version 6 and above interval=Info.lChanDvd*FileH.usPerTime*(1e6*FileH.dTimeBase); start=header(2,1)*FileH.usPerTime*FileH.dTimeBase; end; otherwise warning('SONGetSampleInterval: Invalid channel type Channel #%d',chan); interval=[]; start=[]; return; end; % UNCOMMENT THE LINE BELOW FOR COMPATIBILITY WITH V2.1 AND BELOW %interval=interval*1e-6;
{ "content_hash": "02d06098d3f37390c373a42799f4e73d", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 97, "avg_line_length": 44.38297872340426, "alnum_prop": 0.5795781399808245, "repo_name": "hpay/eyetrack", "id": "6b81fc3d8ac1698b9de08f63710b788e12dfaeef", "size": "2086", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "functions/analyze_calibration/dat/smr-import/son/SONGetSampleInterval.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9215" }, { "name": "M", "bytes": "16789" }, { "name": "Matlab", "bytes": "442158" } ], "symlink_target": "" }
module.exports = { path: 'panel', childRoutes: [], getComponents (nextState, callback) { require.ensure([], () => { callback(null, require('./index')) }) } }
{ "content_hash": "e0eb352c598d130deb6205ce7779a375", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 40, "avg_line_length": 20, "alnum_prop": 0.5555555555555556, "repo_name": "hrSoft-FE/mobile-vote", "id": "4838a0eb3a6135303bcb4ad3be355c44d2690af5", "size": "180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/routes/user/profile/panel/route.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "658444" }, { "name": "HTML", "bytes": "490734" }, { "name": "JavaScript", "bytes": "861142" } ], "symlink_target": "" }
using std::ifstream; using std::ofstream; using std::string; class coreutils { public: string inputFile; string outputFile; inline string openFile(); void makeJSON(); inline string generateErrorMessage(string originText); inline string getLink(string originLine); inline string getMarkName(string originLine); inline string getFolderName(string originLine); void closeFile(); inline string outputTab(int tabCount); private: ifstream reader; ofstream writer; };
{ "content_hash": "969ad7a5610da5ad9ce1d33ed4f7bf86", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 55, "avg_line_length": 23.65, "alnum_prop": 0.7864693446088795, "repo_name": "gordon-zhao/Chrome_bookmarks_to_json", "id": "961f7e57cdfd5ee19cae15e1409cc06e4200891a", "size": "522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cpp/core.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "6048" }, { "name": "Python", "bytes": "4599" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- *** GENERATED FROM project.xml - DO NOT EDIT *** *** EDIT ../build.xml INSTEAD *** For the purpose of easier reading the script is divided into following sections: - initialization - compilation - jar - execution - debugging - javadoc - test compilation - test execution - test debugging - applet - cleanup --> <project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="Diffie-impl"> <fail message="Please build using Ant 1.8.0 or higher."> <condition> <not> <antversion atleast="1.8.0"/> </not> </condition> </fail> <target depends="test,jar,javadoc" description="Build and test whole project." name="default"/> <!-- ====================== INITIALIZATION SECTION ====================== --> <target name="-pre-init"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="-pre-init" name="-init-private"> <property file="nbproject/private/config.properties"/> <property file="nbproject/private/configs/${config}.properties"/> <property file="nbproject/private/private.properties"/> </target> <target depends="-pre-init,-init-private" name="-init-user"> <property file="${user.properties.file}"/> <!-- The two properties below are usually overridden --> <!-- by the active platform. Just a fallback. --> <property name="default.javac.source" value="1.4"/> <property name="default.javac.target" value="1.4"/> </target> <target depends="-pre-init,-init-private,-init-user" name="-init-project"> <property file="nbproject/configs/${config}.properties"/> <property file="nbproject/project.properties"/> </target> <target depends="-pre-init,-init-private,-init-user,-init-project,-init-macrodef-property" name="-do-init"> <property name="platform.java" value="${java.home}/bin/java"/> <available file="${manifest.file}" property="manifest.available"/> <condition property="splashscreen.available"> <and> <not> <equals arg1="${application.splash}" arg2="" trim="true"/> </not> <available file="${application.splash}"/> </and> </condition> <condition property="main.class.available"> <and> <isset property="main.class"/> <not> <equals arg1="${main.class}" arg2="" trim="true"/> </not> </and> </condition> <condition property="profile.available"> <and> <isset property="javac.profile"/> <length length="0" string="${javac.profile}" when="greater"/> <matches pattern="1\.[89](\..*)?" string="${javac.source}"/> </and> </condition> <condition property="do.archive"> <or> <not> <istrue value="${jar.archive.disabled}"/> </not> <istrue value="${not.archive.disabled}"/> </or> </condition> <condition property="do.mkdist"> <and> <isset property="do.archive"/> <isset property="libs.CopyLibs.classpath"/> <not> <istrue value="${mkdist.disabled}"/> </not> </and> </condition> <condition property="do.archive+manifest.available"> <and> <isset property="manifest.available"/> <istrue value="${do.archive}"/> </and> </condition> <condition property="do.archive+main.class.available"> <and> <isset property="main.class.available"/> <istrue value="${do.archive}"/> </and> </condition> <condition property="do.archive+splashscreen.available"> <and> <isset property="splashscreen.available"/> <istrue value="${do.archive}"/> </and> </condition> <condition property="do.archive+profile.available"> <and> <isset property="profile.available"/> <istrue value="${do.archive}"/> </and> </condition> <condition property="have.tests"> <or> <available file="${test.src.dir}"/> </or> </condition> <condition property="have.sources"> <or> <available file="${src.dir}"/> </or> </condition> <condition property="netbeans.home+have.tests"> <and> <isset property="netbeans.home"/> <isset property="have.tests"/> </and> </condition> <condition property="no.javadoc.preview"> <and> <isset property="javadoc.preview"/> <isfalse value="${javadoc.preview}"/> </and> </condition> <property name="run.jvmargs" value=""/> <property name="run.jvmargs.ide" value=""/> <property name="javac.compilerargs" value=""/> <property name="work.dir" value="${basedir}"/> <condition property="no.deps"> <and> <istrue value="${no.dependencies}"/> </and> </condition> <property name="javac.debug" value="true"/> <property name="javadoc.preview" value="true"/> <property name="application.args" value=""/> <property name="source.encoding" value="${file.encoding}"/> <property name="runtime.encoding" value="${source.encoding}"/> <condition property="javadoc.encoding.used" value="${javadoc.encoding}"> <and> <isset property="javadoc.encoding"/> <not> <equals arg1="${javadoc.encoding}" arg2=""/> </not> </and> </condition> <property name="javadoc.encoding.used" value="${source.encoding}"/> <property name="includes" value="**"/> <property name="excludes" value=""/> <property name="do.depend" value="false"/> <condition property="do.depend.true"> <istrue value="${do.depend}"/> </condition> <path id="endorsed.classpath.path" path="${endorsed.classpath}"/> <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'"> <and> <isset property="endorsed.classpath"/> <not> <equals arg1="${endorsed.classpath}" arg2="" trim="true"/> </not> </and> </condition> <condition else="" property="javac.profile.cmd.line.arg" value="-profile ${javac.profile}"> <isset property="profile.available"/> </condition> <condition else="false" property="jdkBug6558476"> <and> <matches pattern="1\.[56]" string="${java.specification.version}"/> <not> <os family="unix"/> </not> </and> </condition> <condition else="false" property="javac.fork"> <or> <istrue value="${jdkBug6558476}"/> <istrue value="${javac.external.vm}"/> </or> </condition> <property name="jar.index" value="false"/> <property name="jar.index.metainf" value="${jar.index}"/> <property name="copylibs.rebase" value="true"/> <available file="${meta.inf.dir}/persistence.xml" property="has.persistence.xml"/> <condition property="junit.available"> <or> <available classname="org.junit.Test" classpath="${run.test.classpath}"/> <available classname="junit.framework.Test" classpath="${run.test.classpath}"/> </or> </condition> <condition property="testng.available"> <available classname="org.testng.annotations.Test" classpath="${run.test.classpath}"/> </condition> <condition property="junit+testng.available"> <and> <istrue value="${junit.available}"/> <istrue value="${testng.available}"/> </and> </condition> <condition else="testng" property="testng.mode" value="mixed"> <istrue value="${junit+testng.available}"/> </condition> <condition else="" property="testng.debug.mode" value="-mixed"> <istrue value="${junit+testng.available}"/> </condition> <property name="java.failonerror" value="true"/> </target> <target name="-post-init"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init" name="-init-check"> <fail unless="src.dir">Must set src.dir</fail> <fail unless="test.src.dir">Must set test.src.dir</fail> <fail unless="build.dir">Must set build.dir</fail> <fail unless="dist.dir">Must set dist.dir</fail> <fail unless="build.classes.dir">Must set build.classes.dir</fail> <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail> <fail unless="build.test.classes.dir">Must set build.test.classes.dir</fail> <fail unless="build.test.results.dir">Must set build.test.results.dir</fail> <fail unless="build.classes.excludes">Must set build.classes.excludes</fail> <fail unless="dist.jar">Must set dist.jar</fail> </target> <target name="-init-macrodef-property"> <macrodef name="property" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute name="name"/> <attribute name="value"/> <sequential> <property name="@{name}" value="${@{value}}"/> </sequential> </macrodef> </target> <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-macrodef-javac-with-processors"> <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${src.dir}" name="srcdir"/> <attribute default="${build.classes.dir}" name="destdir"/> <attribute default="${javac.classpath}" name="classpath"/> <attribute default="${javac.processorpath}" name="processorpath"/> <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="${javac.debug}" name="debug"/> <attribute default="${empty.dir}" name="sourcepath"/> <attribute default="${empty.dir}" name="gensrcdir"/> <element name="customize" optional="true"/> <sequential> <property location="${build.dir}/empty" name="empty.dir"/> <mkdir dir="${empty.dir}"/> <mkdir dir="@{apgeneratedsrcdir}"/> <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> <src> <dirset dir="@{gensrcdir}" erroronmissingdir="false"> <include name="*"/> </dirset> </src> <classpath> <path path="@{classpath}"/> </classpath> <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> <compilerarg line="${javac.profile.cmd.line.arg}"/> <compilerarg line="${javac.compilerargs}"/> <compilerarg value="-processorpath"/> <compilerarg path="@{processorpath}:${empty.dir}"/> <compilerarg line="${ap.processors.internal}"/> <compilerarg line="${annotation.processing.processor.options}"/> <compilerarg value="-s"/> <compilerarg path="@{apgeneratedsrcdir}"/> <compilerarg line="${ap.proc.none.internal}"/> <customize/> </javac> </sequential> </macrodef> </target> <target depends="-init-ap-cmdline-properties" name="-init-macrodef-javac-without-processors" unless="ap.supported.internal"> <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${src.dir}" name="srcdir"/> <attribute default="${build.classes.dir}" name="destdir"/> <attribute default="${javac.classpath}" name="classpath"/> <attribute default="${javac.processorpath}" name="processorpath"/> <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="${javac.debug}" name="debug"/> <attribute default="${empty.dir}" name="sourcepath"/> <attribute default="${empty.dir}" name="gensrcdir"/> <element name="customize" optional="true"/> <sequential> <property location="${build.dir}/empty" name="empty.dir"/> <mkdir dir="${empty.dir}"/> <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> <src> <dirset dir="@{gensrcdir}" erroronmissingdir="false"> <include name="*"/> </dirset> </src> <classpath> <path path="@{classpath}"/> </classpath> <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> <compilerarg line="${javac.profile.cmd.line.arg}"/> <compilerarg line="${javac.compilerargs}"/> <customize/> </javac> </sequential> </macrodef> </target> <target depends="-init-macrodef-javac-with-processors,-init-macrodef-javac-without-processors" name="-init-macrodef-javac"> <macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${src.dir}" name="srcdir"/> <attribute default="${build.classes.dir}" name="destdir"/> <attribute default="${javac.classpath}" name="classpath"/> <sequential> <depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}"> <classpath> <path path="@{classpath}"/> </classpath> </depend> </sequential> </macrodef> <macrodef name="force-recompile" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${build.classes.dir}" name="destdir"/> <sequential> <fail unless="javac.includes">Must set javac.includes</fail> <pathconvert pathsep="${line.separator}" property="javac.includes.binary"> <path> <filelist dir="@{destdir}" files="${javac.includes}"/> </path> <globmapper from="*.java" to="*.class"/> </pathconvert> <tempfile deleteonexit="true" property="javac.includesfile.binary"/> <echo file="${javac.includesfile.binary}" message="${javac.includes.binary}"/> <delete> <files includesfile="${javac.includesfile.binary}"/> </delete> <delete> <fileset file="${javac.includesfile.binary}"/> </delete> </sequential> </macrodef> </target> <target if="${junit.available}" name="-init-macrodef-junit-init"> <condition else="false" property="nb.junit.batch" value="true"> <and> <istrue value="${junit.available}"/> <not> <isset property="test.method"/> </not> </and> </condition> <condition else="false" property="nb.junit.single" value="true"> <and> <istrue value="${junit.available}"/> <isset property="test.method"/> </and> </condition> </target> <target name="-init-test-properties"> <property name="test.binaryincludes" value="&lt;nothing&gt;"/> <property name="test.binarytestincludes" value=""/> <property name="test.binaryexcludes" value=""/> </target> <target if="${nb.junit.single}" name="-init-macrodef-junit-single" unless="${nb.junit.batch}"> <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element name="customize" optional="true"/> <sequential> <property name="junit.forkmode" value="perTest"/> <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> <test methods="@{testmethods}" name="@{testincludes}" todir="${build.test.results.dir}"/> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> <formatter type="brief" usefile="false"/> <formatter type="xml"/> <jvmarg value="-ea"/> <customize/> </junit> </sequential> </macrodef> </target> <target depends="-init-test-properties" if="${nb.junit.batch}" name="-init-macrodef-junit-batch" unless="${nb.junit.single}"> <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element name="customize" optional="true"/> <sequential> <property name="junit.forkmode" value="perTest"/> <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> <batchtest todir="${build.test.results.dir}"> <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> <filename name="@{testincludes}"/> </fileset> <fileset dir="${build.test.classes.dir}" excludes="@{excludes},${excludes},${test.binaryexcludes}" includes="${test.binaryincludes}"> <filename name="${test.binarytestincludes}"/> </fileset> </batchtest> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> <formatter type="brief" usefile="false"/> <formatter type="xml"/> <jvmarg value="-ea"/> <customize/> </junit> </sequential> </macrodef> </target> <target depends="-init-macrodef-junit-init,-init-macrodef-junit-single, -init-macrodef-junit-batch" if="${junit.available}" name="-init-macrodef-junit"/> <target if="${testng.available}" name="-init-macrodef-testng"> <macrodef name="testng" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element name="customize" optional="true"/> <sequential> <condition else="" property="testng.methods.arg" value="@{testincludes}.@{testmethods}"> <isset property="test.method"/> </condition> <union id="test.set"> <fileset dir="${test.src.dir}" excludes="@{excludes},**/*.xml,${excludes}" includes="@{includes}"> <filename name="@{testincludes}"/> </fileset> </union> <taskdef classname="org.testng.TestNGAntTask" classpath="${run.test.classpath}" name="testng"/> <testng classfilesetref="test.set" failureProperty="tests.failed" listeners="org.testng.reporters.VerboseReporter" methods="${testng.methods.arg}" mode="${testng.mode}" outputdir="${build.test.results.dir}" suitename="Diffie" testname="TestNG tests" workingDir="${work.dir}"> <xmlfileset dir="${build.test.classes.dir}" includes="@{testincludes}"/> <propertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </propertyset> <customize/> </testng> </sequential> </macrodef> </target> <target name="-init-macrodef-test-impl"> <macrodef name="test-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element implicit="true" name="customize" optional="true"/> <sequential> <echo>No tests executed.</echo> </sequential> </macrodef> </target> <target depends="-init-macrodef-junit" if="${junit.available}" name="-init-macrodef-junit-impl"> <macrodef name="test-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element implicit="true" name="customize" optional="true"/> <sequential> <j2seproject3:junit excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> <customize/> </j2seproject3:junit> </sequential> </macrodef> </target> <target depends="-init-macrodef-testng" if="${testng.available}" name="-init-macrodef-testng-impl"> <macrodef name="test-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element implicit="true" name="customize" optional="true"/> <sequential> <j2seproject3:testng excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> <customize/> </j2seproject3:testng> </sequential> </macrodef> </target> <target depends="-init-macrodef-test-impl,-init-macrodef-junit-impl,-init-macrodef-testng-impl" name="-init-macrodef-test"> <macrodef name="test" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <sequential> <j2seproject3:test-impl excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> <customize> <classpath> <path path="${run.test.classpath}"/> </classpath> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg line="${run.jvmargs}"/> <jvmarg line="${run.jvmargs.ide}"/> </customize> </j2seproject3:test-impl> </sequential> </macrodef> </target> <target if="${junit.available}" name="-init-macrodef-junit-debug" unless="${nb.junit.batch}"> <macrodef name="junit-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element name="customize" optional="true"/> <sequential> <property name="junit.forkmode" value="perTest"/> <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> <test methods="@{testmethods}" name="@{testincludes}" todir="${build.test.results.dir}"/> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> <formatter type="brief" usefile="false"/> <formatter type="xml"/> <jvmarg value="-ea"/> <jvmarg line="${debug-args-line}"/> <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> <customize/> </junit> </sequential> </macrodef> </target> <target depends="-init-test-properties" if="${nb.junit.batch}" name="-init-macrodef-junit-debug-batch"> <macrodef name="junit-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element name="customize" optional="true"/> <sequential> <property name="junit.forkmode" value="perTest"/> <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> <batchtest todir="${build.test.results.dir}"> <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> <filename name="@{testincludes}"/> </fileset> <fileset dir="${build.test.classes.dir}" excludes="@{excludes},${excludes},${test.binaryexcludes}" includes="${test.binaryincludes}"> <filename name="${test.binarytestincludes}"/> </fileset> </batchtest> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> <formatter type="brief" usefile="false"/> <formatter type="xml"/> <jvmarg value="-ea"/> <jvmarg line="${debug-args-line}"/> <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> <customize/> </junit> </sequential> </macrodef> </target> <target depends="-init-macrodef-junit-debug,-init-macrodef-junit-debug-batch" if="${junit.available}" name="-init-macrodef-junit-debug-impl"> <macrodef name="test-debug-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <element implicit="true" name="customize" optional="true"/> <sequential> <j2seproject3:junit-debug excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> <customize/> </j2seproject3:junit-debug> </sequential> </macrodef> </target> <target if="${testng.available}" name="-init-macrodef-testng-debug"> <macrodef name="testng-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${main.class}" name="testClass"/> <attribute default="" name="testMethod"/> <element name="customize2" optional="true"/> <sequential> <condition else="-testclass @{testClass}" property="test.class.or.method" value="-methods @{testClass}.@{testMethod}"> <isset property="test.method"/> </condition> <condition else="-suitename Diffie -testname @{testClass} ${test.class.or.method}" property="testng.cmd.args" value="@{testClass}"> <matches pattern=".*\.xml" string="@{testClass}"/> </condition> <delete dir="${build.test.results.dir}" quiet="true"/> <mkdir dir="${build.test.results.dir}"/> <j2seproject3:debug classname="org.testng.TestNG" classpath="${debug.test.classpath}"> <customize> <customize2/> <jvmarg value="-ea"/> <arg line="${testng.debug.mode}"/> <arg line="-d ${build.test.results.dir}"/> <arg line="-listener org.testng.reporters.VerboseReporter"/> <arg line="${testng.cmd.args}"/> </customize> </j2seproject3:debug> </sequential> </macrodef> </target> <target depends="-init-macrodef-testng-debug" if="${testng.available}" name="-init-macrodef-testng-debug-impl"> <macrodef name="testng-debug-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${main.class}" name="testClass"/> <attribute default="" name="testMethod"/> <element implicit="true" name="customize2" optional="true"/> <sequential> <j2seproject3:testng-debug testClass="@{testClass}" testMethod="@{testMethod}"> <customize2/> </j2seproject3:testng-debug> </sequential> </macrodef> </target> <target depends="-init-macrodef-junit-debug-impl" if="${junit.available}" name="-init-macrodef-test-debug-junit"> <macrodef name="test-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <attribute default="${main.class}" name="testClass"/> <attribute default="" name="testMethod"/> <sequential> <j2seproject3:test-debug-impl excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> <customize> <classpath> <path path="${run.test.classpath}"/> </classpath> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg line="${run.jvmargs}"/> <jvmarg line="${run.jvmargs.ide}"/> </customize> </j2seproject3:test-debug-impl> </sequential> </macrodef> </target> <target depends="-init-macrodef-testng-debug-impl" if="${testng.available}" name="-init-macrodef-test-debug-testng"> <macrodef name="test-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <attribute default="" name="testmethods"/> <attribute default="${main.class}" name="testClass"/> <attribute default="" name="testMethod"/> <sequential> <j2seproject3:testng-debug-impl testClass="@{testClass}" testMethod="@{testMethod}"> <customize2> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> </customize2> </j2seproject3:testng-debug-impl> </sequential> </macrodef> </target> <target depends="-init-macrodef-test-debug-junit,-init-macrodef-test-debug-testng" name="-init-macrodef-test-debug"/> <!-- pre NB7.2 profiling section; consider it deprecated --> <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile, -profile-init-check" if="profiler.info.jvmargs.agent" name="profile-init"/> <target if="profiler.info.jvmargs.agent" name="-profile-pre-init"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target if="profiler.info.jvmargs.agent" name="-profile-post-init"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target if="profiler.info.jvmargs.agent" name="-profile-init-macrodef-profile"> <macrodef name="resolve"> <attribute name="name"/> <attribute name="value"/> <sequential> <property name="@{name}" value="${env.@{value}}"/> </sequential> </macrodef> <macrodef name="profile"> <attribute default="${main.class}" name="classname"/> <element name="customize" optional="true"/> <sequential> <property environment="env"/> <resolve name="profiler.current.path" value="${profiler.info.pathvar}"/> <java classname="@{classname}" dir="${profiler.info.dir}" failonerror="${java.failonerror}" fork="true" jvm="${profiler.info.jvm}"> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg value="${profiler.info.jvmargs.agent}"/> <jvmarg line="${profiler.info.jvmargs}"/> <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> <arg line="${application.args}"/> <classpath> <path path="${run.classpath}"/> </classpath> <syspropertyset> <propertyref prefix="run-sys-prop."/> <mapper from="run-sys-prop.*" to="*" type="glob"/> </syspropertyset> <customize/> </java> </sequential> </macrodef> </target> <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile" if="profiler.info.jvmargs.agent" name="-profile-init-check"> <fail unless="profiler.info.jvm">Must set JVM to use for profiling in profiler.info.jvm</fail> <fail unless="profiler.info.jvmargs.agent">Must set profiler agent JVM arguments in profiler.info.jvmargs.agent</fail> </target> <!-- end of pre NB7.2 profiling section --> <target depends="-init-debug-args" name="-init-macrodef-nbjpda"> <macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute default="${main.class}" name="name"/> <attribute default="${debug.classpath}" name="classpath"/> <attribute default="" name="stopclassname"/> <sequential> <nbjpdastart addressproperty="jpda.address" name="@{name}" stopclassname="@{stopclassname}" transport="${debug-transport}"> <classpath> <path path="@{classpath}"/> </classpath> </nbjpdastart> </sequential> </macrodef> <macrodef name="nbjpdareload" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute default="${build.classes.dir}" name="dir"/> <sequential> <nbjpdareload> <fileset dir="@{dir}" includes="${fix.classes}"> <include name="${fix.includes}*.class"/> </fileset> </nbjpdareload> </sequential> </macrodef> </target> <target name="-init-debug-args"> <property name="version-output" value="java version &quot;${ant.java.version}"/> <condition property="have-jdk-older-than-1.4"> <or> <contains string="${version-output}" substring="java version &quot;1.0"/> <contains string="${version-output}" substring="java version &quot;1.1"/> <contains string="${version-output}" substring="java version &quot;1.2"/> <contains string="${version-output}" substring="java version &quot;1.3"/> </or> </condition> <condition else="-Xdebug" property="debug-args-line" value="-Xdebug -Xnoagent -Djava.compiler=none"> <istrue value="${have-jdk-older-than-1.4}"/> </condition> <condition else="dt_socket" property="debug-transport-by-os" value="dt_shmem"> <os family="windows"/> </condition> <condition else="${debug-transport-by-os}" property="debug-transport" value="${debug.transport}"> <isset property="debug.transport"/> </condition> </target> <target depends="-init-debug-args" name="-init-macrodef-debug"> <macrodef name="debug" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${main.class}" name="classname"/> <attribute default="${debug.classpath}" name="classpath"/> <element name="customize" optional="true"/> <sequential> <java classname="@{classname}" dir="${work.dir}" failonerror="${java.failonerror}" fork="true"> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg line="${debug-args-line}"/> <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> <jvmarg line="${run.jvmargs}"/> <jvmarg line="${run.jvmargs.ide}"/> <classpath> <path path="@{classpath}"/> </classpath> <syspropertyset> <propertyref prefix="run-sys-prop."/> <mapper from="run-sys-prop.*" to="*" type="glob"/> </syspropertyset> <customize/> </java> </sequential> </macrodef> </target> <target name="-init-macrodef-java"> <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute default="${main.class}" name="classname"/> <attribute default="${run.classpath}" name="classpath"/> <attribute default="jvm" name="jvm"/> <element name="customize" optional="true"/> <sequential> <java classname="@{classname}" dir="${work.dir}" failonerror="${java.failonerror}" fork="true"> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> <jvmarg line="${run.jvmargs}"/> <jvmarg line="${run.jvmargs.ide}"/> <classpath> <path path="@{classpath}"/> </classpath> <syspropertyset> <propertyref prefix="run-sys-prop."/> <mapper from="run-sys-prop.*" to="*" type="glob"/> </syspropertyset> <customize/> </java> </sequential> </macrodef> </target> <target name="-init-macrodef-copylibs"> <macrodef name="copylibs" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${manifest.file}" name="manifest"/> <element name="customize" optional="true"/> <sequential> <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> <pathconvert property="run.classpath.without.build.classes.dir"> <path path="${run.classpath}"/> <map from="${build.classes.dir.resolved}" to=""/> </pathconvert> <pathconvert pathsep=" " property="jar.classpath"> <path path="${run.classpath.without.build.classes.dir}"/> <chainedmapper> <flattenmapper/> <filtermapper> <replacestring from=" " to="%20"/> </filtermapper> <globmapper from="*" to="lib/*"/> </chainedmapper> </pathconvert> <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> <copylibs compress="${jar.compress}" excludeFromCopy="${copylibs.excludes}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> <fileset dir="${build.classes.dir}" excludes="${dist.archive.excludes}"/> <manifest> <attribute name="Class-Path" value="${jar.classpath}"/> <customize/> </manifest> </copylibs> </sequential> </macrodef> </target> <target name="-init-presetdef-jar"> <presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1"> <jar compress="${jar.compress}" index="${jar.index}" jarfile="${dist.jar}"> <j2seproject1:fileset dir="${build.classes.dir}" excludes="${dist.archive.excludes}"/> </jar> </presetdef> </target> <target name="-init-ap-cmdline-properties"> <property name="annotation.processing.enabled" value="true"/> <property name="annotation.processing.processors.list" value=""/> <property name="annotation.processing.processor.options" value=""/> <property name="annotation.processing.run.all.processors" value="true"/> <property name="javac.processorpath" value="${javac.classpath}"/> <property name="javac.test.processorpath" value="${javac.test.classpath}"/> <condition property="ap.supported.internal" value="true"> <not> <matches pattern="1\.[0-5](\..*)?" string="${javac.source}"/> </not> </condition> </target> <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-ap-cmdline-supported"> <condition else="" property="ap.processors.internal" value="-processor ${annotation.processing.processors.list}"> <isfalse value="${annotation.processing.run.all.processors}"/> </condition> <condition else="" property="ap.proc.none.internal" value="-proc:none"> <isfalse value="${annotation.processing.enabled}"/> </condition> </target> <target depends="-init-ap-cmdline-properties,-init-ap-cmdline-supported" name="-init-ap-cmdline"> <property name="ap.cmd.line.internal" value=""/> </target> <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-test,-init-macrodef-test-debug,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar,-init-ap-cmdline" name="init"/> <!-- =================== COMPILATION SECTION =================== --> <target name="-deps-jar-init" unless="built-jar.properties"> <property location="${build.dir}/built-jar.properties" name="built-jar.properties"/> <delete file="${built-jar.properties}" quiet="true"/> </target> <target if="already.built.jar.${basedir}" name="-warn-already-built-jar"> <echo level="warn" message="Cycle detected: Diffie was already built"/> </target> <target depends="init,-deps-jar-init" name="deps-jar" unless="no.deps"> <mkdir dir="${build.dir}"/> <touch file="${built-jar.properties}" verbose="false"/> <property file="${built-jar.properties}" prefix="already.built.jar."/> <antcall target="-warn-already-built-jar"/> <propertyfile file="${built-jar.properties}"> <entry key="${basedir}" value=""/> </propertyfile> </target> <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> <target depends="init" name="-check-automatic-build"> <available file="${build.classes.dir}/.netbeans_automatic_build" property="netbeans.automatic.build"/> </target> <target depends="init" if="netbeans.automatic.build" name="-clean-after-automatic-build"> <antcall target="clean"/> </target> <target depends="init,deps-jar" name="-pre-pre-compile"> <mkdir dir="${build.classes.dir}"/> </target> <target name="-pre-compile"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target if="do.depend.true" name="-compile-depend"> <pathconvert property="build.generated.subdirs"> <dirset dir="${build.generated.sources.dir}" erroronmissingdir="false"> <include name="*"/> </dirset> </pathconvert> <j2seproject3:depend srcdir="${src.dir}:${build.generated.subdirs}"/> </target> <target depends="init,deps-jar,-pre-pre-compile,-pre-compile, -copy-persistence-xml,-compile-depend" if="have.sources" name="-do-compile"> <j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/> <copy todir="${build.classes.dir}"> <fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> </copy> </target> <target if="has.persistence.xml" name="-copy-persistence-xml"> <mkdir dir="${build.classes.dir}/META-INF"/> <copy todir="${build.classes.dir}/META-INF"> <fileset dir="${meta.inf.dir}" includes="persistence.xml orm.xml"/> </copy> </target> <target name="-post-compile"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile,-do-compile,-post-compile" description="Compile project." name="compile"/> <target name="-pre-compile-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-jar,-pre-pre-compile" name="-do-compile-single"> <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> <j2seproject3:force-recompile/> <j2seproject3:javac excludes="" gensrcdir="${build.generated.sources.dir}" includes="${javac.includes}" sourcepath="${src.dir}"/> </target> <target name="-post-compile-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/> <!-- ==================== JAR BUILDING SECTION ==================== --> <target depends="init" name="-pre-pre-jar"> <dirname file="${dist.jar}" property="dist.jar.dir"/> <mkdir dir="${dist.jar.dir}"/> </target> <target name="-pre-jar"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init" if="do.archive" name="-do-jar-create-manifest" unless="manifest.available"> <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> <touch file="${tmp.manifest.file}" verbose="false"/> </target> <target depends="init" if="do.archive+manifest.available" name="-do-jar-copy-manifest"> <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> <copy file="${manifest.file}" tofile="${tmp.manifest.file}"/> </target> <target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+main.class.available" name="-do-jar-set-mainclass"> <manifest file="${tmp.manifest.file}" mode="update"> <attribute name="Main-Class" value="${main.class}"/> </manifest> </target> <target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+profile.available" name="-do-jar-set-profile"> <manifest file="${tmp.manifest.file}" mode="update"> <attribute name="Profile" value="${javac.profile}"/> </manifest> </target> <target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+splashscreen.available" name="-do-jar-set-splashscreen"> <basename file="${application.splash}" property="splashscreen.basename"/> <mkdir dir="${build.classes.dir}/META-INF"/> <copy failonerror="false" file="${application.splash}" todir="${build.classes.dir}/META-INF"/> <manifest file="${tmp.manifest.file}" mode="update"> <attribute name="SplashScreen-Image" value="META-INF/${splashscreen.basename}"/> </manifest> </target> <target depends="init,-init-macrodef-copylibs,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen" if="do.mkdist" name="-do-jar-copylibs"> <j2seproject3:copylibs manifest="${tmp.manifest.file}"/> <echo level="info">To run this application from the command line without Ant, try:</echo> <property location="${dist.jar}" name="dist.jar.resolved"/> <echo level="info">java -jar "${dist.jar.resolved}"</echo> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen" if="do.archive" name="-do-jar-jar" unless="do.mkdist"> <j2seproject1:jar manifest="${tmp.manifest.file}"/> <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> <property location="${dist.jar}" name="dist.jar.resolved"/> <pathconvert property="run.classpath.with.dist.jar"> <path path="${run.classpath}"/> <map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/> </pathconvert> <condition else="" property="jar.usage.message" value="To run this application from the command line without Ant, try:${line.separator}${platform.java} -cp ${run.classpath.with.dist.jar} ${main.class}"> <isset property="main.class.available"/> </condition> <condition else="debug" property="jar.usage.level" value="info"> <isset property="main.class.available"/> </condition> <echo level="${jar.usage.level}" message="${jar.usage.message}"/> </target> <target depends="-do-jar-copylibs" if="do.archive" name="-do-jar-delete-manifest"> <delete> <fileset file="${tmp.manifest.file}"/> </delete> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen,-do-jar-jar,-do-jar-delete-manifest" name="-do-jar-without-libraries"/> <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen,-do-jar-copylibs,-do-jar-delete-manifest" name="-do-jar-with-libraries"/> <target name="-post-jar"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-jar,-do-jar-without-libraries,-do-jar-with-libraries,-post-jar" name="-do-jar"/> <target depends="init,compile,-pre-jar,-do-jar,-post-jar" description="Build JAR." name="jar"/> <!-- ================= EXECUTION SECTION ================= --> <target depends="init,compile" description="Run a main class." name="run"> <j2seproject1:java> <customize> <arg line="${application.args}"/> </customize> </j2seproject1:java> </target> <target name="-do-not-recompile"> <property name="javac.includes.binary" value=""/> </target> <target depends="init,compile-single" name="run-single"> <fail unless="run.class">Must select one file in the IDE or set run.class</fail> <j2seproject1:java classname="${run.class}"/> </target> <target depends="init,compile-test-single" name="run-test-with-main"> <fail unless="run.class">Must select one file in the IDE or set run.class</fail> <j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/> </target> <!-- ================= DEBUGGING SECTION ================= --> <target depends="init" if="netbeans.home" name="-debug-start-debugger"> <j2seproject1:nbjpdastart name="${debug.class}"/> </target> <target depends="init" if="netbeans.home" name="-debug-start-debugger-main-test"> <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${debug.class}"/> </target> <target depends="init,compile" name="-debug-start-debuggee"> <j2seproject3:debug> <customize> <arg line="${application.args}"/> </customize> </j2seproject3:debug> </target> <target depends="init,compile,-debug-start-debugger,-debug-start-debuggee" description="Debug project in IDE." if="netbeans.home" name="debug"/> <target depends="init" if="netbeans.home" name="-debug-start-debugger-stepinto"> <j2seproject1:nbjpdastart stopclassname="${main.class}"/> </target> <target depends="init,compile,-debug-start-debugger-stepinto,-debug-start-debuggee" if="netbeans.home" name="debug-stepinto"/> <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-single"> <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> <j2seproject3:debug classname="${debug.class}"/> </target> <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-single" if="netbeans.home" name="debug-single"/> <target depends="init,compile-test-single" if="netbeans.home" name="-debug-start-debuggee-main-test"> <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> <j2seproject3:debug classname="${debug.class}" classpath="${debug.test.classpath}"/> </target> <target depends="init,compile-test-single,-debug-start-debugger-main-test,-debug-start-debuggee-main-test" if="netbeans.home" name="debug-test-with-main"/> <target depends="init" name="-pre-debug-fix"> <fail unless="fix.includes">Must set fix.includes</fail> <property name="javac.includes" value="${fix.includes}.java"/> </target> <target depends="init,-pre-debug-fix,compile-single" if="netbeans.home" name="-do-debug-fix"> <j2seproject1:nbjpdareload/> </target> <target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/> <!-- ================= PROFILING SECTION ================= --> <!-- pre NB7.2 profiler integration --> <target depends="profile-init,compile" description="Profile a project in the IDE." if="profiler.info.jvmargs.agent" name="-profile-pre72"> <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> <nbprofiledirect> <classpath> <path path="${run.classpath}"/> </classpath> </nbprofiledirect> <profile/> </target> <target depends="profile-init,compile-single" description="Profile a selected class in the IDE." if="profiler.info.jvmargs.agent" name="-profile-single-pre72"> <fail unless="profile.class">Must select one file in the IDE or set profile.class</fail> <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> <nbprofiledirect> <classpath> <path path="${run.classpath}"/> </classpath> </nbprofiledirect> <profile classname="${profile.class}"/> </target> <target depends="profile-init,compile-single" if="profiler.info.jvmargs.agent" name="-profile-applet-pre72"> <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> <nbprofiledirect> <classpath> <path path="${run.classpath}"/> </classpath> </nbprofiledirect> <profile classname="sun.applet.AppletViewer"> <customize> <arg value="${applet.url}"/> </customize> </profile> </target> <target depends="profile-init,compile-test-single" if="profiler.info.jvmargs.agent" name="-profile-test-single-pre72"> <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> <nbprofiledirect> <classpath> <path path="${run.test.classpath}"/> </classpath> </nbprofiledirect> <junit dir="${profiler.info.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" jvm="${profiler.info.jvm}" showoutput="true"> <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> <jvmarg value="${profiler.info.jvmargs.agent}"/> <jvmarg line="${profiler.info.jvmargs}"/> <test name="${profile.class}"/> <classpath> <path path="${run.test.classpath}"/> </classpath> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> <formatter type="brief" usefile="false"/> <formatter type="xml"/> </junit> </target> <!-- end of pre NB72 profiling section --> <target if="netbeans.home" name="-profile-check"> <condition property="profiler.configured"> <or> <contains casesensitive="true" string="${run.jvmargs.ide}" substring="-agentpath:"/> <contains casesensitive="true" string="${run.jvmargs.ide}" substring="-javaagent:"/> </or> </condition> </target> <target depends="-profile-check,-profile-pre72" description="Profile a project in the IDE." if="profiler.configured" name="profile" unless="profiler.info.jvmargs.agent"> <startprofiler/> <antcall target="run"/> </target> <target depends="-profile-check,-profile-single-pre72" description="Profile a selected class in the IDE." if="profiler.configured" name="profile-single" unless="profiler.info.jvmargs.agent"> <fail unless="run.class">Must select one file in the IDE or set run.class</fail> <startprofiler/> <antcall target="run-single"/> </target> <target depends="-profile-test-single-pre72" description="Profile a selected test in the IDE." name="profile-test-single"/> <target depends="-profile-check" description="Profile a selected test in the IDE." if="profiler.configured" name="profile-test" unless="profiler.info.jvmargs"> <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> <startprofiler/> <antcall target="test-single"/> </target> <target depends="-profile-check" description="Profile a selected class in the IDE." if="profiler.configured" name="profile-test-with-main"> <fail unless="run.class">Must select one file in the IDE or set run.class</fail> <startprofiler/> <antcal target="run-test-with-main"/> </target> <target depends="-profile-check,-profile-applet-pre72" if="profiler.configured" name="profile-applet" unless="profiler.info.jvmargs.agent"> <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> <startprofiler/> <antcall target="run-applet"/> </target> <!-- =============== JAVADOC SECTION =============== --> <target depends="init" if="have.sources" name="-javadoc-build"> <mkdir dir="${dist.javadoc.dir}"/> <condition else="" property="javadoc.endorsed.classpath.cmd.line.arg" value="-J${endorsed.classpath.cmd.line.arg}"> <and> <isset property="endorsed.classpath.cmd.line.arg"/> <not> <equals arg1="${endorsed.classpath.cmd.line.arg}" arg2=""/> </not> </and> </condition> <condition else="" property="bug5101868workaround" value="*.java"> <matches pattern="1\.[56](\..*)?" string="${java.version}"/> </condition> <javadoc additionalparam="-J-Dfile.encoding=${file.encoding} ${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}"> <classpath> <path path="${javac.classpath}"/> </classpath> <fileset dir="${src.dir}" excludes="${bug5101868workaround},${excludes}" includes="${includes}"> <filename name="**/*.java"/> </fileset> <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> <include name="**/*.java"/> <exclude name="*.java"/> </fileset> <arg line="${javadoc.endorsed.classpath.cmd.line.arg}"/> </javadoc> <copy todir="${dist.javadoc.dir}"> <fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}"> <filename name="**/doc-files/**"/> </fileset> <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> <include name="**/doc-files/**"/> </fileset> </copy> </target> <target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview"> <nbbrowse file="${dist.javadoc.dir}/index.html"/> </target> <target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/> <!-- ========================= TEST COMPILATION SECTION ========================= --> <target depends="init,compile" if="have.tests" name="-pre-pre-compile-test"> <mkdir dir="${build.test.classes.dir}"/> </target> <target name="-pre-compile-test"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target if="do.depend.true" name="-compile-test-depend"> <j2seproject3:depend classpath="${javac.test.classpath}" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> </target> <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test,-compile-test-depend" if="have.tests" name="-do-compile-test"> <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" processorpath="${javac.test.processorpath}" srcdir="${test.src.dir}"/> <copy todir="${build.test.classes.dir}"> <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> </copy> </target> <target name="-post-compile-test"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-do-compile-test,-post-compile-test" name="compile-test"/> <target name="-pre-compile-test-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test-single" if="have.tests" name="-do-compile-test-single"> <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> <j2seproject3:force-recompile destdir="${build.test.classes.dir}"/> <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" excludes="" includes="${javac.includes}" processorpath="${javac.test.processorpath}" sourcepath="${test.src.dir}" srcdir="${test.src.dir}"/> <copy todir="${build.test.classes.dir}"> <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> </copy> </target> <target name="-post-compile-test-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/> <!-- ======================= TEST EXECUTION SECTION ======================= --> <target depends="init" if="have.tests" name="-pre-test-run"> <mkdir dir="${build.test.results.dir}"/> </target> <target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run"> <j2seproject3:test includes="${includes}" testincludes="**/*Test.java"/> </target> <target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run"> <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> </target> <target depends="init" if="have.tests" name="test-report"/> <target depends="init" if="netbeans.home+have.tests" name="-test-browse"/> <target depends="init,compile-test,-pre-test-run,-do-test-run,test-report,-post-test-run,-test-browse" description="Run unit tests." name="test"/> <target depends="init" if="have.tests" name="-pre-test-run-single"> <mkdir dir="${build.test.results.dir}"/> </target> <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single"> <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> <j2seproject3:test excludes="" includes="${test.includes}" testincludes="${test.includes}"/> </target> <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single" if="have.tests" name="-post-test-run-single"> <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> </target> <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single,-post-test-run-single" description="Run single unit test." name="test-single"/> <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single-method"> <fail unless="test.class">Must select some files in the IDE or set test.class</fail> <fail unless="test.method">Must select some method in the IDE or set test.method</fail> <j2seproject3:test excludes="" includes="${javac.includes}" testincludes="${test.class}" testmethods="${test.method}"/> </target> <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single-method" if="have.tests" name="-post-test-run-single-method"> <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> </target> <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single-method,-post-test-run-single-method" description="Run single unit test." name="test-single-method"/> <!-- ======================= TEST DEBUGGING SECTION ======================= --> <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-debug-start-debuggee-test"> <fail unless="test.class">Must select one file in the IDE or set test.class</fail> <j2seproject3:test-debug excludes="" includes="${javac.includes}" testClass="${test.class}" testincludes="${javac.includes}"/> </target> <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-debug-start-debuggee-test-method"> <fail unless="test.class">Must select one file in the IDE or set test.class</fail> <fail unless="test.method">Must select some method in the IDE or set test.method</fail> <j2seproject3:test-debug excludes="" includes="${javac.includes}" testClass="${test.class}" testMethod="${test.method}" testincludes="${test.class}" testmethods="${test.method}"/> </target> <target depends="init,compile-test" if="netbeans.home+have.tests" name="-debug-start-debugger-test"> <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${test.class}"/> </target> <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test" name="debug-test"/> <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test-method" name="debug-test-method"/> <target depends="init,-pre-debug-fix,compile-test-single" if="netbeans.home" name="-do-debug-fix-test"> <j2seproject1:nbjpdareload dir="${build.test.classes.dir}"/> </target> <target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/> <!-- ========================= APPLET EXECUTION SECTION ========================= --> <target depends="init,compile-single" name="run-applet"> <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> <j2seproject1:java classname="sun.applet.AppletViewer"> <customize> <arg value="${applet.url}"/> </customize> </j2seproject1:java> </target> <!-- ========================= APPLET DEBUGGING SECTION ========================= --> <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet"> <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> <j2seproject3:debug classname="sun.applet.AppletViewer"> <customize> <arg value="${applet.url}"/> </customize> </j2seproject3:debug> </target> <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/> <!-- =============== CLEANUP SECTION =============== --> <target name="-deps-clean-init" unless="built-clean.properties"> <property location="${build.dir}/built-clean.properties" name="built-clean.properties"/> <delete file="${built-clean.properties}" quiet="true"/> </target> <target if="already.built.clean.${basedir}" name="-warn-already-built-clean"> <echo level="warn" message="Cycle detected: Diffie was already built"/> </target> <target depends="init,-deps-clean-init" name="deps-clean" unless="no.deps"> <mkdir dir="${build.dir}"/> <touch file="${built-clean.properties}" verbose="false"/> <property file="${built-clean.properties}" prefix="already.built.clean."/> <antcall target="-warn-already-built-clean"/> <propertyfile file="${built-clean.properties}"> <entry key="${basedir}" value=""/> </propertyfile> </target> <target depends="init" name="-do-clean"> <delete dir="${build.dir}"/> <delete dir="${dist.dir}" followsymlinks="false" includeemptydirs="true"/> </target> <target name="-post-clean"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-clean,-do-clean,-post-clean" description="Clean build products." name="clean"/> <target name="-check-call-dep"> <property file="${call.built.properties}" prefix="already.built."/> <condition property="should.call.dep"> <and> <not> <isset property="already.built.${call.subproject}"/> </not> <available file="${call.script}"/> </and> </condition> </target> <target depends="-check-call-dep" if="should.call.dep" name="-maybe-call-dep"> <ant antfile="${call.script}" inheritall="false" target="${call.target}"> <propertyset> <propertyref prefix="transfer."/> <mapper from="transfer.*" to="*" type="glob"/> </propertyset> </ant> </target> </project>
{ "content_hash": "c48d930b0fb0a89ac30f873197fc98de", "timestamp": "", "source": "github", "line_count": 1419, "max_line_length": 531, "avg_line_length": 56.116279069767444, "alnum_prop": 0.5580379007647968, "repo_name": "ivangarmir/Diffie-Hellman", "id": "eec859b18333a1a8ec7e2189d87c605f6f5fbad6", "size": "79629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nbproject/build-impl.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2616" } ], "symlink_target": "" }
require 5.6.0; use strict; use warnings; use Data::Dumper; use Getopt::Long qw(GetOptions); use Time::HiRes qw(gettimeofday); use lib '../../lib/perl/lib'; use lib 'gen-perl'; use Thrift; use Thrift::BinaryProtocol; use Thrift::BufferedTransport; use Thrift::FramedTransport; use Thrift::SSLServerSocket; use Thrift::ServerSocket; use Thrift::Server; use Thrift::UnixServerSocket; use ThriftTest::ThriftTest; use ThriftTest::Types; $|++; sub usage { print <<EOF; Usage: $0 [OPTIONS] Options: (default) --ca Certificate authority file (optional). --cert Certificate file. Required if using --ssl. --ciphers Acceptable cipher list. --domain-socket <file> Use a unix domain socket. --help Show usage. --key Private key file for certificate. Required if using --ssl and private key is not in the certificate file. --port <portnum> 9090 Port to use. --protocol {binary} binary Protocol to use. --ssl If present, use SSL/TLS. --transport {buffered|framed} buffered Transport to use. EOF } my %opts = ( 'port' => 9090, 'protocol' => 'binary', 'transport' => 'buffered' ); GetOptions(\%opts, qw ( ca=s cert=s ciphers=s domain-socket=s help host=s key=s port=i protocol=s ssl transport=s )) || exit 1; if ($opts{help}) { usage(); exit 0; } if ($opts{ssl} and not defined $opts{cert}) { usage(); exit 1; } my $handler = new ThriftTestHandler(); my $processor = new ThriftTest::ThriftTestProcessor($handler); my $serversocket; if ($opts{"domain-socket"}) { unlink($opts{"domain-socket"}); $serversocket = new Thrift::UnixServerSocket($opts{"domain-socket"}); } elsif ($opts{ssl}) { $serversocket = new Thrift::SSLServerSocket(\%opts); } else { $serversocket = new Thrift::ServerSocket(\%opts); } my $transport; if ($opts{transport} eq 'buffered') { $transport = new Thrift::BufferedTransportFactory(); } elsif ($opts{transport} eq 'framed') { $transport = new Thrift::FramedTransportFactory(); } else { usage(); exit 1; } my $protocol; if ($opts{protocol} eq 'binary') { $protocol = new Thrift::BinaryProtocolFactory(); } else { usage(); exit 1; } my $ssltag = ''; if ($opts{ssl}) { $ssltag = "(SSL)"; } my $listening_on = "$opts{port} $ssltag"; if ($opts{"domain-socket"}) { $listening_on = $opts{"domain-socket"}; } my $server = new Thrift::SimpleServer($processor, $serversocket, $transport, $protocol); print "Starting \"simple\" server ($opts{transport}/$opts{protocol}) listen on: $listening_on\n"; $server->serve(); ### ### Test server implementation ### package ThriftTestHandler; use base qw( ThriftTest::ThriftTestIf ); sub new { my $classname = shift; my $self = {}; return bless($self, $classname); } sub testVoid() { print("testVoid()\n"); } sub testString() { my $self = shift; my $thing = shift; print("testString($thing)\n"); return $thing; } sub testBool() { my $self = shift; my $thing = shift; my $str = $thing ? "true" : "false"; print("testBool($str)\n"); return $thing; } sub testByte() { my $self = shift; my $thing = shift; print("testByte($thing)\n"); return $thing; } sub testI32() { my $self = shift; my $thing = shift; print("testI32($thing)\n"); return $thing; } sub testI64() { my $self = shift; my $thing = shift; print("testI64($thing)\n"); return $thing; } sub testDouble() { my $self = shift; my $thing = shift; print("testDouble($thing)\n"); return $thing; } sub testBinary() { my $self = shift; my $thing = shift; my @bytes = split //, $thing; print("testBinary("); foreach (@bytes) { printf "%02lx", ord $_; } print(")\n"); return $thing; } sub testStruct() { my $self = shift; my $thing = shift; printf("testStruct({\"%s\", %d, %d, %lld})\n", $thing->{string_thing}, $thing->{byte_thing}, $thing->{i32_thing}, $thing->{i64_thing}); return $thing; } sub testNest() { my $self = shift; my $nest = shift; my $thing = $nest->{struct_thing}; printf("testNest({%d, {\"%s\", %d, %d, %lld}, %d})\n", $nest->{byte_thing}, $thing->{string_thing}, $thing->{byte_thing}, $thing->{i32_thing}, $thing->{i64_thing}, $nest->{i32_thing}); return $nest; } sub testMap() { my $self = shift; my $thing = shift; print("testMap({"); my $first = 1; foreach my $key (keys %$thing) { if ($first) { $first = 0; } else { print(", "); } print("$key => $thing->{$key}"); } print("})\n"); return $thing; } sub testStringMap() { my $self = shift; my $thing = shift; print("testStringMap({"); my $first = 1; foreach my $key (keys %$thing) { if ($first) { $first = 0; } else { print(", "); } print("$key => $thing->{$key}"); } print("})\n"); return $thing; } sub testSet() { my $self = shift; my $thing = shift; my @arr; my $result = \@arr; print("testSet({"); my $first = 1; foreach my $key (keys %$thing) { if ($first) { $first = 0; } else { print(", "); } print("$key"); push($result, $key); } print("})\n"); return $result; } sub testList() { my $self = shift; my $thing = shift; print("testList({"); my $first = 1; foreach my $key (@$thing) { if ($first) { $first = 0; } else { print(", "); } print("$key"); } print("})\n"); return $thing; } sub testEnum() { my $self = shift; my $thing = shift; print("testEnum($thing)\n"); return $thing; } sub testTypedef() { my $self = shift; my $thing = shift; print("testTypedef($thing)\n"); return $thing; } sub testMapMap() { my $self = shift; my $hello = shift; printf("testMapMap(%d)\n", $hello); my $result = { 4 => { 1 => 1, 2 => 2, 3 => 3, 4 => 4 }, -4 => { -1 => -1, -2 => -2, -3 => -3, -4 => -4 } }; return $result; } sub testInsanity() { my $self = shift; my $argument = shift; print("testInsanity()\n"); my $hello = new ThriftTest::Xtruct({string_thing => "Hello2", byte_thing => 2, i32_thing => 2, i64_thing => 2}); my @hellos; push(@hellos, $hello); my $goodbye = new ThriftTest::Xtruct({string_thing => "Goodbye4", byte_thing => 4, i32_thing => 4, i64_thing => 4}); my @goodbyes; push(@goodbyes, $goodbye); my $crazy = new ThriftTest::Insanity({userMap => { ThriftTest::Numberz::EIGHT => 8 }, xtructs => \@goodbyes}); my $loony = new ThriftTest::Insanity(); my $result = { 1 => { ThriftTest::Numberz::TWO => $argument, ThriftTest::Numberz::THREE => $argument }, 2 => { ThriftTest::Numberz::SIX => $loony } }; return $result; } sub testMulti() { my $self = shift; my $arg0 = shift; my $arg1 = shift; my $arg2 = shift; my $arg3 = shift; my $arg4 = shift; my $arg5 = shift; print("testMulti()\n"); return new ThriftTest::Xtruct({string_thing => "Hello2", byte_thing => $arg0, i32_thing => $arg1, i64_thing => $arg2}); } sub testException() { my $self = shift; my $arg = shift; print("testException($arg)\n"); if ($arg eq "Xception") { die new ThriftTest::Xception({errorCode => 1001, message => $arg}); } elsif ($arg eq "TException") { die "astring"; # all unhandled exceptions become TExceptions } else { return new ThriftTest::Xtruct({string_thing => $arg}); } } sub testMultiException() { my $self = shift; my $arg0 = shift; my $arg1 = shift; printf("testMultiException(%s, %s)\n", $arg0, $arg1); if ($arg0 eq "Xception") { die new ThriftTest::Xception({errorCode => 1001, message => "This is an Xception"}); } elsif ($arg0 eq "Xception2") { my $struct_thing = new ThriftTest::Xtruct({string_thing => "This is an Xception2"}); die new ThriftTest::Xception2({errorCode => 2002, struct_thing => $struct_thing}); } else { return new ThriftTest::Xtruct({string_thing => $arg1}); } } sub testOneway() { my $self = shift; my $sleepFor = shift; print("testOneway($sleepFor): Sleeping...\n"); sleep $sleepFor; print("testOneway($sleepFor): done sleeping!\n"); } 1;
{ "content_hash": "459eeb8205d883df64441d0387ad8f41", "timestamp": "", "source": "github", "line_count": 379, "max_line_length": 121, "avg_line_length": 22.84168865435356, "alnum_prop": 0.5523853528936121, "repo_name": "project-zerus/thrift", "id": "e2835f4e7a9c97b20a69961f9a2f0560b2ca1387", "size": "9464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/perl/TestServer.pl", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "75532" }, { "name": "C", "bytes": "650514" }, { "name": "C#", "bytes": "359395" }, { "name": "C++", "bytes": "3538877" }, { "name": "CMake", "bytes": "73454" }, { "name": "D", "bytes": "642358" }, { "name": "Emacs Lisp", "bytes": "5361" }, { "name": "Erlang", "bytes": "219560" }, { "name": "Go", "bytes": "430201" }, { "name": "HTML", "bytes": "19315" }, { "name": "Haskell", "bytes": "100516" }, { "name": "Haxe", "bytes": "303334" }, { "name": "Java", "bytes": "942448" }, { "name": "JavaScript", "bytes": "305281" }, { "name": "LLVM", "bytes": "15471" }, { "name": "Lua", "bytes": "48446" }, { "name": "Makefile", "bytes": "15010" }, { "name": "OCaml", "bytes": "39239" }, { "name": "Objective-C", "bytes": "126719" }, { "name": "PHP", "bytes": "276286" }, { "name": "Pascal", "bytes": "383105" }, { "name": "Perl", "bytes": "87705" }, { "name": "Perl6", "bytes": "1524" }, { "name": "Python", "bytes": "306878" }, { "name": "Ruby", "bytes": "383084" }, { "name": "Shell", "bytes": "31769" }, { "name": "Smalltalk", "bytes": "22944" }, { "name": "Thrift", "bytes": "109816" }, { "name": "VimL", "bytes": "2843" } ], "symlink_target": "" }
module RspecWiki class Markdown attr_reader :context def initialize context @context = context end def anchor_link { anchor_group => "* [#{title_with_status}](#{RspecWiki.configuration.wiki_page_url}##{title_anchor})"} end def anchor_group return "#{h3}#{context.metadata[:group]}" if context.metadata[:group].present? described_class = context.described_class.split("::").last described_class.gsub!('Controller', '') described_class.underscore.humanize.prepend(h3) end def print <<-EOC #{header} #{body} #{footer} EOC end def header "#{h3}#{title}" end def body <<-EOC #{description} #{url} | #{request_method} #{parameters} Response #{status} #{javascript(context.response_body)} EOC end def footer <<-EOC #{ back_to_table_of_content } #{ '='*100 } EOC end def description <<-EOC `#{context.content}` EOC end def status "Status: \`#{context.response_status}\`" end def parameters "Parameters: #{format_params}" end def url "URL: __#{context.request_path}__" end def request_method "Method: \`#{context.request_method}\`" end private def title (context.metadata[:title] || context.content).humanize end def title_with_status status = context.response_success? ? "(SUCCESS)" : "(ERROR)" "#{title} #{status}" end def title_anchor title.downcase.gsub(/\s+/, '-') end def format_params context.params.collect do |key, value| "\`#{key}\` => #{value}" end.join("\n\n") end def h3 '###' end def javascript content <<-EOC ```javascript #{content} ``` EOC end def back_to_table_of_content "[Back to table of contents](#{RspecWiki.configuration.wiki_page_url}#table-of-contents)" end end end
{ "content_hash": "8be93f2c1b0eacfea0fd5da8a1eefd47", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 109, "avg_line_length": 17.13157894736842, "alnum_prop": 0.5734767025089605, "repo_name": "nlds90/rspec_wiki", "id": "91ac239716d4a828d05ed2680bc618fa37860b8b", "size": "1953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/rspec_wiki/formatter/markdown.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "683" }, { "name": "HTML", "bytes": "4883" }, { "name": "JavaScript", "bytes": "599" }, { "name": "Ruby", "bytes": "26134" } ], "symlink_target": "" }
<?php require_once(TOOLKIT . '/class.administrationpage.php'); class contentExtensionUrl_routerRoutes extends AdministrationPage { public function __construct(){ parent::__construct(); $this->_driver = Symphony::ExtensionManager()->create('url_router'); } public function __actionIndex() { $this->_driver->saveRoutes(); } public function __viewIndex() { $this->setPageType('form'); $this->addScriptToHead(URL . '/extensions/url_router/assets/url_router.preferences.js', 400, false); $this->setTitle(__('%1$s &ndash; %2$s', array(__('Symphony'), __('URL Router')))); $this->appendSubheading(__('URL Router')); if(isset($this->_context[1]) == 'saved') { $this->pageAlert( __('Routes saved at %s.', array(Widget::Time()->generate())) , Alert::SUCCESS); } $fieldset = new XMLElement('fieldset'); $fieldset->setAttribute('class', 'settings'); $fieldset->appendChild(new XMLElement('legend', __('URL Routes'))); $fieldset->appendChild(new XMLElement('p', __('Choose between a <strong>Route</strong>, which silently shows the content under the original URL, or a <strong>Redirect</strong> which will actually redirect the user to the new URL.'), array('class' => 'help'))); $group = new XMLElement('div'); $group->setAttribute('class', 'frame'); $ol = new XMLElement('ol'); $ol->setAttribute('data-name', __('Add route')); $ol->setAttribute('data-type', __('Remove route')); // Redirect Template $li_re = new XMLElement('li'); $li_re->setAttribute('class', 'template'); $li_re->setAttribute('data-name', 'Redirect'); $li_re->setAttribute('data-type', 'redirect'); $header_re = new XMLElement('header', __('Redirect')); $hidden_re = Widget::Input("settings[url-router][routes][][type]", 'redirect', 'hidden'); $li_re->appendChild($header_re); $li_re->appendChild($hidden_re); // Route Template $li_ro = new XMLElement('li'); $li_ro->setAttribute('class', 'template'); $li_ro->setAttribute('data-name', 'Route'); $li_ro->setAttribute('data-type', 'route'); $header_ro = new XMLElement('header', __('Route')); $hidden_ro = Widget::Input("settings[url-router][routes][][type]", 'route', 'hidden'); $li_ro->appendChild($header_ro); $li_ro->appendChild($hidden_ro); // From To boxes $divgroup = new XMLElement('div'); $divgroup->setAttribute('class', 'group'); $labelfrom = Widget::Label(__('From')); $labelfrom->appendChild(Widget::Input("settings[url-router][routes][][from]")); $labelfrom->appendChild(new XMLElement('p', __('Simplified: <code>page-name/$user/projects/$project</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $labelfrom->appendChild(new XMLElement('p', __('Regular expression: <code>/\\/page-name\\/(.+\\/)/</code> Wrap in <code>/</code> and ensure to escape metacharacters with <code>\\</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $labelto = Widget::Label(__('To')); $labelto->appendChild(Widget::Input("settings[url-router][routes][][to]")); $labelto->appendChild(new XMLElement('p', __('Simplified: <code>/new-page-name/$user/$project</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $labelto->appendChild(new XMLElement('p', __('Regular expression: <code>/new-page-name/$1/</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $divgroup->appendChild($labelfrom); $divgroup->appendChild($labelto); $divcontent = new XMLElement('div'); $divcontent->setAttribute('class', 'content'); $divcontent->appendChild($divgroup); $recontent = clone $divcontent; $regroup = new XMLElement('div'); $regroup->setAttribute('class', 'group'); $label = Widget::Label(); $input = Widget::Input('settings[url-router][routes][][http301]', 'yes', 'checkbox'); $label->setValue($input->generate() . ' ' . __('Send an HTTP 301 Redirect')); $regroup->appendChild($label); $recontent->appendChild($regroup); $li_re->appendChild($recontent); $li_ro->appendChild($divcontent); $ol->appendChild($li_ro); $ol->appendChild($li_re); if($routes = $this->_driver->getRoutes()) { if(is_array($routes)) { foreach($routes as $route) { $from = isset($route['from-clean']) ? $route['from-clean'] : $route['from']; $to = isset($route['to-clean']) ? $route['to-clean'] : $route['to']; $header = new XMLElement('header'); $header->appendChild(new XMLElement('h4', $route['type'] == 'redirect' ? __('Redirect') : __('Route') )); $header->appendChild(new XMLElement('span', __('From'), array('class' => 'type'))); $header->appendChild(new XMLElement('span', $from, array('class' => 'type'))); $header->appendChild(new XMLElement('span', __('To'), array('class' => 'type'))); $header->appendChild(new XMLElement('span', $to, array('class' => 'type'))); $hidden = Widget::Input("settings[url-router][routes][][type]", $route['type'], 'hidden'); $li = new XMLElement('li'); $li->setAttribute('class', 'instance expanded'); $li->appendChild($header); $li->appendChild($hidden); $divcontent = new XMLElement('div'); $divcontent->setAttribute('class', 'content'); $divgroup = new XMLElement('div'); $divgroup->setAttribute('class', 'group'); $labelfrom = Widget::Label(__('From')); $labelfrom->appendChild(Widget::Input("settings[url-router][routes][][from]", General::sanitize($from))); $labelfrom->appendChild(new XMLElement('p', __('Simplified: <code>page-name/$user/projects/$project</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $labelfrom->appendChild(new XMLElement('p', __('Regular expression: <code>/\\/page-name\\/(.+\\/)/</code> Wrap in <code>/</code> and ensure to escape metacharacters with <code>\\</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $labelto = Widget::Label(__('To')); $labelto->appendChild(Widget::Input("settings[url-router][routes][][to]", General::sanitize($to))); $labelto->appendChild(new XMLElement('p', __('Simplified: <code>/new-page-name/$user/$project</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $labelto->appendChild(new XMLElement('p', __('Regular expression: <code>/new-page-name/$1/</code>'), array('class' => 'help', 'style' => 'margin: 0.5em 0 -0.5em;'))); $divgroup->appendChild($labelfrom); $divgroup->appendChild($labelto); $divcontent->appendChild($divgroup); if($route['type'] == 'redirect') { $regroup = new XMLElement('div'); $regroup->setAttribute('class', 'group'); $label = Widget::Label(); $input = Widget::Input('settings[url-router][routes][][http301]', 'yes', 'checkbox'); if($route['http301'] == 'yes') { $input->setAttribute('checked', 'checked'); } $label->setValue($input->generate() . ' ' . __('Send an HTTP 301 Redirect')); $regroup->appendChild($label); $divcontent->appendChild($regroup); } $li->appendChild($divcontent); $ol->appendChild($li); } } } $group->appendChild($ol); $fieldset->appendChild($group); $this->Form->appendChild($fieldset); $div = new XMLElement('div'); $div->setAttribute('class', 'actions'); $div->appendChild(Widget::Input('action[save]', __('Save Changes'), 'submit', array('accesskey' => 's'))); $this->Form->appendChild($div); } }
{ "content_hash": "1d4da27194a73a857d53bb631670f769", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 263, "avg_line_length": 42.138888888888886, "alnum_prop": 0.6101516150296639, "repo_name": "symphonists/url_router", "id": "1e81c060e6bebd54ef0790aed054623c4cfecab9", "size": "7585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/content.routes.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "399" }, { "name": "PHP", "bytes": "16338" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project> <modelVersion>4.0.0</modelVersion> <parent> <groupId>cp.acme</groupId> <artifactId>multimodule-cp-resources</artifactId> <version>1.0-SNAPSHOT</version> </parent> <artifactId>multimodule-cp-resources-html-extra</artifactId> <version>1.0-SNAPSHOT</version> </project>
{ "content_hash": "f9849c8fbf8d5674452c00538e146c6a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 64, "avg_line_length": 27.846153846153847, "alnum_prop": 0.6574585635359116, "repo_name": "quarkusio/quarkus", "id": "3255ab5ba8e1a49d5314bfcb551676f4fadec953", "size": "362", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "integration-tests/maven/src/test/resources-filtered/projects/multimodule-classpath/html-extra/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "23342" }, { "name": "Batchfile", "bytes": "13096" }, { "name": "CSS", "bytes": "6685" }, { "name": "Dockerfile", "bytes": "459" }, { "name": "FreeMarker", "bytes": "8106" }, { "name": "Groovy", "bytes": "16133" }, { "name": "HTML", "bytes": "1418749" }, { "name": "Java", "bytes": "38584810" }, { "name": "JavaScript", "bytes": "90960" }, { "name": "Kotlin", "bytes": "704351" }, { "name": "Mustache", "bytes": "13191" }, { "name": "Scala", "bytes": "9756" }, { "name": "Shell", "bytes": "71729" } ], "symlink_target": "" }
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010. import { Vex } from './vex'; import { Element } from './element'; import { Flow } from './tables'; import { Barline } from './stavebarline'; import { StaveModifier } from './stavemodifier'; import { Repetition } from './staverepetition'; import { StaveSection } from './stavesection'; import { StaveTempo } from './stavetempo'; import { StaveText } from './stavetext'; import { BoundingBox } from './boundingbox'; import { Clef } from './clef'; import { KeySignature } from './keysignature'; import { TimeSignature } from './timesignature'; import { Volta } from './stavevolta'; export class Stave extends Element { constructor(x, y, width, options) { super(); this.setAttribute('type', 'Stave'); this.x = x; this.y = y; this.width = width; this.formatted = false; this.setStartX(x + 5); // this.start_x = x + 5; this.end_x = x + width; this.modifiers = []; // stave modifiers (clef, key, time, barlines, coda, segno, etc.) this.measure = 0; this.clef = 'treble'; this.endClef = undefined; this.font = { family: 'sans-serif', size: 8, weight: '', }; this.options = { vertical_bar_width: 10, // Width around vertical bar end-marker glyph_spacing_px: 10, num_lines: 5, fill_style: '#999999', left_bar: true, // draw vertical bar on left right_bar: true, // draw vertical bar on right spacing_between_lines_px: 10, // in pixels space_above_staff_ln: 4, // in staff lines space_below_staff_ln: 4, // in staff lines top_text_position: 1, // in staff lines }; this.bounds = { x: this.x, y: this.y, w: this.width, h: 0 }; Vex.Merge(this.options, options); this.resetLines(); const BARTYPE = Barline.type; // beg bar this.addModifier(new Barline(this.options.left_bar ? BARTYPE.SINGLE : BARTYPE.NONE)); // end bar this.addEndModifier(new Barline(this.options.right_bar ? BARTYPE.SINGLE : BARTYPE.NONE)); } space(spacing) { return this.options.spacing_between_lines_px * spacing; } resetLines() { this.options.line_config = []; for (let i = 0; i < this.options.num_lines; i++) { this.options.line_config.push({ visible: true }); } this.height = (this.options.num_lines + this.options.space_above_staff_ln) * this.options.spacing_between_lines_px; this.options.bottom_text_position = this.options.num_lines; } getOptions() { return this.options; } setNoteStartX(x) { if (!this.formatted) this.format(); this.setStartX(x); const begBarline = this.modifiers[0]; begBarline.setX(this.start_x - begBarline.getWidth()); return this; } setStartX(x) { this.start_x = x; } getNoteStartX() { if (!this.formatted) this.format(); return this.start_x; } getNoteEndX() { if (!this.formatted) this.format(); return this.end_x; } getTieStartX() { return this.start_x; } getTieEndX() { return this.x + this.width; } getX() { return this.x; } getNumLines() { return this.options.num_lines; } setNumLines(lines) { this.options.num_lines = parseInt(lines, 10); this.resetLines(); return this; } setY(y) { this.y = y; return this; } getTopLineTopY() { return this.getYForLine(0) - (Flow.STAVE_LINE_THICKNESS / 2); } getBottomLineBottomY() { return this.getYForLine(this.getNumLines() - 1) + (Flow.STAVE_LINE_THICKNESS / 2); } setX(x) { const shift = x - this.x; this.formatted = false; this.x = x; this.start_x += shift; this.end_x += shift; for (let i = 0; i < this.modifiers.length; i++) { const mod = this.modifiers[i]; if (mod.x !== undefined) { mod.x += shift; } } return this; } setWidth(width) { this.formatted = false; this.width = width; this.end_x = this.x + width; // reset the x position of the end barline (TODO(0xfe): This makes no sense) // this.modifiers[1].setX(this.end_x); return this; } getWidth() { return this.width; } getStyle() { return { fillStyle: this.options.fill_style, strokeStyle: this.options.fill_style, // yes, this is correct for legacy compatibility lineWidth: Flow.STAVE_LINE_THICKNESS, ...this.style || {} }; } setMeasure(measure) { this.measure = measure; return this; } /** * Gets the pixels to shift from the beginning of the stave * following the modifier at the provided index * @param {Number} index The index from which to determine the shift * @return {Number} The amount of pixels shifted */ getModifierXShift(index = 0) { if (typeof index !== 'number') { throw new Vex.RERR('InvalidIndex', 'Must be of number type'); } if (!this.formatted) this.format(); if (this.getModifiers(StaveModifier.Position.BEGIN).length === 1) { return 0; } let start_x = this.start_x - this.x; const begBarline = this.modifiers[0]; if (begBarline.getType() === Barline.type.REPEAT_BEGIN && start_x > begBarline.getWidth()) { start_x -= begBarline.getWidth(); } return start_x; } // Coda & Segno Symbol functions setRepetitionTypeLeft(type, y) { this.modifiers.push(new Repetition(type, this.x, y)); return this; } setRepetitionTypeRight(type, y) { this.modifiers.push(new Repetition(type, this.x, y)); return this; } // Volta functions setVoltaType(type, number_t, y) { this.modifiers.push(new Volta(type, number_t, this.x, y)); return this; } // Section functions setSection(section, y, xOffset = 0, fontSize = 12) { const staveSection = new StaveSection(section, this.x + xOffset, y); // staveSection.shift_x = xOffset; // has no effect staveSection.font.size = fontSize; this.modifiers.push(staveSection); return this; } // Tempo functions setTempo(tempo, y) { this.modifiers.push(new StaveTempo(tempo, this.x, y)); return this; } // Text functions setText(text, position, options) { this.modifiers.push(new StaveText(text, position, options)); return this; } getHeight() { return this.height; } getSpacingBetweenLines() { return this.options.spacing_between_lines_px; } getBoundingBox() { return new BoundingBox(this.x, this.y, this.width, this.getBottomY() - this.y); } getBottomY() { const options = this.options; const spacing = options.spacing_between_lines_px; const score_bottom = this.getYForLine(options.num_lines) + (options.space_below_staff_ln * spacing); return score_bottom; } getBottomLineY() { return this.getYForLine(this.options.num_lines); } // This returns the y for the *center* of a staff line getYForLine(line) { const options = this.options; const spacing = options.spacing_between_lines_px; const headroom = options.space_above_staff_ln; const y = this.y + (line * spacing) + (headroom * spacing); return y; } getLineForY(y) { // Does the reverse of getYForLine - somewhat dumb and just calls // getYForLine until the right value is reaches const options = this.options; const spacing = options.spacing_between_lines_px; const headroom = options.space_above_staff_ln; return ((y - this.y) / spacing) - headroom; } getYForTopText(line) { const l = line || 0; return this.getYForLine(-l - this.options.top_text_position); } getYForBottomText(line) { const l = line || 0; return this.getYForLine(this.options.bottom_text_position + l); } getYForNote(line) { const options = this.options; const spacing = options.spacing_between_lines_px; const headroom = options.space_above_staff_ln; const y = this.y + (headroom * spacing) + (5 * spacing) - (line * spacing); return y; } getYForGlyphs() { return this.getYForLine(3); } // This method adds a stave modifier to the stave. Note that the first two // modifiers (BarLines) are automatically added upon construction. addModifier(modifier, position) { if (position !== undefined) { modifier.setPosition(position); } modifier.setStave(this); this.formatted = false; this.modifiers.push(modifier); return this; } addEndModifier(modifier) { this.addModifier(modifier, StaveModifier.Position.END); return this; } // Bar Line functions setBegBarType(type) { // Only valid bar types at beginning of stave is none, single or begin repeat const { SINGLE, REPEAT_BEGIN, NONE } = Barline.type; if (type === SINGLE || type === REPEAT_BEGIN || type === NONE) { this.modifiers[0].setType(type); this.formatted = false; } return this; } setEndBarType(type) { // Repeat end not valid at end of stave if (type !== Barline.type.REPEAT_BEGIN) { this.modifiers[1].setType(type); this.formatted = false; } return this; } setClef(clefSpec, size, annotation, position) { if (position === undefined) { position = StaveModifier.Position.BEGIN; } if (position === StaveModifier.Position.END) { this.endClef = clefSpec; } else { this.clef = clefSpec; } const clefs = this.getModifiers(position, Clef.CATEGORY); if (clefs.length === 0) { this.addClef(clefSpec, size, annotation, position); } else { clefs[0].setType(clefSpec, size, annotation); } return this; } setEndClef(clefSpec, size, annotation) { this.setClef(clefSpec, size, annotation, StaveModifier.Position.END); return this; } setKeySignature(keySpec, cancelKeySpec, position) { if (position === undefined) { position = StaveModifier.Position.BEGIN; } const keySignatures = this.getModifiers(position, KeySignature.CATEGORY); if (keySignatures.length === 0) { this.addKeySignature(keySpec, cancelKeySpec, position); } else { keySignatures[0].setKeySig(keySpec, cancelKeySpec); } return this; } setEndKeySignature(keySpec, cancelKeySpec) { this.setKeySignature(keySpec, cancelKeySpec, StaveModifier.Position.END); return this; } setTimeSignature(timeSpec, customPadding, position) { if (position === undefined) { position = StaveModifier.Position.BEGIN; } const timeSignatures = this.getModifiers(position, TimeSignature.CATEGORY); if (timeSignatures.length === 0) { this.addTimeSignature(timeSpec, customPadding, position); } else { timeSignatures[0].setTimeSig(timeSpec); } return this; } setEndTimeSignature(timeSpec, customPadding) { this.setTimeSignature(timeSpec, customPadding, StaveModifier.Position.END); return this; } addKeySignature(keySpec, cancelKeySpec, position) { if (position === undefined) { position = StaveModifier.Position.BEGIN; } this.addModifier(new KeySignature(keySpec, cancelKeySpec) .setPosition(position), position); return this; } addClef(clef, size, annotation, position) { if (position === undefined || position === StaveModifier.Position.BEGIN) { this.clef = clef; } else if (position === StaveModifier.Position.END) { this.endClef = clef; } this.addModifier(new Clef(clef, size, annotation), position); return this; } addEndClef(clef, size, annotation) { this.addClef(clef, size, annotation, StaveModifier.Position.END); return this; } addTimeSignature(timeSpec, customPadding, position) { this.addModifier(new TimeSignature(timeSpec, customPadding), position); return this; } addEndTimeSignature(timeSpec, customPadding) { this.addTimeSignature(timeSpec, customPadding, StaveModifier.Position.END); return this; } // Deprecated addTrebleGlyph() { this.addClef('treble'); return this; } getModifiers(position, category) { if (position === undefined && category === undefined) return this.modifiers; return this.modifiers.filter(modifier => (position === undefined || position === modifier.getPosition()) && (category === undefined || category === modifier.getCategory()) ); } sortByCategory(items, order) { for (let i = items.length - 1; i >= 0; i--) { for (let j = 0; j < i; j++) { if (order[items[j].getCategory()] > order[items[j + 1].getCategory()]) { const temp = items[j]; items[j] = items[j + 1]; items[j + 1] = temp; } } } } format() { const begBarline = this.modifiers[0]; const endBarline = this.modifiers[1]; const begModifiers = this.getModifiers(StaveModifier.Position.BEGIN); const endModifiers = this.getModifiers(StaveModifier.Position.END); this.sortByCategory(begModifiers, { barlines: 0, clefs: 1, keysignatures: 2, timesignatures: 3, }); this.sortByCategory(endModifiers, { timesignatures: 0, keysignatures: 1, barlines: 2, clefs: 3, }); if (begModifiers.length > 1 && begBarline.getType() === Barline.type.REPEAT_BEGIN) { begModifiers.push(begModifiers.splice(0, 1)[0]); begModifiers.splice(0, 0, new Barline(Barline.type.SINGLE)); } if (endModifiers.indexOf(endBarline) > 0) { endModifiers.splice(0, 0, new Barline(Barline.type.NONE)); } let width; let padding; let modifier; let offset = 0; let x = this.x; for (let i = 0; i < begModifiers.length; i++) { modifier = begModifiers[i]; padding = modifier.getPadding(i + offset); width = modifier.getWidth(); // VexFlowPatch: prevent modifier width being NaN and throwing Vexflow error if (isNaN(width)) { modifier.setWidth(10); width = 10; } x += padding; modifier.setX(x); x += width; if (padding + width === 0) offset--; } this.setStartX(x); // this.start_x = x; x = this.x + this.width; const widths = { left: 0, right: 0, paddingRight: 0, paddingLeft: 0, }; let lastBarlineIdx = 0; for (let i = 0; i < endModifiers.length; i++) { modifier = endModifiers[i]; lastBarlineIdx = (modifier.getCategory() === 'barlines') ? i : lastBarlineIdx; widths.right = 0; widths.left = 0; widths.paddingRight = 0; widths.paddingLeft = 0; const layoutMetrics = modifier.getLayoutMetrics(); if (layoutMetrics) { if (i !== 0) { widths.right = layoutMetrics.xMax || 0; widths.paddingRight = layoutMetrics.paddingRight || 0; } widths.left = (-layoutMetrics.xMin) || 0; widths.paddingLeft = layoutMetrics.paddingLeft || 0; if (i === endModifiers.length - 1) { widths.paddingLeft = 0; } } else { widths.paddingRight = modifier.getPadding(i - lastBarlineIdx) || 0; // can be null too if (i !== 0) { widths.right = modifier.getWidth() || 0; } if (i === 0) { widths.left = modifier.getWidth() || 0; } } x -= widths.paddingRight; x -= widths.right; modifier.setX(x); x -= widths.left; x -= widths.paddingLeft; } this.end_x = endModifiers.length === 1 ? this.x + this.width : x; this.formatted = true; } /** * All drawing functions below need the context to be set. */ draw() { this.checkContext(); this.setRendered(); if (!this.formatted) this.format(); const num_lines = this.options.num_lines; const width = this.width; const x = this.x; let y; // Render lines for (let line = 0; line < num_lines; line++) { y = this.getYForLine(line); this.applyStyle(); if (this.options.line_config[line].visible) { this.context.beginPath(); this.context.moveTo(x, y); this.context.lineTo(x + width, y); this.context.stroke(); } this.restoreStyle(); } // Draw the modifiers (bar lines, coda, segno, repeat brackets, etc.) for (let i = 0; i < this.modifiers.length; i++) { // Only draw modifier if it has a draw function if (typeof this.modifiers[i].draw === 'function') { this.modifiers[i].applyStyle(this.context); this.modifiers[i].draw(this, this.getModifierXShift(i)); this.modifiers[i].restoreStyle(this.context); } } // Render measure numbers if (this.measure > 0) { this.context.save(); this.context.setFont(this.font.family, this.font.size, this.font.weight); const text_width = this.context.measureText('' + this.measure).width; y = this.getYForTopText(0) + 3; this.context.fillText('' + this.measure, this.x - text_width / 2, y); this.context.restore(); } return this; } // Draw Simple barlines for backward compatability // Do not delete - draws the beginning bar of the stave drawVertical(x, isDouble) { this.drawVerticalFixed(this.x + x, isDouble); } drawVerticalFixed(x, isDouble) { this.checkContext(); const top_line = this.getYForLine(0); const bottom_line = this.getYForLine(this.options.num_lines - 1); if (isDouble) { this.context.fillRect(x - 3, top_line, 1, bottom_line - top_line + 1); } this.context.fillRect(x, top_line, 1, bottom_line - top_line + 1); } drawVerticalBar(x) { this.drawVerticalBarFixed(this.x + x, false); } drawVerticalBarFixed(x) { this.checkContext(); const top_line = this.getYForLine(0); const bottom_line = this.getYForLine(this.options.num_lines - 1); this.context.fillRect(x, top_line, 1, bottom_line - top_line + 1); } /** * Get the current configuration for the Stave. * @return {Array} An array of configuration objects. */ getConfigForLines() { return this.options.line_config; } /** * Configure properties of the lines in the Stave * @param line_number The index of the line to configure. * @param line_config An configuration object for the specified line. * @throws Vex.RERR "StaveConfigError" When the specified line number is out of * range of the number of lines specified in the constructor. */ setConfigForLine(line_number, line_config) { if (line_number >= this.options.num_lines || line_number < 0) { throw new Vex.RERR( 'StaveConfigError', 'The line number must be within the range of the number of lines in the Stave.' ); } if (line_config.visible === undefined) { throw new Vex.RERR( 'StaveConfigError', "The line configuration object is missing the 'visible' property." ); } if (typeof (line_config.visible) !== 'boolean') { throw new Vex.RERR( 'StaveConfigError', "The line configuration objects 'visible' property must be true or false." ); } this.options.line_config[line_number] = line_config; return this; } /** * Set the staff line configuration array for all of the lines at once. * @param lines_configuration An array of line configuration objects. These objects * are of the same format as the single one passed in to setLineConfiguration(). * The caller can set null for any line config entry if it is desired that the default be used * @throws Vex.RERR "StaveConfigError" When the lines_configuration array does not have * exactly the same number of elements as the num_lines configuration object set in * the constructor. */ setConfigForLines(lines_configuration) { if (lines_configuration.length !== this.options.num_lines) { throw new Vex.RERR( 'StaveConfigError', 'The length of the lines configuration array must match the number of lines in the Stave' ); } // Make sure the defaults are present in case an incomplete set of // configuration options were supplied. // eslint-disable-next-line for (const line_config in lines_configuration) { // Allow 'null' to be used if the caller just wants the default for a particular node. if (!lines_configuration[line_config]) { lines_configuration[line_config] = this.options.line_config[line_config]; } Vex.Merge(this.options.line_config[line_config], lines_configuration[line_config]); } this.options.line_config = lines_configuration; return this; } }
{ "content_hash": "e3b03f0a3a021b784231e3f7959c9a3c", "timestamp": "", "source": "github", "line_count": 712, "max_line_length": 98, "avg_line_length": 28.803370786516854, "alnum_prop": 0.6320460308172421, "repo_name": "opensheetmusicdisplay/opensheetmusicdisplay", "id": "e6f46488e78b15ddf0920093916510f90fc28d8d", "size": "20508", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/VexFlowPatch/src/stave.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "GLSL", "bytes": "1582" }, { "name": "JavaScript", "bytes": "279483" }, { "name": "Shell", "bytes": "8149" }, { "name": "TypeScript", "bytes": "1813375" } ], "symlink_target": "" }
=begin ASF-REST-Adapter Copyright 2010 Raymond Gao @ http://are4.us 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. =end #CallRemote module (methods) for the adapter puts ' loading asf_rest_call_rest_svr module' module CallRemote # instance method #class methods def self.included(base) class << base def call_rest_svr (verb, target, headers, data=nil) case verb when 'GET' return resp = HTTParty.get(target, :headers => headers) when 'POST' return resp = HTTParty.post(target, :body => data, :headers => headers) when 'DELETE' return resp = HTTParty.delete(target, :headers => headers) when 'PATCH' # TODO use Httpgeneric. when 'DEFINE' # TODO for creating a new SObject in Salesfore, e.g. rake when 'REMOVE' # TODO for deleting a new SObject in Salesfore, e.g. rake when 'MODIFY' # TODO for modifying a new SObject in Salesfore, e.g. rake end end end end end
{ "content_hash": "1141e9c95125d03703c074247808af70", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 81, "avg_line_length": 33.977777777777774, "alnum_prop": 0.6671026814911707, "repo_name": "raygao/asf-rest-adapter", "id": "9361437e078ad4fe4231357322cdb87092a33809", "size": "1529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Salesforce/rest/asf_rest_call_rest_svr.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6426" }, { "name": "Ruby", "bytes": "151991" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="apis" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>Facebook API Binding</title> <para> Spring Social Facebook's <interfacename>Facebook</interfacename> interface and its implementation, <classname>FacebookTemplate</classname> provide the operations needed to interact with Facebook on behalf of a user. Creating an instance of <classname>FacebookTemplate</classname> is as simple as constructing it by passing in an authorized access token to the constructor: </para> <programlisting language="java"><![CDATA[ String accessToken = "f8FX29g..."; // access token received from Facebook after OAuth authorization Facebook facebook = new FacebookTemplate(accessToken);]]> </programlisting> <para> In addition, <classname>FacebookTemplate</classname> has a default constructor that creates an instance without any OAuth credentials: </para> <programlisting language="java"><![CDATA[ Facebook facebook = new FacebookTemplate();]]> </programlisting> <para> When constructed with the default constructor, <classname>FacebookTemplate</classname> will allow a few simple operations that do not require authorization, such as retrieving a specific user's profile. Attempting other operations, such as posting a status update will fail with an <classname>MissingAuthorizationException</classname> being thrown. </para> <para> If you are using Spring Social's <ulink url="http://docs.spring.io/spring-social/docs/1.0.x/reference/html/serviceprovider.html">service provider framework</ulink>, you can get an instance of <interfacename>Facebook</interfacename> from a <interfacename>Connection</interfacename>. For example, the following snippet calls <methodname>getApi()</methodname> on a connection to retrieve a <interfacename>Facebook</interfacename>: </para> <programlisting language="java"><![CDATA[ Connection<Facebook> connection = connectionRepository.findPrimaryConnection(Facebook.class); Facebook facebook = connection != null ? connection.getApi() : new FacebookTemplate();]]> </programlisting> <para> Here, <interfacename>ConnectionRepository</interfacename> is being asked for the primary connection that the current user has with Facebook. If a connection to Facebook is found, a call to <methodname>getApi()</methodname> retrieves a <interfacename>Facebook</interfacename> instance that is configured with the connection details received when the connection was first established. If there is no connection, a default instance of <classname>FacebookTemplate</classname> is created. </para> <para> With a <interfacename>Facebook</interfacename> in hand, there are several ways you can use it to interact with Facebook on behalf of the user. Spring Social's Facebook API binding is divided into 9 sub-APIs exposes through the methods of <interfacename>Facebook</interfacename>: </para> <programlisting language="java"><![CDATA[ public interface Facebook extends GraphApi { CommentOperations commentOperations(); EventOperations eventOperations(); FeedOperations feedOperations(); FriendOperations friendOperations(); GroupOperations groupOperations(); LikeOperations likeOperations(); MediaOperations mediaOperations(); PlacesOperations placesOperations(); UserOperations userOperations(); }]]> </programlisting> <para> The sub-API interfaces returned from <interfacename>Facebook</interfacename>'s methods are described in <xref linkend="table-facebook-sub-apis" />. </para> <table xml:id="table-facebook-sub-apis"> <title>Facebook's Sub-APIs</title> <tgroup cols="2"> <colspec align="left" /> <colspec colnum="1" colname="col1" colwidth="2*"/> <colspec colnum="2" colname="col2" colwidth="2*"/> <thead> <row> <entry align="center">Sub-API Interface</entry> <entry align="center">Description</entry> </row> </thead> <tbody> <row> <entry>CommentOperations</entry> <entry>Add, delete, and read comments on Facebook objects.</entry> </row> <row> <entry>EventOperations</entry> <entry>Create and maintain events and RSVP to event invitations.</entry> </row> <row> <entry>FeedOperations</entry> <entry>Read and post to a Facebook wall.</entry> </row> <row> <entry>FriendOperations</entry> <entry>Retrieve a user's friends and maintain friend lists.</entry> </row> <row> <entry>GroupOperations</entry> <entry>Retrieve group details and members.</entry> </row> <row> <entry>LikeOperations</entry> <entry>Retrieve a user's interests and likes. Like and unlike objects.</entry> </row> <row> <entry>MediaOperations</entry> <entry>Maintain albums, photos, and videos.</entry> </row> <row> <entry>PlacesOperations</entry> <entry>Checkin to location in Facebook Places and retrieve places a user and their friends have checked into.</entry> </row> <row> <entry>UserOperations</entry> <entry>Retrieve user profile data and profile images.</entry> </row> </tbody> </tgroup> </table> <para> The following sections will give an overview of common tasks that can be performed via <interfacename>Facebook</interfacename> and its sub-APIs. For complete details on all of the operations available, refer to the JavaDoc. </para> <section id="facebook-getProfile"> <title>Retrieving a user's profile data</title> <para> You can retrieve a user's Facebook profile data using <interfacename>Facebook</interfacename>' <methodname>getUserProfile()</methodname> method: </para> <programlisting language="java"><![CDATA[ FacebookProfile profile = facebook.userOperations().getUserProfile();]]> </programlisting> <para> The <classname>FacebookProfile</classname> object will contain basic profile information about the authenticating user, including their first and last name and their Facebook ID. Depending on what authorization scope has been granted to the application, it may also include additional details about the user such as their email address, birthday, hometown, and religious and political affiliations. For example, <methodname>getBirthday()</methodname> will return the current user's birthday if the application has been granted "user_birthday" permission; null otherwise. Consult the JavaDoc for <classname>FacebookProfile</classname> for details on which permissions are required for each property. </para> <para> If all you need is the user's Facebook ID, you can call <methodname>getProfileId()</methodname> instead: </para> <programlisting language="java"><![CDATA[ String profileId = facebook.userOperations().getProfileId();]]> </programlisting> <para> Or if you want the user's Facebook URL, you can call <methodname>getProfileUrl()</methodname>: </para> <programlisting langauge="java"><![CDATA[ String profileUrl = facebook.userOperations().getProfileUrl();]]> </programlisting> </section> <section id="facebook-friends"> <title>Getting a user's Facebook friends</title> <para> An essential feature of Facebook and other social networks is creating a network of friends or contacts. You can access the user's list of Facebook friends by calling the <methodname>getFriendIds()</methodname> method from <interfacename>FriendOperations</interfacename>: </para> <programlisting language="java"><![CDATA[ List<String> friendIds = facebook.friendOperations().getFriendIds();]]> </programlisting> <para> This returns a list of Facebook IDs belonging to the current user's list of friends. This is just a list of <classname>String</classname> IDs, so to retrieve an individual user's profile data, you can turn around and call the <methodname>getUserProfile()</methodname>, passing in one of those IDs to retrieve the profile data for an individual user: </para> <programlisting language="java"><![CDATA[ FacebookProfile firstFriend = facebook.userOperations().getUserProfile(friendIds.get(0));]]> </programlisting> <para> Or you can get a list of user's friends as <classname>FacebookProfile</classname>s by calling <methodname>getFriendProfiles()</methodname>: </para> <programlisting language="java"><![CDATA[ List<FacebookProfile> friends = facebook.friendOperations().getFriendProfiles();]]> </programlisting> <para> Facebook also enables users to organize their friends into friend lists. To retrieve a list of the authenticating user's friend lists, call <methodname>getFriendLists()</methodname> with no arguments: </para> <programlisting language="java"><![CDATA[ List<Reference> friends = facebook.friendOperations().getFriendLists();]]> </programlisting> <para> You can also retrieve a list of friend lists for a specific user by passing the user ID (or an alias) to <methodname>getFriendLists()</methodname>: </para> <programlisting language="java"><![CDATA[ List<Reference> friends = facebook.friendOperations().getFriendLists("habuma");]]> </programlisting> <para> <methodname>getFriendLists()</methodname> returns a list of <classname>Reference</classname> objects that carry the ID and name of each friend list. </para> <para> To retieve a list of friends who are members of a specific friend list call <methodname>getFriendListMembers()</methodname>, passing in the ID of the friend list: </para> <programlisting language="java"><![CDATA[ List<Reference> friends = facebook.friendOperations().getFriendListMembers("193839228");]]> </programlisting> <para> <interfacename>FriendOperations</interfacename> also support management of friend lists. For example, the <methodname>createFriendList()</methodname> method will create a new friend list for the user: </para> <programlisting language="java"><![CDATA[ Reference collegeFriends = facebook.friendOperations().createFriendList("College Buddies");]]> </programlisting> <para> <methodname>createFriendList()</methodname> returns a <classname>Reference</classname> to the newly created friend list. </para> <para> To add a friend to the friend list, call <methodname>addToFriendList()</methodname>: </para> <programlisting language="java"><![CDATA[ facebook.friendOperations().addToFriendList(collegeFriends.getId(), "527631174");]]> </programlisting> <para> <methodname>addToFriendList()</methodname> takes two arguments: The ID of the friend list and the ID (or alias) of a friend to add to the list. </para> <para> In a similar fashion, you may remove a friend from a list by calling <methodname>removeFromFriendList()</methodname>: </para> <programlisting language="java"><![CDATA[ facebook.friendOperations().removeFromFriendList(collegeFriends.getId(), "527631174");]]> </programlisting> </section> <section id="facebook-status"> <title>Posting to and reading feeds</title> <para> To post a message to the user's Facebook wall, call <interfacename>FeedOperations</interfacename>' <methodname>updateStatus()</methodname> method, passing in the message to be posted: </para> <programlisting language="java"><![CDATA[ facebook.feedOperations().updateStatus("I'm trying out Spring Social!");]]> </programlisting> <para> If you'd like to attach a link to the status message, you can do so by passing in a <classname>FacebookLink</classname> object along with the message: </para> <programlisting language="java"><![CDATA[ FacebookLink link = new FacebookLink("http://www.springsource.org/spring-social", "Spring Social", "The Spring Social Project", "Spring Social is an extension to Spring to enable applications to connect with service providers."); facebook.feedOperations().postLink("I'm trying out Spring Social!", link);]]> </programlisting> <para> When constructing the <classname>FacebookLink</classname> object, the first parameter is the link's URL, the second parameter is the name of the link, the third parameter is a caption, and the fourth is a description of the link. </para> <para> If you want to read posts from a user's feed, <interfacename>FeedOperations</interfacename> has several methods to choose from. The <methodname>getFeed()</methodname> method retrieves recent posts to a user's wall. When called with no parameters, it retrieves posts from the authenticating user's wall: </para> <programlisting language="java"><![CDATA[ List<Post> feed = facebook.feedOperations().getFeed();]]> </programlisting> <para> Or you can read a specific user's wall by passing their Facebook ID to <methodname>getFeed()</methodname>: </para> <programlisting language="java"><![CDATA[ List<Post> feed = facebook.feedOperations().getFeed("habuma");]]> </programlisting> <para> In any event, the <methodname>getFeed()</methodname> method returns a list of <classname>Post</classname> objects. The <classname>Post</classname> class has six subtypes to represent different kinds of posts: </para> <itemizedlist> <listitem><para><classname>CheckinPost</classname> - Reports a user's checkin in Facebook Places.</para></listitem> <listitem><para><classname>LinkPost</classname> - Shares a link the user has posted.</para></listitem> <listitem><para><classname>NotePost</classname> - Publicizes a note that the user has written.</para></listitem> <listitem><para><classname>PhotoPost</classname> - Announces a photo that the user has uploaded.</para></listitem> <listitem><para><classname>StatusPost</classname> - A simple status.</para></listitem> <listitem><para><classname>VideoPost</classname> - Announces a video that the user has uploaded.</para></listitem> </itemizedlist> <para> The <classname>Post</classname>'s <methodname>getType()</methodname> method identifies the type of <classname>Post</classname>. </para> </section> </chapter>
{ "content_hash": "f2f5fc3f983ac7bf3f49f6ddaf2a766b", "timestamp": "", "source": "github", "line_count": 329, "max_line_length": 284, "avg_line_length": 42.84498480243161, "alnum_prop": 0.7338961407491487, "repo_name": "wilkinsona/spring-social-facebook", "id": "72b6eb3c6f6422e123f0e04a71d9880423784c7d", "size": "14096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/reference/docbook/api.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9962" }, { "name": "Groovy", "bytes": "14258" }, { "name": "Java", "bytes": "826817" }, { "name": "Shell", "bytes": "7484" }, { "name": "XSLT", "bytes": "31599" } ], "symlink_target": "" }
package io.sqooba.oss.timeseries.immutable import io.sqooba.oss.timeseries.TimeSeriesTestBench import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec class ColumnTimeSeriesSpec extends AnyFlatSpec with Matchers with TimeSeriesTestBench { "A ColumnTimeSeries" should behave like nonEmptyNonSingletonDoubleTimeSeries( ColumnTimeSeries.ofOrderedEntriesSafe[Double](_) ) it should behave like nonEmptyNonSingletonGenericTimeSeries( ColumnTimeSeries.ofOrderedEntriesSafe[String](_) ) it should behave like nonEmptyNonSingletonDoubleTimeSeriesWithCompression( ColumnTimeSeries.ofOrderedEntriesSafe[Double](_) ) }
{ "content_hash": "cb04ed1146c15f022977392cbe30048a", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 87, "avg_line_length": 34.65, "alnum_prop": 0.8037518037518038, "repo_name": "Shastick/tslib", "id": "29d83b673075ea12edb6411911a0d6d4a94eafa6", "size": "693", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/scala/io/sqooba/oss/timeseries/immutable/ColumnTimeSeriesSpec.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "69421" } ], "symlink_target": "" }
import sys import itk from distutils.version import StrictVersion as VS if VS(itk.Version.GetITKVersion()) < VS("4.9.0"): print("ITK 4.9.0 is required.") sys.exit(1) if len(sys.argv) != 6: print( "Usage: " + sys.argv[0] + " <fixedImageFile> <movingImageFile> " "<outputImagefile> <differenceImageAfter> <differenceImageBefore>" ) sys.exit(1) fixedImageFile = sys.argv[1] movingImageFile = sys.argv[2] outputImageFile = sys.argv[3] differenceImageAfterFile = sys.argv[4] differenceImageBeforeFile = sys.argv[5] PixelType = itk.ctype("float") fixedImage = itk.imread(fixedImageFile, PixelType) movingImage = itk.imread(movingImageFile, PixelType) Dimension = fixedImage.GetImageDimension() FixedImageType = itk.Image[PixelType, Dimension] MovingImageType = itk.Image[PixelType, Dimension] TransformType = itk.TranslationTransform[itk.D, Dimension] initialTransform = TransformType.New() optimizer = itk.RegularStepGradientDescentOptimizerv4.New( LearningRate=4, MinimumStepLength=0.001, RelaxationFactor=0.5, NumberOfIterations=200, ) metric = itk.MeanSquaresImageToImageMetricv4[FixedImageType, MovingImageType].New() registration = itk.ImageRegistrationMethodv4.New( FixedImage=fixedImage, MovingImage=movingImage, Metric=metric, Optimizer=optimizer, InitialTransform=initialTransform, ) movingInitialTransform = TransformType.New() initialParameters = movingInitialTransform.GetParameters() initialParameters[0] = 0 initialParameters[1] = 0 movingInitialTransform.SetParameters(initialParameters) registration.SetMovingInitialTransform(movingInitialTransform) identityTransform = TransformType.New() identityTransform.SetIdentity() registration.SetFixedInitialTransform(identityTransform) registration.SetNumberOfLevels(1) registration.SetSmoothingSigmasPerLevel([0]) registration.SetShrinkFactorsPerLevel([1]) registration.Update() transform = registration.GetTransform() finalParameters = transform.GetParameters() translationAlongX = finalParameters.GetElement(0) translationAlongY = finalParameters.GetElement(1) numberOfIterations = optimizer.GetCurrentIteration() bestValue = optimizer.GetValue() print("Result = ") print(" Translation X = " + str(translationAlongX)) print(" Translation Y = " + str(translationAlongY)) print(" Iterations = " + str(numberOfIterations)) print(" Metric value = " + str(bestValue)) CompositeTransformType = itk.CompositeTransform[itk.D, Dimension] outputCompositeTransform = CompositeTransformType.New() outputCompositeTransform.AddTransform(movingInitialTransform) outputCompositeTransform.AddTransform(registration.GetModifiableTransform()) resampler = itk.ResampleImageFilter.New( Input=movingImage, Transform=outputCompositeTransform, UseReferenceImage=True, ReferenceImage=fixedImage, ) resampler.SetDefaultPixelValue(100) OutputPixelType = itk.ctype("unsigned char") OutputImageType = itk.Image[OutputPixelType, Dimension] caster = itk.CastImageFilter[FixedImageType, OutputImageType].New(Input=resampler) writer = itk.ImageFileWriter.New(Input=caster, FileName=outputImageFile) writer.SetFileName(outputImageFile) writer.Update() difference = itk.SubtractImageFilter.New(Input1=fixedImage, Input2=resampler) intensityRescaler = itk.RescaleIntensityImageFilter[ FixedImageType, OutputImageType ].New( Input=difference, OutputMinimum=itk.NumericTraits[OutputPixelType].min(), OutputMaximum=itk.NumericTraits[OutputPixelType].max(), ) resampler.SetDefaultPixelValue(1) writer.SetInput(intensityRescaler.GetOutput()) writer.SetFileName(differenceImageAfterFile) writer.Update() resampler.SetTransform(identityTransform) writer.SetFileName(differenceImageBeforeFile) writer.Update()
{ "content_hash": "9e3883ef19b242e0abe39762f06676bc", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 83, "avg_line_length": 30.5609756097561, "alnum_prop": 0.7986166533652567, "repo_name": "InsightSoftwareConsortium/ITKExamples", "id": "a13327b2284185018817be6ae07b01e2b74fbfd5", "size": "4357", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Registration/Common/Perform2DTranslationRegistrationWithMeanSquares/Code.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1345317" }, { "name": "CMake", "bytes": "468162" }, { "name": "CSS", "bytes": "2087" }, { "name": "HTML", "bytes": "8446" }, { "name": "JavaScript", "bytes": "4743" }, { "name": "Python", "bytes": "325825" }, { "name": "Shell", "bytes": "37497" } ], "symlink_target": "" }
int main(int, char**) { constexpr std::byte b1{static_cast<std::byte>(1)}; constexpr std::byte b3{static_cast<std::byte>(3)}; static_assert(noexcept(std::to_integer<int>(b1)), "" ); static_assert(std::is_same<int, decltype(std::to_integer<int>(b1))>::value, "" ); static_assert(std::is_same<long, decltype(std::to_integer<long>(b1))>::value, "" ); static_assert(std::is_same<unsigned short, decltype(std::to_integer<unsigned short>(b1))>::value, "" ); static_assert(std::to_integer<int>(b1) == 1, ""); static_assert(std::to_integer<int>(b3) == 3, ""); return 0; }
{ "content_hash": "4e66207ac0aee797e141fedda98550e4", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 107, "avg_line_length": 42.92857142857143, "alnum_prop": 0.6222961730449251, "repo_name": "endlessm/chromium-browser", "id": "ef1779e1b45fed6949d95a966ca14f8db855ced8", "size": "1283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/llvm/libcxx/test/std/language.support/support.types/byteops/to_integer.pass.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import { isLocalLink } from "../is-local-link" describe(`isLocalLink`, () => { it(`returns true on relative link`, () => { expect(isLocalLink(`/docs/some-doc`)).toBe(true) }) it(`returns false on absolute link`, () => { expect(isLocalLink(`https://www.gatsbyjs.com`)).toBe(false) }) it(`returns undefined if input is undefined or not a string`, () => { expect(isLocalLink(undefined)).toBeUndefined() expect(isLocalLink(-1)).toBeUndefined() }) // TODO(v5): Unskip Tests it.skip(`throws TypeError if input is undefined`, () => { expect(() => isLocalLink(undefined)).toThrowError( `Expected a \`string\`, got \`undefined\`` ) }) it.skip(`throws TypeError if input is not a string`, () => { expect(() => isLocalLink(-1)).toThrowError( `Expected a \`string\`, got \`number\`` ) }) })
{ "content_hash": "2e49e914fd6a4a9ed7101af091d3e49c", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 71, "avg_line_length": 33.84, "alnum_prop": 0.6146572104018913, "repo_name": "gatsbyjs/gatsby", "id": "79a52ae5fa53cd90cf0ce17c0d99ae8b93eecb01", "size": "846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/gatsby-link/src/__tests__/is-local-link.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "93774" }, { "name": "Dockerfile", "bytes": "2751" }, { "name": "EJS", "bytes": "461" }, { "name": "HTML", "bytes": "62227" }, { "name": "JavaScript", "bytes": "5243904" }, { "name": "Less", "bytes": "218" }, { "name": "PHP", "bytes": "2010" }, { "name": "Python", "bytes": "281" }, { "name": "SCSS", "bytes": "218" }, { "name": "Shell", "bytes": "10621" }, { "name": "Stylus", "bytes": "206" }, { "name": "TypeScript", "bytes": "3099577" } ], "symlink_target": "" }
In this lesson you will learn about the basic data structures in R and how you can create, modify, access and combine them. A very useful mantra while approaching the R language is concisely summarized in this quote by John Chambers > To understand computations in R, two slogans are helpful: <br/> > 1. Everything that exists is an object. <br/> > 2. Everything that happens is a function call. ## Vectors Every object in R is effectively a `vector`. The simplest way to think about a vector is to picture it as a container of boxes. Each box holds an object. The boxes are ordered sequentially, and can optionally have names. <img src="figure/cats-in-boxes.png"></img> There are two types of vectors in R: 1. (Atomic) Vector 2. List An (atomic) vector, as the name suggests, consists of objects that are indivisible and of the same `type`. There are six atomic types in R: `logical`, `integer`, `double`, `complex`, `character` and `raw`. So a vector could consist of objects that belong to any one of these six types. __Create__ The simplest way to construct a vector is to use the `c` function to _combine_ a set of objects. ```r # vector of the `numeric` type x <- c(1, 2, 3, 4, 5) ``` You can use the `typeof` function to determine the `type` of object a vector contains ```r typeof(x) ## [1] "double" ``` You can also use `vector` to initialize a vector of a given `type` and `length` and then fill it up with objects. ```r x <- vector("character", 2) x[1] <- "A" x[2] <- "B" ``` For those of you coming from a more traditional programming language like `python` or `ruby`, it will be surprising to note that R does not have the concept of a `scalar`. So, an assignment like `x <- 1` is still creating a vector, but of length one. __Access__ While analysing data, we often need to access pieces of data stored inside a data structure. In this section we will learn how to access the objects stored in a vector. To keep things interesting, let me create a vector of cats ```r x <- c(kelli = "girl", tyson = "boy", abbie = "girl", luke = "boy", rufus = "boy", sussy = "girl", misha = "girl" ) ``` Now suppose I want to call out all the girls. There are a number of ways I could do it. __Position__ First, I could use the __position__ of the boxes to identify the cats I want to call out, ```r x[c(1, 3, 6, 7)] ## kelli abbie sussy misha ## "girl" "girl" "girl" "girl" ``` or the cats I DON'T want to call out. ```r x[-c(2, 4, 5)] ## kelli abbie sussy misha ## "girl" "girl" "girl" "girl" ``` The minus sign in this case drops the cats in boxes 2, 4 and 5, leaving only the ones we want to call out. > This might seem confusing to those of you coming from Python, where x[-2] refers to the 2nd element from the end, whereas in R, it refers to all but the 2nd element. __Name__ Second, I could use the __names__ of the cats I want to call out. ```r x[c("kelli", "abbie", "sussy", "misha")] ## kelli abbie sussy misha ## "girl" "girl" "girl" "girl" ``` __Logical__ Yet another way to do this is to create a yes/no sequence to indicate which cats I want to call out (T stands for TRUE and F for FALSE in R) ```r x[c(T, F, T, F, F, T, T)] ## kelli abbie sussy misha ## "girl" "girl" "girl" "girl" ``` We can use this approach to simplify our code to access all girl cats, and write ```r x[x == "girl"] ## kelli abbie sussy misha ## "girl" "girl" "girl" "girl" ``` Sticking with the __named-cats-in-numbered boxes__ example,
{ "content_hash": "0e9317326df33ffc0c2a3fcd5e493caa", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 285, "avg_line_length": 24.921985815602838, "alnum_prop": 0.6818440523619806, "repo_name": "ramnathv/swc-nw-dataviz", "id": "c7f3335194ecbb99a3cd9417f3693640005f3ebf", "size": "3536", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "learn/data_structures.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1118" }, { "name": "JavaScript", "bytes": "2052" } ], "symlink_target": "" }
package org.hl7.fhir.instance.model.valuesets; // Generated on Tue, Sep 1, 2015 19:08-0400 for FHIR v1.0.0 public enum OrganizationType { /** * An organization that provides healthcare services */ PROV, /** * A department or ward within a hospital (Generally is not applicable to top level organizations) */ DEPT, /** * An organizational team is usualy a grouping of practitioners that perform a specific function within an organization (which could be a top level organization, or a department) */ TEAM, /** * A political body, often used when including organization records for government bodies such as a Federal Government, State or Local Government */ GOVT, /** * A company that provides insurance to its subscribers that may include healthcare related policies */ INS, /** * An educational institution that provides education or research facilitites */ EDU, /** * An organization that is identified as a part of a religeous institution */ RELI, /** * An organization that is identified as a Pharmaceutical/Clinical Research Sponsor */ CRS, /** * An un-incorporated community group */ CG, /** * An organization that is a registered business or corporation but not identified by other types */ BUS, /** * Other type of organization not already specified */ OTHER, /** * added to help the parsers */ NULL; public static OrganizationType fromCode(String codeString) throws Exception { if (codeString == null || "".equals(codeString)) return null; if ("prov".equals(codeString)) return PROV; if ("dept".equals(codeString)) return DEPT; if ("team".equals(codeString)) return TEAM; if ("govt".equals(codeString)) return GOVT; if ("ins".equals(codeString)) return INS; if ("edu".equals(codeString)) return EDU; if ("reli".equals(codeString)) return RELI; if ("crs".equals(codeString)) return CRS; if ("cg".equals(codeString)) return CG; if ("bus".equals(codeString)) return BUS; if ("other".equals(codeString)) return OTHER; throw new Exception("Unknown OrganizationType code '"+codeString+"'"); } public String toCode() { switch (this) { case PROV: return "prov"; case DEPT: return "dept"; case TEAM: return "team"; case GOVT: return "govt"; case INS: return "ins"; case EDU: return "edu"; case RELI: return "reli"; case CRS: return "crs"; case CG: return "cg"; case BUS: return "bus"; case OTHER: return "other"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/organization-type"; } public String getDefinition() { switch (this) { case PROV: return "An organization that provides healthcare services"; case DEPT: return "A department or ward within a hospital (Generally is not applicable to top level organizations)"; case TEAM: return "An organizational team is usualy a grouping of practitioners that perform a specific function within an organization (which could be a top level organization, or a department)"; case GOVT: return "A political body, often used when including organization records for government bodies such as a Federal Government, State or Local Government"; case INS: return "A company that provides insurance to its subscribers that may include healthcare related policies"; case EDU: return "An educational institution that provides education or research facilitites"; case RELI: return "An organization that is identified as a part of a religeous institution"; case CRS: return "An organization that is identified as a Pharmaceutical/Clinical Research Sponsor"; case CG: return "An un-incorporated community group"; case BUS: return "An organization that is a registered business or corporation but not identified by other types"; case OTHER: return "Other type of organization not already specified"; default: return "?"; } } public String getDisplay() { switch (this) { case PROV: return "Healthcare Provider"; case DEPT: return "Hospital Department"; case TEAM: return "Organizational team"; case GOVT: return "Government"; case INS: return "Insurance Company"; case EDU: return "Educational Institute"; case RELI: return "Religious Institution"; case CRS: return "Clinical Research Sponsor"; case CG: return "Community Group"; case BUS: return "Non-Healthcare Business or Corporation"; case OTHER: return "Other"; default: return "?"; } } }
{ "content_hash": "8b71b0d47e09bba325b4e35b2f0b2817", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 208, "avg_line_length": 40.15827338129496, "alnum_prop": 0.5714797563597277, "repo_name": "dhf0820/hapi-fhir-1.2", "id": "835efaac444a74b192a7ad7e23f0830a9b255a64", "size": "7159", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/valuesets/OrganizationType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3861" }, { "name": "CSS", "bytes": "228150" }, { "name": "Eagle", "bytes": "1134813" }, { "name": "HTML", "bytes": "189422" }, { "name": "Java", "bytes": "20255767" }, { "name": "JavaScript", "bytes": "23709" }, { "name": "KiCad", "bytes": "12030" }, { "name": "Ruby", "bytes": "238370" }, { "name": "Shell", "bytes": "15086" } ], "symlink_target": "" }
A jQuery plugin for neatly splitting tables / other content across pages when printing ## Usage & defaults The print splitter can optionally take values for different sized pages and margins. Defaults to A4. ``` $(target-element).printSplitter({ paperSize: { width: 11.692, // Width in inches, defaults A4 height: 8.267 // Height in inches, defaults A4 }, margins: { // All in inches top: 0.39, left: 0.39, right: 0.39, bottom: 0.39 }, threshold: 30, // Extra threshold when calculating the break point portraitMode: false, // Wether to print in portrait mode headerElements: [], // Array of extra elements to include in the calculations on the first page of printing. Useful for table key / headings etc callback: function() {} // A callback to run when the print dialog is closed }); ```
{ "content_hash": "3bd6a1c1e64f6a84da8ac45fa902b9a6", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 145, "avg_line_length": 33.875, "alnum_prop": 0.7170971709717097, "repo_name": "Philky/PrintSplitter", "id": "a73dc3b2e03f336e13044dd2a7460dae7cc9c4ee", "size": "837", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4169" } ], "symlink_target": "" }
Package ring contains tools for building and using a consistent hashing ring with replicas, automatic partitioning (ring ranges), and keeping replicas of the same partitions in as distinct tiered nodes as possible (tiers might be devices, servers, cabinets, rooms, data centers, geographical regions, etc.) It also contains tools for using a ring as a messaging hub, easing communication between nodes in the ring. [API Documentation](http://godoc.org/github.com/gholt/ring) This is the latest development area for the package. Eventually a stable version of the package will be established but, for now, all things about this package are subject to change. > Copyright See AUTHORS. All rights reserved. > Use of this source code is governed by a BSD-style > license that can be found in the LICENSE file.
{ "content_hash": "82e596d249c922f1dd27749a9653c02b", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 76, "avg_line_length": 48, "alnum_prop": 0.7892156862745098, "repo_name": "creiht/ring", "id": "76859f9b43fb4f91d8646d606db015a8b6ec5656", "size": "850", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Go", "bytes": "158697" } ], "symlink_target": "" }
<LinearLayout android:id="@+id/main_layout" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/grey_100" android:orientation="vertical" android:weightSum="4"> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="3" android:gravity="center_horizontal" android:orientation="vertical"> <TextView android:id="@+id/title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="@dimen/title_bottom_margin" android:text="@string/facebook_title_text" android:theme="@style/ThemeOverlay.MyTitleText"/> <TextView android:id="@+id/status" style="@style/ThemeOverlay.MyTextDetail" android:text="@string/logged_out"/> <TextView android:id="@+id/detail" style="@style/ThemeOverlay.MyTextDetail" tools:text="SMP User ID: 123456789abc"/> <Button android:id="@+id/logged_in_view_profile" style="@style/Widget.AppCompat.Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/view_profile" android:visibility="gone"/> </LinearLayout> <RelativeLayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@color/grey_300"> <com.facebook.login.widget.LoginButton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_gravity="center_horizontal" android:layout_marginBottom="30dp" android:layout_marginTop="30dp" android:visibility="visible" tools:visibility="gone"/> <Button android:id="@+id/sign_out_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/sign_out" android:theme="@style/ThemeOverlay.MyDarkButton" android:visibility="gone"/> </RelativeLayout> </LinearLayout>
{ "content_hash": "0eb62b282bf8330665b79f76c64788bb", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 72, "avg_line_length": 36.35616438356164, "alnum_prop": 0.5945742275810098, "repo_name": "sessionm/android-mmc-example", "id": "9aad896c1703a3e743f28b9b603a3655429b07bc", "size": "2654", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "SMP_Auth/src/main/res/layout/activity_facebook.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "400730" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using CrudGridExample.Data; using CrudGridExample.Models; using CrudGridExample.Models.CrudGridModels; namespace CrudGridExample.Controllers { class PersonFullName : Person { public string FullName { get; set; } } public class CustomController : PersonController { [HttpGet] public MetadataItem GetMetadata([FromUri] FilterModel filter) { try { var metadata = new MetadataItem(); var fields = new List<Field>() { new Field() { Name = "FirstName", Caption = "First Name", Datatype = typeof (string).Name, Order = 1 }, new Field() { Name = "LastName", Caption = "Last Name", Datatype = typeof (string).Name, Order = 2 }, new Field() { Name = "FullName", Caption = "Full Name", Datatype = typeof (string).Name, Editable = false, Order = 0 } }; metadata = new MetadataItem { Name = ControllerName, Key = "FirstName", Fields = fields, RowCount = DataSources.Persons.Count }; return metadata; } catch (Exception) { return null; } } [HttpGet] public IEnumerable GetWithFullname([FromUri] FilterModel filter) { var customObjectCollection = DataSources.Persons.AsQueryable() .Skip(filter.SkipCount) .Take(filter.Size) .Select(x => new PersonFullName { FirstName = x.FirstName, LastName = x.LastName, FullName = x.FirstName + " " + x.LastName }); if (!string.IsNullOrEmpty(filter.SortName)) { customObjectCollection = filter.SortOrder == FilterModel.SortingOrder.Desc ? customObjectCollection.OrderByDescending(filter.GetSortingExpression<PersonFullName, string>()) : customObjectCollection.OrderBy(filter.GetSortingExpression<PersonFullName, string>()); } return customObjectCollection.ToList(); } } }
{ "content_hash": "189347432861872b923780ed61c6764a", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 117, "avg_line_length": 36.31578947368421, "alnum_prop": 0.3855072463768116, "repo_name": "pjuarezd/crudgrid-ng", "id": "0e0edd77063330c6e4eccb0fb950469ee4f2f940", "size": "3452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CrudGridExample/Controllers/CustomController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "C#", "bytes": "26237" }, { "name": "CSS", "bytes": "21511" }, { "name": "JavaScript", "bytes": "340727" } ], "symlink_target": "" }
package main import ( "bufio" "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net" "os" "os/exec" "path" "path/filepath" "regexp" "strconv" "strings" "sync" "syscall" "time" "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/testutil" icmd "github.com/docker/docker/pkg/testutil/cmd" units "github.com/docker/go-units" "github.com/docker/libnetwork/iptables" "github.com/docker/libtrust" "github.com/go-check/check" "github.com/kr/pty" ) // TestLegacyDaemonCommand test starting docker daemon using "deprecated" docker daemon // command. Remove this test when we remove this. func (s *DockerDaemonSuite) TestLegacyDaemonCommand(c *check.C) { cmd := exec.Command(dockerBinary, "daemon", "--storage-driver=vfs", "--debug") err := cmd.Start() c.Assert(err, checker.IsNil, check.Commentf("could not start daemon using 'docker daemon'")) c.Assert(cmd.Process.Kill(), checker.IsNil) } func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) { s.d.StartWithBusybox(c) cli.Docker( cli.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"), cli.Daemon(s.d), ).Assert(c, icmd.Success) cli.Docker( cli.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"), cli.Daemon(s.d), ).Assert(c, icmd.Success) testRun := func(m map[string]bool, prefix string) { var format string for cont, shouldRun := range m { out := cli.Docker(cli.Cmd("ps"), cli.Daemon(s.d)).Assert(c, icmd.Success).Combined() if shouldRun { format = "%scontainer %q is not running" } else { format = "%scontainer %q is running" } if shouldRun != strings.Contains(out, cont) { c.Fatalf(format, prefix, cont) } } } testRun(map[string]bool{"top1": true, "top2": true}, "") s.d.Restart(c) testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") } func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil { c.Fatal(err, out) } s.d.Restart(c) if _, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil { c.Fatal(err) } if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil { c.Fatal(err, out) } out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1") c.Assert(err, check.IsNil) if _, err := inspectMountPointJSON(out, "/foo"); err != nil { c.Fatalf("Expected volume to exist: /foo, error: %v\n", err) } } // #11008 func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "top1", "--restart", "always", "busybox:latest", "top") c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out)) out, err = s.d.Cmd("run", "-d", "--name", "top2", "--restart", "unless-stopped", "busybox:latest", "top") c.Assert(err, check.IsNil, check.Commentf("run top2: %v", out)) testRun := func(m map[string]bool, prefix string) { var format string for name, shouldRun := range m { out, err := s.d.Cmd("ps") c.Assert(err, check.IsNil, check.Commentf("run ps: %v", out)) if shouldRun { format = "%scontainer %q is not running" } else { format = "%scontainer %q is running" } c.Assert(strings.Contains(out, name), check.Equals, shouldRun, check.Commentf(format, prefix, name)) } } // both running testRun(map[string]bool{"top1": true, "top2": true}, "") out, err = s.d.Cmd("stop", "top1") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("stop", "top2") c.Assert(err, check.IsNil, check.Commentf(out)) // both stopped testRun(map[string]bool{"top1": false, "top2": false}, "") s.d.Restart(c) // restart=always running testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") out, err = s.d.Cmd("start", "top2") c.Assert(err, check.IsNil, check.Commentf("start top2: %v", out)) s.d.Restart(c) // both running testRun(map[string]bool{"top1": true, "top2": true}, "After second daemon restart: ") } func (s *DockerDaemonSuite) TestDaemonRestartOnFailure(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "test1", "--restart", "on-failure:3", "busybox:latest", "false") c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out)) // wait test1 to stop hostArgs := []string{"--host", s.d.Sock()} err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 10*time.Second, hostArgs...) c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not")) // record last start time out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) lastStartTime := out s.d.Restart(c) // test1 shouldn't restart at all err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 0, hostArgs...) c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not")) // make sure test1 isn't restarted when daemon restart // if "StartAt" time updates, means test1 was once restarted. out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) c.Assert(out, checker.Equals, lastStartTime, check.Commentf("test1 shouldn't start after daemon restarts")) } func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) { s.d.Start(c, "--iptables=false") } // Make sure we cannot shrink base device at daemon restart. func (s *DockerDaemonSuite) TestDaemonRestartWithInvalidBasesize(c *check.C) { testRequires(c, Devicemapper) s.d.Start(c) oldBasesizeBytes := s.d.GetBaseDeviceSize(c) var newBasesizeBytes int64 = 1073741824 //1GB in bytes if newBasesizeBytes < oldBasesizeBytes { err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes)) c.Assert(err, check.IsNil, check.Commentf("daemon should not have started as new base device size is less than existing base device size: %v", err)) } s.d.Stop(c) } // Make sure we can grow base device at daemon restart. func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *check.C) { testRequires(c, Devicemapper) s.d.Start(c) oldBasesizeBytes := s.d.GetBaseDeviceSize(c) var newBasesizeBytes int64 = 53687091200 //50GB in bytes if newBasesizeBytes < oldBasesizeBytes { c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes)))) } err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes)) c.Assert(err, check.IsNil, check.Commentf("we should have been able to start the daemon with increased base device size: %v", err)) basesizeAfterRestart := s.d.GetBaseDeviceSize(c) newBasesize, err := convertBasesize(newBasesizeBytes) c.Assert(err, check.IsNil, check.Commentf("Error in converting base device size: %v", err)) c.Assert(newBasesize, check.Equals, basesizeAfterRestart, check.Commentf("Basesize passed is not equal to Basesize set")) s.d.Stop(c) } func convertBasesize(basesizeBytes int64) (int64, error) { basesize := units.HumanSize(float64(basesizeBytes)) basesize = strings.Trim(basesize, " ")[:len(basesize)-3] basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64) if err != nil { return 0, err } return int64(basesizeFloat) * 1024 * 1024 * 1024, nil } // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and // no longer has an IP associated, we should gracefully handle that case and associate // an IP with it rather than fail daemon start func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) { // rather than depending on brctl commands to verify docker0 is created and up // let's start the daemon and stop it, and then make a modification to run the // actual test s.d.Start(c) s.d.Stop(c) // now we will remove the ip from docker0 and then try starting the daemon icmd.RunCommand("ip", "addr", "flush", "dev", "docker0").Assert(c, icmd.Success) if err := s.d.StartWithError(); err != nil { warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix" c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning) } } func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top: %s, %v", out, err) } ipTablesSearchString := "tcp dpt:80" // get output from iptables with container running verifyIPTablesContains(c, ipTablesSearchString) s.d.Stop(c) // get output from iptables after restart verifyIPTablesDoesNotContains(c, ipTablesSearchString) } func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top: %s, %v", out, err) } // get output from iptables with container running ipTablesSearchString := "tcp dpt:80" verifyIPTablesContains(c, ipTablesSearchString) s.d.Restart(c) // make sure the container is not running runningOut, err := s.d.Cmd("inspect", "--format={{.State.Running}}", "top") if err != nil { c.Fatalf("Could not inspect on container: %s, %v", runningOut, err) } if strings.TrimSpace(runningOut) != "true" { c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut)) } // get output from iptables after restart verifyIPTablesContains(c, ipTablesSearchString) } func verifyIPTablesContains(c *check.C, ipTablesSearchString string) { result := icmd.RunCommand("iptables", "-nvL") result.Assert(c, icmd.Success) if !strings.Contains(result.Combined(), ipTablesSearchString) { c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, result.Combined()) } } func verifyIPTablesDoesNotContains(c *check.C, ipTablesSearchString string) { result := icmd.RunCommand("iptables", "-nvL") result.Assert(c, icmd.Success) if strings.Contains(result.Combined(), ipTablesSearchString) { c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, result.Combined()) } } // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge // has the fe80::1 address and that a container is assigned a link-local address func (s *DockerDaemonSuite) TestDaemonIPv6Enabled(c *check.C) { testRequires(c, IPv6) setupV6(c) defer teardownV6(c) s.d.StartWithBusybox(c, "--ipv6") iface, err := net.InterfaceByName("docker0") if err != nil { c.Fatalf("Error getting docker0 interface: %v", err) } addrs, err := iface.Addrs() if err != nil { c.Fatalf("Error getting addresses for docker0 interface: %v", err) } var found bool expected := "fe80::1/64" for i := range addrs { if addrs[i].String() == expected { found = true break } } if !found { c.Fatalf("Bridge does not have an IPv6 Address") } if out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil { c.Fatalf("Could not run container: %s, %v", out, err) } out, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.LinkLocalIPv6Address}}'", "ipv6test") out = strings.Trim(out, " \r\n'") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } if ip := net.ParseIP(out); ip == nil { c.Fatalf("Container should have a link-local IPv6 address") } out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test") out = strings.Trim(out, " \r\n'") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } if ip := net.ParseIP(out); ip != nil { c.Fatalf("Container should not have a global IPv6 address: %v", out) } } // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR // that running containers are given a link-local and global IPv6 address func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) { // IPv6 setup is messing with local bridge address. testRequires(c, SameHostDaemon) // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with // ipv6 enabled deleteInterface(c, "docker0") s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64", "--default-gateway-v6=2001:db8:2::100") out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest") c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err)) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") out = strings.Trim(out, " \r\n'") c.Assert(err, checker.IsNil, check.Commentf(out)) ip := net.ParseIP(out) c.Assert(ip, checker.NotNil, check.Commentf("Container should have a global IPv6 address")) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.IPv6Gateway}}", "ipv6test") c.Assert(err, checker.IsNil, check.Commentf(out)) c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:2::100", check.Commentf("Container should have a global IPv6 gateway")) } // TestDaemonIPv6FixedCIDRAndMac checks that when the daemon is started with ipv6 fixed CIDR // the running containers are given an IPv6 address derived from the MAC address and the ipv6 fixed CIDR func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) { // IPv6 setup is messing with local bridge address. testRequires(c, SameHostDaemon) // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with // ipv6 enabled deleteInterface(c, "docker0") s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:1::/64") out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox") c.Assert(err, checker.IsNil) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") c.Assert(err, checker.IsNil) c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:1::aabb:ccdd:eeff") } func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) { c.Assert(s.d.StartWithError("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level")) } func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) { s.d.Start(c, "--log-level=debug") content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) { // we creating new daemons to create new logFile s.d.Start(c, "--log-level=fatal") content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) if strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) { s.d.Start(c, "-D") content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) { s.d.Start(c, "--debug") content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) { s.d.Start(c, "--debug", "--log-level=fatal") content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) { listeningPorts := [][]string{ {"0.0.0.0", "0.0.0.0", "5678"}, {"127.0.0.1", "127.0.0.1", "1234"}, {"localhost", "127.0.0.1", "1235"}, } cmdArgs := make([]string, 0, len(listeningPorts)*2) for _, hostDirective := range listeningPorts { cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2])) } s.d.StartWithBusybox(c, cmdArgs...) for _, hostDirective := range listeningPorts { output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true") if err == nil { c.Fatalf("Container should not start, expected port already allocated error: %q", output) } else if !strings.Contains(output, "port is already allocated") { c.Fatalf("Expected port is already allocated error: %q", output) } } } func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) { // TODO: skip or update for Windows daemon os.Remove("/etc/docker/key.json") s.d.Start(c) s.d.Stop(c) k, err := libtrust.LoadKeyFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error opening key file") } kid := k.KeyID() // Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF) if len(kid) != 59 { c.Fatalf("Bad key ID: %s", kid) } } func (s *DockerDaemonSuite) TestDaemonKeyMigration(c *check.C) { // TODO: skip or update for Windows daemon os.Remove("/etc/docker/key.json") k1, err := libtrust.GenerateECP256PrivateKey() if err != nil { c.Fatalf("Error generating private key: %s", err) } if err := os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".docker"), 0755); err != nil { c.Fatalf("Error creating .docker directory: %s", err) } if err := libtrust.SaveKey(filepath.Join(os.Getenv("HOME"), ".docker", "key.json"), k1); err != nil { c.Fatalf("Error saving private key: %s", err) } s.d.Start(c) s.d.Stop(c) k2, err := libtrust.LoadKeyFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error opening key file") } if k1.KeyID() != k2.KeyID() { c.Fatalf("Key not migrated") } } // GH#11320 - verify that the daemon exits on failure properly // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) { //attempt to start daemon with incorrect flags (we know -b and --bip conflict) if err := s.d.StartWithError("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil { //verify we got the right error if !strings.Contains(err.Error(), "Daemon exited") { c.Fatalf("Expected daemon not to start, got %v", err) } // look in the log and make sure we got the message that daemon is shutting down icmd.RunCommand("grep", "Error starting daemon", s.d.LogFileName()).Assert(c, icmd.Success) } else { //if we didn't get an error and the daemon is running, this is a failure c.Fatal("Conflicting options should cause the daemon to error out with a failure") } } func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) { d := s.d err := d.StartWithError("--bridge", "nosuchbridge") c.Assert(err, check.NotNil, check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail")) defer d.Restart(c) bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName) ipTablesSearchString := bridgeIPNet.String() icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ Out: ipTablesSearchString, }) _, err = d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top") c.Assert(err, check.IsNil) containerIP, err := d.FindContainerIP("ExtContainer") c.Assert(err, checker.IsNil) ip := net.ParseIP(containerIP) c.Assert(bridgeIPNet.Contains(ip), check.Equals, true, check.Commentf("Container IP-Address must be in the same subnet range : %s", containerIP)) } func (s *DockerDaemonSuite) TestDaemonBridgeNone(c *check.C) { // start with bridge none d := s.d d.StartWithBusybox(c, "--bridge", "none") defer d.Restart(c) // verify docker0 iface is not there icmd.RunCommand("ifconfig", "docker0").Assert(c, icmd.Expected{ ExitCode: 1, Error: "exit status 1", Err: "Device not found", }) // verify default "bridge" network is not there out, err := d.Cmd("network", "inspect", "bridge") c.Assert(err, check.NotNil, check.Commentf("\"bridge\" network should not be present if daemon started with --bridge=none")) c.Assert(strings.Contains(out, "No such network"), check.Equals, true) } func createInterface(c *check.C, ifType string, ifName string, ipNet string) { icmd.RunCommand("ip", "link", "add", "name", ifName, "type", ifType).Assert(c, icmd.Success) icmd.RunCommand("ifconfig", ifName, ipNet, "up").Assert(c, icmd.Success) } func deleteInterface(c *check.C, ifName string) { icmd.RunCommand("ip", "link", "delete", ifName).Assert(c, icmd.Success) icmd.RunCommand("iptables", "-t", "nat", "--flush").Assert(c, icmd.Success) icmd.RunCommand("iptables", "--flush").Assert(c, icmd.Success) } func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) { // TestDaemonBridgeIP Steps // 1. Delete the existing docker0 Bridge // 2. Set --bip daemon configuration and start the new Docker Daemon // 3. Check if the bip config has taken effect using ifconfig and iptables commands // 4. Launch a Container and make sure the IP-Address is in the expected subnet // 5. Delete the docker0 Bridge // 6. Restart the Docker Daemon (via deferred action) // This Restart takes care of bringing docker0 interface back to auto-assigned IP defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIP := "192.169.1.1/24" ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) d.StartWithBusybox(c, "--bip", bridgeIP) defer d.Restart(c) ifconfigSearchString := ip.String() icmd.RunCommand("ifconfig", defaultNetworkBridge).Assert(c, icmd.Expected{ Out: ifconfigSearchString, }) ipTablesSearchString := bridgeIPNet.String() icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ Out: ipTablesSearchString, }) _, err := d.Cmd("run", "-d", "--name", "test", "busybox", "top") c.Assert(err, check.IsNil) containerIP, err := d.FindContainerIP("test") c.Assert(err, checker.IsNil) ip = net.ParseIP(containerIP) c.Assert(bridgeIPNet.Contains(ip), check.Equals, true, check.Commentf("Container IP-Address must be in the same subnet range : %s", containerIP)) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *check.C) { s.d.Start(c) defer s.d.Restart(c) s.d.Stop(c) // now we will change the docker0's IP and then try starting the daemon bridgeIP := "192.169.100.1/24" _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) icmd.RunCommand("ifconfig", "docker0", bridgeIP).Assert(c, icmd.Success) s.d.Start(c, "--bip", bridgeIP) //check if the iptables contains new bridgeIP MASQUERADE rule ipTablesSearchString := bridgeIPNet.String() icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ Out: ipTablesSearchString, }) } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) { d := s.d bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) args := []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"} d.StartWithBusybox(c, args...) defer d.Restart(c) for i := 0; i < 4; i++ { cName := "Container" + strconv.Itoa(i) out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top") if err != nil { c.Assert(strings.Contains(out, "no available IPv4 addresses"), check.Equals, true, check.Commentf("Could not run a Container : %s %s", err.Error(), out)) } } } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *check.C) { d := s.d bridgeName := "external-bridge" bridgeIP := "10.2.2.1/16" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bip", bridgeIP, "--fixed-cidr", "10.2.2.0/24") defer s.d.Restart(c) out, err := d.Cmd("run", "-d", "--name", "bb", "busybox", "top") c.Assert(err, checker.IsNil, check.Commentf(out)) defer d.Cmd("stop", "bb") out, err = d.Cmd("exec", "bb", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") c.Assert(out, checker.Equals, "10.2.2.0\n") out, err = d.Cmd("run", "--rm", "busybox", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") c.Assert(err, checker.IsNil, check.Commentf(out)) c.Assert(out, checker.Equals, "10.2.2.2\n") } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *check.C) { d := s.d bridgeName := "external-bridge" bridgeIP := "172.27.42.1/16" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName, "--fixed-cidr", bridgeIP) defer s.d.Restart(c) out, err := d.Cmd("run", "-d", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf(out)) cid1 := strings.TrimSpace(out) defer d.Cmd("stop", cid1) } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *check.C) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIP := "192.169.1.1" bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP) d.StartWithBusybox(c, "--bip", bridgeIPNet) defer d.Restart(c) expectedMessage := fmt.Sprintf("default via %s dev", bridgeIP) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") c.Assert(err, checker.IsNil) c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, check.Commentf("Implicit default gateway should be bridge IP %s, but default route was '%s'", bridgeIP, strings.TrimSpace(out))) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *check.C) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIP := "192.169.1.1" bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP) gatewayIP := "192.169.1.254" d.StartWithBusybox(c, "--bip", bridgeIPNet, "--default-gateway", gatewayIP) defer d.Restart(c) expectedMessage := fmt.Sprintf("default via %s dev", gatewayIP) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") c.Assert(err, checker.IsNil) c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, check.Commentf("Explicit default gateway should be %s, but default route was '%s'", gatewayIP, strings.TrimSpace(out))) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4ExplicitOutsideContainerSubnet(c *check.C) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) // Program a custom default gateway outside of the container subnet, daemon should accept it and start s.d.StartWithBusybox(c, "--bip", "172.16.0.10/16", "--fixed-cidr", "172.16.1.0/24", "--default-gateway", "172.16.0.254") deleteInterface(c, defaultNetworkBridge) s.d.Restart(c) } func (s *DockerDaemonSuite) TestDaemonDefaultNetworkInvalidClusterConfig(c *check.C) { testRequires(c, DaemonIsLinux, SameHostDaemon) // Start daemon without docker0 bridge defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) discoveryBackend := "consul://consuladdr:consulport/some/path" s.d.Start(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend)) // Start daemon with docker0 bridge result := icmd.RunCommand("ifconfig", defaultNetworkBridge) c.Assert(result, icmd.Matches, icmd.Success) s.d.Restart(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend)) } func (s *DockerDaemonSuite) TestDaemonIP(c *check.C) { d := s.d ipStr := "192.170.1.1/24" ip, _, _ := net.ParseCIDR(ipStr) args := []string{"--ip", ip.String()} d.StartWithBusybox(c, args...) defer d.Restart(c) out, err := d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") c.Assert(err, check.NotNil, check.Commentf("Running a container must fail with an invalid --ip option")) c.Assert(strings.Contains(out, "Error starting userland proxy"), check.Equals, true) ifName := "dummy" createInterface(c, "dummy", ifName, ipStr) defer deleteInterface(c, ifName) _, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") c.Assert(err, check.IsNil) result := icmd.RunCommand("iptables", "-t", "nat", "-nvL") result.Assert(c, icmd.Success) regex := fmt.Sprintf("DNAT.*%s.*dpt:8000", ip.String()) matched, _ := regexp.MatchString(regex, result.Combined()) c.Assert(matched, check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined())) } func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) { testRequires(c, bridgeNfIptables) d := s.d bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") defer d.Restart(c) result := icmd.RunCommand("iptables", "-nvL", "FORWARD") result.Assert(c, icmd.Success) regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) matched, _ := regexp.MatchString(regex, result.Combined()) c.Assert(matched, check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined())) // Pinging another container must fail with --icc=false pingContainers(c, d, true) ipStr := "192.171.1.1/24" ip, _, _ := net.ParseCIDR(ipStr) ifName := "icc-dummy" createInterface(c, "dummy", ifName, ipStr) // But, Pinging external or a Host interface must succeed pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String()) runArgs := []string{"run", "--rm", "busybox", "sh", "-c", pingCmd} _, err := d.Cmd(runArgs...) c.Assert(err, check.IsNil) } func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) { d := s.d bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") defer d.Restart(c) result := icmd.RunCommand("iptables", "-nvL", "FORWARD") result.Assert(c, icmd.Success) regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) matched, _ := regexp.MatchString(regex, result.Combined()) c.Assert(matched, check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined())) out, err := d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567") c.Assert(err, check.IsNil, check.Commentf(out)) } func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *check.C) { bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) s.d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") defer s.d.Restart(c) _, err := s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top") c.Assert(err, check.IsNil) _, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top") c.Assert(err, check.IsNil) childIP, err := s.d.FindContainerIP("child") c.Assert(err, checker.IsNil) parentIP, err := s.d.FindContainerIP("parent") c.Assert(err, checker.IsNil) sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"} destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"} if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) { c.Fatal("Iptables rules not found") } s.d.Cmd("rm", "--link", "parent/http") if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) { c.Fatal("Iptables rules should be removed when unlink") } s.d.Cmd("kill", "child") s.d.Cmd("kill", "parent") } func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) { testRequires(c, DaemonIsLinux) s.d.StartWithBusybox(c, "--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024") out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)") if err != nil { c.Fatal(out, err) } outArr := strings.Split(out, "\n") if len(outArr) < 2 { c.Fatalf("got unexpected output: %s", out) } nofile := strings.TrimSpace(outArr[0]) nproc := strings.TrimSpace(outArr[1]) if nofile != "42" { c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile) } if nproc != "2048" { c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc) } // Now restart daemon with a new default s.d.Restart(c, "--default-ulimit", "nofile=43") out, err = s.d.Cmd("start", "-a", "test") if err != nil { c.Fatal(err) } outArr = strings.Split(out, "\n") if len(outArr) < 2 { c.Fatalf("got unexpected output: %s", out) } nofile = strings.TrimSpace(outArr[0]) nproc = strings.TrimSpace(outArr[1]) if nofile != "43" { c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile) } if nproc != "2048" { c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc) } } // #11315 func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil { c.Fatal(err, out) } if out, err := s.d.Cmd("rename", "test", "test2"); err != nil { c.Fatal(err, out) } s.d.Restart(c) if out, err := s.d.Cmd("start", "test2"); err != nil { c.Fatal(err, out) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") c.Assert(err, check.IsNil, check.Commentf(out)) id, err := s.d.GetIDByName("test") c.Assert(err, check.IsNil) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err != nil { c.Fatal(err) } f, err := os.Open(logPath) if err != nil { c.Fatal(err) } defer f.Close() var res struct { Log string `json:"log"` Stream string `json:"stream"` Time time.Time `json:"time"` } if err := json.NewDecoder(f).Decode(&res); err != nil { c.Fatal(err) } if res.Log != "testline\n" { c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") } if res.Stream != "stdout" { c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") } if !time.Now().After(res.Time) { c.Fatalf("Log time %v in future", res.Time) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name=test", "--log-driver=none", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") c.Assert(err, check.IsNil) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) { s.d.StartWithBusybox(c, "--log-driver=none") out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") c.Assert(err, check.IsNil) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { s.d.StartWithBusybox(c, "--log-driver=none") out, err := s.d.Cmd("run", "--name=test", "--log-driver=json-file", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") c.Assert(err, check.IsNil) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err != nil { c.Fatal(err) } f, err := os.Open(logPath) if err != nil { c.Fatal(err) } defer f.Close() var res struct { Log string `json:"log"` Stream string `json:"stream"` Time time.Time `json:"time"` } if err := json.NewDecoder(f).Decode(&res); err != nil { c.Fatal(err) } if res.Log != "testline\n" { c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") } if res.Stream != "stdout" { c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") } if !time.Now().After(res.Time) { c.Fatalf("Log time %v in future", res.Time) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { s.d.StartWithBusybox(c, "--log-driver=none") out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") c.Assert(err, checker.IsNil, check.Commentf(out)) out, err = s.d.Cmd("logs", "test") c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver")) expected := `configured logging driver does not support reading` c.Assert(out, checker.Contains, expected) } func (s *DockerDaemonSuite) TestDaemonLoggingDriverShouldBeIgnoredForBuild(c *check.C) { s.d.StartWithBusybox(c, "--log-driver=splunk") out, err := s.d.Cmd("build") out, code, err := s.d.BuildImageWithOut("busyboxs", ` FROM busybox RUN echo foo`, false) comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err) c.Assert(err, check.IsNil, comment) c.Assert(code, check.Equals, 0, comment) c.Assert(out, checker.Contains, "foo", comment) } func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) { dir, err := ioutil.TempDir("", "socket-cleanup-test") if err != nil { c.Fatal(err) } defer os.RemoveAll(dir) sockPath := filepath.Join(dir, "docker.sock") s.d.Start(c, "--host", "unix://"+sockPath) if _, err := os.Stat(sockPath); err != nil { c.Fatal("socket does not exist") } s.d.Stop(c) if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) { c.Fatal("unix socket is not cleaned up") } } func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *check.C) { type Config struct { Crv string `json:"crv"` D string `json:"d"` Kid string `json:"kid"` Kty string `json:"kty"` X string `json:"x"` Y string `json:"y"` } os.Remove("/etc/docker/key.json") s.d.Start(c) s.d.Stop(c) config := &Config{} bytes, err := ioutil.ReadFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error reading key.json file: %s", err) } // byte[] to Data-Struct if err := json.Unmarshal(bytes, &config); err != nil { c.Fatalf("Error Unmarshal: %s", err) } //replace config.Kid with the fake value config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4" // NEW Data-Struct to byte[] newBytes, err := json.Marshal(&config) if err != nil { c.Fatalf("Error Marshal: %s", err) } // write back if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil { c.Fatalf("Error ioutil.WriteFile: %s", err) } defer os.Remove("/etc/docker/key.json") if err := s.d.StartWithError(); err == nil { c.Fatalf("It should not be successful to start daemon with wrong key: %v", err) } content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) if !strings.Contains(string(content), "Public Key ID does not match") { c.Fatalf("Missing KeyID message from daemon logs: %s", string(content)) } } func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat") if err != nil { c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out) } containerID := strings.TrimSpace(out) if out, err := s.d.Cmd("kill", containerID); err != nil { c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out) } s.d.Restart(c) errchan := make(chan error) go func() { if out, err := s.d.Cmd("wait", containerID); err != nil { errchan <- fmt.Errorf("%v:\n%s", err, out) } close(errchan) }() select { case <-time.After(5 * time.Second): c.Fatal("Waiting on a stopped (killed) container timed out") case err := <-errchan: if err != nil { c.Fatal(err) } } } // TestHTTPSInfo connects via two-way authenticated HTTPS to the info endpoint func (s *DockerDaemonSuite) TestHTTPSInfo(c *check.C) { const ( testDaemonHTTPSAddr = "tcp://localhost:4271" ) s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr) args := []string{ "--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem", "info", } out, err := s.d.Cmd(args...) if err != nil { c.Fatalf("Error Occurred: %s and output: %s", err, out) } } // TestHTTPSRun connects via two-way authenticated HTTPS to the create, attach, start, and wait endpoints. // https://github.com/docker/docker/issues/19280 func (s *DockerDaemonSuite) TestHTTPSRun(c *check.C) { const ( testDaemonHTTPSAddr = "tcp://localhost:4271" ) s.d.StartWithBusybox(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr) args := []string{ "--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem", "run", "busybox", "echo", "TLS response", } out, err := s.d.Cmd(args...) if err != nil { c.Fatalf("Error Occurred: %s and output: %s", err, out) } if !strings.Contains(out, "TLS response") { c.Fatalf("expected output to include `TLS response`, got %v", out) } } // TestTLSVerify verifies that --tlsverify=false turns on tls func (s *DockerDaemonSuite) TestTLSVerify(c *check.C) { out, err := exec.Command(dockerdBinary, "--tlsverify=false").CombinedOutput() if err == nil || !strings.Contains(string(out), "Could not load X509 key pair") { c.Fatalf("Daemon should not have started due to missing certs: %v\n%s", err, string(out)) } } // TestHTTPSInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint // by using a rogue client certificate and checks that it fails with the expected error. func (s *DockerDaemonSuite) TestHTTPSInfoRogueCert(c *check.C) { const ( errBadCertificate = "bad certificate" testDaemonHTTPSAddr = "tcp://localhost:4271" ) s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr) args := []string{ "--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem", "info", } out, err := s.d.Cmd(args...) if err == nil || !strings.Contains(out, errBadCertificate) { c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out) } } // TestHTTPSInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint // which provides a rogue server certificate and checks that it fails with the expected error func (s *DockerDaemonSuite) TestHTTPSInfoRogueServerCert(c *check.C) { const ( errCaUnknown = "x509: certificate signed by unknown authority" testDaemonRogueHTTPSAddr = "tcp://localhost:4272" ) s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem", "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHTTPSAddr) args := []string{ "--host", testDaemonRogueHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem", "info", } out, err := s.d.Cmd(args...) if err == nil || !strings.Contains(out, errCaUnknown) { c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out) } } func pingContainers(c *check.C, d *daemon.Daemon, expectFailure bool) { var dargs []string if d != nil { dargs = []string{"--host", d.Sock()} } args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top") dockerCmd(c, args...) args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c") pingCmd := "ping -c 1 %s -W 1" args = append(args, fmt.Sprintf(pingCmd, "alias1")) _, _, err := dockerCmdWithError(args...) if expectFailure { c.Assert(err, check.NotNil) } else { c.Assert(err, check.IsNil) } args = append(dargs, "rm", "-f", "container1") dockerCmd(c, args...) } func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) { s.d.StartWithBusybox(c) socket := filepath.Join(s.d.Folder, "docker.sock") out, err := s.d.Cmd("run", "--restart=always", "-v", socket+":/sock", "busybox") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) s.d.Restart(c) } // os.Kill should kill daemon ungracefully, leaving behind container mounts. // A subsequent daemon restart shoud clean up said mounts. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *check.C) { d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ Experimental: testEnv.ExperimentalDaemon(), }) d.StartWithBusybox(c) out, err := d.Cmd("run", "-d", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) id := strings.TrimSpace(out) c.Assert(d.Signal(os.Kill), check.IsNil) mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) // container mounts should exist even after daemon has crashed. comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment) // kill the container icmd.RunCommand(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", id).Assert(c, icmd.Success) // restart daemon. d.Restart(c) // Now, container mounts should be gone. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo") c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) d.Stop(c) } // os.Interrupt should perform a graceful daemon shutdown and hence cleanup mounts. func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *check.C) { d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ Experimental: testEnv.ExperimentalDaemon(), }) d.StartWithBusybox(c) out, err := d.Cmd("run", "-d", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) id := strings.TrimSpace(out) // Send SIGINT and daemon should clean up c.Assert(d.Signal(os.Interrupt), check.IsNil) // Wait for the daemon to stop. c.Assert(<-d.Wait, checker.IsNil) mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) } func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) { testRequires(c, DaemonIsLinux, NotUserNamespace) s.d.StartWithBusybox(c, "-b", "none") out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.Contains(out, "eth0"), check.Equals, false, check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out)) out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.Contains(out, "eth0"), check.Equals, false, check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out)) // the extra grep and awk clean up the output of `ip` to only list the number and name of // interfaces, allowing for different versions of ip (e.g. inside and outside the container) to // be used while still verifying that the interface list is the exact same cmd := exec.Command("sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '") stdout := bytes.NewBuffer(nil) cmd.Stdout = stdout if err := cmd.Run(); err != nil { c.Fatal("Failed to get host network interface") } out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(out, check.Equals, fmt.Sprintf("%s", stdout), check.Commentf("The network interfaces in container should be the same with host when --net=host when bridge network is disabled: %s", out)) } func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) { s.d.StartWithBusybox(t) if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil { t.Fatal(out, err) } s.d.Restart(t) // Container 'test' should be removed without error if out, err := s.d.Cmd("rm", "test"); err != nil { t.Fatal(out, err) } } func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top") if err != nil { c.Fatal(out, err) } // Get sandbox key via inspect out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } fileName := strings.Trim(out, " \r\n'") if out, err := s.d.Cmd("stop", "netns"); err != nil { c.Fatal(out, err) } // Test if the file still exists icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{ Out: fileName, }) // Remove the container and restart the daemon if out, err := s.d.Cmd("rm", "netns"); err != nil { c.Fatal(out, err) } s.d.Restart(c) // Test again and see now the netns file does not exist icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{ Err: "No such file or directory", ExitCode: 1, }) } // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored func (s *DockerDaemonSuite) TestDaemonTLSVerifyIssue13964(c *check.C) { host := "tcp://localhost:4271" s.d.Start(c, "-H", host) icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "-H", host, "info"}, Env: []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}, }).Assert(c, icmd.Expected{ ExitCode: 1, Err: "error during connect", }) } func setupV6(c *check.C) { // Hack to get the right IPv6 address on docker0, which has already been created result := icmd.RunCommand("ip", "addr", "add", "fe80::1/64", "dev", "docker0") result.Assert(c, icmd.Success) } func teardownV6(c *check.C) { result := icmd.RunCommand("ip", "addr", "del", "fe80::1/64", "dev", "docker0") result.Assert(c, icmd.Success) } func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") c.Assert(err, check.IsNil) id := strings.TrimSpace(out) _, err = s.d.Cmd("stop", id) c.Assert(err, check.IsNil) _, err = s.d.Cmd("wait", id) c.Assert(err, check.IsNil) out, err = s.d.Cmd("ps", "-q") c.Assert(err, check.IsNil) c.Assert(out, check.Equals, "") s.d.Restart(c) out, err = s.d.Cmd("ps", "-q") c.Assert(err, check.IsNil) c.Assert(strings.TrimSpace(out), check.Equals, id[:12]) } func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) { s.d.StartWithBusybox(c, "--log-opt=max-size=1k") name := "logtest" out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err)) out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(out, checker.Contains, "max-size:1k") c.Assert(out, checker.Contains, "max-file:5") out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.TrimSpace(out), checker.Equals, "json-file") } func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil { c.Fatal(err, out) } if out, err := s.d.Cmd("pause", "test"); err != nil { c.Fatal(err, out) } s.d.Restart(c) errchan := make(chan error) go func() { out, err := s.d.Cmd("start", "test") if err != nil { errchan <- fmt.Errorf("%v:\n%s", err, out) } name := strings.TrimSpace(out) if name != "test" { errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name) } close(errchan) }() select { case <-time.After(5 * time.Second): c.Fatal("Waiting on start a container timed out") case err := <-errchan: if err != nil { c.Fatal(err) } } } func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox") c.Assert(err, check.IsNil, check.Commentf(out)) s.d.Restart(c) out, err = s.d.Cmd("volume", "rm", "test") c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart")) c.Assert(out, checker.Contains, "in use") } func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) { s.d.Start(c) _, err := s.d.Cmd("volume", "create", "test") c.Assert(err, check.IsNil) s.d.Restart(c) _, err = s.d.Cmd("volume", "inspect", "test") c.Assert(err, check.IsNil) } // FIXME(vdemeester) should be a unit test func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) { d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ Experimental: testEnv.ExperimentalDaemon(), }) c.Assert(d.StartWithError("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil) expected := "Failed to set log opts: syslog-address should be in form proto://address" icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success) } // FIXME(vdemeester) should be a unit test func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *check.C) { d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ Experimental: testEnv.ExperimentalDaemon(), }) c.Assert(d.StartWithError("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil) expected := "Failed to set log opts: invalid fluentd-address corrupted:c: " icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success) } // FIXME(vdemeester) Use a new daemon instance instead of the Suite one func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *check.C) { s.d.UseDefaultHost = true defer func() { s.d.UseDefaultHost = false }() s.d.Start(c) } // FIXME(vdemeester) Use a new daemon instance instead of the Suite one func (s *DockerDaemonSuite) TestDaemonStartWithDefalutTLSHost(c *check.C) { s.d.UseDefaultTLSHost = true defer func() { s.d.UseDefaultTLSHost = false }() s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem") // The client with --tlsverify should also use default host localhost:2376 tmpHost := os.Getenv("DOCKER_HOST") defer func() { os.Setenv("DOCKER_HOST", tmpHost) }() os.Setenv("DOCKER_HOST", "") out, _ := dockerCmd( c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem", "version", ) if !strings.Contains(out, "Server") { c.Fatalf("docker version should return information of server side") } } func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) bridgeIP := "192.169.1.1" bridgeRange := bridgeIP + "/30" s.d.StartWithBusybox(c, "--bip", bridgeRange) defer s.d.Restart(c) var cont int for { contName := fmt.Sprintf("container%d", cont) _, err := s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2") if err != nil { // pool exhausted break } ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName) c.Assert(err, check.IsNil) c.Assert(ip, check.Not(check.Equals), bridgeIP) cont++ } } // Test daemon for no space left on device error func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) { testRequires(c, SameHostDaemon, DaemonIsLinux, Network) testDir, err := ioutil.TempDir("", "no-space-left-on-device-test") c.Assert(err, checker.IsNil) defer os.RemoveAll(testDir) c.Assert(mount.MakeRShared(testDir), checker.IsNil) defer mount.Unmount(testDir) // create a 2MiB image and mount it as graph root // Why in a container? Because `mount` sometimes behaves weirdly and often fails outright on this test in debian:jessie (which is what the test suite runs under if run from the Makefile) dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=2 count=0") icmd.RunCommand("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img")).Assert(c, icmd.Success) result := icmd.RunCommand("losetup", "-f", "--show", filepath.Join(testDir, "testfs.img")) result.Assert(c, icmd.Success) loopname := strings.TrimSpace(string(result.Combined())) defer exec.Command("losetup", "-d", loopname).Run() dockerCmd(c, "run", "--privileged", "--rm", "-v", testDir+":/test:shared", "busybox", "sh", "-c", fmt.Sprintf("mkdir -p /test/test-mount && mount -t ext4 -no loop,rw %v /test/test-mount", loopname)) defer mount.Unmount(filepath.Join(testDir, "test-mount")) s.d.Start(c, "--graph", filepath.Join(testDir, "test-mount")) defer s.d.Stop(c) // pull a repository large enough to fill the mount point pullOut, err := s.d.Cmd("pull", "registry:2") c.Assert(err, checker.NotNil, check.Commentf(pullOut)) c.Assert(pullOut, checker.Contains, "no space left on device") } // Test daemon restart with container links + auto restart func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) { s.d.StartWithBusybox(c) parent1Args := []string{} parent2Args := []string{} wg := sync.WaitGroup{} maxChildren := 10 chErr := make(chan error, maxChildren) for i := 0; i < maxChildren; i++ { wg.Add(1) name := fmt.Sprintf("test%d", i) if i < maxChildren/2 { parent1Args = append(parent1Args, []string{"--link", name}...) } else { parent2Args = append(parent2Args, []string{"--link", name}...) } go func() { _, err := s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top") chErr <- err wg.Done() }() } wg.Wait() close(chErr) for err := range chErr { c.Assert(err, check.IsNil) } parent1Args = append([]string{"run", "-d"}, parent1Args...) parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...) parent2Args = append([]string{"run", "-d"}, parent2Args...) parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...) _, err := s.d.Cmd(parent1Args...) c.Assert(err, check.IsNil) _, err = s.d.Cmd(parent2Args...) c.Assert(err, check.IsNil) s.d.Stop(c) // clear the log file -- we don't need any of it but may for the next part // can ignore the error here, this is just a cleanup os.Truncate(s.d.LogFileName(), 0) s.d.Start(c) for _, num := range []string{"1", "2"} { out, err := s.d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num) c.Assert(err, check.IsNil) if strings.TrimSpace(out) != "true" { log, _ := ioutil.ReadFile(s.d.LogFileName()) c.Fatalf("parent container is not running\n%s", string(log)) } } } func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) { testRequires(c, DaemonIsLinux) cgroupParent := "test" name := "cgroup-test" s.d.StartWithBusybox(c, "--cgroup-parent", cgroupParent) defer s.d.Restart(c) out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup") c.Assert(err, checker.IsNil) cgroupPaths := testutil.ParseCgroupPaths(string(out)) c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out))) out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name) c.Assert(err, checker.IsNil) id := strings.TrimSpace(string(out)) expectedCgroup := path.Join(cgroupParent, id) found := false for _, path := range cgroupPaths { if strings.HasSuffix(path, expectedCgroup) { found = true break } } c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths)) } func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) { testRequires(c, DaemonIsLinux) // Windows does not support links s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc") c.Assert(err, check.IsNil, check.Commentf(out)) s.d.Restart(c) // should fail since test is not running yet out, err = s.d.Cmd("start", "test2") c.Assert(err, check.NotNil, check.Commentf(out)) out, err = s.d.Cmd("start", "test") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("start", "-a", "test2") c.Assert(err, check.IsNil, check.Commentf(out)) c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out)) } func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) { testRequires(c, DaemonIsLinux) // Windows does not support links s.d.StartWithBusybox(c) out, err := s.d.Cmd("create", "--name=test", "busybox") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf(out)) test2ID := strings.TrimSpace(out) out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top") test3ID := strings.TrimSpace(out) s.d.Restart(c) out, err = s.d.Cmd("create", "--name=test", "busybox") c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name")) // this one is no longer needed, removing simplifies the remainder of the test out, err = s.d.Cmd("rm", "-f", "test") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("ps", "-a", "--no-trunc") c.Assert(err, check.IsNil, check.Commentf(out)) lines := strings.Split(strings.TrimSpace(out), "\n")[1:] test2validated := false test3validated := false for _, line := range lines { fields := strings.Fields(line) names := fields[len(fields)-1] switch fields[0] { case test2ID: c.Assert(names, check.Equals, "test2,test3/abc") test2validated = true case test3ID: c.Assert(names, check.Equals, "test3") test3validated = true } } c.Assert(test2validated, check.Equals, true) c.Assert(test3validated, check.Equals, true) } // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check.C) { // TODO(mlaventure): Not sure what would the exit code be on windows testRequires(t, DaemonIsLinux) s.d.StartWithBusybox(t) cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top") defer s.d.Stop(t) if err != nil { t.Fatal(cid, err) } cid = strings.TrimSpace(cid) pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) t.Assert(err, check.IsNil) pid = strings.TrimSpace(pid) // Kill the daemon if err := s.d.Kill(); err != nil { t.Fatal(err) } // kill the container icmd.RunCommand(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", cid).Assert(t, icmd.Success) // Give time to containerd to process the command if we don't // the exit event might be received after we do the inspect result := icmd.RunCommand("kill", "-0", pid) for result.ExitCode == 0 { time.Sleep(1 * time.Second) // FIXME(vdemeester) should we check it doesn't error out ? result = icmd.RunCommand("kill", "-0", pid) } // restart the daemon s.d.Start(t) // Check that we've got the correct exit code out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid) t.Assert(err, check.IsNil) out = strings.TrimSpace(out) if out != "143" { t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "143", out, cid) } } // os.Kill should kill daemon ungracefully, leaving behind live containers. // The live containers should be known to the restarted daemon. Stopping // them now, should remove the mounts. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) { testRequires(c, DaemonIsLinux) s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) id := strings.TrimSpace(out) c.Assert(s.d.Signal(os.Kill), check.IsNil) mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) // container mounts should exist even after daemon has crashed. comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.Root, mountOut) c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment) // restart daemon. s.d.Start(c, "--live-restore") // container should be running. out, err = s.d.Cmd("inspect", "--format={{.State.Running}}", id) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) out = strings.TrimSpace(out) if out != "true" { c.Fatalf("Container %s expected to stay alive after daemon restart", id) } // 'docker stop' should work. out, err = s.d.Cmd("stop", id) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) // Now, container mounts should be gone. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo") c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.Root, mountOut) c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) } // TestDaemonRestartWithUnpausedRunningContainer requires live restore of running containers. func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *check.C) { // TODO(mlaventure): Not sure what would the exit code be on windows testRequires(t, DaemonIsLinux) s.d.StartWithBusybox(t, "--live-restore") cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top") defer s.d.Stop(t) if err != nil { t.Fatal(cid, err) } cid = strings.TrimSpace(cid) pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) t.Assert(err, check.IsNil) // pause the container if _, err := s.d.Cmd("pause", cid); err != nil { t.Fatal(cid, err) } // Kill the daemon if err := s.d.Kill(); err != nil { t.Fatal(err) } // resume the container result := icmd.RunCommand( ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "resume", cid) t.Assert(result, icmd.Matches, icmd.Success) // Give time to containerd to process the command if we don't // the resume event might be received after we do the inspect waitAndAssert(t, defaultReconciliationTimeout, func(*check.C) (interface{}, check.CommentInterface) { result := icmd.RunCommand("kill", "-0", strings.TrimSpace(pid)) return result.ExitCode, nil }, checker.Equals, 0) // restart the daemon s.d.Start(t, "--live-restore") // Check that we've got the correct status out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid) t.Assert(err, check.IsNil) out = strings.TrimSpace(out) if out != "running" { t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "running", out, cid) } if _, err := s.d.Cmd("kill", cid); err != nil { t.Fatal(err) } } // TestRunLinksChanged checks that creating a new container with the same name does not update links // this ensures that the old, pre gh#16032 functionality continues on func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) { testRequires(c, DaemonIsLinux) // Windows does not support links s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc") c.Assert(err, check.IsNil, check.Commentf(out)) c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received") out, err = s.d.Cmd("rm", "-f", "test") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = s.d.Cmd("start", "-a", "test2") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received") s.d.Restart(c) out, err = s.d.Cmd("start", "-a", "test2") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received") } func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) { testRequires(c, DaemonIsLinux, NotPpc64le) infoLog := "\x1b[34mINFO\x1b" b := bytes.NewBuffer(nil) done := make(chan bool) p, tty, err := pty.Open() c.Assert(err, checker.IsNil) defer func() { tty.Close() p.Close() }() go func() { io.Copy(b, p) done <- true }() // Enable coloring explicitly s.d.StartWithLogFile(tty, "--raw-logs=false") s.d.Stop(c) // Wait for io.Copy() before checking output <-done c.Assert(b.String(), checker.Contains, infoLog) b.Reset() // "tty" is already closed in prev s.d.Stop(), // we have to close the other side "p" and open another pair of // pty for the next test. p.Close() p, tty, err = pty.Open() c.Assert(err, checker.IsNil) go func() { io.Copy(b, p) done <- true }() // Disable coloring explicitly s.d.StartWithLogFile(tty, "--raw-logs=true") s.d.Stop(c) // Wait for io.Copy() before checking output <-done c.Assert(b.String(), check.Not(check.Equals), "") c.Assert(b.String(), check.Not(checker.Contains), infoLog) } func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) { testRequires(c, DaemonIsLinux, NotPpc64le) debugLog := "\x1b[37mDEBU\x1b" p, tty, err := pty.Open() c.Assert(err, checker.IsNil) defer func() { tty.Close() p.Close() }() b := bytes.NewBuffer(nil) go io.Copy(b, p) s.d.StartWithLogFile(tty, "--debug") s.d.Stop(c) c.Assert(b.String(), checker.Contains, debugLog) } func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) { testRequires(c, SameHostDaemon, DaemonIsLinux) // daemon config file daemonConfig := `{ "debug" : false }` configFile, err := ioutil.TempFile("", "test-daemon-discovery-backend-config-reload-config") c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload")) configFilePath := configFile.Name() defer func() { configFile.Close() os.RemoveAll(configFile.Name()) }() _, err = configFile.Write([]byte(daemonConfig)) c.Assert(err, checker.IsNil) // --log-level needs to be set so that d.Start() doesn't add --debug causing // a conflict with the config s.d.Start(c, "--config-file", configFilePath, "--log-level=info") // daemon config file daemonConfig = `{ "cluster-store": "consul://consuladdr:consulport/some/path", "cluster-advertise": "192.168.56.100:0", "debug" : false }` err = configFile.Truncate(0) c.Assert(err, checker.IsNil) _, err = configFile.Seek(0, os.SEEK_SET) c.Assert(err, checker.IsNil) _, err = configFile.Write([]byte(daemonConfig)) c.Assert(err, checker.IsNil) err = s.d.ReloadConfig() c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config")) out, err := s.d.Cmd("info") c.Assert(err, checker.IsNil) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path")) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0")) } // Test for #21956 func (s *DockerDaemonSuite) TestDaemonLogOptions(c *check.C) { s.d.StartWithBusybox(c, "--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514") out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf(out)) id := strings.TrimSpace(out) out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id) c.Assert(err, check.IsNil, check.Commentf(out)) c.Assert(out, checker.Contains, "{json-file map[]}") } // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) { s.d.Start(c, "--max-concurrent-uploads=6", "--max-concurrent-downloads=8") expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) } // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) { testRequires(c, SameHostDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) c.Assert(err, checker.IsNil) defer os.Remove(configFilePath) daemonConfig := `{ "max-concurrent-downloads" : 8 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) configFile, err = os.Create(configFilePath) c.Assert(err, checker.IsNil) daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) // syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP) time.Sleep(3 * time.Second) expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"` content, err = s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) } // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *check.C) { testRequires(c, SameHostDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) c.Assert(err, checker.IsNil) defer os.Remove(configFilePath) daemonConfig := `{ "max-concurrent-uploads" : null }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"` content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) configFile, err = os.Create(configFilePath) c.Assert(err, checker.IsNil) daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) // syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP) time.Sleep(3 * time.Second) expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` content, err = s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) configFile, err = os.Create(configFilePath) c.Assert(err, checker.IsNil) daemonConfig = `{ "labels":["foo=bar"] }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) time.Sleep(3 * time.Second) expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` content, err = s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) } func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *check.C) { s.d.StartWithBusybox(c, "-b=none", "--iptables=false") out, code, err := s.d.BuildImageWithOut("busyboxs", `FROM busybox RUN cat /etc/hosts`, false) comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err) c.Assert(err, check.IsNil, comment) c.Assert(code, check.Equals, 0, comment) } // Test case for #21976 func (s *DockerDaemonSuite) TestDaemonDNSFlagsInHostMode(c *check.C) { testRequires(c, SameHostDaemon, DaemonIsLinux) s.d.StartWithBusybox(c, "--dns", "1.2.3.4", "--dns-search", "example.com", "--dns-opt", "timeout:3") expectedOutput := "nameserver 1.2.3.4" out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf") c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) expectedOutput = "search example.com" c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) expectedOutput = "options timeout:3" c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) } func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { conf, err := ioutil.TempFile("", "config-file-") c.Assert(err, check.IsNil) configName := conf.Name() conf.Close() defer os.Remove(configName) config := ` { "runtimes": { "oci": { "path": "docker-runc" }, "vm": { "path": "/usr/local/bin/vm-manager", "runtimeArgs": [ "--debug" ] } } } ` ioutil.WriteFile(configName, []byte(config), 0644) s.d.StartWithBusybox(c, "--config-file", configName) // Run with default runtime out, err := s.d.Cmd("run", "--rm", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with oci (same path as default) but keep it around out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with "vm" out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Reset config to only have the default config = ` { "runtimes": { } } ` ioutil.WriteFile(configName, []byte(config), 0644) c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) // Give daemon time to reload config <-time.After(1 * time.Second) // Run with default runtime out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with "oci" out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Start previously created container with oci out, err = s.d.Cmd("start", "oci-runtime-ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Check that we can't override the default runtime config = ` { "runtimes": { "runc": { "path": "my-runc" } } } ` ioutil.WriteFile(configName, []byte(config), 0644) c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) // Give daemon time to reload config <-time.After(1 * time.Second) content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, `file configuration validation failed (runtime name 'runc' is reserved)`) // Check that we can select a default runtime config = ` { "default-runtime": "vm", "runtimes": { "oci": { "path": "docker-runc" }, "vm": { "path": "/usr/local/bin/vm-manager", "runtimeArgs": [ "--debug" ] } } } ` ioutil.WriteFile(configName, []byte(config), 0644) c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) // Give daemon time to reload config <-time.After(1 * time.Second) out, err = s.d.Cmd("run", "--rm", "busybox", "ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) } func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { s.d.StartWithBusybox(c, "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager") // Run with default runtime out, err := s.d.Cmd("run", "--rm", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with oci (same path as default) but keep it around out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with "vm" out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Start a daemon without any extra runtimes s.d.Stop(c) s.d.StartWithBusybox(c) // Run with default runtime out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) // Run with "oci" out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Start previously created container with oci out, err = s.d.Cmd("start", "oci-runtime-ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Check that we can't override the default runtime s.d.Stop(c) c.Assert(s.d.StartWithError("--add-runtime", "runc=my-runc"), checker.NotNil) content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, `runtime name 'runc' is reserved`) // Check that we can select a default runtime s.d.Stop(c) s.d.StartWithBusybox(c, "--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager") out, err = s.d.Cmd("run", "--rm", "busybox", "ls") c.Assert(err, check.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") c.Assert(err, check.IsNil, check.Commentf(out)) } func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C) { s.d.StartWithBusybox(c) // top1 will exist after daemon restarts out, err := s.d.Cmd("run", "-d", "--name", "top1", "busybox:latest", "top") c.Assert(err, checker.IsNil, check.Commentf("run top1: %v", out)) // top2 will be removed after daemon restarts out, err = s.d.Cmd("run", "-d", "--rm", "--name", "top2", "busybox:latest", "top") c.Assert(err, checker.IsNil, check.Commentf("run top2: %v", out)) out, err = s.d.Cmd("ps") c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should be running")) c.Assert(out, checker.Contains, "top2", check.Commentf("top2 should be running")) // now restart daemon gracefully s.d.Restart(c) out, err = s.d.Cmd("ps", "-a") c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should exist after daemon restarts")) c.Assert(out, checker.Not(checker.Contains), "top2", check.Commentf("top2 should be removed after daemon restarts")) } func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) { s.d.StartWithBusybox(c) containerName := "error-values" // Make a container with both a non 0 exit code and an error message // We explicitly disable `--init` for this test, because `--init` is enabled by default // on "experimental". Enabling `--init` results in a different behavior; because the "init" // process itself is PID1, the container does not fail on _startup_ (i.e., `docker-init` starting), // but directly after. The exit code of the container is still 127, but the Error Message is not // captured, so `.State.Error` is empty. // See the discussion on https://github.com/docker/docker/pull/30227#issuecomment-274161426, // and https://github.com/docker/docker/pull/26061#r78054578 for more information. out, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto") c.Assert(err, checker.NotNil) // Check that those values were saved on disk out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) out = strings.TrimSpace(out) c.Assert(err, checker.IsNil) c.Assert(out, checker.Equals, "127") errMsg1, err := s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) errMsg1 = strings.TrimSpace(errMsg1) c.Assert(err, checker.IsNil) c.Assert(errMsg1, checker.Contains, "executable file not found") // now restart daemon s.d.Restart(c) // Check that those values are still around out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) out = strings.TrimSpace(out) c.Assert(err, checker.IsNil) c.Assert(out, checker.Equals, "127") out, err = s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) out = strings.TrimSpace(out) c.Assert(err, checker.IsNil) c.Assert(out, checker.Equals, errMsg1) } func (s *DockerDaemonSuite) TestDaemonBackcompatPre17Volumes(c *check.C) { testRequires(c, SameHostDaemon) d := s.d d.StartWithBusybox(c) // hack to be able to side-load a container config out, err := d.Cmd("create", "busybox:latest") c.Assert(err, checker.IsNil, check.Commentf(out)) id := strings.TrimSpace(out) out, err = d.Cmd("inspect", "--type=image", "--format={{.ID}}", "busybox:latest") c.Assert(err, checker.IsNil, check.Commentf(out)) d.Stop(c) <-d.Wait imageID := strings.TrimSpace(out) volumeID := stringid.GenerateNonCryptoID() vfsPath := filepath.Join(d.Root, "vfs", "dir", volumeID) c.Assert(os.MkdirAll(vfsPath, 0755), checker.IsNil) config := []byte(` { "ID": "` + id + `", "Name": "hello", "Driver": "` + d.StorageDriver() + `", "Image": "` + imageID + `", "Config": {"Image": "busybox:latest"}, "NetworkSettings": {}, "Volumes": { "/bar":"/foo", "/foo": "` + vfsPath + `", "/quux":"/quux" }, "VolumesRW": { "/bar": true, "/foo": true, "/quux": false } } `) configPath := filepath.Join(d.Root, "containers", id, "config.v2.json") err = ioutil.WriteFile(configPath, config, 600) d.Start(c) out, err = d.Cmd("inspect", "--type=container", "--format={{ json .Mounts }}", id) c.Assert(err, checker.IsNil, check.Commentf(out)) type mount struct { Name string Source string Destination string Driver string RW bool } ls := []mount{} err = json.NewDecoder(strings.NewReader(out)).Decode(&ls) c.Assert(err, checker.IsNil) expected := []mount{ {Source: "/foo", Destination: "/bar", RW: true}, {Name: volumeID, Destination: "/foo", RW: true}, {Source: "/quux", Destination: "/quux", RW: false}, } c.Assert(ls, checker.HasLen, len(expected)) for _, m := range ls { var matched bool for _, x := range expected { if m.Source == x.Source && m.Destination == x.Destination && m.RW == x.RW || m.Name != x.Name { matched = true break } } c.Assert(matched, checker.True, check.Commentf("did find match for %+v", m)) } } func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *check.C) { testRequires(c, SameHostDaemon, DaemonIsLinux) dockerProxyPath, err := exec.LookPath("docker-proxy") c.Assert(err, checker.IsNil) tmpDir, err := ioutil.TempDir("", "test-docker-proxy") c.Assert(err, checker.IsNil) newProxyPath := filepath.Join(tmpDir, "docker-proxy") cmd := exec.Command("cp", dockerProxyPath, newProxyPath) c.Assert(cmd.Run(), checker.IsNil) // custom one s.d.StartWithBusybox(c, "--userland-proxy-path", newProxyPath) out, err := s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") c.Assert(err, checker.IsNil, check.Commentf(out)) // try with the original one s.d.Restart(c, "--userland-proxy-path", dockerProxyPath) out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") c.Assert(err, checker.IsNil, check.Commentf(out)) // not exist s.d.Restart(c, "--userland-proxy-path", "/does/not/exist") out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") c.Assert(err, checker.NotNil, check.Commentf(out)) c.Assert(out, checker.Contains, "driver failed programming external connectivity on endpoint") c.Assert(out, checker.Contains, "/does/not/exist: no such file or directory") } // Test case for #22471 func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) { testRequires(c, SameHostDaemon) s.d.StartWithBusybox(c, "--shutdown-timeout=3") _, err := s.d.Cmd("run", "-d", "busybox", "top") c.Assert(err, check.IsNil) c.Assert(s.d.Signal(syscall.SIGINT), checker.IsNil) select { case <-s.d.Wait: case <-time.After(5 * time.Second): } expectedMessage := `level=debug msg="start clean shutdown of all containers with a 3 seconds timeout..."` content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMessage) } // Test case for #22471 func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) { testRequires(c, SameHostDaemon) // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) c.Assert(err, checker.IsNil) defer os.Remove(configFilePath) daemonConfig := `{ "shutdown-timeout" : 8 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) configFile, err = os.Create(configFilePath) c.Assert(err, checker.IsNil) daemonConfig = `{ "shutdown-timeout" : 5 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) select { case <-s.d.Wait: case <-time.After(3 * time.Second): } expectedMessage := `level=debug msg="Reset Shutdown Timeout: 5"` content, err := s.d.ReadLogFile() c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, expectedMessage) } // Test case for 29342 func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *check.C) { testRequires(c, DaemonIsLinux) s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "sh", "-c", "addgroup -S test && adduser -S -G test test -D -s /bin/sh && top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) s.d.WaitRun("top") out1, err := s.d.Cmd("exec", "-u", "test", "top", "id") // uid=100(test) gid=101(test) groups=101(test) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out1)) // restart daemon. s.d.Restart(c, "--live-restore") out2, err := s.d.Cmd("exec", "-u", "test", "top", "id") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out2)) c.Assert(out1, check.Equals, out2, check.Commentf("Output: before restart '%s', after restart '%s'", out1, out2)) out, err = s.d.Cmd("stop", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) } func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { testRequires(c, DaemonIsLinux, overlayFSSupported, SameHostDaemon) s.d.StartWithBusybox(c, "--live-restore", "--storage-driver", "overlay") out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) s.d.WaitRun("top") // restart daemon. s.d.Restart(c, "--live-restore", "--storage-driver", "overlay") out, err = s.d.Cmd("stop", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) // test if the rootfs mountpoint still exist mountpoint, err := s.d.InspectField("top", ".GraphDriver.Data.MergedDir") c.Assert(err, check.IsNil) f, err := os.Open("/proc/self/mountinfo") c.Assert(err, check.IsNil) defer f.Close() sc := bufio.NewScanner(f) for sc.Scan() { line := sc.Text() if strings.Contains(line, mountpoint) { c.Fatalf("mountinfo should not include the mountpoint of stop container") } } out, err = s.d.Cmd("rm", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) } // #29598 func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { testRequires(c, DaemonIsLinux, SameHostDaemon) s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) id := strings.TrimSpace(out) type state struct { Running bool StartedAt time.Time } out, err = s.d.Cmd("inspect", "-f", "{{json .State}}", id) c.Assert(err, checker.IsNil, check.Commentf("output: %s", out)) var origState state err = json.Unmarshal([]byte(strings.TrimSpace(out)), &origState) c.Assert(err, checker.IsNil) s.d.Restart(c, "--live-restore") pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", id) c.Assert(err, check.IsNil) pidint, err := strconv.Atoi(strings.TrimSpace(pid)) c.Assert(err, check.IsNil) c.Assert(pidint, checker.GreaterThan, 0) c.Assert(syscall.Kill(pidint, syscall.SIGKILL), check.IsNil) ticker := time.NewTicker(50 * time.Millisecond) timeout := time.After(10 * time.Second) for range ticker.C { select { case <-timeout: c.Fatal("timeout waiting for container restart") default: } out, err := s.d.Cmd("inspect", "-f", "{{json .State}}", id) c.Assert(err, checker.IsNil, check.Commentf("output: %s", out)) var newState state err = json.Unmarshal([]byte(strings.TrimSpace(out)), &newState) c.Assert(err, checker.IsNil) if !newState.Running { continue } if newState.StartedAt.After(origState.StartedAt) { break } } out, err = s.d.Cmd("stop", id) c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) } func (s *DockerDaemonSuite) TestShmSize(c *check.C) { testRequires(c, DaemonIsLinux) size := 67108864 * 2 pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) s.d.StartWithBusybox(c, "--default-shm-size", fmt.Sprintf("%v", size)) name := "shm1" out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(pattern.MatchString(out), checker.True) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) } func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) { testRequires(c, DaemonIsLinux) configPath, err := ioutil.TempDir("", "test-daemon-shm-size-reload-config") c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload")) defer os.RemoveAll(configPath) // clean up configFile := filepath.Join(configPath, "config.json") size := 67108864 * 2 configData := []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload")) pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) s.d.StartWithBusybox(c, "--config-file", configFile) name := "shm1" out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(pattern.MatchString(out), checker.True) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) size = 67108864 * 3 configData = []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload")) pattern = regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) err = s.d.ReloadConfig() c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config")) name = "shm2" out, err = s.d.Cmd("run", "--name", name, "busybox", "mount") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(pattern.MatchString(out), checker.True) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) }
{ "content_hash": "83e347a6a7525d6de7a7db360176c687", "timestamp": "", "source": "github", "line_count": 2949, "max_line_length": 199, "avg_line_length": 34.23092573753815, "alnum_prop": 0.6765233241205781, "repo_name": "thtanaka/docker", "id": "b6bb7470ee0272da9e71be76763126e7a43d990d", "size": "100964", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integration-cli/docker_cli_daemon_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "81" }, { "name": "C", "bytes": "5027" }, { "name": "Go", "bytes": "7095297" }, { "name": "Makefile", "bytes": "12767" }, { "name": "PowerShell", "bytes": "23242" }, { "name": "Shell", "bytes": "505351" }, { "name": "Vim script", "bytes": "1350" } ], "symlink_target": "" }
import socket import sys # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = ('localhost', 10000) message = b'This is the message. It will be repeated.' try: # Send data print('sending {!r}'.format(message)) sent = sock.sendto(message, server_address) # Receive response print('waiting to receive') data, server = sock.recvfrom(4096) print('received {!r}'.format(data)) finally: print('closing socket') sock.close()
{ "content_hash": "03ee448582d1996f7ec718bffcd48f0c", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 55, "avg_line_length": 21.782608695652176, "alnum_prop": 0.6746506986027944, "repo_name": "scotthuang1989/Python-3-Module-of-the-Week", "id": "fa0fd889e8a149803bba71f566c60ff694099f61", "size": "501", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "networking/socket_echo_client_dgram.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jupyter Notebook", "bytes": "913525" }, { "name": "Python", "bytes": "53855" }, { "name": "Shell", "bytes": "91" } ], "symlink_target": "" }
namespace { using extensions::PrinterProviderAPI; using extensions::PrinterProviderAPIFactory; // Callback for PrinterProviderAPI::DispatchGetPrintersRequested calls. // It appends items in |printers| to |*printers_out|. If |done| is set, it runs // |callback|. void AppendPrintersAndRunCallbackIfDone(base::ListValue* printers_out, const base::Closure& callback, const base::ListValue& printers, bool done) { for (size_t i = 0; i < printers.GetSize(); ++i) { const base::DictionaryValue* printer = NULL; EXPECT_TRUE(printers.GetDictionary(i, &printer)) << "Found invalid printer value at index " << i << ": " << printers; if (printer) printers_out->Append(printer->DeepCopy()); } if (done && !callback.is_null()) callback.Run(); } // Callback for PrinterProviderAPI::DispatchPrintRequested calls. // It copies |value| to |*result| and runs |callback|. void RecordPrintResultAndRunCallback(bool* result_success, std::string* result_status, const base::Closure& callback, bool success, const std::string& status) { *result_success = success; *result_status = status; if (!callback.is_null()) callback.Run(); } // Callback for PrinterProviderAPI::DispatchGetCapabilityRequested calls. // It saves reported |value| as JSON string to |*result| and runs |callback|. void RecordDictAndRunCallback(std::string* result, const base::Closure& callback, const base::DictionaryValue& value) { JSONStringValueSerializer serializer(result); EXPECT_TRUE(serializer.Serialize(value)); if (!callback.is_null()) callback.Run(); } // Tests for chrome.printerProvider API. class PrinterProviderApiTest : public extensions::ShellApiTest { public: enum PrintRequestDataType { PRINT_REQUEST_DATA_TYPE_NOT_SET, PRINT_REQUEST_DATA_TYPE_FILE, PRINT_REQUEST_DATA_TYPE_FILE_DELETED, PRINT_REQUEST_DATA_TYPE_BYTES }; PrinterProviderApiTest() {} ~PrinterProviderApiTest() override {} void StartGetPrintersRequest( const PrinterProviderAPI::GetPrintersCallback& callback) { PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(browser_context()) ->DispatchGetPrintersRequested(callback); } void StartPrintRequestWithNoData( const std::string& extension_id, const PrinterProviderAPI::PrintCallback& callback) { extensions::PrinterProviderPrintJob job; job.printer_id = extension_id + ":printer_id"; job.ticket_json = "{}"; job.content_type = "application/pdf"; PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(browser_context()) ->DispatchPrintRequested(job, callback); } void StartPrintRequestUsingDocumentBytes( const std::string& extension_id, const PrinterProviderAPI::PrintCallback& callback) { extensions::PrinterProviderPrintJob job; job.printer_id = extension_id + ":printer_id"; job.job_title = base::ASCIIToUTF16("Print job"); job.ticket_json = "{}"; job.content_type = "application/pdf"; const unsigned char kDocumentBytes[] = {'b', 'y', 't', 'e', 's'}; job.document_bytes = new base::RefCountedBytes(kDocumentBytes, arraysize(kDocumentBytes)); PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(browser_context()) ->DispatchPrintRequested(job, callback); } bool StartPrintRequestUsingFileInfo( const std::string& extension_id, const PrinterProviderAPI::PrintCallback& callback) { extensions::PrinterProviderPrintJob job; const char kBytes[] = {'b', 'y', 't', 'e', 's'}; if (!CreateTempFileWithContents(kBytes, static_cast<int>(arraysize(kBytes)), &job.document_path, &job.file_info)) { ADD_FAILURE() << "Failed to create test file."; return false; } job.printer_id = extension_id + ":printer_id"; job.job_title = base::ASCIIToUTF16("Print job"); job.ticket_json = "{}"; job.content_type = "image/pwg-raster"; PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(browser_context()) ->DispatchPrintRequested(job, callback); return true; } void StartCapabilityRequest( const std::string& extension_id, const PrinterProviderAPI::GetCapabilityCallback& callback) { PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(browser_context()) ->DispatchGetCapabilityRequested(extension_id + ":printer_id", callback); } // Loads chrome.printerProvider test app and initializes is for test // |test_param|. // When the app's background page is loaded, the app will send 'loaded' // message. As a response to the message it will expect string message // specifying the test that should be run. When the app initializes its state // (e.g. registers listener for a chrome.printerProvider event) it will send // message 'ready', at which point the test may be started. // If the app is successfully initialized, |*extension_id_out| will be set to // the loaded extension's id, otherwise it will remain unchanged. void InitializePrinterProviderTestApp(const std::string& app_path, const std::string& test_param, std::string* extension_id_out) { ExtensionTestMessageListener loaded_listener("loaded", true); ExtensionTestMessageListener ready_listener("ready", false); const extensions::Extension* extension = LoadApp(app_path); ASSERT_TRUE(extension); const std::string extension_id = extension->id(); loaded_listener.set_extension_id(extension_id); ready_listener.set_extension_id(extension_id); ASSERT_TRUE(loaded_listener.WaitUntilSatisfied()); loaded_listener.Reply(test_param); ASSERT_TRUE(ready_listener.WaitUntilSatisfied()); *extension_id_out = extension_id; } // Runs a test for chrome.printerProvider.onPrintRequested event. // |test_param|: The test that should be run. // |expected_result|: The print result the app is expected to report. void RunPrintRequestTestApp(const std::string& test_param, PrintRequestDataType data_type, const std::string& expected_result) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_print", test_param, &extension_id); if (extension_id.empty()) return; base::RunLoop run_loop; bool success; std::string print_status; PrinterProviderAPI::PrintCallback callback = base::Bind(&RecordPrintResultAndRunCallback, &success, &print_status, run_loop.QuitClosure()); switch (data_type) { case PRINT_REQUEST_DATA_TYPE_NOT_SET: StartPrintRequestWithNoData(extension_id, callback); break; case PRINT_REQUEST_DATA_TYPE_FILE: ASSERT_TRUE(StartPrintRequestUsingFileInfo(extension_id, callback)); break; case PRINT_REQUEST_DATA_TYPE_FILE_DELETED: ASSERT_TRUE(StartPrintRequestUsingFileInfo(extension_id, callback)); ASSERT_TRUE(data_dir_.Delete()); break; case PRINT_REQUEST_DATA_TYPE_BYTES: StartPrintRequestUsingDocumentBytes(extension_id, callback); break; } if (data_type != PRINT_REQUEST_DATA_TYPE_NOT_SET) ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); EXPECT_EQ(expected_result, print_status); EXPECT_EQ(expected_result == "OK", success); } // Runs a test for chrome.printerProvider.onGetCapabilityRequested // event. // |test_param|: The test that should be run. // |expected_result|: The printer capability the app is expected to report. void RunPrinterCapabilitiesRequestTest(const std::string& test_param, const std::string& expected_result) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp( "api_test/printer_provider/request_capability", test_param, &extension_id); if (extension_id.empty()) return; base::RunLoop run_loop; std::string result; StartCapabilityRequest( extension_id, base::Bind(&RecordDictAndRunCallback, &result, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); EXPECT_EQ(expected_result, result); } bool SimulateExtensionUnload(const std::string& extension_id) { extensions::ExtensionRegistry* extension_registry = extensions::ExtensionRegistry::Get(browser_context()); const extensions::Extension* extension = extension_registry->GetExtensionById( extension_id, extensions::ExtensionRegistry::ENABLED); if (!extension) return false; extension_registry->RemoveEnabled(extension_id); extension_registry->TriggerOnUnloaded( extension, extensions::UnloadedExtensionInfo::REASON_TERMINATE); return true; } // Validates that set of printers reported by test apps via // chrome.printerProvider.onGetPritersRequested is the same as the set of // printers in |expected_printers|. |expected_printers| contains list of // printer objects formatted as a JSON string. It is assumed that the values // in |expoected_printers| are unique. void ValidatePrinterListValue( const base::ListValue& printers, const std::vector<std::string>& expected_printers) { ASSERT_EQ(expected_printers.size(), printers.GetSize()); for (size_t i = 0; i < expected_printers.size(); ++i) { JSONStringValueDeserializer deserializer(expected_printers[i]); int error_code; scoped_ptr<base::Value> printer_value( deserializer.Deserialize(&error_code, NULL)); ASSERT_TRUE(printer_value) << "Failed to deserialize " << expected_printers[i] << ": " << "error code " << error_code; EXPECT_TRUE(printers.Find(*printer_value) != printers.end()) << "Unabe to find " << *printer_value << " in " << printers; } } private: // Initializes |data_dir_| if needed and creates a file in it containing // provided data. bool CreateTempFileWithContents(const char* data, int size, base::FilePath* path, base::File::Info* file_info) { if (!data_dir_.IsValid() && !data_dir_.CreateUniqueTempDir()) return false; *path = data_dir_.path().AppendASCII("data.pwg"); int written = base::WriteFile(*path, data, size); if (written != size) return false; if (!base::GetFileInfo(*path, file_info)) return false; return true; } base::ScopedTempDir data_dir_; DISALLOW_COPY_AND_ASSIGN(PrinterProviderApiTest); }; IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintJobSuccess) { RunPrintRequestTestApp("OK", PRINT_REQUEST_DATA_TYPE_BYTES, "OK"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintJobWithFileSuccess) { RunPrintRequestTestApp("OK", PRINT_REQUEST_DATA_TYPE_FILE, "OK"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintJobWithFile_FileDeletedBeforeDispatch) { RunPrintRequestTestApp("OK", PRINT_REQUEST_DATA_TYPE_FILE_DELETED, "INVALID_DATA"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintJobAsyncSuccess) { RunPrintRequestTestApp("ASYNC_RESPONSE", PRINT_REQUEST_DATA_TYPE_BYTES, "OK"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintJobFailed) { RunPrintRequestTestApp("INVALID_TICKET", PRINT_REQUEST_DATA_TYPE_BYTES, "INVALID_TICKET"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, NoPrintEventListener) { RunPrintRequestTestApp("NO_LISTENER", PRINT_REQUEST_DATA_TYPE_BYTES, "FAILED"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintRequestInvalidCallbackParam) { RunPrintRequestTestApp("INVALID_VALUE", PRINT_REQUEST_DATA_TYPE_BYTES, "FAILED"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintRequestDataNotSet) { RunPrintRequestTestApp("IGNORE_CALLBACK", PRINT_REQUEST_DATA_TYPE_NOT_SET, "FAILED"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, PrintRequestAppUnloaded) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_print", "IGNORE_CALLBACK", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; bool success = false; std::string status; StartPrintRequestUsingDocumentBytes( extension_id, base::Bind(&RecordPrintResultAndRunCallback, &success, &status, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(SimulateExtensionUnload(extension_id)); run_loop.Run(); EXPECT_FALSE(success); EXPECT_EQ("FAILED", status); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetCapabilitySuccess) { RunPrinterCapabilitiesRequestTest("OK", "{\"capability\":\"value\"}"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetCapabilityAsyncSuccess) { RunPrinterCapabilitiesRequestTest("ASYNC_RESPONSE", "{\"capability\":\"value\"}"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, EmptyCapability) { RunPrinterCapabilitiesRequestTest("EMPTY", "{}"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, NoCapabilityEventListener) { RunPrinterCapabilitiesRequestTest("NO_LISTENER", "{}"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, CapabilityInvalidValue) { RunPrinterCapabilitiesRequestTest("INVALID_VALUE", "{}"); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetCapabilityAppUnloaded) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp( "api_test/printer_provider/request_capability", "IGNORE_CALLBACK", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; std::string result; StartCapabilityRequest( extension_id, base::Bind(&RecordDictAndRunCallback, &result, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(SimulateExtensionUnload(extension_id)); run_loop.Run(); EXPECT_EQ("{}", result); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersSuccess) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "OK", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); std::vector<std::string> expected_printers; expected_printers.push_back(base::StringPrintf( "{" "\"description\":\"Test printer\"," "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printer1\"," "\"name\":\"Printer 1\"" "}", extension_id.c_str(), extension_id.c_str())); expected_printers.push_back(base::StringPrintf( "{" "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printerNoDesc\"," "\"name\":\"Printer 2\"" "}", extension_id.c_str(), extension_id.c_str())); ValidatePrinterListValue(printers, expected_printers); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersAsyncSuccess) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "ASYNC_RESPONSE", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); std::vector<std::string> expected_printers; expected_printers.push_back(base::StringPrintf( "{" "\"description\":\"Test printer\"," "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printer1\"," "\"name\":\"Printer 1\"" "}", extension_id.c_str(), extension_id.c_str())); ValidatePrinterListValue(printers, expected_printers); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersTwoExtensions) { extensions::ResultCatcher catcher; std::string extension_id_1; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "OK", &extension_id_1); ASSERT_FALSE(extension_id_1.empty()); std::string extension_id_2; InitializePrinterProviderTestApp( "api_test/printer_provider/request_printers_second", "OK", &extension_id_2); ASSERT_FALSE(extension_id_2.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); std::vector<std::string> expected_printers; expected_printers.push_back(base::StringPrintf( "{" "\"description\":\"Test printer\"," "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printer1\"," "\"name\":\"Printer 1\"" "}", extension_id_1.c_str(), extension_id_1.c_str())); expected_printers.push_back(base::StringPrintf( "{" "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printerNoDesc\"," "\"name\":\"Printer 2\"" "}", extension_id_1.c_str(), extension_id_1.c_str())); expected_printers.push_back(base::StringPrintf( "{" "\"description\":\"Test printer\"," "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printer1\"," "\"name\":\"Printer 1\"" "}", extension_id_2.c_str(), extension_id_2.c_str())); expected_printers.push_back(base::StringPrintf( "{" "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printerNoDesc\"," "\"name\":\"Printer 2\"" "}", extension_id_2.c_str(), extension_id_2.c_str())); ValidatePrinterListValue(printers, expected_printers); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersTwoExtensionsBothUnloaded) { extensions::ResultCatcher catcher; std::string extension_id_1; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "IGNORE_CALLBACK", &extension_id_1); ASSERT_FALSE(extension_id_1.empty()); std::string extension_id_2; InitializePrinterProviderTestApp( "api_test/printer_provider/request_printers_second", "IGNORE_CALLBACK", &extension_id_2); ASSERT_FALSE(extension_id_2.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(SimulateExtensionUnload(extension_id_1)); ASSERT_TRUE(SimulateExtensionUnload(extension_id_2)); run_loop.Run(); EXPECT_TRUE(printers.empty()); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersTwoExtensionsOneFails) { extensions::ResultCatcher catcher; std::string extension_id_1; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "NOT_ARRAY", &extension_id_1); ASSERT_FALSE(extension_id_1.empty()); std::string extension_id_2; InitializePrinterProviderTestApp( "api_test/printer_provider/request_printers_second", "OK", &extension_id_2); ASSERT_FALSE(extension_id_2.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); std::vector<std::string> expected_printers; expected_printers.push_back(base::StringPrintf( "{" "\"description\":\"Test printer\"," "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printer1\"," "\"name\":\"Printer 1\"" "}", extension_id_2.c_str(), extension_id_2.c_str())); expected_printers.push_back(base::StringPrintf( "{" "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printerNoDesc\"," "\"name\":\"Printer 2\"" "}", extension_id_2.c_str(), extension_id_2.c_str())); ValidatePrinterListValue(printers, expected_printers); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersTwoExtensionsOneWithNoListener) { extensions::ResultCatcher catcher; std::string extension_id_1; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "NO_LISTENER", &extension_id_1); ASSERT_FALSE(extension_id_1.empty()); std::string extension_id_2; InitializePrinterProviderTestApp( "api_test/printer_provider/request_printers_second", "OK", &extension_id_2); ASSERT_FALSE(extension_id_2.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); std::vector<std::string> expected_printers; expected_printers.push_back(base::StringPrintf( "{" "\"description\":\"Test printer\"," "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printer1\"," "\"name\":\"Printer 1\"" "}", extension_id_2.c_str(), extension_id_2.c_str())); expected_printers.push_back(base::StringPrintf( "{" "\"extensionId\":\"%s\"," "\"extensionName\": \"Test printer provider\"," "\"id\":\"%s:printerNoDesc\"," "\"name\":\"Printer 2\"" "}", extension_id_2.c_str(), extension_id_2.c_str())); ValidatePrinterListValue(printers, expected_printers); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersNoListener) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "NO_LISTENER", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); EXPECT_TRUE(printers.empty()); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersNotArray) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "NOT_ARRAY", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); EXPECT_TRUE(printers.empty()); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersInvalidPrinterValueType) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "INVALID_PRINTER_TYPE", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); EXPECT_TRUE(printers.empty()); } IN_PROC_BROWSER_TEST_F(PrinterProviderApiTest, GetPrintersInvalidPrinterValue) { extensions::ResultCatcher catcher; std::string extension_id; InitializePrinterProviderTestApp("api_test/printer_provider/request_printers", "INVALID_PRINTER", &extension_id); ASSERT_FALSE(extension_id.empty()); base::RunLoop run_loop; base::ListValue printers; StartGetPrintersRequest(base::Bind(&AppendPrintersAndRunCallbackIfDone, &printers, run_loop.QuitClosure())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); run_loop.Run(); EXPECT_TRUE(printers.empty()); } } // namespace
{ "content_hash": "e99d98aa7e4846b313962767fa0eaded", "timestamp": "", "source": "github", "line_count": 750, "max_line_length": 80, "avg_line_length": 35.141333333333336, "alnum_prop": 0.6505918955835484, "repo_name": "fujunwei/chromium-crosswalk", "id": "dfe5086ed684e52ab5349be678cf38bf9c1db4a3", "size": "27423", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "extensions/browser/api/printer_provider/printer_provider_apitest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "23829" }, { "name": "Batchfile", "bytes": "8451" }, { "name": "C", "bytes": "4116349" }, { "name": "C++", "bytes": "233601977" }, { "name": "CSS", "bytes": "931025" }, { "name": "Emacs Lisp", "bytes": "988" }, { "name": "HTML", "bytes": "28881204" }, { "name": "Java", "bytes": "9824090" }, { "name": "JavaScript", "bytes": "19683742" }, { "name": "Makefile", "bytes": "68017" }, { "name": "Objective-C", "bytes": "1478432" }, { "name": "Objective-C++", "bytes": "8653645" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "171186" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "456460" }, { "name": "Python", "bytes": "7963013" }, { "name": "Shell", "bytes": "468673" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
require 'spec_helper' describe Chef::Provider::Service::Systemd do let(:node) { Chef::Node.new } let(:events) { Chef::EventDispatch::Dispatcher.new } let(:run_context) { Chef::RunContext.new(node, {}, events) } let(:service_name) { "rsyslog.service" } let(:new_resource) { Chef::Resource::Service.new(service_name) } let(:provider) { Chef::Provider::Service::Systemd.new(new_resource, run_context) } let(:shell_out_success) do double('shell_out_with_systems_locale', exitstatus: 0, :error? => false) end let(:shell_out_failure) do double('shell_out_with_systems_locale', exitstatus: 1, :error? => true) end let(:current_resource) { Chef::Resource::Service.new(service_name) } before(:each) do allow(Chef::Resource::Service).to receive(:new).with(service_name).and_return(current_resource) end describe "load_current_resource" do before(:each) do allow(provider).to receive(:is_active?).and_return(false) allow(provider).to receive(:is_enabled?).and_return(false) end it "should create a current resource with the name of the new resource" do expect(Chef::Resource::Service).to receive(:new).with(new_resource.name).and_return(current_resource) provider.load_current_resource end it "should set the current resources service name to the new resources service name" do provider.load_current_resource expect(current_resource.service_name).to eql(service_name) end it "should check if the service is running" do expect(provider).to receive(:is_active?) provider.load_current_resource end it "should set running to true if the service is running" do allow(provider).to receive(:is_active?).and_return(true) provider.load_current_resource expect(current_resource.running).to be true end it "should set running to false if the service is not running" do allow(provider).to receive(:is_active?).and_return(false) provider.load_current_resource expect(current_resource.running).to be false end describe "when a status command has been specified" do before do allow(new_resource).to receive(:status_command).and_return("/bin/chefhasmonkeypants status") end it "should run the services status command if one has been specified" do allow(provider).to receive(:shell_out).and_return(shell_out_success) provider.load_current_resource expect(current_resource.running).to be true end it "should run the services status command if one has been specified and properly set status check state" do allow(provider).to receive(:shell_out).with("/bin/chefhasmonkeypants status").and_return(shell_out_success) provider.load_current_resource expect(provider.status_check_success).to be true end it "should set running to false if a status command fails" do allow(provider).to receive(:shell_out).and_return(shell_out_failure) provider.load_current_resource expect(current_resource.running).to be false end it "should update state to indicate status check failed when a status command fails" do allow(provider).to receive(:shell_out).and_return(shell_out_failure) provider.load_current_resource expect(provider.status_check_success).to be false end end it "should check if the service is enabled" do expect(provider).to receive(:is_enabled?) provider.load_current_resource end it "should set enabled to true if the service is enabled" do allow(provider).to receive(:is_enabled?).and_return(true) provider.load_current_resource expect(current_resource.enabled).to be true end it "should set enabled to false if the service is not enabled" do allow(provider).to receive(:is_enabled?).and_return(false) provider.load_current_resource expect(current_resource.enabled).to be false end it "should return the current resource" do expect(provider.load_current_resource).to eql(current_resource) end end def setup_current_resource provider.current_resource = current_resource current_resource.service_name(service_name) end %w{/usr/bin/systemctl /bin/systemctl}.each do |systemctl_path| describe "when systemctl path is #{systemctl_path}" do before(:each) do setup_current_resource allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path) end describe "start and stop service" do it "should call the start command if one is specified" do allow(new_resource).to receive(:start_command).and_return("/sbin/rsyslog startyousillysally") expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog startyousillysally") provider.start_service end it "should call '#{systemctl_path} start service_name' if no start command is specified" do expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} start #{service_name}").and_return(shell_out_success) provider.start_service end it "should not call '#{systemctl_path} start service_name' if it is already running" do current_resource.running(true) expect(provider).not_to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} start #{service_name}") provider.start_service end it "should call the restart command if one is specified" do current_resource.running(true) allow(new_resource).to receive(:restart_command).and_return("/sbin/rsyslog restartyousillysally") expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog restartyousillysally") provider.restart_service end it "should call '#{systemctl_path} restart service_name' if no restart command is specified" do current_resource.running(true) expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} restart #{service_name}").and_return(shell_out_success) provider.restart_service end describe "reload service" do context "when a reload command is specified" do it "should call the reload command" do current_resource.running(true) allow(new_resource).to receive(:reload_command).and_return("/sbin/rsyslog reloadyousillysally") expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog reloadyousillysally") provider.reload_service end end context "when a reload command is not specified" do it "should call '#{systemctl_path} reload service_name' if the service is running" do current_resource.running(true) expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} reload #{service_name}").and_return(shell_out_success) provider.reload_service end it "should start the service if the service is not running" do current_resource.running(false) expect(provider).to receive(:start_service).and_return(true) provider.reload_service end end end it "should call the stop command if one is specified" do current_resource.running(true) allow(new_resource).to receive(:stop_command).and_return("/sbin/rsyslog stopyousillysally") expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog stopyousillysally") provider.stop_service end it "should call '#{systemctl_path} stop service_name' if no stop command is specified" do current_resource.running(true) expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} stop #{service_name}").and_return(shell_out_success) provider.stop_service end it "should not call '#{systemctl_path} stop service_name' if it is already stopped" do current_resource.running(false) expect(provider).not_to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} stop #{service_name}") provider.stop_service end end describe "enable and disable service" do before(:each) do provider.current_resource = current_resource current_resource.service_name(service_name) allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}") end it "should call '#{systemctl_path} enable service_name' to enable the service" do expect(provider).to receive(:shell_out!).with("#{systemctl_path} enable #{service_name}").and_return(shell_out_success) provider.enable_service end it "should call '#{systemctl_path} disable service_name' to disable the service" do expect(provider).to receive(:shell_out!).with("#{systemctl_path} disable #{service_name}").and_return(shell_out_success) provider.disable_service end end describe "is_active?" do before(:each) do provider.current_resource = current_resource current_resource.service_name(service_name) allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}") end it "should return true if '#{systemctl_path} is-active service_name' returns 0" do expect(provider).to receive(:shell_out).with("#{systemctl_path} is-active #{service_name} --quiet").and_return(shell_out_success) expect(provider.is_active?).to be true end it "should return false if '#{systemctl_path} is-active service_name' returns anything except 0" do expect(provider).to receive(:shell_out).with("#{systemctl_path} is-active #{service_name} --quiet").and_return(shell_out_failure) expect(provider.is_active?).to be false end end describe "is_enabled?" do before(:each) do provider.current_resource = current_resource current_resource.service_name(service_name) allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}") end it "should return true if '#{systemctl_path} is-enabled service_name' returns 0" do expect(provider).to receive(:shell_out).with("#{systemctl_path} is-enabled #{service_name} --quiet").and_return(shell_out_success) expect(provider.is_enabled?).to be true end it "should return false if '#{systemctl_path} is-enabled service_name' returns anything except 0" do expect(provider).to receive(:shell_out).with("#{systemctl_path} is-enabled #{service_name} --quiet").and_return(shell_out_failure) expect(provider.is_enabled?).to be false end end end end end
{ "content_hash": "c70683533a97c5ad6d53239cb234d787", "timestamp": "", "source": "github", "line_count": 261, "max_line_length": 153, "avg_line_length": 42.3639846743295, "alnum_prop": 0.6678122456362485, "repo_name": "askl56/chef", "id": "b02ceff2616ee8066260fdb83609794aeab4e66f", "size": "11740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/unit/provider/service/systemd_service_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "386" }, { "name": "CSS", "bytes": "21551" }, { "name": "Groff", "bytes": "270674" }, { "name": "HTML", "bytes": "542920" }, { "name": "JavaScript", "bytes": "49785" }, { "name": "Makefile", "bytes": "884" }, { "name": "Perl6", "bytes": "64" }, { "name": "PowerShell", "bytes": "12510" }, { "name": "Python", "bytes": "9728" }, { "name": "Ruby", "bytes": "7270663" }, { "name": "Shell", "bytes": "688" } ], "symlink_target": "" }
/** * */ package br.com.tamandua.service.vo; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; /** * @author Everton Rosario ([email protected]) */ @XmlRootElement(name = "music_album") public class MusicAlbumVO implements Serializable { private static final long serialVersionUID = 1L; private MusicAlbumIdVO id; private Integer numIndex; /** * @return the id */ public MusicAlbumIdVO getId() { return id; } /** * @param id the id to set */ public void setId(MusicAlbumIdVO id) { this.id = id; } /** * @return the numIndex */ public Integer getNumIndex() { return numIndex; } /** * @param numIndex the numIndex to set */ public void setNumIndex(Integer numIndex) { this.numIndex = numIndex; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((numIndex == null) ? 0 : numIndex.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MusicAlbumVO other = (MusicAlbumVO) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (numIndex == null) { if (other.numIndex != null) return false; } else if (!numIndex.equals(other.numIndex)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "MusicAlbumVO [" + (id != null ? "id=" + id + ", " : "") + (numIndex != null ? "numIndex=" + numIndex : "") + "]"; } }
{ "content_hash": "e75bc7156630d6098bb0f7f7dd3b4024", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 129, "avg_line_length": 26.195402298850574, "alnum_prop": 0.5146994295743748, "repo_name": "everton-rosario/tamandua", "id": "ab57198c4323c66bfb9735f7d8c507891b45f783", "size": "2279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/tamandua-ws-client/src/main/java/br/com/tamandua/service/vo/MusicAlbumVO.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "73883" }, { "name": "Erlang", "bytes": "553" }, { "name": "Groovy", "bytes": "241" }, { "name": "Java", "bytes": "932667" }, { "name": "JavaScript", "bytes": "162300" }, { "name": "PHP", "bytes": "1039" }, { "name": "Perl", "bytes": "25153" }, { "name": "Racket", "bytes": "3517" }, { "name": "Ruby", "bytes": "87" }, { "name": "Shell", "bytes": "28274" } ], "symlink_target": "" }
package mxgo import ( "github.com/howeyc/fsnotify" "path" "strings" ) func WatchDoTask(callback func(filePath string, event *fsnotify.FileEvent), filePaths ...string) { watcher, err := fsnotify.NewWatcher() if err != nil { mxLog.Error(err) } go func() { for { select { case ev := <-watcher.Event: if !strings.HasPrefix(path.Base(ev.Name), ".") { callback(ev.Name, ev) } case <-watcher.Error: continue } } }() for i := range filePaths { err = watcher.Watch(filePaths[i]) if err != nil { mxLog.Error(err) } } }
{ "content_hash": "f460760a1204495cdb9909bb1c4a4d80", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 98, "avg_line_length": 16.676470588235293, "alnum_prop": 0.6119929453262787, "repo_name": "menghx/mxgo", "id": "87ccc257b1261686be34425a4990b81e72966e06", "size": "567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "watcher.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "16398" } ], "symlink_target": "" }
<!doctype html><title>Minimal tQuery Page</title> <script src="../../../build/tquery-bundle-require.js"></script> <script src="../../../vendor/three.js/examples/js/shaders/BlendShader.js"></script> <body><script> require(['tquery.pproc'], function(){ var world = tQuery.createWorld().boilerplate().start(); world.removeCameraControls() // your code goes here // setup the RenderTarget var textureW = 1024; var textureH = 1024; var rtTexture = new THREE.WebGLRenderTarget(textureW, textureH, { minFilter : THREE.LinearFilter, magFilter : THREE.NearestFilter, format : THREE.RGBAFormat }); var tSceneGlow = new THREE.Scene(); var tCameraGlow = new THREE.PerspectiveCamera(45, textureW/textureH, 0.01, 10000 ); tCameraGlow.position = world.camera().get(0).position; tCameraGlow.rotation = world.camera().get(0).rotation; tSceneGlow.add(tCameraGlow); // THREEx.WindowResize.bind(rtTexture, tCameraGlow) torus = tQuery.createTorus().addTo(tSceneGlow) .scaleBy(2) // var glowRenderer = new THREE.WebGLRenderer(); // //glowRenderer.autoClear = true; // glowRenderer.setSize( textureW, textureH ); var glowRenderer = world.tRenderer(); console.dir(glowRenderer) world.hook(function(delta, now){ var tScene = tSceneGlow var tCamera = world.camera().get(0) glowRenderer.autoClear = true; glowRenderer.render(tSceneGlow, tCameraGlow, rtTexture, true); glowRenderer.autoClear = false; }) world.hook(function(delta, now){ torus.rotateY(delta * Math.PI * 2 * 1) }) var object = tQuery.createPlane().addTo(world) .scaleBy(2) .setBasicMaterial() .color('red') //.map(rtTexture) .map('../../assets/images/ash_uvgrid01.jpg') .back() var composer = tQuery.createEffectComposer() .renderPass() effectBlend.uniforms[ 'tDiffuse2' ].value = effectSave.renderTarget; effectBlend.uniforms[ 'mixRatio' ].value = 0.65; var effect = new THREE.ShaderPass( blendShader ); composer._tComposer.addPass( effect ); composer.finish(); // console.dir(composer.tComposer()) }); </script></body>
{ "content_hash": "1a301234fa84b972840e76c704ae40d9", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 84, "avg_line_length": 29.2, "alnum_prop": 0.7123287671232876, "repo_name": "modulexcite/tquery", "id": "ec44e2c8ecb8d3095f8fd1b6d641a48ef2aa8bd4", "size": "2044", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "plugins/glow/examples/manual.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "303" }, { "name": "CSS", "bytes": "43714" }, { "name": "HTML", "bytes": "878509" }, { "name": "Java", "bytes": "553" }, { "name": "JavaScript", "bytes": "4312631" }, { "name": "Makefile", "bytes": "7946" }, { "name": "PHP", "bytes": "7474" }, { "name": "Python", "bytes": "6114" }, { "name": "Ruby", "bytes": "920" }, { "name": "Shell", "bytes": "154" } ], "symlink_target": "" }
from django.utils.version import get_version VERSION = (3, 2, 15, 'alpha', 0) __version__ = get_version(VERSION) def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf import settings from django.urls import set_script_prefix from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) if set_prefix: set_script_prefix( '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME ) apps.populate(settings.INSTALLED_APPS)
{ "content_hash": "51cbba8c7222c5ad5a42ec0810c320b7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 85, "avg_line_length": 33.333333333333336, "alnum_prop": 0.70625, "repo_name": "koordinates/django", "id": "99439c4f61c8186eeb6908a06a73a88ccb95d7e1", "size": "800", "binary": false, "copies": "1", "ref": "refs/heads/stable/3.2.x-kx", "path": "django/__init__.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "84917" }, { "name": "HTML", "bytes": "223820" }, { "name": "JavaScript", "bytes": "139791" }, { "name": "Makefile", "bytes": "125" }, { "name": "Procfile", "bytes": "47" }, { "name": "Python", "bytes": "14472067" }, { "name": "Shell", "bytes": "809" }, { "name": "Smarty", "bytes": "142" } ], "symlink_target": "" }
#include "libtorrent/session.hpp" #include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/alert_types.hpp" using namespace libtorrent; namespace lt = libtorrent; int test_main() { settings_pack p; p.set_int(settings_pack::alert_mask, ~0); lt::session ses(p); settings_pack sett; sett.set_int(settings_pack::cache_size, 100); sett.set_int(settings_pack::max_queued_disk_bytes, 1000 * 16 * 1024); ses.apply_settings(sett); // verify that we get the appropriate performance warning because // we're allowing a larger queue than we have cache. alert const* a; for (;;) { a = wait_for_alert(ses, performance_alert::alert_type, "ses1"); if (a == NULL) break; TEST_EQUAL(a->type(), performance_alert::alert_type); if (alert_cast<performance_alert>(a)->warning_code == performance_alert::too_high_disk_queue_limit) break; } TEST_CHECK(a); sett.set_int(settings_pack::unchoke_slots_limit, 0); ses.apply_settings(sett); TEST_CHECK(ses.get_settings().get_int(settings_pack::unchoke_slots_limit) == 0); sett.set_int(settings_pack::unchoke_slots_limit, -1); ses.apply_settings(sett); TEST_CHECK(ses.get_settings().get_int(settings_pack::unchoke_slots_limit) == -1); sett.set_int(settings_pack::unchoke_slots_limit, 8); ses.apply_settings(sett); TEST_CHECK(ses.get_settings().get_int(settings_pack::unchoke_slots_limit) == 8); // make sure the destructor waits properly // for the asynchronous call to set the alert // mask completes, before it goes on to destruct // the session object return 0; }
{ "content_hash": "afce13624c4a3670a6bc01b5ee3877b5", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 82, "avg_line_length": 25.57377049180328, "alnum_prop": 0.7083333333333334, "repo_name": "TeoTwawki/libtorrent", "id": "af81e68202272c64d23023058b25fe92ed6e6bd4", "size": "3077", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/test_session.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "432668" }, { "name": "C++", "bytes": "5345256" }, { "name": "CMake", "bytes": "14380" }, { "name": "JavaScript", "bytes": "4394" }, { "name": "Perl", "bytes": "22273" }, { "name": "Python", "bytes": "58234" }, { "name": "Shell", "bytes": "23494" } ], "symlink_target": "" }
package org.apache.lucene.analysis.fa; /** * Normalizer for Persian. * <p> * Normalization is done in-place for efficiency, operating on a termbuffer. * <p> * Normalization is defined as: * <ul> * <li>Normalization of various heh + hamza forms and heh goal to heh. * <li>Normalization of farsi yeh and yeh barree to arabic yeh * <li>Normalization of persian keheh to arabic kaf * </ul> * */ public class PersianNormalizer { public static final char YEH = '\u064A'; public static final char FARSI_YEH = '\u06CC'; public static final char YEH_BARREE = '\u06D2'; public static final char KEHEH = '\u06A9'; public static final char KAF = '\u0643'; public static final char HAMZA_ABOVE = '\u0654'; public static final char HEH_YEH = '\u06C0'; public static final char HEH_GOAL = '\u06C1'; public static final char HEH = '\u0647'; /** * Normalize an input buffer of Persian text * * @param s input buffer * @param len length of input buffer * @return length of input buffer after normalization */ public int normalize(char s[], int len) { for (int i = 0; i < len; i++) { if (s[i] == FARSI_YEH || s[i] == YEH_BARREE) s[i] = YEH; if (s[i] == KEHEH) s[i] = KAF; if (s[i] == HEH_YEH || s[i] == HEH_GOAL) s[i] = HEH; if (s[i] == HAMZA_ABOVE) { // necessary for HEH + HAMZA len = delete(s, i, len); i--; } } return len; } /** * Delete a character in-place * * @param s Input Buffer * @param pos Position of character to delete * @param len length of input buffer * @return length of input buffer after deletion */ protected int delete(char s[], int pos, int len) { if (pos < len) System.arraycopy(s, pos + 1, s, pos, len - pos - 1); return len - 1; } }
{ "content_hash": "3be063a84e32e891afa2a6ba6761a7fd", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 76, "avg_line_length": 23.0125, "alnum_prop": 0.603476371537208, "repo_name": "Photobucket/Solbase-Lucene", "id": "53caa6ebbf088f877fc3b17c7e7a39955ce56fc8", "size": "2643", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "contrib/analyzers/common/src/java/org/apache/lucene/analysis/fa/PersianNormalizer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9882222" }, { "name": "JavaScript", "bytes": "43988" }, { "name": "Perl", "bytes": "32431" }, { "name": "Shell", "bytes": "1183" } ], "symlink_target": "" }
using System; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json; using System.Linq; using STEP; namespace IFC { /// <summary> /// <see href="http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifccompressor.htm"/> /// </summary> public partial class IfcCompressor : IfcFlowMovingDevice { public IfcCompressorTypeEnum PredefinedType{get;set;} // optional /// <summary> /// Construct a IfcCompressor with all required attributes. /// </summary> public IfcCompressor(IfcGloballyUniqueId globalId):base(globalId) { } /// <summary> /// Construct a IfcCompressor with required and optional attributes. /// </summary> [JsonConstructor] public IfcCompressor(IfcGloballyUniqueId globalId,IfcOwnerHistory ownerHistory,IfcLabel name,IfcText description,IfcLabel objectType,IfcObjectPlacement objectPlacement,IfcProductRepresentation representation,IfcIdentifier tag,IfcCompressorTypeEnum predefinedType):base(globalId,ownerHistory,name,description,objectType,objectPlacement,representation,tag) { PredefinedType = predefinedType; } public static new IfcCompressor FromJSON(string json){ return JsonConvert.DeserializeObject<IfcCompressor>(json); } public override string GetStepParameters() { var parameters = new List<string>(); parameters.Add(GlobalId != null ? GlobalId.ToStepValue() : "$"); parameters.Add(OwnerHistory != null ? OwnerHistory.ToStepValue() : "$"); parameters.Add(Name != null ? Name.ToStepValue() : "$"); parameters.Add(Description != null ? Description.ToStepValue() : "$"); parameters.Add(ObjectType != null ? ObjectType.ToStepValue() : "$"); parameters.Add(ObjectPlacement != null ? ObjectPlacement.ToStepValue() : "$"); parameters.Add(Representation != null ? Representation.ToStepValue() : "$"); parameters.Add(Tag != null ? Tag.ToStepValue() : "$"); parameters.Add(PredefinedType.ToStepValue()); return string.Join(", ", parameters.ToArray()); } } }
{ "content_hash": "deb35ab157a8090d0605c500f8df0a71", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 356, "avg_line_length": 37.629629629629626, "alnum_prop": 0.7258858267716536, "repo_name": "ikeough/IFC-gen", "id": "08f953fa2511e2aeac85b3812b13975d4b52e221", "size": "2034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lang/csharp/src/IFC/IfcCompressor.g.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "16049" }, { "name": "Batchfile", "bytes": "593" }, { "name": "C#", "bytes": "2679991" }, { "name": "JavaScript", "bytes": "319" }, { "name": "Makefile", "bytes": "1222" }, { "name": "TypeScript", "bytes": "1605804" } ], "symlink_target": "" }
/** * @externs */ class DualDefer { /** * @param {function(!angular.$http.Response): ?} resolveCallback * @return {DualDefer} */ onCacheFetched(resolveCallback) {} /** * @param {function(!angular.$http.Response): ?} resolveCallback * @param {(function(!angular.$http.Response): ?)=} opt_rejectCallback * @return {DualDefer} */ onServerResponded(resolveCallback, opt_rejectCallback) {} /** * @param {function(!angular.$http.Response): ?} callback * @return {DualDefer} */ finally(callback) {} } class DualHttpService { /** * @param {string} url * @param {angular.$http.Config=} opt_config * @return {!DualDefer} */ get(url, opt_config) {} }
{ "content_hash": "bc94b05f7b023d3a7a023229f3c764f6", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 72, "avg_line_length": 19.135135135135137, "alnum_prop": 0.617231638418079, "repo_name": "google/dualhttp", "id": "6fc264faefc506b8e942138fa5d5ba54d9f1feb6", "size": "1337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/for_angular_externs.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "5669" }, { "name": "Python", "bytes": "871" } ], "symlink_target": "" }
package com.github.plastiv.crashlyticsdemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.crashlytics.android.Crashlytics; public class CrashlyticsDemoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crashlytics_demo); findViewById(R.id.buttonHandled).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { throw new RuntimeException("Check Crashlytics handled exceptions are working"); } catch (Exception e) { Crashlytics.getInstance().core.logException(e); } } }); findViewById(R.id.buttonUnhandled).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { throw new RuntimeException("Check Crashlytics Unhandled exceptions are working"); } }); } }
{ "content_hash": "5d5c9c9dc6ed0f4ef83f14430bf706a7", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 99, "avg_line_length": 34.25, "alnum_prop": 0.6478102189781022, "repo_name": "plastiv/CrashlyticsDemo", "id": "097c4b5da3d978e7bfdfa592f933b6dde47463e6", "size": "1096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/github/plastiv/crashlyticsdemo/CrashlyticsDemoActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1500" } ], "symlink_target": "" }
export { default as Application } from './system/application'; export { default as ApplicationInstance } from './system/application-instance'; export { default as Resolver } from './system/resolver'; export { default as Engine } from './system/engine'; export { default as EngineInstance } from './system/engine-instance'; export { getEngineParent, setEngineParent } from './system/engine-parent';
{ "content_hash": "4b52958c5272d6105f8878df0475eeb5", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 79, "avg_line_length": 66.33333333333333, "alnum_prop": 0.7512562814070352, "repo_name": "Gaurav0/ember.js", "id": "2cba30ca7dc90827c206f1a74239ff8854f8bbeb", "size": "398", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/ember-application/lib/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "9386" }, { "name": "JavaScript", "bytes": "3680676" }, { "name": "Shell", "bytes": "730" }, { "name": "TypeScript", "bytes": "283048" } ], "symlink_target": "" }
package server.userauth; import java.sql.Date; import java.util.concurrent.ConcurrentHashMap; import javax.crypto.SecretKey; import org.json.JSONObject; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslMasterTokenException; import com.netflix.msl.MslUserIdTokenException; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.tokens.TokenFactory; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.util.JsonUtils; import com.netflix.msl.util.MslContext; /** * <p>A memory-backed token factory.</p> * * @author Wesley Miaw <[email protected]> */ public class SimpleTokenFactory implements TokenFactory { /** Renewal window start offset in milliseconds. */ private static final int RENEWAL_OFFSET = 60000; /** Expiration offset in milliseconds. */ private static final int EXPIRATION_OFFSET = 120000; /** Non-replayable ID acceptance window. */ private static final long NON_REPLAYABLE_ID_WINDOW = 65536; /** * Return true if the provided master token is the newest master token * as far as we know. * * @param masterToken the master token. * @return true if this is the newest master token. * @throws MslMasterTokenException if the master token is not decrypted. */ private boolean isNewestMasterToken(final MasterToken masterToken) throws MslMasterTokenException { if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); // Return true if we have no sequence number records or if the master // token sequence number is the most recently issued one. final Long newestSeqNo = mtSequenceNumbers.get(masterToken.getIdentity()); return (newestSeqNo == null || newestSeqNo.longValue() == masterToken.getSequenceNumber()); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRevoked(final MslContext ctx, final MasterToken masterToken) { // No support for revoked master tokens. return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#acceptNonReplayableId(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, long) */ @Override public MslError acceptNonReplayableId(final MslContext ctx, final MasterToken masterToken, final long nonReplayableId) throws MslException { if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); if (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "nonReplayableId " + nonReplayableId); // Accept if there is no non-replayable ID. final String key = masterToken.getIdentity() + ":" + masterToken.getSerialNumber(); final Long largestNonReplayableId = nonReplayableIds.get(key); if (largestNonReplayableId == null) { nonReplayableIds.put(key, nonReplayableId); return null; } // Reject if the non-replayable ID is equal or just a few messages // behind. The sender can recover by incrementing. final long catchupWindow = MslConstants.MAX_MESSAGES / 2; if (nonReplayableId <= largestNonReplayableId && nonReplayableId > largestNonReplayableId - catchupWindow) { return MslError.MESSAGE_REPLAYED; } // Reject if the non-replayable ID is larger by more than the // acceptance window. The sender cannot recover quickly. if (nonReplayableId - NON_REPLAYABLE_ID_WINDOW > largestNonReplayableId) return MslError.MESSAGE_REPLAYED_UNRECOVERABLE; // If the non-replayable ID is smaller reject it if it is outside the // wrap-around window. The sender cannot recover quickly. if (nonReplayableId < largestNonReplayableId) { final long cutoff = largestNonReplayableId - MslConstants.MAX_LONG_VALUE + NON_REPLAYABLE_ID_WINDOW; if (nonReplayableId >= cutoff) return MslError.MESSAGE_REPLAYED_UNRECOVERABLE; } // Accept the non-replayable ID. // // This is not perfect, since it's possible a smaller value will // overwrite a larger value, but it's good enough for the example. nonReplayableIds.put(key, nonReplayableId); return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData, javax.crypto.SecretKey, javax.crypto.SecretKey, org.json.JSONObject) */ @Override public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final JSONObject issuerData) throws MslEncodingException, MslCryptoException { final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); final long sequenceNumber = 0; long serialNumber = -1; do { serialNumber = ctx.getRandom().nextLong(); } while (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE); final String identity = entityAuthData.getIdentity(); final MasterToken masterToken = new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, issuerData, identity, encryptionKey, hmacKey); // Remember the sequence number. // // This is not perfect, since it's possible a smaller value will // overwrite a larger value, but it's good enough for the example. mtSequenceNumbers.put(identity, sequenceNumber); // Return the new master token. return masterToken; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRenewable(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRenewable(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException { if (!isNewestMasterToken(masterToken)) return MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC; return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, javax.crypto.SecretKey, javax.crypto.SecretKey, org.json.JSONObject) */ @Override public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final JSONObject issuerData) throws MslEncodingException, MslCryptoException, MslMasterTokenException { if (!isNewestMasterToken(masterToken)) throw new MslMasterTokenException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC, masterToken); // Renew master token. final JSONObject mergedIssuerData = JsonUtils.merge(masterToken.getIssuerData(), issuerData); final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); final long oldSequenceNumber = masterToken.getSequenceNumber(); final long sequenceNumber = (oldSequenceNumber == MslConstants.MAX_LONG_VALUE) ? 0 : oldSequenceNumber + 1; final long serialNumber = masterToken.getSerialNumber(); final String identity = masterToken.getIdentity(); final MasterToken newMasterToken = new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, mergedIssuerData, identity, encryptionKey, hmacKey); // Remember the sequence number. // // This is not perfect, since it's possible a smaller value will // overwrite a larger value, but it's good enough for the example. mtSequenceNumbers.put(identity, sequenceNumber); // Return the new master token. return newMasterToken; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isUserIdTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken) */ @Override public MslError isUserIdTokenRevoked(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) { // No support for revoked user ID tokens. return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MslUser, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslEncodingException, MslCryptoException { final JSONObject issuerData = null; final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); long serialNumber = -1; do { serialNumber = ctx.getRandom().nextLong(); } while (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE); return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.UserIdToken, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) throws MslEncodingException, MslCryptoException, MslUserIdTokenException { if (!userIdToken.isDecrypted()) throw new MslUserIdTokenException(MslError.USERIDTOKEN_NOT_DECRYPTED, userIdToken).setMasterToken(masterToken); final JSONObject issuerData = null; final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); final long serialNumber = userIdToken.getSerialNumber(); final MslUser user = userIdToken.getUser(); return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUser(com.netflix.msl.util.MslContext, java.lang.String) */ @Override public MslUser createUser(final MslContext ctx, final String userdata) { return new SimpleUser(userdata); } /** Map of entity identities onto sequence numbers. */ private final ConcurrentHashMap<String,Long> mtSequenceNumbers = new ConcurrentHashMap<String,Long>(); /** Map of entity identities and serial numbers onto non-replayable IDs. */ private final ConcurrentHashMap<String,Long> nonReplayableIds = new ConcurrentHashMap<String,Long>(); }
{ "content_hash": "c35ab52f44a403b84e022413b5f58f8a", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 252, "avg_line_length": 50.43231441048035, "alnum_prop": 0.7112304095592692, "repo_name": "rspieldenner/msl", "id": "80f0e5e75291afd348c37e5dba57123050301655", "size": "12172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/simple/src/main/java/server/userauth/SimpleTokenFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6537" }, { "name": "HTML", "bytes": "26023" }, { "name": "Java", "bytes": "3043532" }, { "name": "JavaScript", "bytes": "3838693" } ], "symlink_target": "" }
import { createStore } from 'redux'; import rootReducer from '../reducers/accountReducers'; export default function configureStore(initialState) { return createStore( rootReducer, initialState ); }
{ "content_hash": "1b6108fc567de78aa460255f62f4d391", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 54, "avg_line_length": 24.77777777777778, "alnum_prop": 0.7040358744394619, "repo_name": "opopeieie/plant-static", "id": "943e16048d9a035ff79031440cf209ded0bc6cd7", "size": "223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plant/src/redux/store/configureStore.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8855" }, { "name": "JavaScript", "bytes": "17644" } ], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var runQuery_1 = require("./runQuery"); exports.runQuery = runQuery_1.runQuery; exports.LogStep = runQuery_1.LogStep; exports.LogAction = runQuery_1.LogAction; var runHttpQuery_1 = require("./runHttpQuery"); exports.runHttpQuery = runHttpQuery_1.runHttpQuery; exports.HttpQueryError = runHttpQuery_1.HttpQueryError; var graphqlOptions_1 = require("./graphqlOptions"); exports.resolveGraphqlOptions = graphqlOptions_1.resolveGraphqlOptions; //# sourceMappingURL=index.js.map
{ "content_hash": "3d0281542c934bba79174faae5de73a4", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 71, "avg_line_length": 45.833333333333336, "alnum_prop": 0.7854545454545454, "repo_name": "Daadler6/graphql-boilerplate", "id": "d806ab9469b1a6f86f62d88cfe643f9a3c5d68b6", "size": "550", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/apollo-server-core/dist/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "5767" } ], "symlink_target": "" }
from datetime import date, timedelta import os from django import forms from wefacts import wefacts import util from models import Order class OrderForm(forms.Form): weather_address = forms.CharField(label='Address', max_length=100000, required=False, widget=forms.TextInput(attrs={'size': 38})) weather_start_date = forms.DateField(label='From', input_formats=['%Y-%m-%d'], initial=date.today()-timedelta(days=14), widget=forms.TextInput(attrs={'size': 12})) weather_end_date = forms.DateField(label='To', input_formats=['%Y-%m-%d'], initial=date.today()-timedelta(days=7), widget=forms.TextInput(attrs={'size': 12})) customer_email = forms.EmailField(label='Your Email (optional)', required=False) class DocumentForm(forms.Form): address_file = forms.FileField( label='Upload address list (separated by lines) ', widget=forms.ClearableFileInput(attrs={'size': 40}) ) class StationChoiceForm(forms.Form): def __init__(self, *args, **kwargs): order_id = kwargs.pop('order_id') order = Order.objects.get(pk=order_id) address_list = [a.strip() for a in order.weather_address.split(';')] start_date_local = int(order.weather_start_date.strftime('%Y%m%d')) end_date_local = int(order.weather_end_date.strftime('%Y%m%d')) metadata_list = [_get_nearby_stations_metadata(address, start_date_local, end_date_local) for address in address_list] stations, initial_stations = [], [] for meta, addr in zip(metadata_list, address_list): if meta is None: stations.append(('no_station_found', '%s : No stations found. Try another address :) ' % addr)) else: ss = [('%s' % s, '%s : STA %s, at GPS(%+.2f, %+.2f), %02d miles away, %s' % (addr, s, l['lat'], l['lng'], l['distance'], l['name'])) for s, l in meta['station2location'].items()] stations.extend(ss) initial_stations.append(ss[0][0]) super(StationChoiceForm, self).__init__(*args, **kwargs) self.fields['selected_stations'] = forms.MultipleChoiceField( choices=stations, widget=forms.CheckboxSelectMultiple(), label='Select weather stations to download', initial=initial_stations, required=False ) self.metadata = metadata_list def _get_nearby_stations_metadata(address, start_date_local, end_date_local): result = wefacts.search_nearby_stations( address, start_date_local, end_date_local, search_station_num=8, search_option='usaf_wban', dir_raw=util.DIR_RAW, dir_local=util.DIR_LOCAL) if result is not None: station2location, gps, local_tz = result[0], result[1], result[2] metadata = { 'gps': gps, 'local_tz': local_tz, 'station2location': station2location, 'start_date_local': start_date_local, 'end_date_local': end_date_local, 'weather_address': address } else: metadata = None return metadata
{ "content_hash": "13d21725374de040091b8ad631ca9687", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 97, "avg_line_length": 39.550561797752806, "alnum_prop": 0.5477272727272727, "repo_name": "shawxiaozhang/we_web", "id": "d9ad931c848da6b39a6dcb9405f836043a81008a", "size": "3520", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "we_search/forms.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "79891" }, { "name": "HTML", "bytes": "3446" }, { "name": "JavaScript", "bytes": "97398" }, { "name": "Python", "bytes": "20207" } ], "symlink_target": "" }
DROP TABLE client_service CASCADE CONSTRAINTS; DROP TABLE service_endpoint CASCADE CONSTRAINTS; DROP TABLE service CASCADE CONSTRAINTS; DROP TABLE client CASCADE CONSTRAINTS; DROP TABLE user_profile CASCADE CONSTRAINTS; DROP TABLE audit_log CASCADE CONSTRAINTS; DROP TABLE refresh_token CASCADE CONSTRAINTS; DROP TABLE oauth_provider CASCADE CONSTRAINTS; CREATE TABLE user_profile ( user_id VARCHAR2(32) NOT NULL, user_type VARCHAR2(16) NOT NULL, -- admin, customer, employee, partner first_name VARCHAR2(32) NOT NULL, last_name VARCHAR2(32) NOT NULL, email VARCHAR2(64) NOT NULL, password VARCHAR2(1024) NOT NULL, roles VARCHAR2(2048), -- space delimited roles CONSTRAINT user_profile_pk PRIMARY KEY (user_id) ); CREATE UNIQUE INDEX email_idx ON user_profile(email); CREATE TABLE client ( client_id VARCHAR2(36) NOT NULL, client_type VARCHAR2(12) NOT NULL, -- public, confidential, trusted, external client_profile VARCHAR2(10) NOT NULL, -- webserver, mobile, browser, service, batch client_secret VARCHAR2(1024) NOT NULL, client_name VARCHAR2(32) NOT NULL, client_desc VARCHAR2(2048), scope VARCHAR2(4000), custom_claim VARCHAR2(4000), -- custom claim(s) in json format that will be included in the jwt token redirect_uri VARCHAR2(1024), authenticate_class VARCHAR2(256), deref_client_id VARCHAR2(36), -- only this client calls AS to deref token to JWT for external client type owner_id VARCHAR2(64) NOT NULL, host VARCHAR2(64) NOT NULL, CONSTRAINT client_pk PRIMARY KEY (client_id) ); CREATE TABLE service ( service_id VARCHAR2(32) NOT NULL, service_type VARCHAR2(16) NOT NULL, -- swagger, openapi, graphql, hybrid service_name VARCHAR2(32) NOT NULL, service_desc VARCHAR2(1024), scope VARCHAR2(1024), owner_id VARCHAR2(64) NOT NULL, host VARCHAR2(64) NOT NULL, CONSTRAINT service_pk PRIMARY KEY (service_id) ); CREATE TABLE service_endpoint ( service_id VARCHAR2(32) NOT NULL, endpoint VARCHAR2(256) NOT NULL, -- different framework will have different endpoint format. operation VARCHAR2(256) NOT NULL, scope VARCHAR2(64) NOT NULL, CONSTRAINT service_endpoint_pk PRIMARY KEY (service_id, endpoint), CONSTRAINT service_endpoint_service_fk FOREIGN KEY (service_id) REFERENCES service(service_id) ); CREATE TABLE client_service ( client_id VARCHAR2(36) NOT NULL, service_id VARCHAR2(32) NOT NULL, endpoint VARCHAR2(256) NOT NULL, -- different framework will have different endpoint format. CONSTRAINT client_service_pk PRIMARY KEY (client_id, service_id, endpoint), CONSTRAINT client_service_endpoint_fk FOREIGN KEY (service_id, endpoint) REFERENCES service_endpoint(service_id, endpoint), CONSTRAINT client_service_client_fk FOREIGN KEY (client_id) REFERENCES client(client_id) ); CREATE TABLE refresh_token ( user_id VARCHAR2(36) NOT NULL, user_type VARCHAR2(36), roles VARCHAR2(2048), client_id VARCHAR2(36) NOT NULL, scope VARCHAR2(64) NOT NULL, remember VARCHAR2(1) NOT NULL, refresh_token VARCHAR2(256) NOT NULL, start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, CONSTRAINT refresh_token_pk PRIMARY KEY (client_id, refresh_token), CONSTRAINT refresh_token_client_fk FOREIGN KEY (client_id) REFERENCES client(client_id) ); CREATE TABLE oauth_provider ( provider_id VARCHAR2(2) NOT NULL, server_url VARCHAR2(256) NOT NULL, -- different framework will have different endpoint format. uri VARCHAR2(64) NOT NULL, provider_name VARCHAR2(64), CONSTRAINT provider_pk PRIMARY KEY (provider_id) ); create table audit_log ( log_id numeric, -- system milliseonds from 1970. service_id VARCHAR2(32) NOT NULL, endpoint VARCHAR2(256) NOT NULL, request_header VARCHAR2(4000), request_body VARCHAR2(4000), response_code INT, response_header VARCHAR2(4000), response_body VARCHAR2(4000) ); INSERT INTO user_profile (user_id, user_type, first_name, last_name, email, roles, password) VALUES('admin', 'admin', 'admin', 'admin', '[email protected]', 'user admin', '1000:5b39342c202d37372c203132302c202d3132302c2034372c2032332c2034352c202d34342c202d31362c2034372c202d35392c202d35362c2039302c202d352c202d38322c202d32385d:949e6fcf9c4bb8a3d6a8c141a3a9182a572fb95fe8ccdc93b54ba53df8ef2e930f7b0348590df0d53f242ccceeae03aef6d273a34638b49c559ada110ec06992'); INSERT INTO client (client_id, client_secret, client_type, client_profile, client_name, client_desc, scope, custom_claim, redirect_uri, owner_id, host) VALUES('f7d42348-c647-4efb-a52d-4c5787421e72', '1000:5b37332c202d36362c202d36392c203131362c203132362c2036322c2037382c20342c202d37382c202d3131352c202d35332c202d34352c202d342c202d3132322c203130322c2033325d:29ad1fe88d66584c4d279a6f58277858298dbf9270ffc0de4317a4d38ba4b41f35f122e0825c466f2fa14d91e17ba82b1a2f2a37877a2830fae2973076d93cc2', 'public', 'mobile', 'PetStore Web Server', 'PetStore Web Server that calls PetStore API', 'petstore.r petstore.w', '{"c1": "361", "c2": "67"}', 'http://localhost:8080/authorization', 'admin', 'lightapi.net'); INSERT INTO service (service_id, service_type, service_name, service_desc, scope, owner_id, host) VALUES ('AACT0001', 'openapi', 'Account Service', 'A microservice that serves account information', 'a.r b.r', 'admin', 'lightapi.net');
{ "content_hash": "fe5e79efb7be654759b6ccad1e0c6690", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 543, "avg_line_length": 47.027027027027025, "alnum_prop": 0.7745210727969348, "repo_name": "networknt/light-oauth2", "id": "c218660e3dc834b90857dd008fcf9575f9634be5", "size": "5220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/oracle/create_oracle.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "11370" }, { "name": "Java", "bytes": "797820" }, { "name": "Shell", "bytes": "13294" }, { "name": "TSQL", "bytes": "4815" } ], "symlink_target": "" }
package com.github.alezhka.wavesj; import org.junit.Assert; import org.junit.Test; public class WavAssetPairTest { @Test public void wavesWaves() { final WavAssetPair pair = new WavAssetPair(); final WavAssetPair pair1 = new WavAssetPair(null, null); Assert.assertEquals(pair.getAmountAsset(), Waves.ASSET_WAVES); Assert.assertEquals(pair.getPriceAsset(), Waves.ASSET_WAVES); Assert.assertEquals(pair1.getAmountAsset(), Waves.ASSET_WAVES); Assert.assertEquals(pair1.getPriceAsset(), Waves.ASSET_WAVES); } @Test public void wavesAsset() { final String asset1 = "GKPwsZSY825wc8nbKPKQH4zPoHpq6CVduzv9eSdwry5T"; final String asset2 = "57WtCm8cvpPNoSNMmAPUGEgi1NxfUf7XNEP2zPfVJPwj"; final WavAssetPair pair = new WavAssetPair(asset1, null); final WavAssetPair pair1 = new WavAssetPair(null, asset1); final WavAssetPair pair2 = new WavAssetPair(asset1, asset2); Assert.assertEquals(pair.getAmountAsset(), asset1); Assert.assertEquals(pair.getPriceAsset(), Waves.ASSET_WAVES); Assert.assertEquals(pair1.getAmountAsset(), Waves.ASSET_WAVES); Assert.assertEquals(pair1.getPriceAsset(), asset1); Assert.assertEquals(pair2.getAmountAsset(), asset1); Assert.assertEquals(pair2.getPriceAsset(), asset2); } }
{ "content_hash": "f8a61d0c8eae8570b689a4bfc836f994", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 77, "avg_line_length": 36.83783783783784, "alnum_prop": 0.7057960381511372, "repo_name": "Alezhka/JWaves", "id": "12856f2f1ddf5ba052fe03b102676ee41e1f58f3", "size": "1363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wavesj/src/test/java/com/github/alezhka/wavesj/WavAssetPairTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "836611" }, { "name": "Shell", "bytes": "92" } ], "symlink_target": "" }
module Policies class <%= class_name %> < Walruz::Policy # depends_on OtherPolicy def authorized?(actor, subject) raise NotImplementedError.new("You need to implement policy") end end end
{ "content_hash": "5ae73a0a6d86201ad1f5e8639368839e", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 67, "avg_line_length": 21.9, "alnum_prop": 0.6621004566210046, "repo_name": "noomii/walruz-rails", "id": "7c5f6b68602bd91dfe4035c0628d55b0e6c73ac5", "size": "219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rails_generators/templates/policy.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "148" }, { "name": "Ruby", "bytes": "61559" } ], "symlink_target": "" }
layout: layout title: "About Adam Clark" --- <section class="content about"> <h1 class="big thin">Adam Clark</h1> </section>
{ "content_hash": "96b8a640a1105d2cfa23de551e8b4bfe", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 37, "avg_line_length": 18.142857142857142, "alnum_prop": 0.6850393700787402, "repo_name": "adamclerk/adamclerk.github.com", "id": "34310632b2109c91bb64a1068ad3948de77254f5", "size": "131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "187101" }, { "name": "Ruby", "bytes": "1448" } ], "symlink_target": "" }
body { background: #fff }
{ "content_hash": "2ba2f7a035678a3263ebbd6645d6861c", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 20, "avg_line_length": 10, "alnum_prop": 0.5666666666666667, "repo_name": "lellex/accessimap-lecteur-der", "id": "96a763754953904dc65934cfa29f30705d0a44a2", "size": "30", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/der-reader/css/styles.css", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "12314" }, { "name": "C", "bytes": "823" }, { "name": "C#", "bytes": "140652" }, { "name": "C++", "bytes": "250493" }, { "name": "CSS", "bytes": "20827" }, { "name": "HTML", "bytes": "102041" }, { "name": "Java", "bytes": "742013" }, { "name": "JavaScript", "bytes": "1006030" }, { "name": "Objective-C", "bytes": "321700" }, { "name": "Shell", "bytes": "436" } ], "symlink_target": "" }
CREATE TABLE port_spec( id int, name varchar(22), type varchar(255), spec varchar(255), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE module( id int, cache int, name varchar(255), namespace varchar(255), package varchar(511), version varchar(255), tag varchar(255), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE tag( id int, name varchar(255), parent_id int, entity_id int, entity_type char(16) ) engine=InnoDB; CREATE TABLE port( id int, type varchar(255), moduleId int, moduleName varchar(255), name varchar(255), spec varchar(4095), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE group_tbl( id int, cache int, name varchar(255), namespace varchar(255), package varchar(511), version varchar(255), tag varchar(255), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE log_tbl( id int not null auto_increment primary key, entity_type char(16), version char(16), name varchar(255), last_modified datetime, vistrail_id int ) engine=InnoDB; CREATE TABLE machine( id int, name varchar(255), os varchar(255), architecture varchar(255), processor varchar(255), ram int, vt_id int, log_id int, entity_id int, entity_type char(16) ) engine=InnoDB; CREATE TABLE add_tbl( id int, what varchar(255), object_id int, par_obj_id int, par_obj_type char(16), action_id int, entity_id int, entity_type char(16) ) engine=InnoDB; CREATE TABLE other( id int, okey varchar(255), value varchar(255), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE location( id int, x DECIMAL(18,12), y DECIMAL(18,12), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE parameter( id int, pos int, name varchar(255), type varchar(255), val varchar(8191), alias varchar(255), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE plugin_data( id int, data varchar(8191), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE function( id int, pos int, name varchar(255), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE abstraction( id int, cache int, name varchar(255), namespace varchar(255), package varchar(511), version varchar(255), internal_version varchar(255), tag varchar(255), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE workflow( id int not null auto_increment primary key, entity_id int, entity_type char(16), name varchar(255), version char(16), last_modified datetime, vistrail_id int, parent_id int, parent_type char(16) ) engine=InnoDB; CREATE TABLE annotation( id int, akey varchar(255), value varchar(8191), parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE change_tbl( id int, what varchar(255), old_obj_id int, new_obj_id int, par_obj_id int, par_obj_type char(16), action_id int, entity_id int, entity_type char(16) ) engine=InnoDB; CREATE TABLE workflow_exec( id int, user varchar(255), ip varchar(255), session int, vt_version varchar(255), ts_start datetime, ts_end datetime, parent_id int, parent_type varchar(255), parent_version int, completed int, name varchar(255), log_id int, entity_id int, entity_type char(16) ) engine=InnoDB; CREATE TABLE connection_tbl( id int, parent_type char(16), entity_id int, entity_type char(16), parent_id int ) engine=InnoDB; CREATE TABLE action( id int, prev_id int, date datetime, session int, user varchar(255), prune int, parent_id int, entity_id int, entity_type char(16) ) engine=InnoDB; CREATE TABLE delete_tbl( id int, what varchar(255), object_id int, par_obj_id int, par_obj_type char(16), action_id int, entity_id int, entity_type char(16) ) engine=InnoDB; CREATE TABLE vistrail( id int not null auto_increment primary key, entity_type char(16), version char(16), name varchar(255), last_modified datetime ) engine=InnoDB; CREATE TABLE module_exec( id int, ts_start datetime, ts_end datetime, cached int, module_id int, module_name varchar(255), completed int, error varchar(1023), abstraction_id int, abstraction_version int, machine_id int, wf_exec_id int, entity_id int, entity_type char(16) ) engine=InnoDB;
{ "content_hash": "86029b43e3652181ca3c95f4a66e06a2", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 47, "avg_line_length": 19.615671641791046, "alnum_prop": 0.6309682328324139, "repo_name": "Nikea/VisTrails", "id": "3cb4dc2d7fa8a30ac7d7e0b43444f2b59a84543f", "size": "7181", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vistrails/db/versions/v0_9_4/schemas/sql/vistrails.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1421" }, { "name": "Inno Setup", "bytes": "19611" }, { "name": "Makefile", "bytes": "768" }, { "name": "Mako", "bytes": "66415" }, { "name": "PHP", "bytes": "49038" }, { "name": "Python", "bytes": "19674395" }, { "name": "R", "bytes": "778864" }, { "name": "Rebol", "bytes": "3972" }, { "name": "Shell", "bytes": "34182" }, { "name": "TeX", "bytes": "145219" }, { "name": "XSLT", "bytes": "1090" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using Mono.Cecil; using Mono.Cecil.Cil; namespace RavenfieldCheater { public partial class RavenfieldCheater : Form { private string filePath; private string originalPath; ModuleDefinition assembly; public RavenfieldCheater() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { FolderBrowserDialog selectDLL = new FolderBrowserDialog(); selectDLL.Description = "Please find ravenfield_Data in Ravenfield folder if on Windows/Linux or Data in Mac ravenfield.app/Contet/Resources."; if (selectDLL.ShowDialog() == System.Windows.Forms.DialogResult.OK) { originalPath = selectDLL.SelectedPath; // In case we need to access any other DLLs/Resources filePath = originalPath + "\\Managed\\Assembly-CSharp.dll"; // Where RF stores it's source code } } private void Backup_Click(object sender, EventArgs e) { if (filePath == null) { MessageBox.Show("Please select the folder Ravenfield is in."); return; } try { if (File.Exists(filePath + ".bak")) { File.Delete(filePath + ".bak"); } File.Copy(filePath, filePath + ".bak"); MessageBox.Show("Backup Complete!"); } catch (FileNotFoundException error) { MessageBox.Show(error.Message); } } private void Restore_Click(object sender, EventArgs e) { if (filePath == null) { MessageBox.Show("Please select the folder Ravenfield is in."); return; } try { if (File.Exists(filePath)) { File.Delete(filePath); } File.Copy(filePath + ".bak", filePath); MessageBox.Show("Restore Complete!"); } catch (FileNotFoundException error) { MessageBox.Show(error.Message); } } private void NoFall_Click(object sender, EventArgs e) { if (filePath == null) { MessageBox.Show("Please select the folder Ravenfield is in."); return; } assembly = ModuleDefinition.ReadModule(filePath); // Load Assembly-CSharp.dll TypeDefinition ActorClass = assembly.Types.First(t => t.Name == "Actor"); // Finds Actor class (no namespace) in Assembly-CSharp.dll if (ActorClass == null) // If Actor does not exist, stop { MessageBox.Show("Actor Class Not Found!"); return; } Application.DoEvents(); // Lets the program catch up MethodDefinition FallOverMethod = ActorClass.Methods.First(m => m.Name == "FallOver"); // Finds Actor.FallOver() if (FallOverMethod == null) // If Actor.FallOver() does not exist, stop { MessageBox.Show("Actor.FallOver() Method Not Found!"); return; } Application.DoEvents(); // Catch up ILProcessor processor = FallOverMethod.Body.GetILProcessor(); // Erases Actor.FallOver() foreach (var instuc in processor.Body.Instructions.ToArray()) { processor.Body.Instructions.Remove(instuc); } // Added a "ret" instruction to the empty method so the function does run as // some methods are still depended on the method FallOverMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); try { assembly.Write(filePath); // Try to write it back to Assembly-CSharp.dll } catch (Mono.Cecil.AssemblyResolutionException error) { MessageBox.Show(error.Message); return; } MessageBox.Show("No Fall Added Successfully!"); Application.DoEvents(); } private void Fast_Click(object sender, EventArgs e) { if (filePath == null) { MessageBox.Show("Please select the folder Ravenfield is in."); return; } assembly = ModuleDefinition.ReadModule(filePath); // Load Assembly-CSharp.dll ModuleDefinition UnityDLL = ModuleDefinition.ReadModule(originalPath + "\\Managed\\UnityEngine.dll"); // Load UnityEngine for referencing TypeDefinition FpsActorControllerClass = assembly.Types.First(t => t.Name == "FpsActorController"); // Finds FpsActorController class (no namespace) in Assembly-CSharp.dll if (FpsActorControllerClass == null) // If FpsActorController does not exist, stop { MessageBox.Show("FpsActorController Class Not Found!"); return; } Application.DoEvents(); // Lets the program catch up MethodDefinition UpdateMethod = FpsActorControllerClass.Methods.First(m => m.Name == "Update"); // Finds FpsActorControllerClass.Update() if (UpdateMethod == null) // If FpsActorController.Update() does not exist, stop { MessageBox.Show("FpsActorController.Update() Method Not Found!"); return; } Application.DoEvents(); ILProcessor processor = UpdateMethod.Body.GetILProcessor(); Instruction original; original = processor.Body.Instructions[212]; MethodReference timeScaleRef = assembly.Import(typeof(UnityEngine.Time).GetMethod("get_timeScale", new[] { typeof(UnityEngine.Object), typeof(UnityEngine.Object) })); foreach (var instuction in processor.Body.Instructions) { if (instuction.Operand == timeScaleRef) { original = instuction.Next; original = original.Next; } } // Changes if (Time.timeScale < 1f) to a > sign Instruction replace = original; replace.OpCode = OpCodes.Ble_Un; processor.Replace(original, replace); //original = processor.Body.Instructions[216]; original = original.Next; original = original.Next; original = original.Next; original = original.Next; /*for (int i = i; i <= 4; i++) { original = original.Next; }*/ // Changes Time.timeScale = 0.2f; to 2. replace = original; replace.Operand = 2f; processor.Replace(original, replace); try { assembly.Write(filePath); // Try to write it back to Assembly-CSharp.dll } catch (Mono.Cecil.AssemblyResolutionException error) { MessageBox.Show(error.Message); return; } MessageBox.Show("Fast Motion Added Successfully!"); Application.DoEvents(); } private void Ammo_Click(object sender, EventArgs e) { assembly = ModuleDefinition.ReadModule(filePath); // Load Assembly-CSharp.dll TypeDefinition WeaponClass = assembly.Types.First(t => t.Name == "Weapon"); // Finds Weapon class (no namespace) in Assembly-CSharp.dll if (WeaponClass == null) // If Actor does not exist, stop { MessageBox.Show("Weapon Class Class Not Found!"); return; } Application.DoEvents(); // Lets the program catch up MethodDefinition LateUpdateMethod; // Does Weapon.LateUpdate() exist? try { WeaponClass.Methods.First<MethodReference>(m => m.Name == "LateUpdate"); } catch (Exception exc) { // Creates Weapon.LateUpdate() LateUpdateMethod = new MethodDefinition("LateUpdate", MethodAttributes.Public, assembly.TypeSystem.Void); WeaponClass.Methods.Add(LateUpdateMethod); LateUpdateMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); goto skip; } MessageBox.Show("Actor.LateUpdate() exists already. This may cause problems down the line."); LateUpdateMethod = WeaponClass.Methods.First<MethodDefinition>(m => m.Name == "LateUpdate"); Application.DoEvents(); skip: ILProcessor processor = LateUpdateMethod.Body.GetILProcessor(); FieldReference WeaponAmmo = WeaponClass.Fields.First<FieldReference>(f => f.Name == "ammo");// Finds ammo for reference MethodReference WeaponUserIsPlayer; try { WeaponUserIsPlayer = WeaponClass.Methods.First<MethodReference>(m => m.Name == "UserIsPlayer"); // Finds UserIsPlayer() for reference } catch (Exception exc) // If Weapon.UserIsPlayer() does not exist, create it { MessageBox.Show("Weapon.UserIsPlayer() not found, creating"); MethodDefinition method = new MethodDefinition("UserIsPlayer", MethodAttributes.Public, assembly.TypeSystem.Boolean); WeaponClass.Methods.Add(method); ILProcessor ilProc = method.Body.GetILProcessor(); FieldReference user = WeaponClass.Fields.First<FieldReference>(f => f.Name == "user"); FieldReference aiControlled = assembly.Types.First<TypeDefinition>(t => t.Name == "Actor") .Fields.First(f => f.Name == "aiControlled"); MethodReference uIneq = assembly.Import(typeof(UnityEngine.Object).GetMethod("op_Inequality", new[] { typeof(UnityEngine.Object), typeof(UnityEngine.Object) })); Instruction[] structs = new Instruction[13]; structs[11] = ilProc.Create(OpCodes.Ldc_I4_0); structs[12] = ilProc.Create(OpCodes.Ret); structs = new Instruction[13] { ilProc.Create(OpCodes.Ldarg_0), ilProc.Create(OpCodes.Ldfld, user), ilProc.Create(OpCodes.Ldnull), ilProc.Create(OpCodes.Call, uIneq), ilProc.Create(OpCodes.Brfalse, structs[11]), ilProc.Create(OpCodes.Ldarg_0), ilProc.Create(OpCodes.Ldfld, user), ilProc.Create(OpCodes.Ldfld, aiControlled), ilProc.Create(OpCodes.Ldc_I4_0), ilProc.Create(OpCodes.Ceq), ilProc.Create(OpCodes.Br_S, structs[12]), ilProc.Create(OpCodes.Ldc_I4_0), ilProc.Create(OpCodes.Ret) }; foreach (Instruction i in structs) method.Body.Instructions.Add(i); method.Body.Instructions[4] = ilProc.Create(OpCodes.Brfalse, method.Body.Instructions[11]); // pointing Break If instructions to the right place method.Body.Instructions[10] = ilProc.Create(OpCodes.Br_S, method.Body.Instructions[12]); WeaponUserIsPlayer = WeaponClass.Methods.First<MethodReference>(m => m.Name == "UserIsPlayer"); } // Inserts a if statment to check if Actor is Player, if so, make ammo 1000 Instruction[] instructions = processor.Body.Instructions.ToArray(); Instruction lastInstruc = instructions[instructions.Length - 1]; Instruction insertInstruc = processor.Create(OpCodes.Stfld, WeaponAmmo); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Ldc_I4, 1000); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Ldarg_0); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Brfalse_S, instructions[instructions.Length - 1]); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Call, WeaponUserIsPlayer); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Ldarg_0); processor.InsertBefore(lastInstruc, insertInstruc); try { assembly.Write(filePath); // Try to write it back to Assembly-CSharp.dll } catch (Mono.Cecil.AssemblyResolutionException error) { MessageBox.Show(error.Message); return; } MessageBox.Show("Infinite Ammo Added Successfully!"); Application.DoEvents(); } private void Health_Click(object sender, EventArgs e) { if (filePath == null) { MessageBox.Show("Please select the folder Ravenfield is in."); return; } assembly = ModuleDefinition.ReadModule(filePath); // Load Assembly-CSharp.dll TypeDefinition ActorClass = assembly.Types.First(t => t.Name == "Actor"); // Finds Actor class (no namespace) in Assembly-CSharp.dll if (ActorClass == null) // If Actor does not exist, stop { MessageBox.Show("Actor Class Class Not Found!"); return; } Application.DoEvents(); // Lets the program catch up MethodDefinition LateUpdateMethod; // Does Actor.LateUpdate() exist? try { ActorClass.Methods.First<MethodReference>(m => m.Name == "LateUpdate"); } catch (Exception exc) { // Creates Actor.LateUpdate() LateUpdateMethod = new MethodDefinition("LateUpdate", MethodAttributes.Public, assembly.TypeSystem.Void); ActorClass.Methods.Add(LateUpdateMethod); LateUpdateMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); goto skip; } MessageBox.Show("Actor.LateUpdate() exists already. This may cause problems down the line."); LateUpdateMethod = ActorClass.Methods.First<MethodDefinition>(m => m.Name == "LateUpdate"); Application.DoEvents(); skip: ILProcessor processor = LateUpdateMethod.Body.GetILProcessor(); FieldReference ActorHealth = ActorClass.Fields.First<FieldReference>(f => f.Name == "health");// Finds health for reference FieldReference ActorAiControlled = ActorClass.Fields.First<FieldReference>(f => f.Name == "aiControlled");// Finds aiControlled for reference // Inserts a if statment to check if Actor is AI, if not, make health 1000f Instruction[] instructions = processor.Body.Instructions.ToArray(); Instruction lastInstruc = instructions[instructions.Length - 1]; Instruction insertInstruc = processor.Create(OpCodes.Stfld, ActorHealth); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Ldc_R4, 1000f); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Ldarg_0); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Brtrue_S, instructions[instructions.Length - 1]); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Ldfld, ActorAiControlled); processor.InsertBefore(lastInstruc, insertInstruc); lastInstruc = insertInstruc; insertInstruc = processor.Create(OpCodes.Ldarg_0); processor.InsertBefore(lastInstruc, insertInstruc); try { assembly.Write(filePath); // Try to write it back to Assembly-CSharp.dll } catch (Mono.Cecil.AssemblyResolutionException error) { MessageBox.Show(error.Message); return; } MessageBox.Show("Infinite Health Added Successfully!"); Application.DoEvents(); } private void SecretWeapons_Click(object sender, EventArgs e) { /* if (filePath == null) { MessageBox.Show("Please select the folder Ravenfield is in."); return; } assembly = ModuleDefinition.ReadModule(filePath); // Load Assembly-CSharp.dll TypeDefinition WeaponManagerClass = assembly.Types.First(t => t.Name == "WeaponManager"); // Finds WeaponManager class (no namespace) in Assembly-CSharp.dll if (WeaponManagerClass == null) // If WeaponManager does not exist, stop { MessageBox.Show("WeaponManager Class Class Not Found!"); return; } Application.DoEvents(); // Lets the program catch up MethodDefinition AwakeMethod = WeaponManagerClass.Methods.First(m => m.Name == "Awake"); // Finds WeaponManager.Awake() if (AwakeMethod == null) // If WeaponManager.Awake() does not exist, stop { MessageBox.Show("WeaponManager.Awake() Method Not Found!"); return; } Application.DoEvents(); ILProcessor processor = AwakeMethod.Body.GetILProcessor(); Instruction[] instructions = processor.Body.Instructions.ToArray(); */ } private void label1_Click(object sender, EventArgs e) { } } }
{ "content_hash": "9a71fc7d5dec90cb7f5bab14c0be8d34", "timestamp": "", "source": "github", "line_count": 430, "max_line_length": 183, "avg_line_length": 42.95813953488372, "alnum_prop": 0.584181463837159, "repo_name": "MilesFM/RavenfieldCheater", "id": "6410df0a2673e0597d777f9fb5b52fcbeb7cf1dd", "size": "18474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Form1.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "20414" } ], "symlink_target": "" }
python manage.py migrate exec $@
{ "content_hash": "40b9c9af6cbce954227c1fa401c9180c", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 24, "avg_line_length": 11.333333333333334, "alnum_prop": 0.7352941176470589, "repo_name": "istrategylabs/franklin-api", "id": "8a3c8e2c35fb2416348fe24e3cdaf7f122e6dfea", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker-entrypoint.sh", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "1249" }, { "name": "Python", "bytes": "87738" }, { "name": "Shell", "bytes": "539" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Vanessa Ng - Graphic / Blueprint Rebrand</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/css/tachyons.min.css"/> --> <link href="./resources/css/tachyons-merged/css/tachyons.css" rel="stylesheet"> <style> .polygon-header { width: 100%; height: 1000px; transform: skew(0deg, 7deg); top: -790px; position: absolute; /*background-color: #0078e8;*/ } .circle { width: 11em; height: 11em; border-radius: 50%; border: 0.4em solid white; position: absolute; bottom:0; left: 0; right: 0; margin: auto; } .title { position: absolute; bottom:0; left: 0; right: 0; margin: auto; top: 180px; } .outer-container { position: relative; width: 100%; height: 240px; } .project-img { width: 100%; border-radius: 8px; } .project-rect { width: 100%; height: 28em; float: left; } .prefooter { width: 100%; float: left; } .footer { width: 100%; height: 400px; float: left; } </style> </head> <body> <nav class="db dt-l w-100 border-box pa3 ph5-l" style="position: absolute; z-index: 10"> <a class="db dtc-l v-mid x-purple-70 cabin f5 f4-l tracked-mega link dim w-100 w-25-l tc tl-l mb2 mb0-l" href="#" title="Home">vanesng <!-- <img src="http://tachyons.io/img/logo.jpg" class="dib w2 h2 br-100" alt="Site Name"> --> </a> <div class="db dtc-l v-mid w-100 w-75-l tc tr-l"> <a class="link dim x-purple-70 cabin f6 f5-l tracked dib mr3 mr4-l" href="./index.html" title="Home">Home</a> <a class="link dim x-purple-70 cabin f6 f5-l tracked dib mr3 mr4-l" href="#" title="About">About</a> <a class="link dim x-purple-70 cabin f6 f5-l tracked dib mr3 mr4-l" href="./uiux.html" title="UIUX">UIUX</a> <a class="link dim x-purple-70 cabin f6 f5-l tracked dib mr3 mr4-l" href="./graphic.html" title="Graphic">Graphic</a> <a class="link dim x-purple-70 cabin f6 f5-l tracked dib" href="#" title="Other">Other</a> </div> </nav> <header class="fixed w-100 bg-white-80 pa3 ph5-l"> <nav class="db dt-l w-100 border-box"> <a class="db dtc-l v-mid x-purple cabin f5 f4-l tracked-mega link dim w-100 w-25-l tc tl-l mb2 mb0-l" href="#" title="Home">vanesng <!-- <img src="http://tachyons.io/img/logo.jpg" class="dib w2 h2 br-100" alt="Site Name"> --> </a> <div class="db dtc-l v-mid w-100 w-75-l tc tr-l"> <a class="link dim x-purple cabin f6 f5-l tracked dib mr3 mr4-l" href="./index.html" title="Home">Home</a> <a class="link dim x-purple cabin f6 f5-l tracked dib mr3 mr4-l" href="#" title="About">About</a> <a class="link dim x-purple cabin f6 f5-l tracked dib mr3 mr4-l" href="./uiux.html" title="UIUX">UIUX</a> <a class="link dim x-purple cabin f6 f5-l tracked dib mr3 mr4-l" href="./graphic.html" title="Graphic">Graphic</a> <a class="link dim x-purple cabin f6 f5-l tracked dib" href="#" title="Other">Other</a> </div> </nav> </header> <div class="outer-container"> <div class="polygon-header bg-x-cyan"></div> </div> <div class="article-start tl ph7 pt2 pb5"> <div class="f3 fw5 merriweather x-purple-70 pb3 link dim">Graphic / </div> <div class="f1 fw8 merriweather x-purple">Blueprint Rebrand</div> <div class="f4 fw6 nunito x-purple pt4">The motivations and thought process behind Blueprint's rebrand</div> </div> <div class="project-rect bg-black-10 pv5 ph6"> </div> <div class="tl ph7 pt5 fl"> <div class="f4 avenir fw6 i x-purple bl b--x-light-purple pl3 lh-copy">Blueprint is a student organization at UC Berkeley that dedicates itself to social good through pro-bono development of technologies for nonprofits.</div> <div class="f4 nunito x-font pt4 lh-copy">As we underwent a major rebrand early this year, some questions have been raised about why the process was necessary. Since Blueprint’s inception, its logo had only seen minor changes and thus a consistent brand had been built. This post explains why we underwent a rebranding of our logo, and documents our thought process behind each design decision.</div> <div class="tc f2 fw6 merriweather x-light-purple pt5">. . .</div> <div class="f3 fw6 merriweather x-purple pt5">Audience perception</div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">Before we jumped in redesigning the logo, we first wanted to know what people thought about the logo and what it implied about Blueprint. We believed these insights could identify key problems to tackle and characteristics that should be retained.</div> <div class="img bg-black-10 center" style="width: 20em; height: 16em"></div> <div class="caption f5 avenir i x-purple-70 tc pv4">Our previous logo, very similar to the original logo back in 2012</div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">We split up our audience into three categories and asked them what came to their mind when they saw the logo, and whether it related to our mission. Their responses were telling:</div> <div class="f4 nunito x-purple bl b--x-light-purple pl3 lh-copy">Blueprint members: <i>“I kind of like it.”</i><br><br> Other Berkeley students: <i>“It looks alright. They build software, right?”</i><br><br> People completely unfamiliar with Blueprint: <i>“Do you guys volunteer at pet shelters? It doesn’t tell me anything about software and isn’t visually appealing. And why is the paw print there?”</i></div> <div class="f4 fw7 nunito x-purple pt5 pb4 lh-copy">Immediately, we knew that the paw print was misleading and had to be removed or replaced.</div> <div class="f4 nunito x-purple lh-copy">We approached the logo rebrand with three main driving ideas in mind:</div> <div class="f4 nunito x-purple pt4 pl3 lh-copy"> <b>1) Cleaner Design:</b> as we wanted to create a more professional feel to appeal to clients and sponsors.<br><br> <b>2) Consistency: </b> as the bear print (iconic to Berkeley) was misleading and would no longer remain relevant after expansion to different chapters.<br><br> <b>3) Identity:</b> as we didn’t want a complete overhaul of our legacy, and wanted to retain the characteristic of social good.</div> <div class="tc f2 fw6 merriweather x-light-purple pt5">. . .</div> <div class="f3 fw6 merriweather x-purple pt5">Ideation</div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">We started off by expanding from what we had, and explored concepts similar to a gear to find a cleaner compromise.</div> <div class="img bg-black-10 center" style="width: 40em; height: 24em"></div> <div class="caption f5 avenir i x-purple-70 tc pv4">Early rough sketches of possible ideas</div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">As we narrowed down our options, we started to apply our blue palette and played around with different hues.</div> <div class="img bg-black-10 center pb4" style="width: 40em; height: 24em"></div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">After several rounds of developing ideas, we narrowed our concepts down to a select few. Of course, with these concepts further questions were raised about more specific details.</div> <div class="img bg-black-10 center pb4" style="width: 40em; height: 24em"></div> <div class="tc f2 fw6 merriweather x-light-purple pt5">. . .</div> <div class="f3 fw6 merriweather x-purple pt5">Font and Color</div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">In order to remain consistent among chapters, we also collaborated with John (Design Director of the Blueprint Chapter at University of Waterloo) throughout the entire process.</div> <div class="img bg-black-10 center pb4" style="width: 40em; height: 24em"></div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">Using the font Poppins, we used uncapitalized text in order to keep the ‘b’ and ‘l’ at consistent heights. We also decided on a semibold font weight to give a friendlier feel, instead of the more ‘corporate’ feel that a lighter font might give off. <br><br>With the font and color variables fixed, we started to consider how our logo would fit next to the font. With our selected concept, we realized the lines on the logo had to be thickened to match the text’s font weight.</div> <div class="img bg-black-10 center" style="width: 48em; height: 16em"></div> <div class="caption f5 avenir i x-purple-70 tc pv4">Selected concept with thickened lines</div> <div class="f4 nunito x-purple pt4 pb5 lh-copy">In our final considerations, we debated whether to make the weave mono or dual-colored, and whether we should keep the heart in the design. <br><br>We ended up choosing against the heart to remove clutter, and chose a dual-colored logo to focus on the unique interweaving of the design rather than a shape as a whole, since this might be interpreted as clunky or even as a flower. <br><br>And with that, our rebrand was complete.</div> <div class="img bg-black-10 center" style="width: 48em; height: 24em"></div> <div class="caption f5 avenir i x-purple-70 tc pv4">The completed logo design</div> <div class="tc f2 fw6 merriweather x-light-purple pt2">. . .</div> </div> <div class="prefooter ph7 pv3 fl"> <div class="tc f3 fw6 merriweather x-purple pt5">Other designs for Blueprint </div> </div> <div class="footer bg-x-purple"> </div> </body> </html>
{ "content_hash": "ca72fb92c6c21cd43fac38b8376e8a32", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 531, "avg_line_length": 53.175141242937855, "alnum_prop": 0.6950701232469189, "repo_name": "vanesng/vanesng.github.io", "id": "27ca9f609387a170c667b6bb205f176dbd8b1320", "size": "9446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blueprint3.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "265364" }, { "name": "HTML", "bytes": "168169" } ], "symlink_target": "" }
package okhttp3; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.net.ssl.SSLPeerUnverifiedException; import okhttp3.internal.Util; import okhttp3.internal.tls.CertificateChainCleaner; import okio.ByteString; /** * Constrains which certificates are trusted. Pinning certificates defends against attacks on * certificate authorities. It also prevents connections through man-in-the-middle certificate * authorities either known or unknown to the application's user. * * <p>This class currently pins a certificate's Subject Public Key Info as described on <a * href="http://goo.gl/AIx3e5">Adam Langley's Weblog</a>. Pins are either base64 SHA-256 hashes as * in <a href="http://tools.ietf.org/html/rfc7469">HTTP Public Key Pinning (HPKP)</a> or SHA-1 * base64 hashes as in Chromium's <a href="http://goo.gl/XDh6je">static certificates</a>. * * <h3>Setting up Certificate Pinning</h3> * * <p>The easiest way to pin a host is turn on pinning with a broken configuration and read the * expected configuration when the connection fails. Be sure to do this on a trusted network, and * without man-in-the-middle tools like <a href="http://charlesproxy.com">Charles</a> or <a * href="http://fiddlertool.com">Fiddler</a>. * * <p>For example, to pin {@code https://publicobject.com}, start with a broken * configuration: <pre> {@code * * String hostname = "publicobject.com"; * CertificatePinner certificatePinner = new CertificatePinner.Builder() * .add(hostname, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") * .build(); * OkHttpClient client = new OkHttpClient(); * client.setCertificatePinner(certificatePinner); * * Request request = new Request.Builder() * .url("https://" + hostname) * .build(); * client.newCall(request).execute(); * }</pre> * * As expected, this fails with a certificate pinning exception: <pre> {@code * * javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure! * Peer certificate chain: * sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: CN=publicobject.com, OU=PositiveSSL * sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: CN=COMODO RSA Secure Server CA * sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: CN=COMODO RSA Certification Authority * sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=: CN=AddTrust External CA Root * Pinned certificates for publicobject.com: * sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= * at okhttp3.CertificatePinner.check(CertificatePinner.java) * at okhttp3.Connection.upgradeToTls(Connection.java) * at okhttp3.Connection.connect(Connection.java) * at okhttp3.Connection.connectAndSetOwner(Connection.java) * }</pre> * * Follow up by pasting the public key hashes from the exception into the * certificate pinner's configuration: <pre> {@code * * CertificatePinner certificatePinner = new CertificatePinner.Builder() * .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=") * .add("publicobject.com", "sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=") * .add("publicobject.com", "sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=") * .add("publicobject.com", "sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=") * .build(); * }</pre> * * Pinning is per-hostname and/or per-wildcard pattern. To pin both {@code publicobject.com} and * {@code www.publicobject.com}, you must configure both hostnames. * * <p>Wildcard pattern rules: * <ol> * <li>Asterisk {@code *} is only permitted in the left-most domain name label and must be the * only character in that label (i.e., must match the whole left-most label). For example, * {@code *.example.com} is permitted, while {@code *a.example.com}, {@code a*.example.com}, * {@code a*b.example.com}, {@code a.*.example.com} are not permitted. * <li>Asterisk {@code *} cannot match across domain name labels. For example, * {@code *.example.com} matches {@code test.example.com} but does not match * {@code sub.test.example.com}. * <li>Wildcard patterns for single-label domain names are not permitted. * </ol> * * If hostname pinned directly and via wildcard pattern, both direct and wildcard pins will be used. * For example: {@code *.example.com} pinned with {@code pin1} and {@code a.example.com} pinned with * {@code pin2}, to check {@code a.example.com} both {@code pin1} and {@code pin2} will be used. * * <h3>Warning: Certificate Pinning is Dangerous!</h3> * * <p>Pinning certificates limits your server team's abilities to update their TLS certificates. By * pinning certificates, you take on additional operational complexity and limit your ability to * migrate between certificate authorities. Do not use certificate pinning without the blessing of * your server's TLS administrator! * * <h4>Note about self-signed certificates</h4> * * <p>{@link CertificatePinner} can not be used to pin self-signed certificate if such certificate * is not accepted by {@link javax.net.ssl.TrustManager}. * * @see <a href="https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning"> OWASP: * Certificate and Public Key Pinning</a> */ public final class CertificatePinner { public static final CertificatePinner DEFAULT = new Builder().build(); private final List<Pin> pins; private final CertificateChainCleaner certificateChainCleaner; private CertificatePinner(Builder builder) { this.pins = Util.immutableList(builder.pins); this.certificateChainCleaner = builder.certificateChainCleaner; } /** * Confirms that at least one of the certificates pinned for {@code hostname} is in {@code * peerCertificates}. Does nothing if there are no certificates pinned for {@code hostname}. * OkHttp calls this after a successful TLS handshake, but before the connection is used. * * @throws SSLPeerUnverifiedException if {@code peerCertificates} don't match the certificates * pinned for {@code hostname}. */ public void check(String hostname, List<Certificate> peerCertificates) throws SSLPeerUnverifiedException { List<Pin> pins = findMatchingPins(hostname); if (pins.isEmpty()) return; if (certificateChainCleaner != null) { peerCertificates = certificateChainCleaner.clean(peerCertificates); } for (int c = 0, certsSize = peerCertificates.size(); c < certsSize; c++) { X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(c); // Lazily compute the hashes for each certificate. ByteString sha1 = null; ByteString sha256 = null; for (int p = 0, pinsSize = pins.size(); p < pinsSize; p++) { Pin pin = pins.get(p); if (pin.hashAlgorithm.equals("sha256/")) { if (sha256 == null) sha256 = sha256(x509Certificate); if (pin.hash.equals(sha256)) return; // Success! } else if (pin.hashAlgorithm.equals("sha1/")) { if (sha1 == null) sha1 = sha1(x509Certificate); if (pin.hash.equals(sha1)) return; // Success! } else { throw new AssertionError(); } } } // If we couldn't find a matching pin, format a nice exception. StringBuilder message = new StringBuilder() .append("Certificate pinning failure!") .append("\n Peer certificate chain:"); for (int c = 0, certsSize = peerCertificates.size(); c < certsSize; c++) { X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(c); message.append("\n ").append(pin(x509Certificate)) .append(": ").append(x509Certificate.getSubjectDN().getName()); } message.append("\n Pinned certificates for ").append(hostname).append(":"); for (int p = 0, pinsSize = pins.size(); p < pinsSize; p++) { Pin pin = pins.get(p); message.append("\n ").append(pin); } throw new SSLPeerUnverifiedException(message.toString()); } /** @deprecated replaced with {@link #check(String, List)}. */ public void check(String hostname, Certificate... peerCertificates) throws SSLPeerUnverifiedException { check(hostname, Arrays.asList(peerCertificates)); } /** * Returns list of matching certificates' pins for the hostname. Returns an empty list if the * hostname does not have pinned certificates. */ List<Pin> findMatchingPins(String hostname) { List<Pin> result = Collections.emptyList(); for (Pin pin : pins) { if (pin.matches(hostname)) { if (result.isEmpty()) result = new ArrayList<>(); result.add(pin); } } return result; } Builder newBuilder() { return new Builder(this); } /** * Returns the SHA-256 of {@code certificate}'s public key. * * <p>In OkHttp 3.1.2 and earlier, this returned a SHA-1 hash of the public key. Both types are * supported, but SHA-256 is preferred. */ public static String pin(Certificate certificate) { if (!(certificate instanceof X509Certificate)) { throw new IllegalArgumentException("Certificate pinning requires X509 certificates"); } return "sha256/" + sha256((X509Certificate) certificate).base64(); } static ByteString sha1(X509Certificate x509Certificate) { return Util.sha1(ByteString.of(x509Certificate.getPublicKey().getEncoded())); } static ByteString sha256(X509Certificate x509Certificate) { return Util.sha256(ByteString.of(x509Certificate.getPublicKey().getEncoded())); } static final class Pin { /** A hostname like {@code example.com} or a pattern like {@code *.example.com}. */ final String pattern; /** Either {@code sha1/} or {@code sha256/}. */ final String hashAlgorithm; /** The hash of the pinned certificate using {@link #hashAlgorithm}. */ final ByteString hash; Pin(String pattern, String pin) { this.pattern = pattern; if (pin.startsWith("sha1/")) { this.hashAlgorithm = "sha1/"; this.hash = ByteString.decodeBase64(pin.substring("sha1/".length())); } else if (pin.startsWith("sha256/")) { this.hashAlgorithm = "sha256/"; this.hash = ByteString.decodeBase64(pin.substring("sha256/".length())); } else { throw new IllegalArgumentException("pins must start with 'sha256/' or 'sha1/': " + pin); } if (this.hash == null) { throw new IllegalArgumentException("pins must be base64: " + pin); } } boolean matches(String hostname) { if (pattern.equals(hostname)) return true; int firstDot = hostname.indexOf('.'); return pattern.startsWith("*.") && hostname.regionMatches(false, firstDot + 1, pattern, 2, pattern.length() - 2); } @Override public boolean equals(Object other) { return other instanceof Pin && pattern.equals(((Pin) other).pattern) && hashAlgorithm.equals(((Pin) other).hashAlgorithm) && hash.equals(((Pin) other).hash); } @Override public int hashCode() { int result = 17; result = 31 * result + pattern.hashCode(); result = 31 * result + hashAlgorithm.hashCode(); result = 31 * result + hash.hashCode(); return result; } @Override public String toString() { return hashAlgorithm + hash.base64(); } } /** Builds a configured certificate pinner. */ public static final class Builder { private final List<Pin> pins = new ArrayList<>(); private CertificateChainCleaner certificateChainCleaner; public Builder() { } Builder(CertificatePinner certificatePinner) { this.pins.addAll(certificatePinner.pins); this.certificateChainCleaner = certificatePinner.certificateChainCleaner; } public Builder certificateChainCleaner(CertificateChainCleaner certificateChainCleaner) { this.certificateChainCleaner = certificateChainCleaner; return this; } /** * Pins certificates for {@code pattern}. * * @param pattern lower-case host name or wildcard pattern such as {@code *.example.com}. * @param pins SHA-256 or SHA-1 hashes. Each pin is a hash of a certificate's Subject Public Key * Info, base64-encoded and prefixed with either {@code sha256/} or {@code sha1/}. */ public Builder add(String pattern, String... pins) { if (pattern == null) throw new NullPointerException("pattern == null"); for (String pin : pins) { this.pins.add(new Pin(pattern, pin)); } return this; } public CertificatePinner build() { return new CertificatePinner(this); } } }
{ "content_hash": "370afd8e1784914ac127b9d2d2ec786d", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 100, "avg_line_length": 40.95207667731629, "alnum_prop": 0.687236698392885, "repo_name": "SunnyDayDev/okhttp", "id": "f3344d00dd4d6e7ffe534408154a730981b1f7b7", "size": "13418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "okhttp/src/main/java/okhttp3/CertificatePinner.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3695" }, { "name": "HTML", "bytes": "9878" }, { "name": "Java", "bytes": "2419240" }, { "name": "Shell", "bytes": "2641" } ], "symlink_target": "" }
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-} module MC.Protocol.Types ( Packet(..) , prefixFieldName , showPacketInline , showPacketRecord , getTextUTF16be , putTextUTF16be , Point(..) , pointX , pointY , pointZ , getIntPoint , putIntPoint , getBlockPosWithY , putBlockPosWithY , PlayerPos(..) , playerPosPoint , playerPosStance , playerPosX , playerPosY , playerPosZ , getPlayerPosXSYZ , putPlayerPosXSYZ , ChunkPos(..) , chunkPosX , chunkPosZ , Direction(..) , directionYaw , directionPitch , getByteDirection , putByteDirection , Orientation(..) , orientationDirection , orientationRoll , orientationYaw , orientationPitch , getByteOrientation , putByteOrientation , EntityID(..) , getEntityID , WorldID(..) , getWorldID , BlockID(..) , getBlockID , ItemID(..) , getItemID , WindowID(..) , getWindowID , ItemOrBlockID(..) , Item(..) , HeldItem(..) , getMaybeHeldItem , putMaybeHeldItem , Block(..) , Placement(..) , Equipment(..) , CurrentItem(..) , Fireball(..) , ExplosionData(..) , ExplosionItem(..) , WindowItems(..) , MultiBlockChangeData(..) , MultiBlockChangeItem(..) , MapData(..) , EntityData(..) , EntityField(..) , EntityFieldValue(..) , MapChunk(..) , Difficulty(..) , ServerHandshake(..) ) where import MC.Utils import Data.Int import Data.Word import Data.Bits import Data.Char import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.Text (Text) import qualified Data.Text.Encoding as TE import qualified Data.Text.Encoding.Error as TEE import Data.Serialize (Serialize, Get, Putter) import qualified Data.Serialize as SE import qualified Data.Serialize.IEEE754 as SE754 import Control.Applicative import Control.Monad class Packet a where packetName :: a -> String packetShowsFieldsPrec :: Int -> a -> [(String,ShowS)] prefixFieldName :: String -> String -> String prefixFieldName cs "" = error $ "prefixFieldName " ++ show cs ++ "\"\"" prefixFieldName "" fs = error $ "prefixFieldName \"\" " ++ show fs prefixFieldName (c:cs) (f:fs) = toLower c : cs ++ toUpper f : fs showPacketInline :: (Packet a) => a -> ShowS showPacketInline p = showString (packetName p) . showConcatMap (\(_,f) -> showString " " . f) (packetShowsFieldsPrec 11 p) showPacketRecord :: (Packet a) => a -> ShowS showPacketRecord p = showString (packetName p) . showFields '{' ',' (showString "\n }") (packetShowsFieldsPrec 0 p) where showField c x = showString "\n " . showChar c . showChar ' ' . showField' x showField' (name,f) = showString (prefixFieldName (packetName p) name) . showString " = " . f showFields _ _ _ [] = id showFields start mid end (x:xs) = showField start x . showConcatMap (showField mid) xs . end getTextUTF16be :: Get Text getTextUTF16be = do len <- SE.get :: Get Int16 TE.decodeUtf16BEWith TEE.ignore <$> SE.getBytes (fromIntegral len * 2) putTextUTF16be :: Putter Text putTextUTF16be text = do -- The length is sent as the number of UTF-16 components, not as the -- number of codepoints; surrogates are counted as two -- components. Data.Text.length returns the number of codepoints, so -- it's not suitable here. let encoded = TE.encodeUtf16BE text SE.put (fromIntegral (B.length encoded `div` 2) :: Int16) SE.putByteString encoded data Point = Point !Double !Double !Double deriving (Eq, Show) instance Serialize Point where get = Point <$> SE754.getFloat64be <*> SE754.getFloat64be <*> SE754.getFloat64be put (Point x y z) = do SE754.putFloat64be x SE754.putFloat64be y SE754.putFloat64be z pointX :: Point -> Double pointX (Point x _ _) = x pointY :: Point -> Double pointY (Point _ y _) = y pointZ :: Point -> Double pointZ (Point _ _ z) = z getIntPoint :: Get Point getIntPoint = Point <$> getCoord <*> getCoord <*> getCoord where getCoord = ((/ 32) . fromIntegral) <$> (SE.get :: Get Int32) putIntPoint :: Putter Point putIntPoint (Point x y z) = do putCoord x putCoord y putCoord z where putCoord = (SE.put :: Putter Int32) . truncate . (* 32) getBlockPosWithY :: (Integral a) => Get a -> Get Point getBlockPosWithY getY = do x <- SE.get :: Get Int32 y <- getY z <- SE.get :: Get Int32 return $ Point (fromIntegral x) (fromIntegral y) (fromIntegral z) -- This makes me slightly uneasy, since you could pass a Point that -- isn't on a block position. FIXME: Possibly give "non-fractional" -- positions their own type? putBlockPosWithY :: (Integral a) => Putter a -> Putter Point putBlockPosWithY putY (Point x y z) = do SE.put (truncate x :: Int32) putY $ truncate y SE.put (truncate z :: Int32) data PlayerPos = PlayerPos !Point !Double deriving (Eq, Show) instance Serialize PlayerPos where get = do x <- SE754.getFloat64be y <- SE754.getFloat64be stance <- SE754.getFloat64be z <- SE754.getFloat64be return (PlayerPos (Point x y z) stance) put (PlayerPos (Point x y z) stance) = do SE754.putFloat64be x SE754.putFloat64be y SE754.putFloat64be stance SE754.putFloat64be z playerPosPoint :: PlayerPos -> Point playerPosPoint (PlayerPos p _) = p playerPosStance :: PlayerPos -> Double playerPosStance (PlayerPos _ stance) = stance playerPosX :: PlayerPos -> Double playerPosX = pointX . playerPosPoint playerPosY :: PlayerPos -> Double playerPosY = pointY . playerPosPoint playerPosZ :: PlayerPos -> Double playerPosZ = pointZ . playerPosPoint -- See the comments on S.PlayerPositionLook for an explanation of -- this. getPlayerPosXSYZ :: Get PlayerPos getPlayerPosXSYZ = do x <- SE754.getFloat64be stance <- SE754.getFloat64be y <- SE754.getFloat64be z <- SE754.getFloat64be return (PlayerPos (Point x y z) stance) putPlayerPosXSYZ :: Putter PlayerPos putPlayerPosXSYZ (PlayerPos (Point x y z) stance) = do SE754.putFloat64be x SE754.putFloat64be stance SE754.putFloat64be y SE754.putFloat64be z data ChunkPos = ChunkPos !Int32 !Int32 deriving (Eq, Show) instance Serialize ChunkPos where get = ChunkPos <$> SE.get <*> SE.get put (ChunkPos x z) = do SE.put x SE.put z chunkPosX :: ChunkPos -> Int32 chunkPosX (ChunkPos x _) = x chunkPosZ :: ChunkPos -> Int32 chunkPosZ (ChunkPos _ z) = z data Direction = Direction !Float !Float deriving (Eq, Show) instance Serialize Direction where get = Direction <$> SE754.getFloat32be <*> SE754.getFloat32be put (Direction yaw pitch) = do SE754.putFloat32be yaw SE754.putFloat32be pitch directionYaw :: Direction -> Float directionYaw (Direction yaw _) = yaw directionPitch :: Direction -> Float directionPitch (Direction _ pitch) = pitch getByteDirection :: Get Direction getByteDirection = Direction <$> getComponent <*> getComponent where getComponent = ((/ 256) . (* 360) . fromIntegral) <$> SE.getWord8 putByteDirection :: Putter Direction putByteDirection (Direction yaw pitch) = do putComponent yaw putComponent pitch where putComponent = SE.putWord8 . truncate . (/ 360) . (* 256) data Orientation = Orientation !Direction !Float deriving (Eq, Show) orientationDirection :: Orientation -> Direction orientationDirection (Orientation dir _) = dir orientationRoll :: Orientation -> Float orientationRoll (Orientation _ roll) = roll orientationYaw :: Orientation -> Float orientationYaw = directionYaw . orientationDirection orientationPitch :: Orientation -> Float orientationPitch = directionPitch . orientationDirection -- FIXME: Annoying duplication with {get,put}ByteDirection getByteOrientation :: Get Orientation getByteOrientation = Orientation <$> getByteDirection <*> getComponent where getComponent = ((/ 256) . (* 360) . fromIntegral) <$> SE.getWord8 putByteOrientation :: Putter Orientation putByteOrientation (Orientation dir roll) = do putByteDirection dir putComponent roll where putComponent = SE.putWord8 . truncate . (/ 360) . (* 256) newtype EntityID = EntityID Int32 deriving (Eq, Show, Serialize) getEntityID :: EntityID -> Int32 getEntityID (EntityID i) = i newtype WorldID = WorldID Int8 deriving (Eq, Show, Serialize) getWorldID :: WorldID -> Int8 getWorldID (WorldID i) = i newtype BlockID = BlockID Int8 deriving (Eq, Show, Serialize) getBlockID :: BlockID -> Int8 getBlockID (BlockID i) = i newtype ItemID = ItemID Int16 deriving (Eq, Show, Serialize) getItemID :: ItemID -> Int16 getItemID (ItemID i) = i newtype WindowID = WindowID Int8 deriving (Eq, Show, Serialize) getWindowID :: WindowID -> Int8 getWindowID (WindowID i) = i data ItemOrBlockID = IsItem !ItemID | IsBlock !BlockID deriving (Eq, Show) instance Serialize ItemOrBlockID where get = do sh <- SE.lookAhead SE.get :: Get Int16 if sh > 255 then IsItem <$> SE.get else do -- discard the additional byte SE.skip 1 IsBlock <$> SE.get put (IsItem itemID) = SE.put itemID put (IsBlock blockID) = do -- add the additional byte SE.putWord8 0 SE.put blockID -- Int16 is metadata data Item = Item !ItemOrBlockID !Int16 deriving (Eq, Show) -- Note that this instance is *not* used in other instances; usually -- the amount appears first. instance Serialize Item where get = Item <$> SE.get <*> SE.get put (Item itemOrBlockID metadata) = do SE.put itemOrBlockID SE.put metadata -- Int8 is amount data HeldItem = HeldItem !Item !Int8 deriving (Eq, Show) instance Serialize HeldItem where get = do itemOrBlockID <- SE.get amount <- SE.get metadata <- SE.get return $ HeldItem (Item itemOrBlockID metadata) amount put (HeldItem (Item itemOrBlockID metadata) amount) = do SE.put itemOrBlockID SE.put amount SE.put metadata getMaybeHeldItem :: Get (Maybe HeldItem) getMaybeHeldItem = do let getShort = SE.get :: Get Int16 sh <- SE.lookAhead getShort if sh < 0 then getShort >> return Nothing else Just <$> SE.get putMaybeHeldItem :: Putter (Maybe HeldItem) putMaybeHeldItem Nothing = SE.put (-1 :: Int16) putMaybeHeldItem (Just heldItem) = SE.put heldItem -- Int8 is metadata data Block = Block !BlockID !Int8 deriving (Eq, Show) instance Serialize Block where get = Block <$> SE.get <*> SE.get put (Block blockID metadata) = do SE.put blockID SE.put metadata data Placement = EmptyHanded | Place !HeldItem deriving (Eq, Show) instance Serialize Placement where get = do let getShort = SE.get :: Get Int16 sh <- SE.lookAhead getShort if sh < 0 then getShort >> return EmptyHanded else Place <$> SE.get put EmptyHanded = SE.put (-1 :: Int16) put (Place heldItem) = SE.put heldItem -- FIXME: Annoying duplication with HeldItem and Placement, especially -- since -1 is used to denote "nothing held" in both data Equipment = NothingEquipped | Equipped !Item deriving (Eq, Show) instance Serialize Equipment where get = do let getShort = SE.get :: Get Int16 sh <- SE.lookAhead getShort if sh < 0 then getShort >> getShort >> return NothingEquipped else Equipped <$> (Item <$> SE.get <*> SE.get) put NothingEquipped = do SE.put (-1 :: Int16) -- FIXME: What does the official server send for metadata in this -- case? SE.put (0 :: Int16) put (Equipped (Item itemOrBlockID metadata)) = do SE.put itemOrBlockID SE.put metadata data CurrentItem = NoCurrentItem | CurrentItem !ItemID deriving (Eq, Show) instance Serialize CurrentItem where get = do let getShort = SE.get :: Get Int16 sh <- SE.lookAhead getShort if sh == 0 then getShort >> return NoCurrentItem else CurrentItem <$> SE.get put NoCurrentItem = SE.put (0 :: Int16) put (CurrentItem itemID) = SE.put itemID -- the EntityID is the entity ID of the fireball thrower, not of the -- fireball itself data Fireball = NotFireball | Fireball !EntityID !Int16 !Int16 !Int16 deriving (Eq, Show) instance Serialize Fireball where get = do let getInt = SE.get :: Get Int32 int <- SE.lookAhead getInt if int == 0 then getInt >> return NotFireball else Fireball <$> SE.get <*> SE.get <*> SE.get <*> SE.get put NotFireball = SE.put (0 :: Int32) put (Fireball entityID unknown1 unknown2 unknown3) = do SE.put entityID SE.put unknown1 SE.put unknown2 SE.put unknown3 newtype ExplosionData = ExplosionData [ExplosionItem] deriving (Eq, Show) -- FIXME: Are these signed or unsigned? data ExplosionItem = ExplosionItem !Int8 !Int8 !Int8 deriving (Eq, Show) instance Serialize ExplosionItem where get = ExplosionItem <$> SE.get <*> SE.get <*> SE.get put (ExplosionItem x y z) = do SE.put x SE.put y SE.put z instance Serialize ExplosionData where get = do count <- SE.get :: Get Int16 ExplosionData <$> replicateM (fromIntegral count) SE.get put (ExplosionData xs) = do SE.put (fromIntegral (length xs) :: Int16) mapM_ SE.put xs newtype WindowItems = WindowItems [Maybe HeldItem] deriving (Eq, Show) instance Serialize WindowItems where get = do count <- SE.get :: Get Int16 WindowItems <$> replicateM (fromIntegral count) getMaybeHeldItem put (WindowItems xs) = do SE.put (fromIntegral (length xs) :: Int16) mapM_ putMaybeHeldItem xs newtype MultiBlockChangeData = MultiBlockChangeData [MultiBlockChangeItem] deriving (Eq, Show) -- FIXME: Should probably be named BlockChange and be used for single -- block changes too -- -- FIXME: The Int8 fields should possibly be Word8s data MultiBlockChangeItem = MultiBlockChangeItem !Int8 !Int8 !Int8 !Block deriving (Eq, Show) instance Serialize MultiBlockChangeData where get = do count <- fromIntegral <$> (SE.get :: Get Int16) coords <- replicateM count (unpackCoords <$> SE.get) types <- replicateM count SE.get metadata <- replicateM count SE.get return $ MultiBlockChangeData (zipWith3 makeItem coords types metadata) where -- FIXME: might be Word16 unpackCoords :: Int16 -> (Int8,Int8,Int8) unpackCoords sh = (fromIntegral (sh `shiftL` 12), fromIntegral ((sh `shiftL` 8) .&. 0xF), fromIntegral (sh .&. 0xF)) makeItem :: (Int8,Int8,Int8) -> Int8 -> Int8 -> MultiBlockChangeItem makeItem (x,y,z) blockType metadata = MultiBlockChangeItem x y z (Block (BlockID blockType) metadata) put (MultiBlockChangeData xs) = do SE.put (fromIntegral (length xs) :: Int16) mapM_ putCoords xs mapM_ putType xs mapM_ putMetadata xs where putCoords (MultiBlockChangeItem x y z _) = SE.put (fromIntegral (x `shiftR` 12) .|. fromIntegral (y `shiftR` 8) .|. fromIntegral z :: Int16) putType (MultiBlockChangeItem _ _ _ (Block (BlockID blockID) _)) = SE.put blockID putMetadata (MultiBlockChangeItem _ _ _ (Block _ metadata)) = SE.put metadata -- TODO FIXME: Parse this properly rather than this ridiculously lazy hack newtype MapData = MapData ByteString deriving (Eq, Show) instance Serialize MapData where get = do bytes <- SE.getWord8 MapData <$> SE.getByteString (fromIntegral bytes) put (MapData str) = do SE.putWord8 $ fromIntegral (B.length str) SE.putByteString str newtype EntityData = EntityData [EntityField] deriving (Eq, Show) -- FIXME: Should maybe be Int8 data EntityField = EntityField !Word8 !EntityFieldValue deriving (Eq, Show) data EntityFieldValue = EntityInt8 !Int8 | EntityInt16 !Int16 | EntityInt32 !Int32 | EntityFloat !Float | EntityString !Text | EntityHeldItem !HeldItem | EntityVector !Int32 !Int32 !Int32 deriving (Eq, Show) instance Serialize EntityField where get = do (fieldType,ident) <- unpackEntityByte <$> SE.getWord8 value <- case fieldType of 0 -> EntityInt8 <$> SE.get 1 -> EntityInt16 <$> SE.get 2 -> EntityInt32 <$> SE.get 3 -> EntityFloat <$> SE754.getFloat32be 4 -> EntityString <$> getTextUTF16be 5 -> EntityHeldItem <$> SE.get 6 -> EntityVector <$> SE.get <*> SE.get <*> SE.get _ -> fail $ "Unknown entity data field type: " ++ show fieldType return (EntityField ident value) where unpackEntityByte byte = (byte `shiftR` 5, byte .&. 0x1F) put (EntityField ident value) = do let (fieldType,action) = f value SE.putWord8 $ (fieldType `shiftL` 5) .|. ident action where f (EntityInt8 v) = (0, SE.put v) f (EntityInt16 v) = (1, SE.put v) f (EntityInt32 v) = (2, SE.put v) f (EntityFloat v) = (3, SE754.putFloat32be v) f (EntityString s) = (4, putTextUTF16be s) f (EntityHeldItem heldItem) = (5, SE.put heldItem) f (EntityVector x y z) = (6, SE.put x >> SE.put y >> SE.put z) instance Serialize EntityData where get = do byte <- SE.lookAhead SE.getWord8 if byte == 0x7F then SE.getWord8 >> return (EntityData []) else do field <- SE.get EntityData rest <- SE.get return (EntityData (field:rest)) put (EntityData xs) = do mapM_ SE.put xs SE.putWord8 0x7F -- FIXME: Maybe this should be its own proper type which just gets -- compressed/decompressed on serialisation/deserialisation, rather -- than the trivial newtype it is now. newtype MapChunk = MapChunk ByteString deriving (Eq, Show) instance Serialize MapChunk where get = do bytes <- SE.get :: Get Int32 MapChunk <$> SE.getByteString (fromIntegral bytes) put (MapChunk str) = do SE.put (fromIntegral (B.length str) :: Int32) SE.putByteString str data Difficulty = Peaceful | Easy | Normal | Hard deriving (Eq, Show, Enum) instance Serialize Difficulty where get = do n <- SE.get :: Get Int8 case n of 0 -> return Peaceful 1 -> return Easy 2 -> return Normal 3 -> return Hard _ -> fail $ "Unknown difficulty value " ++ show n put Peaceful = SE.put (0 :: Int8) put Easy = SE.put (1 :: Int8) put Normal = SE.put (2 :: Int8) put Hard = SE.put (3 :: Int8) data ServerHandshake = NoAuthentication | Authenticate -- The field is a unique connection ID; the official server -- generates a 64-bit word and converts it to lowercase hexadecimal -- to generate this. -- -- FIXME: Maybe it should be a String instead? It's pretty short, -- though so are all the strings used in the protocol, and Text is -- used for them. It'd still have to be converted to Text to -- serialise it, because there's no UTF-16 decoder for Strings. | LoggedIn !Text deriving (Eq, Show) instance Serialize ServerHandshake where get = do str <- getTextUTF16be case str of "-" -> return NoAuthentication "+" -> return Authenticate _ -> return (LoggedIn str) put NoAuthentication = putTextUTF16be "-" put Authenticate = putTextUTF16be "+" put (LoggedIn str) = putTextUTF16be str
{ "content_hash": "136f19d87e4d2a1d3a1b9ba1a2f86845", "timestamp": "", "source": "github", "line_count": 622, "max_line_length": 126, "avg_line_length": 30.183279742765272, "alnum_prop": 0.6875998721636305, "repo_name": "ehird/mchost", "id": "3d327733799092e4b40f1e0dcb59dcef2a946207", "size": "18774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MC/Protocol/Types.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "44074" } ], "symlink_target": "" }
c3bottles can use any map source that can be configured as a layer in [Leaflet](https://leafletjs.com/). Map configuration happens in two stages: 1. Map sources and their paramters (e.g. tile server URL, zoom levels, layers and building levels, coordinate bounds etc.) are configured as properties of Python objects in `c3bottles/config/map.py`. These are hard-coded but can of course be adapted to specific setups if needed. 2. One of these sources is chosen in `config.py` by setting the `MAP_SOURCE` configuration parameter. In addition to selecting one of the map sources, the user can decide to override specific parameters (typically tile server URLs) by doing something like this in `config.py`: from c3bottles.config.map import ExampleMapSource MAP_SOURCE = ExampleMapSource ExampleMapSource.override("tileserver", "https://tiles.example.org/") The configuration file is Python code that is executed on server startup, so a lot of things are possible here, if needed. ## Preconfigured map sources c3bottles ships with a number of map sources that can be used directly: * **OpenStreetMap**: This is the easiest way to use geographical tiles for an outdoor event. This source uses tiles directly from the tile servers behind [OpenStreetMap](https://www.openstreetmap.org/). The *OpenStreetMapCamp2019* configuration is an example for OpenStreetMap and pointing at the location of the Chaos Communication Camp 2019 in Mildenberg. The starting location and zoom levels can be easily adapted as needed. OpenStreepMap only has one layer. The `tileserver_subdomains` option is used to distribute load over different tile servers. * **c3nav**: c3nav is a routing webservice for chaos events that is available for use at [https://c3nav.de/](https://c3nav.de/) and being developed at [https://github.com/c3nav/c3nav/](https://github.com/c3nav/c3nav/). Like c3bottles, c3nav is based on Leaflet and provides high-quality tiles of venues for events like the Chaos Communication Congress which we can use via this map source. The configuration named *C3Nav35C3* contains an event-specific tile server URL which probably changes with the next event. The c3nav configuration contains a `level_configuration` since it uses a number of map layers that correlate to building levels. In addition, it needs a number of specific hacks, which are needed to properly use the tiles: * The `hack_257px` option enables a code snippet in `js/map.js` to deal with the non-standard tile size of 257x257 pixels. * The `simple_crs` option changes the coordinate reference system used from the default (geographical coordinates) to a simpler one that is better suited for hand-crafted custom tiles for a plane like a building instead of a globe. If you want to use tiles from c3nav, please contact the c3nav developers beforehand. It is their decision if they let you use their tiles (and the bandwidth on their tile servers). ## Adding map sources You can easily add your own map source either to `c3bottles/config/map.py`, define it directly in `config.py` or add it somewhere else and import it from there. Map sources are Python classes inheriting from `MapSource` which is defined in `c3bottles/config/map.py`. Please make sure to use this base class as it provides a few methods and special characteristics that are needed for it to work properly. Parameters of map sources are static, class level variables. The following configuration parameters are currently used from map sources (types shown are Python data types): * **tileserver** (*str*, mandatory): The base tile server URL. This should end with a `/` and is used to create the tile URLs. Currently, this is simply appended by `level/zoom/longitude/latitude.png` with the `level/` part being optional (depending on whether a `level_configuration` has been given). The string `{s}` in the URL is randomly replaced by one of the elements from `tileserver_subdomains` if that has been set. * **tileserver_subdomains** (*list* of *str*, optional): An optional list of subdomain strings that are chosen randomly to distribute load over a number of different tile servers. * **attribution** (*str*, optional): An attribution text, and possibly a link that is shown in the bottom right corner to properly attribute the tile provider. This has to be set in accordance with the tile provider and usually contains a link to the service whose tiles are used and possibly a copyright statement for the tile author(s). This is not mandatory from a technical point of view but should always be set. * **min_zoom** (*int*, mandatory): The minimum zoom level that the user may choose. * **max_zoom** (*int*, mandatory): The maximum zoom level that the user may choose. * **bounds** (*list* of *lists* of *floats*, optional): This setting can be used to restrict the user to a specific region on the map. This must be a list with two elements, which in turn are lists of two floats, like such: [[min_x, min_y], [max_x, max_y]] Make sure to use *lists* here instead of *tuples* as this value is directly embedded in JavaScript code. * **initial_view** (*dict* of *floats*, optional): The initial default view used on the map. This is a *dict* that needs three values: `lat` for the latitude, `lng` for the longitude and `zoom`. if this is not set, the map will call Leaflet's `fitBound()` method, if `bounds` have been set and `fitWorld()` otherwise. * **level_config** (*list* of *lists* of *ints*, optional): This setting defines a correlation between map layers (as they are used in tile URLs) and e.g. building levels. For this, a list of lists of two integers has to be given where the first corresponds to a map layer number and the second one to a level number that is used in the c3bottles database and shown in the level selector widget on the map, like such: [[23, -1], [30, 0], [42, 1]] If no `level_config` has been set, all drop points will default to a level of 0 and levels will be disabled completely in the frontend. Make sure to use *lists* here instead of *tuples* as this value is directly embedded in JavaScript code. Specific map sources may have their own configuration parameters used as special hacks to enable code only needed for these sources. For these parameters see the list of preconfigured map sources above. ## Rendering your own tiles Originally, c3bottles has been designed for a map that was a huge image and from which tiles could rendered with a semi-automatic toolchain. Other maps then can simply be used by exchanging the base image and rendering new tiles. These tiles are built using Imagemagick, GDAL and gdal2tiles. If you use Debian, you can install the dependencies like this: sudo apt install imagemagick gdal-bin libgdal-dev pip install gdal2tiles The base image for the tiles needs to be a square with a size that is a power of 2. Suppose your image is named `static/img/map.png`, then you first have to convert it to a square with an edge length of the next power of 2. You can find out the size of the image with `file` or `identify`: cd static/img identify map.png The output looks like this: map.png PNG 5500x10500 5500x10500+0+0 8-bit sRGB 21.7418MiB 0.000u 0:00.000 In this case, the next power of 2 larger than 10500 pixels would be 16384, so the image needs to be resized to 16384x16384 pixels: convert map.png -background white -compose Copy -gravity center \ -resize 16384x16384 -extent 16384x16384 map_sq.png If this fails, you may have to increase your ImageMagick memory limit in `/etc/ImageMagick-6/policy.xml` After you have successfully create a square image, you can render the tiles from `map_sq.png` using GDAL and gdal2tiles: gdal_translate -of vrt map_sq.png map_sq.vrt gdal2tiles.py -w none -p raster map_sq.vrt tiles Your tiles will be in the `static/img/tiles` directory and can be used with a map source like this in `c3bottles/config/map.py`: class CustomTiles(MapSource): attribution = "self-made" tileserver = "/static/img/tiles/" min_zoom = 0 max_zoom = 6 tms = True no_wrap = True
{ "content_hash": "66a8d880bc6447f68c0bf5cc449a5f20", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 79, "avg_line_length": 46.10326086956522, "alnum_prop": 0.7319344571495933, "repo_name": "der-michik/c3bottles", "id": "e74fa05742275ece2c7e57d425e73cec1170c0ff", "size": "8504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/MAP.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1937" }, { "name": "Dockerfile", "bytes": "1010" }, { "name": "HTML", "bytes": "61195" }, { "name": "JavaScript", "bytes": "32088" }, { "name": "Makefile", "bytes": "584" }, { "name": "Mako", "bytes": "494" }, { "name": "Python", "bytes": "97736" }, { "name": "Shell", "bytes": "497" } ], "symlink_target": "" }
package com.stratio.crossdata.common.manifest; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DataStoreFunctionsType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DataStoreFunctionsType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Function" type="{}FunctionType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DataStoreFunctionsType", propOrder = { "function" }) public class DataStoreFunctionsType implements Serializable { private static final long serialVersionUID = -3216129288591658070L; @XmlElement(name = "Function", required = true) protected List<FunctionType> function; /** * Gets the value of the function property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the function property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFunction().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FunctionType } * * @return a list of {@link com.stratio.crossdata.common.manifest.FunctionType} . */ public List<FunctionType> getFunction() { if (function == null) { function = new ArrayList<>(); } return this.function; } /** * Set the functions of datastore. * @param function The list of functions. */ public void setFunction(List<FunctionType> function) { this.function = function; } }
{ "content_hash": "1f74747be4f8c988e4fb7a01787c43f7", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 95, "avg_line_length": 29, "alnum_prop": 0.6556089044085552, "repo_name": "ccaballe/crossdata", "id": "f7a87216aba362862af643d9ee854773bf81c280", "size": "3077", "binary": false, "copies": "2", "ref": "refs/heads/branch-0.4", "path": "crossdata-common/src/main/java/com/stratio/crossdata/common/manifest/DataStoreFunctionsType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "53456" }, { "name": "Java", "bytes": "2536616" }, { "name": "Scala", "bytes": "357035" }, { "name": "Shell", "bytes": "40443" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jorge Escalante | Desarrollador Web e Ingenierio en Informática</title> <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1"> <meta name="description" content="Desarrollador web full-stack (Frontend y backend) y con pensum cerrado en Ingeniería en Informática y Sistemas"> <link rel="shortcut icon" href="{{ asset('favicon.ico')}}"/> <link rel="stylesheet" href="{{ asset('css/main-index.css')}}"> </head> <body> <input type="checkbox" id="NavTrigger" class="NavTrigger" /> <div class="SiteWrap" > <header class="ProfileCard"> <div class="wrapper"> <div class="ProfileCard-menu"> <label class="icon-menu ProfileCard-menu-menuButton NavTrigger-button" for="NavTrigger"></label> </div> <img class="ProfileCard-avatar" src="{{asset('img/perfil.png')}}" alt="Foto de perfil" height="120" width="120"> <h1 class="ProfileCard-name">Jorge Escalante</h1> <h2 class="ProfileCard-description">Desarrollador web full-stack (Frontend y Backend) y con pensum cerrado en Ingeniería en Informática y Sistemas</h2> <a class="u-button ProfileCard-contactButton" href="#">Contáctame</a> </div> </header> <section class="AboutMe"> <div class="wrapper u-sectionBorderBottom"> <h3 class="AboutMe-title u-sectionTitle">Acerca de mí</h3> <p class="AboutMe-description">Soy desarrollador con formación en multiples disciplinas de diseño y desarrollo de aplicaciones web y de escritorio. Cuento con conocimientos en análisis y diseño de software, redes, seguridad y administración de servidores</p> <section name="AboutMe" class="AboutMe-features"> <ul> <li class="AboutMe-features-profession"><p><span class="icon-profession"></span>Ingeniería en Informática y Sistemas</p></li> <li class="AboutMe-features-location"><p><span class="icon-location"></span>Quetzaltenango, Guatemala</p></li> <li class="AboutMe-features-tags"><p><span class="icon-tag"></span>#desarrollador #responsable #autodidacta #detallista #web #superacion #dedicado #tecnologico</p></li> </ul> </section> </div> </section> <section class="Skills"> <div class="wrapper u-sectionBorderBottom"> <h3 class="Skills-title u-sectionTitle">Habilidades Técnicas</h3> <section class="Skills-subSection"> <h4 class="u-subSectionTitle">Lenguajes de programación y tecnologías</h4> <section class="Skills-subSection-content"> @include('partials.skill', array('skill'=>'HTML')) @include('partials.skill', array('skill'=>'CSS')) @include('partials.skill', array('skill'=>'Javascript')) @include('partials.skill', array('skill'=>'Python')) @include('partials.skill', array('skill'=>'PHP')) @include('partials.skill', array('skill'=>'Java')) @include('partials.skill', array('skill'=>'C#')) </section> </section> <section class="Skills-subSection"> <h4 class="u-subSectionTitle">Frameworks y librerías</h4> <section class="Skills-subSection-content"> @include('partials.skill', array('skill'=>'Backbonejs')) @include('partials.skill', array('skill'=>'Django')) @include('partials.skill', array('skill'=>'Laravel')) @include('partials.skill', array('skill'=>'Node.js')) @include('partials.skill', array('skill'=>'Angular')) @include('partials.skill', array('skill'=>'JQuery')) </section> </section> <section class="Skills-subSection"> <h4 class="u-subSectionTitle">Otras habilidades</h4> <section class="Skills-subSection-content"> @include('partials.skill', array('skill'=>'Web Performance')) @include('partials.skill', array('skill'=>'Administracion de servidores')) @include('partials.skill', array('skill'=>'Alta disponibilidad en servidores y bases de datos')) </section> </section> </div> </section> <section class="Projects"> <div class="wrapper"> <h3 class="Projects-title u-sectionTitle">Proyectos</h3> <section class="Projects-content"> @include('partials.project-detail') <!-- @include('partials.project', array('name'=>'Proyecto de rendmiento para sitio web', 'job'=> 'Desarrollador Frontend y Backend')) @include('partials.project', array('name'=>'Proyecto cualquiera', 'job'=> 'Director Tecnico')) @include('partials.project', array('name'=>'MuseoXela', 'job'=> 'Arquitecto de información')) @include('partials.project', array('name'=>'Proyecto XY', 'job'=> 'Desarrollador Frontend y Backend')) @include('partials.project', array('name'=>'Imagenes empresariales', 'job'=> 'Administrador y gestor de servidores')) --> </section> </div> </section> <section class="ContactMe"> <div class="wrapper"> <section class="ContactMe-text"> <h3 class="ContactMe-title u-sectionTitle">Contáctame</h3> <p class="ContactMe-description">¿Dudas? ¿Comentarios? Será un gusto escucharte</p> </section> <section class="ContactMe-form"> <form action=""> <label for="contactForm-name">Nombre:</label> <input type="text" name="contactForm-name" id="contactForm-name" placeholder="Ingresa tu nombre"> <label for="contactForm-email">Correo Electrónico:</label> <input type="email" name="contactForm-email" id="contactForm-email" placeholder="Ingresa tu correo electrónico"> <label for="contactForm-subject">Asunto:</label> <input type="text" name="contactForm-subject" id="contactForm-subject" placeholder="¿Por que me deseas contactar?"> <label for="contactForm-message">Mensaje:</label> <textarea name="contactForm-message" id="contactForm-message" cols="30" rows="10" placeholder="Ingresa tu mensaje"></textarea> <button class="u-button" type="submit">Enviar</button> </form> </section> </div> </section> <footer class="Footer"> <div class="wrapper"> <p>Hecho con <span class="icon-heart"></span> en Guatemala</p> <p>Todos los derechos reservados 2015</p> </div> </footer> </div> <nav class="Menu"> <ul> <li><label for="NavTrigger"><span class="icon-close"></span>Cerrar</label></li> <li><a href="#"><span class="icon-home"></span>Inicio</a></li> <li><a href="#"><span class="icon-blog"></span>Blog</a></li> <li><a href="#AboutMe"><span class="icon-about"></span>Acerca de mí</a></li> <li><a href="#"><span class="icon-skill"></span>Habilidades</a></li> <li><a href="#"><span class="icon-job"></span>Proyectos</a></li> <li><a href="#"><span class="icon-message"></span>Contactame</a></li> </ul> </nav> </body> </html>
{ "content_hash": "1e37f7797d6ab9ab0dbf5868b6274345", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 268, "avg_line_length": 56.40769230769231, "alnum_prop": 0.6057548070366835, "repo_name": "JEscalanteGT/portafolio", "id": "12db26c2f40b7ff96e4430898e4d397eb995e767", "size": "7360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/assets/templates/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "147124" }, { "name": "HTML", "bytes": "11463" }, { "name": "JavaScript", "bytes": "1324" }, { "name": "PHP", "bytes": "90649" }, { "name": "XML", "bytes": "729" } ], "symlink_target": "" }
namespace OverviewApp.Auxiliary.Helpers { public class RefreshSummary { } }
{ "content_hash": "b3ea8356180589bb919eec94cbb118ec", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 39, "avg_line_length": 14.5, "alnum_prop": 0.7011494252873564, "repo_name": "salda8/Overview-Application", "id": "96946330294359aefcdd91b84fb2eedda3d3559d", "size": "87", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Overview Application/Auxiliary/Helpers/RefreshSummary.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "407400" }, { "name": "Smalltalk", "bytes": "5762" } ], "symlink_target": "" }
package interretis.advanced import interretis.utils.SparkContextBuilder._ import interretis.utils.Resources._ import org.apache.spark.sql.DataFrame import org.apache.spark.sql.SQLContext import org.apache.spark.sql.Row import language.postfixOps object WikiExploration { private val dataDirectory = mainResources + "/wiki_parquet" private val table = "wikiData" def main(args: Array[String]): Unit = { val sqlContext = buildSqlContext(getClass.getSimpleName) val app = new WikiExploration(sqlContext) val count = app.countArticles println(s"There are $count articles in Wiki") val topUsers = app.retrieveTopUsers topUsers foreach (println) val californiaArticles = app countArticlesWith "california" println(s"There are $californiaArticles that mention California") } private def loadWikiData(sqlContext: SQLContext): Unit = { val data = sqlContext.read.parquet(dataDirectory) data registerTempTable table } } case class TopUser(name: String, count: Long) class WikiExploration(sqlContext: SQLContext) { import sqlContext._ import sqlContext.implicits._ import WikiExploration.{ loadWikiData, table } loadWikiData(sqlContext) def countArticles: Long = { val df = sql(s"SELECT count(*) FROM $table") df.collect.head.getLong(0) } def retrieveTopUsers: Array[TopUser] = { val df = sql(s"SELECT username, count(*) AS cnt FROM $table WHERE username <> '' GROUP BY username ORDER BY cnt DESC LIMIT 10") val topUsers = df map { case Row(username: String, count: Long) => TopUser(username, count) } topUsers collect } def countArticlesWith(word: String): Long = { val df = sql(s"SELECT count(*) FROM $table WHERE text LIKE '%$word%'") df.collect.head.getLong(0) } }
{ "content_hash": "d84edcdd4ca6b5060f18d8e6d50b4c10", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 131, "avg_line_length": 27.890625, "alnum_prop": 0.7226890756302521, "repo_name": "MarekDudek/spark-certification", "id": "dced1b14870b0028d58a502fb44034f31b56b8ac", "size": "1785", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/interretis/advanced/WikiExploration.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "35613" }, { "name": "Shell", "bytes": "1990" } ], "symlink_target": "" }
from __future__ import print_function, division, absolute_import from docutils import nodes from docutils.parsers import rst from docutils.parsers.rst import directives from docutils import statemachine import traceback def _indent(text, level=1): ''' Format Bintypes ''' prefix = ' ' * (4 * level) def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return ''.join(prefixed_lines()) def _format_datacubes(datacubes): ''' Format Spectra ''' n_bins = len(datacubes) b = datacubes[0] yield '.. list-table:: Datacubes' yield _indent(':widths: 15 50 50 10 10 20 20') yield _indent(':header-rows: 1') yield '' yield _indent('* - Name') yield _indent(' - Description') yield _indent(' - Unit') yield _indent(' - Ivar') yield _indent(' - Mask') yield _indent(' - DB') yield _indent(' - FITS') for datacube in datacubes: dbcolumn = '{0}.{1}'.format(datacube.db_table, datacube.db_column()) yield _indent('* - {0}'.format(datacube.name)) yield _indent(' - {0}'.format(datacube.description)) yield _indent(' - {0}'.format(datacube.unit.to_string())) yield _indent(' - {0}'.format(datacube.has_ivar())) yield _indent(' - {0}'.format(datacube.has_mask())) yield _indent(' - {0}'.format(dbcolumn)) yield _indent(' - {0}'.format(datacube.fits_extension())) yield '' def _format_spectra(spectra): ''' Format Spectra ''' n_bins = len(spectra) b = spectra[0] yield '.. topic:: Spectra' yield '.. list-table:: Spectra' yield _indent(':widths: 15 100 20 20 20') yield _indent(':header-rows: 1') yield '' yield _indent('* - Name') yield _indent(' - Description') yield _indent(' - Unit') yield _indent(' - DB') yield _indent(' - FITS') for spectrum in spectra: dbcolumn = '{0}.{1}'.format(spectrum.db_table, spectrum.db_column()) yield _indent('* - {0}'.format(spectrum.name)) yield _indent(' - {0}'.format(spectrum.description)) yield _indent(' - {0}'.format(spectrum.unit.to_string())) yield _indent(' - {0}'.format(dbcolumn)) yield _indent(' - {0}'.format(spectrum.fits_extension())) yield '' def _format_bintypes(bintypes): ''' Format Bintypes ''' n_bins = len(bintypes) b = bintypes[0] yield '.. list-table:: Bintypes' yield _indent(':widths: 15 100 10') yield _indent(':header-rows: 1') yield '' yield _indent('* - Name') yield _indent(' - Description') yield _indent(' - Binned') for bintype in bintypes: yield _indent('* - {0}'.format(bintype.name)) yield _indent(' - {0}'.format(bintype.description)) yield _indent(' - {0}'.format(bintype.binned)) yield '' def _format_templates(templates): ''' Format Templates ''' n_temps = len(templates) b = templates[0] yield '.. list-table:: Templates' yield _indent(':widths: 15 100') yield _indent(':header-rows: 1') yield '' yield _indent('* - Name') yield _indent(' - Description') for template in templates: yield _indent('* - {0}'.format(template.name)) yield _indent(' - {0}'.format(template.description)) yield '' def _format_models(models): ''' Format Models ''' n_temps = len(models) b = models[0] yield '.. list-table:: Models' yield _indent(':widths: 15 100 50 20 15 15') yield _indent(':header-rows: 1') yield '' yield _indent('* - Name') yield _indent(' - Description') yield _indent(' - Unit') yield _indent(' - BinId') yield _indent(' - Ivar') yield _indent(' - Mask') for model in models: yield _indent('* - {0}'.format(model.name)) yield _indent(' - {0}'.format(model.description)) yield _indent(' - {0}'.format(model.unit)) yield _indent(' - {0}'.format(model.binid.name)) yield _indent(' - {0}'.format(model.has_ivar())) yield _indent(' - {0}'.format(model.has_mask())) yield '' def _format_properties(properties): ''' Format Properties ''' n_temps = len(properties) b = properties[0] exts = properties.extensions n_exts = len(exts) yield '.. list-table:: Properties' yield _indent(':widths: 15 100 100 15 15 100 50') yield _indent(':header-rows: 1') yield '' yield _indent('* - Name') yield _indent(' - Channels') yield _indent(' - Description') yield _indent(' - Ivar') yield _indent(' - Mask') yield _indent(' - DB') yield _indent(' - FITS') for prop in exts: yield _indent('* - {0}'.format(prop.name)) if 'MultiChannelProperty' in str(prop.__class__): channels = ', '.join([c.name for c in prop.channels]) dbcolumn = ', '.join(['{0}.{1}'.format(prop.db_table, c) for c in prop.db_columns()]) else: channels = prop.channel dbcolumn = '{0}.{1}'.format(prop.db_table, prop.db_column()) yield _indent(' - {0}'.format(channels)) yield _indent(' - {0}'.format(prop.description)) yield _indent(' - {0}'.format(prop.ivar)) yield _indent(' - {0}'.format(prop.mask)) yield _indent(' - {0}'.format(dbcolumn)) yield _indent(' - {0}'.format(prop.fits_extension())) yield '' def _format_parameters(parameters): ''' Format Query Parameters ''' yield '.. topic:: Query Parameters' yield '.. list-table:: Query Parameters' yield _indent(':widths: 25 50 10 20 20 20 20') yield _indent(':header-rows: 1') yield '' yield _indent('* - Group') yield _indent(' - Full Name') yield _indent(' - Best') yield _indent(' - Name') yield _indent(' - DB Schema') yield _indent(' - DB Table') yield _indent(' - DB Column') for param in parameters: yield _indent('* - {0}'.format(param.group)) yield _indent(' - {0}'.format(param.full)) yield _indent(' - {0}'.format(param.best)) yield _indent(' - {0}'.format(param.name)) yield _indent(' - {0}'.format(param.db_schema)) yield _indent(' - {0}'.format(param.db_table)) yield _indent(' - {0}'.format(param.db_column)) yield '' def _format_schema(schema): ''' Format a maskbit schema ''' schema_dict = schema.to_dict() indices = schema_dict['bit'].keys() yield '.. list-table:: Schema' yield _indent(':widths: 5 50 50') yield _indent(':header-rows: 1') yield '' yield _indent('* - Bit') yield _indent(' - Label') yield _indent(' - Description') for index in indices: yield _indent('* - {0}'.format(schema_dict['bit'][index])) yield _indent(' - {0}'.format(schema_dict['label'][index].strip())) yield _indent(' - {0}'.format(schema_dict['description'][index].strip())) yield '' def _format_bitmasks(maskbit, bittype): ''' Format Maskbits ''' for name, mask in maskbit.items(): if bittype.lower() in name.lower(): #yield '.. program:: {0}'.format(name) yield '{0}: {1}'.format(name, mask.description) yield '' for line in _format_schema(mask.schema): yield line def _format_command(name, command, **kwargs): """Format the output of `click.Command`.""" # docstring # yield command.__doc__ # yield '' # bintypes if 'bintypes' in kwargs: for line in _format_bintypes(command.bintypes): yield line # templates if 'templates' in kwargs: for line in _format_templates(command.templates): yield line # models if 'models' in kwargs: for line in _format_models(command.models): yield line # properties if 'properties' in kwargs: for line in _format_properties(command.properties): yield line # spectra if 'spectra' in kwargs: for line in _format_spectra(command.spectra): yield line # datacubes if 'datacubes' in kwargs: for line in _format_datacubes(command.datacubes): yield line # query parameters if 'parameters' in kwargs: for line in _format_parameters(command.parameters): yield line # bitmasks if 'bitmasks' in kwargs: for line in _format_bitmasks(command.bitmasks, kwargs.get('bittype', None)): yield line class DataModelDirective(rst.Directive): has_content = False required_arguments = 1 option_spec = { 'prog': directives.unchanged_required, 'title': directives.unchanged, 'bintypes': directives.flag, 'templates': directives.flag, 'models': directives.flag, 'properties': directives.flag, 'datacubes': directives.flag, 'spectra': directives.flag, 'bitmasks': directives.flag, 'parameters': directives.flag, 'bittype': directives.unchanged, } def _load_module(self, module_path): """Load the module.""" # __import__ will fail on unicode, # so we ensure module path is a string here. module_path = str(module_path) try: module_name, attr_name = module_path.split(':', 1) except ValueError: # noqa raise self.error('"{0}" is not of format "module:parser"'.format(module_path)) try: mod = __import__(module_name, globals(), locals(), [attr_name]) except (Exception, SystemExit) as exc: # noqa err_msg = 'Failed to import "{0}" from "{1}". '.format(attr_name, module_name) if isinstance(exc, SystemExit): err_msg += 'The module appeared to call sys.exit()' else: err_msg += 'The following exception was raised:\n{0}'.format(traceback.format_exc()) raise self.error(err_msg) if not hasattr(mod, attr_name): raise self.error('Module "{0}" has no attribute "{1}"'.format(module_name, attr_name)) return getattr(mod, attr_name) def _generate_nodes(self, name, command, parent=None, options={}): """Generate the relevant Sphinx nodes. Format a `click.Group` or `click.Command`. :param name: Name of command, as used on the command line :param command: Instance of `click.Group` or `click.Command` :param parent: Instance of `click.Context`, or None :param show_nested: Whether subcommands should be included in output :returns: A list of nested docutil nodes """ # Title source_name = name section = nodes.section( '', nodes.title(text=name), ids=[nodes.make_id(source_name)], names=[nodes.fully_normalize_name(source_name)]) # Summary result = statemachine.ViewList() lines = _format_command(name, command, **options) for line in lines: result.append(line, source_name) self.state.nested_parse(result, 0, section) return [section] def run(self): self.env = self.state.document.settings.env command = self._load_module(self.arguments[0]) if 'prog' in self.options: prog_name = self.options.get('prog') else: raise self.error(':prog: must be specified') return self._generate_nodes(prog_name, command, None, options=self.options) def setup(app): app.add_directive('datamodel', DataModelDirective)
{ "content_hash": "b32fb110ea37a16312be564e60caf7b5", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 100, "avg_line_length": 30.359375, "alnum_prop": 0.5751415337107566, "repo_name": "albireox/marvin", "id": "55dce13904c683d391f04f64964dcfdc9e55acac", "size": "11888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/marvin/utils/datamodel/docudatamodel.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "210343" }, { "name": "HTML", "bytes": "68596" }, { "name": "JavaScript", "bytes": "217699" }, { "name": "PLpgSQL", "bytes": "1577" }, { "name": "Python", "bytes": "1390874" }, { "name": "SQLPL", "bytes": "141212" }, { "name": "Shell", "bytes": "1150" } ], "symlink_target": "" }
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>Base Action Element</title> <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/> <meta name="title" content="Base Action Element"/> <meta name="generator" content="Org-mode"/> <meta name="generated" content="2012-10-18 03:26:31 CDT"/> <meta name="author" content="Rusty Klophaus (@rustyio)"/> <meta name="description" content=""/> <meta name="keywords" content=""/> <style type="text/css"> <!--/*--><![CDATA[/*><!--*/ html { font-family: Times, serif; font-size: 12pt; } .title { text-align: center; } .todo { color: red; } .done { color: green; } .tag { background-color: #add8e6; font-weight:normal } .target { } .timestamp { color: #bebebe; } .timestamp-kwd { color: #5f9ea0; } .right {margin-left:auto; margin-right:0px; text-align:right;} .left {margin-left:0px; margin-right:auto; text-align:left;} .center {margin-left:auto; margin-right:auto; text-align:center;} p.verse { margin-left: 3% } pre { border: 1pt solid #AEBDCC; background-color: #F3F5F7; padding: 5pt; font-family: courier, monospace; font-size: 90%; overflow:auto; } table { border-collapse: collapse; } td, th { vertical-align: top; } th.right { text-align:center; } th.left { text-align:center; } th.center { text-align:center; } td.right { text-align:right; } td.left { text-align:left; } td.center { text-align:center; } dt { font-weight: bold; } div.figure { padding: 0.5em; } div.figure p { text-align: center; } div.inlinetask { padding:10px; border:2px solid gray; margin:10px; background: #ffffcc; } textarea { overflow-x: auto; } .linenr { font-size:smaller } .code-highlighted {background-color:#ffff00;} .org-info-js_info-navigation { border-style:none; } #org-info-js_console-label { font-size:10px; font-weight:bold; white-space:nowrap; } .org-info-js_search-highlight {background-color:#ffff00; color:#000000; font-weight:bold; } /*]]>*/--> </style> <LINK href='../stylesheet.css' rel='stylesheet' type='text/css' /> <script type="text/javascript"> <!--/*--><![CDATA[/*><!--*/ function CodeHighlightOn(elem, id) { var target = document.getElementById(id); if(null != target) { elem.cacheClassElem = elem.className; elem.cacheClassTarget = target.className; target.className = "code-highlighted"; elem.className = "code-highlighted"; } } function CodeHighlightOff(elem, id) { var target = document.getElementById(id); if(elem.cacheClassElem) elem.className = elem.cacheClassElem; if(elem.cacheClassTarget) target.className = elem.cacheClassTarget; } /*]]>*///--> </script> </head> <body> <div id="preamble"> </div> <div id="content"> <h1 class="title">Base Action Element</h1> <p><a href="../index.html">Getting Started</a> | <a href="../api.html">API</a> | <a href="../elements.html">Elements</a> | <a href="../actions.html"><b>Actions</b></a> | <a href="../validators.html">Validators</a> | <a href="../handlers.html">Handlers</a> | <a href="../config.html">Configuration Options</a> | <a href="../about.html">About</a> </p> <div id="table-of-contents"> <h2>Table of Contents</h2> <div id="text-table-of-contents"> <ul> <li><a href="#sec-1">1 Base Action</a></li> </ul> </div> </div> <div id="outline-container-1" class="outline-2"> <h2 id="sec-1"><span class="section-number-2">1</span> Base Action</h2> <div class="outline-text-2" id="text-1"> <p> In object-oriented parlance, all Nitrogen actions are subclasses of the base actions. This means that all Nitrogen elements can use the attributes listed below. </p> </div> <div id="outline-container-1-1" class="outline-3"> <h3 id="sec-1-1"><span class="section-number-3"></span> Attributes</h3> <div class="outline-text-3" id="text-1-1"> <dl> <dt>module - (<i>atom</i>)</dt><dd>The module containing the logic for this action. Set automatically. </dd> <dt>trigger - (<i>atom</i>)</dt><dd>The id of the Nitrogen element that will trigger this action. Set automatically. </dd> <dt>target - (<i>atom</i>)</dt><dd>The id of the Nitrogen element to be referenced by obj('me'). Set automatically. </dd> <dt>actions - (<i>list af actions</i>)</dt><dd>A list of actions grouped within this action. </dd> <dt>show_if - (<i>boolean</i>)</dt><dd>If set to true, this action will be rendered. Otherwise, it will not. </dd> </dl> </div> </div> </div> </div> <div id="postamble"> <p class="date">Date: 2012-10-18 03:26:31 CDT</p> <p class="author">Author: Rusty Klophaus (@rustyio)</p> <p class="creator">Org version 7.8.02 with Emacs version 23</p> <a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a> </div><h2>Comments</h2> <b>Note:</b><!-- Disqus does not currently support Erlang for its syntax highlighting, so t-->To specify <!--Erlang--> code blocks, just use the generic code block syntax: <pre><b>&lt;pre&gt;&lt;code&gt;your code here&lt;/code&gt;&lt;/pre&gt;</b></pre> <br /> <br /> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'nitrogenproject'; // required: replace example with your forum shortname var disqus_identifier = 'html/actions/base.html'; //This will be replaced with the path part of the url /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> </body> </html>
{ "content_hash": "aa61f14614137b560d162a72a3416400", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 344, "avg_line_length": 35.43181818181818, "alnum_prop": 0.6536241180243746, "repo_name": "jpyle/nitrogen_core", "id": "28734504f0edbb730fa8b1c26f17053a3ecff8ab", "size": "6236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/actions/base.html", "mode": "33188", "license": "mit", "language": [ { "name": "Emacs Lisp", "bytes": "611" }, { "name": "Erlang", "bytes": "332710" }, { "name": "JavaScript", "bytes": "107901" }, { "name": "Perl", "bytes": "2916" }, { "name": "Shell", "bytes": "1252" } ], "symlink_target": "" }
package com.jayway.annostatemachine; public interface StateMachineFront<SignalType> { void send(SignalType signal, SignalPayload payload); void send(SignalType signal); }
{ "content_hash": "c4e02520f5523f721df06c3dfebe53d4", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 56, "avg_line_length": 20.333333333333332, "alnum_prop": 0.7759562841530054, "repo_name": "jayway/anno-state-machine", "id": "59a54b047e9926f1998172002860b618b8167115", "size": "796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "anno-state-machine/src/main/java/com/jayway/annostatemachine/StateMachineFront.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "223656" }, { "name": "Shell", "bytes": "147" } ], "symlink_target": "" }
namespace media { // TODO(rileya): Devise a better way of specifying trace/UMA/etc strings for // templated classes such as this. template <DemuxerStream::Type StreamType> static const char* GetTraceString(); #define FUNCTION_DVLOG(level) \ DVLOG(level) << __FUNCTION__ << "<" << GetStreamTypeString() << ">" template <> const char* GetTraceString<DemuxerStream::VIDEO>() { return "DecoderStream<VIDEO>::Decode"; } template <> const char* GetTraceString<DemuxerStream::AUDIO>() { return "DecoderStream<AUDIO>::Decode"; } template <DemuxerStream::Type StreamType> DecoderStream<StreamType>::DecoderStream( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, ScopedVector<Decoder> decoders, const scoped_refptr<MediaLog>& media_log) : task_runner_(task_runner), media_log_(media_log), state_(STATE_UNINITIALIZED), stream_(NULL), decoder_selector_(new DecoderSelector<StreamType>(task_runner, std::move(decoders), media_log)), decoded_frames_since_fallback_(0), active_splice_(false), decoding_eos_(false), pending_decode_requests_(0), duration_tracker_(8), weak_factory_(this) {} template <DemuxerStream::Type StreamType> DecoderStream<StreamType>::~DecoderStream() { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); decoder_selector_.reset(); if (!init_cb_.is_null()) { task_runner_->PostTask(FROM_HERE, base::Bind(base::ResetAndReturn(&init_cb_), false)); } if (!read_cb_.is_null()) { task_runner_->PostTask(FROM_HERE, base::Bind( base::ResetAndReturn(&read_cb_), ABORTED, scoped_refptr<Output>())); } if (!reset_cb_.is_null()) task_runner_->PostTask(FROM_HERE, base::ResetAndReturn(&reset_cb_)); stream_ = NULL; decoder_.reset(); decrypting_demuxer_stream_.reset(); } template <DemuxerStream::Type StreamType> std::string DecoderStream<StreamType>::GetStreamTypeString() { return DecoderStreamTraits<StreamType>::ToString(); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::Initialize( DemuxerStream* stream, const InitCB& init_cb, CdmContext* cdm_context, const StatisticsCB& statistics_cb, const base::Closure& waiting_for_decryption_key_cb) { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, STATE_UNINITIALIZED); DCHECK(init_cb_.is_null()); DCHECK(!init_cb.is_null()); statistics_cb_ = statistics_cb; init_cb_ = init_cb; waiting_for_decryption_key_cb_ = waiting_for_decryption_key_cb; stream_ = stream; state_ = STATE_INITIALIZING; SelectDecoder(cdm_context); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::Read(const ReadCB& read_cb) { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK(state_ != STATE_UNINITIALIZED && state_ != STATE_INITIALIZING) << state_; // No two reads in the flight at any time. DCHECK(read_cb_.is_null()); // No read during resetting or stopping process. DCHECK(reset_cb_.is_null()); if (state_ == STATE_ERROR) { task_runner_->PostTask( FROM_HERE, base::Bind(read_cb, DECODE_ERROR, scoped_refptr<Output>())); return; } if (state_ == STATE_END_OF_STREAM && ready_outputs_.empty()) { task_runner_->PostTask( FROM_HERE, base::Bind(read_cb, OK, StreamTraits::CreateEOSOutput())); return; } if (!ready_outputs_.empty()) { task_runner_->PostTask(FROM_HERE, base::Bind(read_cb, OK, ready_outputs_.front())); ready_outputs_.pop_front(); } else { read_cb_ = read_cb; } if (state_ == STATE_NORMAL && CanDecodeMore()) ReadFromDemuxerStream(); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::Reset(const base::Closure& closure) { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_NE(state_, STATE_UNINITIALIZED); DCHECK(reset_cb_.is_null()); reset_cb_ = closure; if (!read_cb_.is_null()) { task_runner_->PostTask(FROM_HERE, base::Bind( base::ResetAndReturn(&read_cb_), ABORTED, scoped_refptr<Output>())); } ready_outputs_.clear(); // During decoder reinitialization, the Decoder does not need to be and // cannot be Reset(). |decrypting_demuxer_stream_| was reset before decoder // reinitialization. if (state_ == STATE_REINITIALIZING_DECODER) return; // During pending demuxer read and when not using DecryptingDemuxerStream, // the Decoder will be reset after demuxer read is returned // (in OnBufferReady()). if (state_ == STATE_PENDING_DEMUXER_READ && !decrypting_demuxer_stream_) return; if (decrypting_demuxer_stream_) { decrypting_demuxer_stream_->Reset(base::Bind( &DecoderStream<StreamType>::ResetDecoder, weak_factory_.GetWeakPtr())); return; } ResetDecoder(); } template <DemuxerStream::Type StreamType> bool DecoderStream<StreamType>::CanReadWithoutStalling() const { DCHECK(task_runner_->BelongsToCurrentThread()); return !ready_outputs_.empty() || decoder_->CanReadWithoutStalling(); } template <> bool DecoderStream<DemuxerStream::AUDIO>::CanReadWithoutStalling() const { DCHECK(task_runner_->BelongsToCurrentThread()); return true; } template <DemuxerStream::Type StreamType> int DecoderStream<StreamType>::GetMaxDecodeRequests() const { return decoder_->GetMaxDecodeRequests(); } template <> int DecoderStream<DemuxerStream::AUDIO>::GetMaxDecodeRequests() const { return 1; } template <DemuxerStream::Type StreamType> bool DecoderStream<StreamType>::CanDecodeMore() const { DCHECK(task_runner_->BelongsToCurrentThread()); // Limit total number of outputs stored in |ready_outputs_| and being decoded. // It only makes sense to saturate decoder completely when output queue is // empty. int num_decodes = static_cast<int>(ready_outputs_.size()) + pending_decode_requests_; return !decoding_eos_ && num_decodes < GetMaxDecodeRequests(); } template <DemuxerStream::Type StreamType> base::TimeDelta DecoderStream<StreamType>::AverageDuration() const { DCHECK(task_runner_->BelongsToCurrentThread()); return duration_tracker_.count() ? duration_tracker_.Average() : base::TimeDelta(); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::SelectDecoder(CdmContext* cdm_context) { decoder_selector_->SelectDecoder( stream_, cdm_context, base::Bind(&DecoderStream<StreamType>::OnDecoderSelected, weak_factory_.GetWeakPtr()), base::Bind(&DecoderStream<StreamType>::OnDecodeOutputReady, weak_factory_.GetWeakPtr()), waiting_for_decryption_key_cb_); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::OnDecoderSelected( scoped_ptr<Decoder> selected_decoder, scoped_ptr<DecryptingDemuxerStream> decrypting_demuxer_stream) { FUNCTION_DVLOG(2) << ": " << (selected_decoder ? selected_decoder->GetDisplayName() : "No decoder selected."); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK(state_ == STATE_INITIALIZING || state_ == STATE_REINITIALIZING_DECODER) << state_; if (state_ == STATE_INITIALIZING) { DCHECK(!init_cb_.is_null()); DCHECK(read_cb_.is_null()); DCHECK(reset_cb_.is_null()); } else { DCHECK(decoder_); } previous_decoder_ = std::move(decoder_); decoded_frames_since_fallback_ = 0; decoder_ = std::move(selected_decoder); if (decrypting_demuxer_stream) { decrypting_demuxer_stream_ = std::move(decrypting_demuxer_stream); stream_ = decrypting_demuxer_stream_.get(); } if (!decoder_) { if (state_ == STATE_INITIALIZING) { state_ = STATE_UNINITIALIZED; MEDIA_LOG(ERROR, media_log_) << GetStreamTypeString() << " decoder initialization failed"; base::ResetAndReturn(&init_cb_).Run(false); } else { CompleteDecoderReinitialization(false); } return; } media_log_->SetBooleanProperty(GetStreamTypeString() + "_dds", !!decrypting_demuxer_stream_); media_log_->SetStringProperty(GetStreamTypeString() + "_decoder", decoder_->GetDisplayName()); if (state_ == STATE_REINITIALIZING_DECODER) { CompleteDecoderReinitialization(true); return; } // Initialization succeeded. state_ = STATE_NORMAL; if (StreamTraits::NeedsBitstreamConversion(decoder_.get())) stream_->EnableBitstreamConverter(); base::ResetAndReturn(&init_cb_).Run(true); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::SatisfyRead( Status status, const scoped_refptr<Output>& output) { DCHECK(!read_cb_.is_null()); base::ResetAndReturn(&read_cb_).Run(status, output); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::Decode( const scoped_refptr<DecoderBuffer>& buffer) { FUNCTION_DVLOG(2); DCHECK(state_ == STATE_NORMAL || state_ == STATE_FLUSHING_DECODER) << state_; DCHECK_LT(pending_decode_requests_, GetMaxDecodeRequests()); DCHECK(reset_cb_.is_null()); DCHECK(buffer.get()); int buffer_size = buffer->end_of_stream() ? 0 : buffer->data_size(); TRACE_EVENT_ASYNC_BEGIN2( "media", GetTraceString<StreamType>(), this, "key frame", !buffer->end_of_stream() && buffer->is_key_frame(), "timestamp (ms)", !buffer->end_of_stream() ? buffer->timestamp().InMilliseconds() : 0); if (buffer->end_of_stream()) decoding_eos_ = true; else if (buffer->duration() != kNoTimestamp()) duration_tracker_.AddSample(buffer->duration()); ++pending_decode_requests_; decoder_->Decode(buffer, base::Bind(&DecoderStream<StreamType>::OnDecodeDone, weak_factory_.GetWeakPtr(), buffer_size, buffer->end_of_stream())); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::FlushDecoder() { Decode(DecoderBuffer::CreateEOSBuffer()); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::OnDecodeDone(int buffer_size, bool end_of_stream, typename Decoder::Status status) { FUNCTION_DVLOG(2) << ": " << status; DCHECK(state_ == STATE_NORMAL || state_ == STATE_FLUSHING_DECODER || state_ == STATE_PENDING_DEMUXER_READ || state_ == STATE_ERROR) << state_; DCHECK_GT(pending_decode_requests_, 0); --pending_decode_requests_; TRACE_EVENT_ASYNC_END0("media", GetTraceString<StreamType>(), this); if (end_of_stream) { DCHECK(!pending_decode_requests_); decoding_eos_ = false; } if (state_ == STATE_ERROR) { DCHECK(read_cb_.is_null()); return; } // Drop decoding result if Reset() was called during decoding. // The resetting process will be handled when the decoder is reset. if (!reset_cb_.is_null()) return; switch (status) { case Decoder::kDecodeError: state_ = STATE_ERROR; MEDIA_LOG(ERROR, media_log_) << GetStreamTypeString() << " decode error"; ready_outputs_.clear(); if (!read_cb_.is_null()) SatisfyRead(DECODE_ERROR, NULL); return; case Decoder::kAborted: // Decoder can return kAborted during Reset() or during destruction. return; case Decoder::kOk: // Any successful decode counts! if (buffer_size > 0) StreamTraits::ReportStatistics(statistics_cb_, buffer_size); if (state_ == STATE_NORMAL) { if (end_of_stream) { state_ = STATE_END_OF_STREAM; if (ready_outputs_.empty() && !read_cb_.is_null()) SatisfyRead(OK, StreamTraits::CreateEOSOutput()); return; } if (CanDecodeMore()) ReadFromDemuxerStream(); return; } if (state_ == STATE_FLUSHING_DECODER && !pending_decode_requests_) ReinitializeDecoder(); return; } } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::OnDecodeOutputReady( const scoped_refptr<Output>& output) { FUNCTION_DVLOG(2) << ": " << output->timestamp().InMilliseconds() << " ms"; DCHECK(output.get()); DCHECK(state_ == STATE_NORMAL || state_ == STATE_FLUSHING_DECODER || state_ == STATE_PENDING_DEMUXER_READ || state_ == STATE_ERROR) << state_; if (state_ == STATE_ERROR) { DCHECK(read_cb_.is_null()); return; } // Drop decoding result if Reset() was called during decoding. // The resetting process will be handled when the decoder is reset. if (!reset_cb_.is_null()) return; if (!read_cb_.is_null()) { // If |ready_outputs_| was non-empty, the read would have already been // satisifed by Read(). DCHECK(ready_outputs_.empty()); SatisfyRead(OK, output); return; } // Store decoded output. ready_outputs_.push_back(output); // Destruct any previous decoder once we've decoded enough frames to ensure // that it's no longer in use. if (previous_decoder_ && ++decoded_frames_since_fallback_ > limits::kMaxVideoFrames) { previous_decoder_.reset(); } } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::ReadFromDemuxerStream() { FUNCTION_DVLOG(2); DCHECK_EQ(state_, STATE_NORMAL); DCHECK(CanDecodeMore()); DCHECK(reset_cb_.is_null()); state_ = STATE_PENDING_DEMUXER_READ; stream_->Read(base::Bind(&DecoderStream<StreamType>::OnBufferReady, weak_factory_.GetWeakPtr())); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::OnBufferReady( DemuxerStream::Status status, const scoped_refptr<DecoderBuffer>& buffer) { FUNCTION_DVLOG(2) << ": " << status << ", " << (buffer.get() ? buffer->AsHumanReadableString() : "NULL"); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK(state_ == STATE_PENDING_DEMUXER_READ || state_ == STATE_ERROR) << state_; DCHECK_EQ(buffer.get() != NULL, status == DemuxerStream::kOk) << status; // Decoding has been stopped (e.g due to an error). if (state_ != STATE_PENDING_DEMUXER_READ) { DCHECK(state_ == STATE_ERROR); DCHECK(read_cb_.is_null()); return; } state_ = STATE_NORMAL; if (status == DemuxerStream::kConfigChanged) { FUNCTION_DVLOG(2) << ": " << "ConfigChanged"; DCHECK(stream_->SupportsConfigChanges()); if (!config_change_observer_cb_.is_null()) config_change_observer_cb_.Run(); state_ = STATE_FLUSHING_DECODER; if (!reset_cb_.is_null()) { // If we are using DecryptingDemuxerStream, we already called DDS::Reset() // which will continue the resetting process in it's callback. if (!decrypting_demuxer_stream_) Reset(base::ResetAndReturn(&reset_cb_)); // Reinitialization will continue after Reset() is done. } else { FlushDecoder(); } return; } if (!reset_cb_.is_null()) { // If we are using DecryptingDemuxerStream, we already called DDS::Reset() // which will continue the resetting process in it's callback. if (!decrypting_demuxer_stream_) Reset(base::ResetAndReturn(&reset_cb_)); return; } if (status == DemuxerStream::kAborted) { if (!read_cb_.is_null()) SatisfyRead(DEMUXER_READ_ABORTED, NULL); return; } if (!splice_observer_cb_.is_null() && !buffer->end_of_stream()) { const bool has_splice_ts = buffer->splice_timestamp() != kNoTimestamp(); if (active_splice_ || has_splice_ts) { splice_observer_cb_.Run(buffer->splice_timestamp()); active_splice_ = has_splice_ts; } } DCHECK(status == DemuxerStream::kOk) << status; Decode(buffer); // Read more data if the decoder supports multiple parallel decoding requests. if (CanDecodeMore()) ReadFromDemuxerStream(); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::ReinitializeDecoder() { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, STATE_FLUSHING_DECODER); DCHECK_EQ(pending_decode_requests_, 0); state_ = STATE_REINITIALIZING_DECODER; // Decoders should not need a new CDM during reinitialization. DecoderStreamTraits<StreamType>::InitializeDecoder( decoder_.get(), stream_, nullptr, base::Bind(&DecoderStream<StreamType>::OnDecoderReinitialized, weak_factory_.GetWeakPtr()), base::Bind(&DecoderStream<StreamType>::OnDecodeOutputReady, weak_factory_.GetWeakPtr())); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::OnDecoderReinitialized(bool success) { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, STATE_REINITIALIZING_DECODER); // ReinitializeDecoder() can be called in two cases: // 1, Flushing decoder finished (see OnDecodeOutputReady()). // 2, Reset() was called during flushing decoder (see OnDecoderReset()). // Also, Reset() can be called during pending ReinitializeDecoder(). // This function needs to handle them all! if (!success) { // Reinitialization failed. Try to fall back to one of the remaining // decoders. This will consume at least one decoder so doing it more than // once is safe. // For simplicity, don't attempt to fall back to a decrypting decoder. // Calling this with a null CdmContext ensures that one won't be selected. SelectDecoder(nullptr); } else { CompleteDecoderReinitialization(true); } } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::CompleteDecoderReinitialization(bool success) { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, STATE_REINITIALIZING_DECODER); state_ = success ? STATE_NORMAL : STATE_ERROR; if (!reset_cb_.is_null()) { base::ResetAndReturn(&reset_cb_).Run(); return; } if (read_cb_.is_null()) return; if (state_ == STATE_ERROR) { MEDIA_LOG(ERROR, media_log_) << GetStreamTypeString() << " decoder reinitialization failed"; SatisfyRead(DECODE_ERROR, NULL); return; } ReadFromDemuxerStream(); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::ResetDecoder() { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK(state_ == STATE_NORMAL || state_ == STATE_FLUSHING_DECODER || state_ == STATE_ERROR || state_ == STATE_END_OF_STREAM) << state_; DCHECK(!reset_cb_.is_null()); decoder_->Reset(base::Bind(&DecoderStream<StreamType>::OnDecoderReset, weak_factory_.GetWeakPtr())); } template <DemuxerStream::Type StreamType> void DecoderStream<StreamType>::OnDecoderReset() { FUNCTION_DVLOG(2); DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK(state_ == STATE_NORMAL || state_ == STATE_FLUSHING_DECODER || state_ == STATE_ERROR || state_ == STATE_END_OF_STREAM) << state_; // If Reset() was called during pending read, read callback should be fired // before the reset callback is fired. DCHECK(read_cb_.is_null()); DCHECK(!reset_cb_.is_null()); if (state_ != STATE_FLUSHING_DECODER) { state_ = STATE_NORMAL; active_splice_ = false; base::ResetAndReturn(&reset_cb_).Run(); return; } // The resetting process will be continued in OnDecoderReinitialized(). ReinitializeDecoder(); } template class DecoderStream<DemuxerStream::VIDEO>; template class DecoderStream<DemuxerStream::AUDIO>; } // namespace media
{ "content_hash": "fae8aea0431aec5b0c506ea540ce91ce", "timestamp": "", "source": "github", "line_count": 603, "max_line_length": 80, "avg_line_length": 32.885572139303484, "alnum_prop": 0.6576903681290973, "repo_name": "highweb-project/highweb-webcl-html5spec", "id": "4b03587253fa06cccd378d527ddf8f1de8e7ff5a", "size": "20613", "binary": false, "copies": "3", "ref": "refs/heads/highweb-20160310", "path": "media/filters/decoder_stream.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.reginald.pluginm.parser; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.ProviderInfo; import android.content.pm.ServiceInfo; import android.os.Build; import android.os.SystemClock; import android.util.Log; import android.util.LogPrinter; import com.reginald.pluginm.BuildConfig; import com.reginald.pluginm.PluginInfo; import com.reginald.pluginm.utils.Logger; import java.io.File; import java.util.List; /** * Created by lxy on 16-6-21. */ public class ApkParser { private static final String TAG = "ApkParser"; private static final boolean DEBUG = BuildConfig.DEBUG_LOG & false; public static PluginInfo parsePluginInfo(Context context, String apkFile) { long startTime = SystemClock.elapsedRealtime(); try { PluginPackageParser pluginPackageParser = getPackageParser(context, apkFile); Logger.d(TAG, String.format("parsePluginInfo() apk = %s, create parser cost %d ms", apkFile, SystemClock.elapsedRealtime() - startTime)); if (pluginPackageParser != null) { PluginInfo pluginInfo = new PluginInfo(); pluginInfo.pkgParser = pluginPackageParser; pluginInfo.packageName = pluginPackageParser.getPackageName(); pluginInfo.applicationInfo = pluginPackageParser.getApplicationInfo(0); PackageInfo packageInfo = pluginPackageParser.getPackageInfo(0); if (packageInfo != null) { pluginInfo.versionName = packageInfo.versionName; pluginInfo.versionCode = packageInfo.versionCode; } //test: if (DEBUG) { showPluginInfo(pluginInfo.pkgParser); } return pluginInfo; } } catch (Exception e) { Logger.e(TAG, "parsePluginInfo() error!", e); return null; } finally { Logger.d(TAG, String.format("parsePluginInfo() apk = %s, all cost %d ms", apkFile, SystemClock.elapsedRealtime() - startTime)); } return null; } public static PluginPackageParser getPackageParser(Context context, String apkFile) { return parsePackage(context, apkFile); } private static void showPluginInfo(PluginPackageParser pluginPackageParser) { // test try { Logger.d(TAG, "\n## packageInfo.packageInfo.applicationInfo: "); pluginPackageParser.getApplicationInfo(0).dump(new LogPrinter(Log.DEBUG, TAG), ""); Logger.d(TAG, "\n\n"); List<ActivityInfo> activityInfoList = pluginPackageParser.getActivities(); if (activityInfoList != null) { Logger.d(TAG, "\n## packageInfo.activities: "); int i = 0; for (ActivityInfo activityInfo : activityInfoList) { Logger.d(TAG, "packageInfo.activitie No." + ++i); activityInfo.dump(new LogPrinter(Log.DEBUG, TAG), ""); Logger.d(TAG, "\n"); } } List<ServiceInfo> serviceInfos = pluginPackageParser.getServices(); if (serviceInfos != null) { Logger.d(TAG, "\n## packageInfo.services: "); int i = 0; for (ServiceInfo serviceInfo : serviceInfos) { Logger.d(TAG, "packageInfo.service No." + ++i); serviceInfo.dump(new LogPrinter(Log.DEBUG, TAG), ""); Logger.d(TAG, "\n"); } } List<ActivityInfo> receivers = pluginPackageParser.getReceivers(); if (receivers != null) { Logger.d(TAG, "\n## packageInfo.receivers: "); int i = 0; for (ActivityInfo receiverInfo : receivers) { Logger.d(TAG, "packageInfo.receiver No." + ++i); receiverInfo.dump(new LogPrinter(Log.DEBUG, TAG), ""); Logger.d(TAG, "\n"); } } List<ProviderInfo> providerInfos = pluginPackageParser.getProviders(); if (providerInfos != null) { Logger.d(TAG, "\n## packageInfo.providers: "); int i = 0; for (ProviderInfo providerInfo : providerInfos) { Logger.d(TAG, "packageInfo.provider No." + ++i); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { providerInfo.dump(new LogPrinter(Log.DEBUG, TAG), ""); } else { Logger.d(TAG, " " + providerInfo); } Logger.d(TAG, "\n"); } } } catch (Exception e) { Logger.e(TAG, "showPluginInfo error!", e); } } private static PluginPackageParser parsePackage(Context context, String apkFile) { try { return new PluginPackageParser(context, new File(apkFile)); } catch (Exception e) { Logger.e(TAG, "parsePackage error!", e); } return null; } }
{ "content_hash": "90ff8c2593447fe11f2df386294166ec", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 95, "avg_line_length": 37.73571428571429, "alnum_prop": 0.5614234336551202, "repo_name": "xyxyLiu/PluginM", "id": "3a58e95e778379c0f04a1c9e81387bf9810f0729", "size": "5283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PluginManager/src/main/java/com/reginald/pluginm/parser/ApkParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "219" }, { "name": "Java", "bytes": "571098" }, { "name": "Makefile", "bytes": "1147" }, { "name": "Shell", "bytes": "2206" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in J. Linn. Soc. , Bot. 11(no. 56): 521 (1871) #### Original name Agaricus diminutus Berk. & Broome ### Remarks null
{ "content_hash": "cba56b94217aecd69af088d57f0e643f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 43, "avg_line_length": 13.615384615384615, "alnum_prop": 0.6610169491525424, "repo_name": "mdoering/backbone", "id": "00e02a1ac8821f0702aaed8675dfb5fd0f195158", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Agaricaceae/Agaricus/Agaricus diminutus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8a9fea6aaa72e6b5f3e5ae0dda7fd2c0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "25e40111517a094261293546ebd56b5caae56911", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Phytolaccaceae/Gisekia/Gisekia pentadecandra/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:drawSelectorOnTop="true" android:scrollbarStyle="outsideOverlay" android:divider="@android:color/transparent" android:dividerHeight="2dp" android:paddingTop="8dp" > </ListView>
{ "content_hash": "00c39c189d3f3692f9605e3baacdf8e6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 68, "avg_line_length": 34.15384615384615, "alnum_prop": 0.6981981981981982, "repo_name": "eyal-lezmy/Android-DataLib", "id": "8edb47d4e23bb8c28effed59394f2b48ece1ef89", "size": "444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Android-DataLib-Sample-Netflix/res/layout/fgmt_categories.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1346224" } ], "symlink_target": "" }
export function keys(object) { return Object.keys(object); } export function eachKeyValue(object, callback) { const objectKeys = keys(object); for (let i = 0; i < objectKeys.length; i += 1) { const key = objectKeys[i]; callback(key, object[key]); } } export function mapValues(object, callback) { const objectKeys = keys(object); const result = {}; for (let i = 0; i < objectKeys.length; i += 1) { const key = objectKeys[i]; result[key] = callback(object[key]); } return result; } export function findKey(object, predicate) { const objectKeys = keys(object); for (let i = 0; i < objectKeys.length; i += 1) { const key = objectKeys[i]; if (predicate(object[key])) { return key; } } return undefined; } export function unique(array) { if (array.length === 0) { return []; } const result = []; const cache = {}; for (let i = 0; i < array.length; i += 1) { const value = array[i]; if (!{}.hasOwnProperty.call(cache, value)) { cache[value] = true; result.push(value); } } return result; } export function intersection(a, b) { if (a.length === 0 || b.length === 0) { return []; } const x = a.length > b.length ? b : a; const y = a.length > b.length ? a : b; const hitsMap = {}; for (let i = 0; i < x.length; i += 1) { hitsMap[x[i]] = false; } for (let i = 0; i < y.length; i += 1) { const hit = y[i]; if (hitsMap[hit] === false) { hitsMap[hit] = true; } } const result = []; const hits = keys(hitsMap); for (let i = 0; i < hits.length; i += 1) { const hit = hits[i]; if (hitsMap[hit]) { result.push(hit); } } return result; } export function isObject(value) { return value != null && typeof value === "object"; } export function isFunction(value) { if (value == null) { return false; } const tag = {}.toString.call(value); if (tag.substring(tag.length - 9) === "Function]") { return true; } if (tag.substring(tag.length - 6) === "Proxy]") { return true; } return false; }
{ "content_hash": "8d4d9665ef28237d118d721788812e05", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 54, "avg_line_length": 17.8135593220339, "alnum_prop": 0.5651760228353948, "repo_name": "demiazz/fluxxor", "id": "f62db46dfa99dc8799206a65735bb1ace29a0cf6", "size": "2102", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/utils.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "44881" } ], "symlink_target": "" }
<?php /** * (c) 2011 - ∞ Vespolina Project http://www.vespolina-project.org * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Vespolina\CommerceBundle\Controller\Checkout; use Vespolina\CommerceBundle\Controller\AbstractController; use Vespolina\CommerceBundle\Process\ProcessInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\DependencyInjection\ContainerAware; /** * @author Richard D Shank <[email protected]> */ class CheckoutController extends AbstractController { public function checkoutAction() { $processManager = $this->container->get('vespolina.process_manager'); $processOwner = $this->container->get('session')->getId(); $checkoutProcess = $processManager->getActiveProcessByOwner('checkout_b2c', $processOwner); if (null == $checkoutProcess) { $checkoutProcess = $processManager->createProcess('checkout_b2c', $processOwner); $checkoutProcess->init(true); // initialize with first time set to true $context = $checkoutProcess->getContext(); $context['cart'] = $this->getCart(); } $processResult = $checkoutProcess->execute(); $processManager->updateProcess($checkoutProcess); if (null != $processResult) { return $processResult; } // If we get here then there was a serious error throw new \Exception('Checkout failed - internal error - could not find process step to execute for current state ' . $checkoutProcess->getState()); } public function executeAction($processId, $processStepName) { $processManager = $this->container->get('vespolina.process_manager'); $process = $processManager->findProcessById($processId); if (null === $process) { throw new \Exception('Process session expired'); } if ($process->isCompleted()) { return $this->handleProcessCompletion($process); } $processStep = $process->getProcessStepByName($processStepName); // Assert that the current process step (according to the process) is the same as the step name // passed on to the request if ($processStep->getName() != $processStepName) { throw new \Exception(sprintf( 'Checkout failed - process step names differ : "%s" != "%s"', $processStep->getName(), $processStepName ) ); } return $processStep->getProcess()->execute(); } public function gotoProcessStepAction($processId, $processStepName) { $processManager = $this->container->get('vespolina.process_manager'); $process = $processManager->findProcessById($processId); $processStep = $process->getProcessStepByName($processStepName); return $process->gotoProcessStep($processStep); } protected function getCart() { return $this->container->get('vespolina.order_provider')->getOpenOrder(); } protected function handleProcessCompletion(ProcessInterface $process) { return new RedirectResponse('/', 302); } protected function getEngine() { return $this->container->getParameter('vespolina_commerce.template_engine'); } }
{ "content_hash": "836ced29e17a41562ce21d0a6ea91ed0", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 156, "avg_line_length": 35.447916666666664, "alnum_prop": 0.6485454011166618, "repo_name": "vespolina/VespolinaCommerceBundle", "id": "9adb6a17bea2564c9578040eb7df4801cc756bf8", "size": "3405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Controller/Checkout/CheckoutController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13175" }, { "name": "JavaScript", "bytes": "623494" }, { "name": "PHP", "bytes": "142501" } ], "symlink_target": "" }
package openeye.responses; import openeye.logic.IContext; import openeye.protocol.responses.IResponse; public interface IExecutableResponse extends IResponse { public void execute(IContext context); }
{ "content_hash": "5141f0443dfb6ce10c4a9455bdf4c392", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 25.5, "alnum_prop": 0.8333333333333334, "repo_name": "OpenMods/OpenData", "id": "e8d8a07d52279254438b526512a884559adba7ae", "size": "204", "binary": false, "copies": "1", "ref": "refs/heads/1.12.1", "path": "src/main/java/openeye/responses/IExecutableResponse.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "160446" } ], "symlink_target": "" }
/* * Description: * What is this file about? * * Revision history: * Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here * xxxx-xx-xx, author, fix bug about xxx */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using rDSN.Tron.Utility; namespace rDSN.Tron.LanguageProvider { public abstract class IdlTranslator { public IdlTranslator() { } public IdlTranslator(ServiceSpecType t) { specType = t; } public ServiceSpecType GetSpecType() { return specType; } public static IdlTranslator GetInstance(ServiceSpecType t) { switch(t) { case ServiceSpecType.Thrift: return new ThriftTranslator(); case ServiceSpecType.Proto: throw new NotImplementedException(); default: return null; } } public virtual bool ToCommonInterface(string dir, string file) { return ToCommonInterface(dir, file, dir, null, false); } public virtual bool ToCommonInterface(string dir, string file, List<string> args) { return ToCommonInterface(dir, file, dir, args, false); } public virtual bool ToCommonInterface(string dir, string file, string outDir) { return ToCommonInterface(dir, file, outDir, null, false); } /// <summary> /// translate the target IDL file to Common Interface /// </summary> /// <param name="dir"></param> /// <param name="file"></param> /// <param name="outDir"></param> /// /// <param name="args"></param> /// <returns></returns> public abstract bool ToCommonInterface(string dir, string file, string outDir, List<string> args, bool needCompiled = false); protected bool Compile(string input) { return Compile(input, Path.GetDirectoryName(input)); } protected static bool Compile(string input, string outDir) { var dir = Path.GetDirectoryName(input); var file = Path.GetFileName(input); var output = Path.Combine(outDir, Path.GetFileNameWithoutExtension(file) + ".dll"); var cscPath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "csc.exe"); const string libFiles = "rDSN.Tron.Contract.dll "; var arguments = "/target:library /out:" + output + " " + input + " /r:" + libFiles; // if input is a folder, the default action is to compile all *.cs files in the folder recursively if (Directory.Exists(input)) { return false; } if (!Directory.Exists(dir)) { Console.WriteLine(dir + "does not exist!"); return false; } if (!File.Exists(input)) { Console.WriteLine(file + " does not exist!"); return false; } return SystemHelper.RunProcess(cscPath, arguments) == 0; } protected ServiceSpecType specType; protected const string extension = ".cs"; } }
{ "content_hash": "c19e4cb1891b85249fd955bbdd272c14", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 133, "avg_line_length": 29.81578947368421, "alnum_prop": 0.5528096498970285, "repo_name": "glglwty/rDSN", "id": "629d4035770486b279eefb86adc7c77f0a7ef30a", "size": "4609", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/dist/flow/LanguageProvider/IdlTranslator.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "25290" }, { "name": "C", "bytes": "110032" }, { "name": "C++", "bytes": "3149292" }, { "name": "CMake", "bytes": "55282" }, { "name": "Objective-C", "bytes": "3073" }, { "name": "PHP", "bytes": "88752" }, { "name": "Protocol Buffer", "bytes": "331" }, { "name": "Python", "bytes": "11100" }, { "name": "Shell", "bytes": "52656" }, { "name": "Thrift", "bytes": "13577" } ], "symlink_target": "" }
/** ## `_b8r_` — Built-in Event Handlers The `_b8r_` object is registered by default as a useful set of always available methods, especially for handling events. You can use them the obvious way: <button data-event="click:_b8r_.echo"> Click Me, I cause console spam </button> _b8r_.echo // logs events to the console _b8r_.stopEvent // use this to simply catch an event silently _b8r_._update_ // this is used by b8r to update models automatically */ import { getBindings } from './b8r.bindings.js' import { findAbove, findWithin } from './b8r.dom.js' let set export const _insertSet = f => { set = f } let fromTargets export const _insertFromTargets = t => { fromTargets = t } export default {} const hasFromTarget = t => fromTargets[t.target] export const _b8r_ = { echo: evt => console.log(evt) || true, stopEvent: () => {}, _update_: evt => { let elements = findAbove(evt.target, '[data-bind]', null, true) // update elements with selected fromTarget if (evt.target.tagName === 'SELECT') { const options = findWithin( evt.target, 'option[data-bind]:not([data-list])' ) elements = elements.concat(options) } elements .filter(elt => !elt.matches('[data-list]')) .forEach(elt => { if (elt.matches('[data-debug],[data-debug-bind]')) { console.debug('b8r-warn', 'Add a conditional breakpoint here to debug changes to the registry triggered by events' ) } const bindings = getBindings(elt) for (let i = 0; i < bindings.length; i++) { const { targets, path } = bindings[i] const boundTargets = targets.filter(hasFromTarget) const processFromTargets = t => { // jshint ignore:line // all bets are off on bound values! const value = fromTargets[t.target](elt, t.key) if (value !== undefined) { delete elt._b8rBoundValues set(path, value, elt) } } boundTargets.forEach(processFromTargets) } }) return true } }
{ "content_hash": "f2185c1c4aa260eaee8eb2ee8780c5dc", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 100, "avg_line_length": 30.070422535211268, "alnum_prop": 0.5967213114754099, "repo_name": "tonioloewald/Bind-O-Matic.js", "id": "6dd2e9f38388e718e61a3406883be3dc7c4a8b3a", "size": "2137", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/b8r._b8r_.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4506" }, { "name": "HTML", "bytes": "50940" }, { "name": "JavaScript", "bytes": "33173" } ], "symlink_target": "" }
#include <winpr/config.h> #include <winpr/crt.h> #include <winpr/path.h> #include <winpr/synch.h> #include <winpr/handle.h> #include <winpr/pipe.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifndef _WIN32 #include "../handle/handle.h" #include <fcntl.h> #include <errno.h> #include <sys/un.h> #include <sys/socket.h> #include <winpr/assert.h> #include <unistd.h> #ifdef HAVE_SYS_AIO_H #undef HAVE_SYS_AIO_H /* disable for now, incomplete */ #endif #ifdef HAVE_SYS_AIO_H #include <aio.h> #endif #include "pipe.h" #include "../log.h" #define TAG WINPR_TAG("pipe") /* * Since the WinPR implementation of named pipes makes use of UNIX domain * sockets, it is not possible to bind the same name more than once (i.e., * SO_REUSEADDR does not work with UNIX domain sockets). As a result, the * first call to CreateNamedPipe with name n creates a "shared" UNIX domain * socket descriptor that gets duplicated via dup() for the first and all * subsequent calls to CreateNamedPipe with name n. * * The following array keeps track of the references to the shared socked * descriptors. If an entry's reference count is zero the base socket * descriptor gets closed and the entry is removed from the list. */ static wArrayList* g_NamedPipeServerSockets = NULL; typedef struct { char* name; int serverfd; int references; } NamedPipeServerSocketEntry; static BOOL PipeIsHandled(HANDLE handle) { return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_ANONYMOUS_PIPE, FALSE); } static int PipeGetFd(HANDLE handle) { WINPR_PIPE* pipe = (WINPR_PIPE*)handle; if (!PipeIsHandled(handle)) return -1; return pipe->fd; } static BOOL PipeCloseHandle(HANDLE handle) { WINPR_PIPE* pipe = (WINPR_PIPE*)handle; if (!PipeIsHandled(handle)) return FALSE; if (pipe->fd != -1) { close(pipe->fd); pipe->fd = -1; } free(handle); return TRUE; } static BOOL PipeRead(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) { SSIZE_T io_status; WINPR_PIPE* pipe; BOOL status = TRUE; if (lpOverlapped) { WLog_ERR(TAG, "WinPR %s does not support the lpOverlapped parameter", __FUNCTION__); SetLastError(ERROR_NOT_SUPPORTED); return FALSE; } pipe = (WINPR_PIPE*)Object; do { io_status = read(pipe->fd, lpBuffer, nNumberOfBytesToRead); } while ((io_status < 0) && (errno == EINTR)); if (io_status < 0) { status = FALSE; switch (errno) { case EWOULDBLOCK: SetLastError(ERROR_NO_DATA); break; } } if (lpNumberOfBytesRead) *lpNumberOfBytesRead = (DWORD)io_status; return status; } static BOOL PipeWrite(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) { SSIZE_T io_status; WINPR_PIPE* pipe; if (lpOverlapped) { WLog_ERR(TAG, "WinPR %s does not support the lpOverlapped parameter", __FUNCTION__); SetLastError(ERROR_NOT_SUPPORTED); return FALSE; } pipe = (WINPR_PIPE*)Object; do { io_status = write(pipe->fd, lpBuffer, nNumberOfBytesToWrite); } while ((io_status < 0) && (errno == EINTR)); if ((io_status < 0) && (errno == EWOULDBLOCK)) io_status = 0; *lpNumberOfBytesWritten = (DWORD)io_status; return TRUE; } static HANDLE_OPS ops = { PipeIsHandled, PipeCloseHandle, PipeGetFd, NULL, /* CleanupHandle */ PipeRead, NULL, /* FileReadEx */ NULL, /* FileReadScatter */ PipeWrite, NULL, /* FileWriteEx */ NULL, /* FileWriteGather */ NULL, /* FileGetFileSize */ NULL, /* FlushFileBuffers */ NULL, /* FileSetEndOfFile */ NULL, /* FileSetFilePointer */ NULL, /* SetFilePointerEx */ NULL, /* FileLockFile */ NULL, /* FileLockFileEx */ NULL, /* FileUnlockFile */ NULL, /* FileUnlockFileEx */ NULL /* SetFileTime */ , NULL }; static BOOL NamedPipeIsHandled(HANDLE handle) { return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_NAMED_PIPE, TRUE); } static int NamedPipeGetFd(HANDLE handle) { WINPR_NAMED_PIPE* pipe = (WINPR_NAMED_PIPE*)handle; if (!NamedPipeIsHandled(handle)) return -1; if (pipe->ServerMode) return pipe->serverfd; return pipe->clientfd; } static BOOL NamedPipeCloseHandle(HANDLE handle) { WINPR_NAMED_PIPE* pNamedPipe = (WINPR_NAMED_PIPE*)handle; /* This check confuses the analyzer. Since not all handle * types are handled here, it guesses that the memory of a * NamedPipeHandle may leak. */ #ifndef __clang_analyzer__ if (!NamedPipeIsHandled(handle)) return FALSE; #endif if (pNamedPipe->pfnUnrefNamedPipe) pNamedPipe->pfnUnrefNamedPipe(pNamedPipe); free(pNamedPipe->name); free(pNamedPipe->lpFileName); free(pNamedPipe->lpFilePath); if (pNamedPipe->serverfd != -1) close(pNamedPipe->serverfd); if (pNamedPipe->clientfd != -1) close(pNamedPipe->clientfd); free(pNamedPipe); return TRUE; } BOOL NamedPipeRead(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) { SSIZE_T io_status; WINPR_NAMED_PIPE* pipe; BOOL status = TRUE; if (lpOverlapped) { WLog_ERR(TAG, "WinPR %s does not support the lpOverlapped parameter", __FUNCTION__); SetLastError(ERROR_NOT_SUPPORTED); return FALSE; } pipe = (WINPR_NAMED_PIPE*)Object; if (!(pipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)) { if (pipe->clientfd == -1) return FALSE; do { io_status = read(pipe->clientfd, lpBuffer, nNumberOfBytesToRead); } while ((io_status < 0) && (errno == EINTR)); if (io_status == 0) { SetLastError(ERROR_BROKEN_PIPE); status = FALSE; } else if (io_status < 0) { status = FALSE; switch (errno) { case EWOULDBLOCK: SetLastError(ERROR_NO_DATA); break; default: SetLastError(ERROR_BROKEN_PIPE); break; } } if (lpNumberOfBytesRead) *lpNumberOfBytesRead = (DWORD)io_status; } else { /* Overlapped I/O */ if (!lpOverlapped) return FALSE; if (pipe->clientfd == -1) return FALSE; pipe->lpOverlapped = lpOverlapped; #ifdef HAVE_SYS_AIO_H { int aio_status; struct aiocb cb = { 0 }; cb.aio_fildes = pipe->clientfd; cb.aio_buf = lpBuffer; cb.aio_nbytes = nNumberOfBytesToRead; cb.aio_offset = lpOverlapped->Offset; cb.aio_sigevent.sigev_notify = SIGEV_SIGNAL; cb.aio_sigevent.sigev_signo = SIGIO; cb.aio_sigevent.sigev_value.sival_ptr = (void*)lpOverlapped; InstallAioSignalHandler(); aio_status = aio_read(&cb); WLog_DBG(TAG, "aio_read status: %d", aio_status); if (aio_status < 0) status = FALSE; return status; } #else /* synchronous behavior */ lpOverlapped->Internal = 0; lpOverlapped->InternalHigh = (ULONG_PTR)nNumberOfBytesToRead; lpOverlapped->Pointer = (PVOID)lpBuffer; SetEvent(lpOverlapped->hEvent); #endif } return status; } BOOL NamedPipeWrite(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) { SSIZE_T io_status; WINPR_NAMED_PIPE* pipe; BOOL status = TRUE; if (lpOverlapped) { WLog_ERR(TAG, "WinPR %s does not support the lpOverlapped parameter", __FUNCTION__); SetLastError(ERROR_NOT_SUPPORTED); return FALSE; } pipe = (WINPR_NAMED_PIPE*)Object; if (!(pipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)) { if (pipe->clientfd == -1) return FALSE; do { io_status = write(pipe->clientfd, lpBuffer, nNumberOfBytesToWrite); } while ((io_status < 0) && (errno == EINTR)); if (io_status < 0) { *lpNumberOfBytesWritten = 0; switch (errno) { case EWOULDBLOCK: io_status = 0; status = TRUE; break; default: status = FALSE; } } *lpNumberOfBytesWritten = (DWORD)io_status; return status; } else { /* Overlapped I/O */ if (!lpOverlapped) return FALSE; if (pipe->clientfd == -1) return FALSE; pipe->lpOverlapped = lpOverlapped; #ifdef HAVE_SYS_AIO_H { struct aiocb cb = { 0 }; cb.aio_fildes = pipe->clientfd; cb.aio_buf = (void*)lpBuffer; cb.aio_nbytes = nNumberOfBytesToWrite; cb.aio_offset = lpOverlapped->Offset; cb.aio_sigevent.sigev_notify = SIGEV_SIGNAL; cb.aio_sigevent.sigev_signo = SIGIO; cb.aio_sigevent.sigev_value.sival_ptr = (void*)lpOverlapped; InstallAioSignalHandler(); io_status = aio_write(&cb); WLog_DBG("aio_write status: %" PRIdz, io_status); if (io_status < 0) status = FALSE; return status; } #else /* synchronous behavior */ lpOverlapped->Internal = 1; lpOverlapped->InternalHigh = (ULONG_PTR)nNumberOfBytesToWrite; { union { LPCVOID cpv; PVOID pv; } cnv; cnv.cpv = lpBuffer; lpOverlapped->Pointer = cnv.pv; } SetEvent(lpOverlapped->hEvent); #endif } return TRUE; } static HANDLE_OPS namedOps = { NamedPipeIsHandled, NamedPipeCloseHandle, NamedPipeGetFd, NULL, /* CleanupHandle */ NamedPipeRead, NULL, NULL, NamedPipeWrite, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; static BOOL InitWinPRPipeModule() { if (g_NamedPipeServerSockets) return TRUE; g_NamedPipeServerSockets = ArrayList_New(FALSE); return g_NamedPipeServerSockets != NULL; } /* * Unnamed pipe */ BOOL CreatePipe(PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize) { int pipe_fd[2]; WINPR_PIPE* pReadPipe; WINPR_PIPE* pWritePipe; WINPR_UNUSED(lpPipeAttributes); WINPR_UNUSED(nSize); pipe_fd[0] = -1; pipe_fd[1] = -1; if (pipe(pipe_fd) < 0) { WLog_ERR(TAG, "failed to create pipe"); return FALSE; } pReadPipe = (WINPR_PIPE*)calloc(1, sizeof(WINPR_PIPE)); pWritePipe = (WINPR_PIPE*)calloc(1, sizeof(WINPR_PIPE)); if (!pReadPipe || !pWritePipe) { free(pReadPipe); free(pWritePipe); return FALSE; } pReadPipe->fd = pipe_fd[0]; pWritePipe->fd = pipe_fd[1]; WINPR_HANDLE_SET_TYPE_AND_MODE(pReadPipe, HANDLE_TYPE_ANONYMOUS_PIPE, WINPR_FD_READ); pReadPipe->common.ops = &ops; *((ULONG_PTR*)hReadPipe) = (ULONG_PTR)pReadPipe; WINPR_HANDLE_SET_TYPE_AND_MODE(pWritePipe, HANDLE_TYPE_ANONYMOUS_PIPE, WINPR_FD_READ); pWritePipe->common.ops = &ops; *((ULONG_PTR*)hWritePipe) = (ULONG_PTR)pWritePipe; return TRUE; } /** * Named pipe */ static void winpr_unref_named_pipe(WINPR_NAMED_PIPE* pNamedPipe) { size_t index; NamedPipeServerSocketEntry* baseSocket; if (!pNamedPipe) return; WINPR_ASSERT(pNamedPipe->name); WINPR_ASSERT(g_NamedPipeServerSockets); // WLog_VRB(TAG, "%p (%s)", (void*) pNamedPipe, pNamedPipe->name); ArrayList_Lock(g_NamedPipeServerSockets); for (index = 0; index < ArrayList_Count(g_NamedPipeServerSockets); index++) { baseSocket = (NamedPipeServerSocketEntry*)ArrayList_GetItem(g_NamedPipeServerSockets, index); WINPR_ASSERT(baseSocket->name); if (!strcmp(baseSocket->name, pNamedPipe->name)) { WINPR_ASSERT(baseSocket->references > 0); WINPR_ASSERT(baseSocket->serverfd != -1); if (--baseSocket->references == 0) { // WLog_DBG(TAG, "removing shared server socked resource"); // WLog_DBG(TAG, "closing shared serverfd %d", baseSocket->serverfd); ArrayList_Remove(g_NamedPipeServerSockets, baseSocket); close(baseSocket->serverfd); free(baseSocket->name); free(baseSocket); } break; } } ArrayList_Unlock(g_NamedPipeServerSockets); } HANDLE CreateNamedPipeA(LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes) { size_t index; char* lpPipePath; struct sockaddr_un s; WINPR_NAMED_PIPE* pNamedPipe = NULL; int serverfd = -1; NamedPipeServerSocketEntry* baseSocket = NULL; WINPR_UNUSED(lpSecurityAttributes); if (dwOpenMode & FILE_FLAG_OVERLAPPED) { WLog_ERR(TAG, "WinPR %s does not support the FILE_FLAG_OVERLAPPED flag", __FUNCTION__); SetLastError(ERROR_NOT_SUPPORTED); return INVALID_HANDLE_VALUE; } if (!lpName) return INVALID_HANDLE_VALUE; if (!InitWinPRPipeModule()) return INVALID_HANDLE_VALUE; pNamedPipe = (WINPR_NAMED_PIPE*)calloc(1, sizeof(WINPR_NAMED_PIPE)); if (!pNamedPipe) return INVALID_HANDLE_VALUE; ArrayList_Lock(g_NamedPipeServerSockets); WINPR_HANDLE_SET_TYPE_AND_MODE(pNamedPipe, HANDLE_TYPE_NAMED_PIPE, WINPR_FD_READ); pNamedPipe->serverfd = -1; pNamedPipe->clientfd = -1; if (!(pNamedPipe->name = _strdup(lpName))) goto out; if (!(pNamedPipe->lpFileName = GetNamedPipeNameWithoutPrefixA(lpName))) goto out; if (!(pNamedPipe->lpFilePath = GetNamedPipeUnixDomainSocketFilePathA(lpName))) goto out; pNamedPipe->dwOpenMode = dwOpenMode; pNamedPipe->dwPipeMode = dwPipeMode; pNamedPipe->nMaxInstances = nMaxInstances; pNamedPipe->nOutBufferSize = nOutBufferSize; pNamedPipe->nInBufferSize = nInBufferSize; pNamedPipe->nDefaultTimeOut = nDefaultTimeOut; pNamedPipe->dwFlagsAndAttributes = dwOpenMode; pNamedPipe->clientfd = -1; pNamedPipe->ServerMode = TRUE; pNamedPipe->common.ops = &namedOps; for (index = 0; index < ArrayList_Count(g_NamedPipeServerSockets); index++) { baseSocket = (NamedPipeServerSocketEntry*)ArrayList_GetItem(g_NamedPipeServerSockets, index); if (!strcmp(baseSocket->name, lpName)) { serverfd = baseSocket->serverfd; // WLog_DBG(TAG, "using shared socked resource for pipe %p (%s)", (void*) pNamedPipe, // lpName); break; } } /* If this is the first instance of the named pipe... */ if (serverfd == -1) { /* Create the UNIX domain socket and start listening. */ if (!(lpPipePath = GetNamedPipeUnixDomainSocketBaseFilePathA())) goto out; if (!winpr_PathFileExists(lpPipePath)) { if (!CreateDirectoryA(lpPipePath, 0)) { free(lpPipePath); goto out; } UnixChangeFileMode(lpPipePath, 0xFFFF); } free(lpPipePath); if (winpr_PathFileExists(pNamedPipe->lpFilePath)) winpr_DeleteFile(pNamedPipe->lpFilePath); if ((serverfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { WLog_ERR(TAG, "CreateNamedPipeA: socket error, %s", strerror(errno)); goto out; } ZeroMemory(&s, sizeof(struct sockaddr_un)); s.sun_family = AF_UNIX; sprintf_s(s.sun_path, ARRAYSIZE(s.sun_path), "%s", pNamedPipe->lpFilePath); if (bind(serverfd, (struct sockaddr*)&s, sizeof(struct sockaddr_un)) == -1) { WLog_ERR(TAG, "CreateNamedPipeA: bind error, %s", strerror(errno)); goto out; } if (listen(serverfd, 2) == -1) { WLog_ERR(TAG, "CreateNamedPipeA: listen error, %s", strerror(errno)); goto out; } UnixChangeFileMode(pNamedPipe->lpFilePath, 0xFFFF); if (!(baseSocket = (NamedPipeServerSocketEntry*)malloc(sizeof(NamedPipeServerSocketEntry)))) goto out; if (!(baseSocket->name = _strdup(lpName))) { free(baseSocket); goto out; } baseSocket->serverfd = serverfd; baseSocket->references = 0; if (!ArrayList_Append(g_NamedPipeServerSockets, baseSocket)) { free(baseSocket->name); goto out; } // WLog_DBG(TAG, "created shared socked resource for pipe %p (%s). base serverfd = %d", // (void*) pNamedPipe, lpName, serverfd); } pNamedPipe->serverfd = dup(baseSocket->serverfd); // WLog_DBG(TAG, "using serverfd %d (duplicated from %d)", pNamedPipe->serverfd, // baseSocket->serverfd); pNamedPipe->pfnUnrefNamedPipe = winpr_unref_named_pipe; baseSocket->references++; if (dwOpenMode & FILE_FLAG_OVERLAPPED) { #if 0 int flags = fcntl(pNamedPipe->serverfd, F_GETFL); if (flags != -1) fcntl(pNamedPipe->serverfd, F_SETFL, flags | O_NONBLOCK); #endif } ArrayList_Unlock(g_NamedPipeServerSockets); return pNamedPipe; out: NamedPipeCloseHandle(pNamedPipe); if (serverfd != -1) close(serverfd); ArrayList_Unlock(g_NamedPipeServerSockets); return INVALID_HANDLE_VALUE; } HANDLE CreateNamedPipeW(LPCWSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes) { WLog_ERR(TAG, "%s is not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return NULL; } BOOL ConnectNamedPipe(HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped) { int status; socklen_t length; struct sockaddr_un s; WINPR_NAMED_PIPE* pNamedPipe; if (lpOverlapped) { WLog_ERR(TAG, "WinPR %s does not support the lpOverlapped parameter", __FUNCTION__); SetLastError(ERROR_NOT_SUPPORTED); return FALSE; } if (!hNamedPipe) return FALSE; pNamedPipe = (WINPR_NAMED_PIPE*)hNamedPipe; if (!(pNamedPipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)) { length = sizeof(struct sockaddr_un); ZeroMemory(&s, sizeof(struct sockaddr_un)); status = accept(pNamedPipe->serverfd, (struct sockaddr*)&s, &length); if (status < 0) { WLog_ERR(TAG, "ConnectNamedPipe: accept error"); return FALSE; } pNamedPipe->clientfd = status; pNamedPipe->ServerMode = FALSE; } else { if (!lpOverlapped) return FALSE; if (pNamedPipe->serverfd == -1) return FALSE; pNamedPipe->lpOverlapped = lpOverlapped; /* synchronous behavior */ lpOverlapped->Internal = 2; lpOverlapped->InternalHigh = (ULONG_PTR)0; lpOverlapped->Pointer = (PVOID)NULL; SetEvent(lpOverlapped->hEvent); } return TRUE; } BOOL DisconnectNamedPipe(HANDLE hNamedPipe) { WINPR_NAMED_PIPE* pNamedPipe; pNamedPipe = (WINPR_NAMED_PIPE*)hNamedPipe; if (pNamedPipe->clientfd != -1) { close(pNamedPipe->clientfd); pNamedPipe->clientfd = -1; } return TRUE; } BOOL PeekNamedPipe(HANDLE hNamedPipe, LPVOID lpBuffer, DWORD nBufferSize, LPDWORD lpBytesRead, LPDWORD lpTotalBytesAvail, LPDWORD lpBytesLeftThisMessage) { WLog_ERR(TAG, "%s: Not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; } BOOL TransactNamedPipe(HANDLE hNamedPipe, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesRead, LPOVERLAPPED lpOverlapped) { WLog_ERR(TAG, "%s: Not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; } BOOL WaitNamedPipeA(LPCSTR lpNamedPipeName, DWORD nTimeOut) { BOOL status; DWORD nWaitTime; char* lpFilePath; DWORD dwSleepInterval; if (!lpNamedPipeName) return FALSE; lpFilePath = GetNamedPipeUnixDomainSocketFilePathA(lpNamedPipeName); if (!lpFilePath) return FALSE; if (nTimeOut == NMPWAIT_USE_DEFAULT_WAIT) nTimeOut = 50; nWaitTime = 0; status = TRUE; dwSleepInterval = 10; while (!winpr_PathFileExists(lpFilePath)) { Sleep(dwSleepInterval); nWaitTime += dwSleepInterval; if (nWaitTime >= nTimeOut) { status = FALSE; break; } } free(lpFilePath); return status; } BOOL WaitNamedPipeW(LPCWSTR lpNamedPipeName, DWORD nTimeOut) { WLog_ERR(TAG, "%s: Not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; } BOOL SetNamedPipeHandleState(HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout) { int fd; int flags; WINPR_NAMED_PIPE* pNamedPipe; pNamedPipe = (WINPR_NAMED_PIPE*)hNamedPipe; if (lpMode) { pNamedPipe->dwPipeMode = *lpMode; fd = (pNamedPipe->ServerMode) ? pNamedPipe->serverfd : pNamedPipe->clientfd; if (fd == -1) return FALSE; flags = fcntl(fd, F_GETFL); if (flags < 0) return FALSE; if (pNamedPipe->dwPipeMode & PIPE_NOWAIT) flags = (flags | O_NONBLOCK); else flags = (flags & ~(O_NONBLOCK)); if (fcntl(fd, F_SETFL, flags) < 0) return FALSE; } if (lpMaxCollectionCount) { } if (lpCollectDataTimeout) { } return TRUE; } BOOL ImpersonateNamedPipeClient(HANDLE hNamedPipe) { WLog_ERR(TAG, "%s: Not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; } BOOL GetNamedPipeClientComputerNameA(HANDLE Pipe, LPCSTR ClientComputerName, ULONG ClientComputerNameLength) { WLog_ERR(TAG, "%s: Not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; } BOOL GetNamedPipeClientComputerNameW(HANDLE Pipe, LPCWSTR ClientComputerName, ULONG ClientComputerNameLength) { WLog_ERR(TAG, "%s: Not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; } #endif
{ "content_hash": "9cbbfbb3bafd2aa180430cd088efa4a5", "timestamp": "", "source": "github", "line_count": 908, "max_line_length": 96, "avg_line_length": 23.570484581497798, "alnum_prop": 0.6579291654985515, "repo_name": "erbth/FreeRDP", "id": "ec7252d51cae2ea05b9cd34d42506e7c87146f7f", "size": "22190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "winpr/libwinpr/pipe/pipe.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "15047579" }, { "name": "C#", "bytes": "6365" }, { "name": "C++", "bytes": "138156" }, { "name": "CMake", "bytes": "635206" }, { "name": "CSS", "bytes": "5696" }, { "name": "HTML", "bytes": "99139" }, { "name": "Java", "bytes": "371005" }, { "name": "Lua", "bytes": "27390" }, { "name": "Makefile", "bytes": "1677" }, { "name": "Objective-C", "bytes": "517066" }, { "name": "Perl", "bytes": "8044" }, { "name": "Python", "bytes": "53966" }, { "name": "Rich Text Format", "bytes": "937" }, { "name": "Roff", "bytes": "12141" }, { "name": "Shell", "bytes": "32964" } ], "symlink_target": "" }
layout: study--link title: nationalarchives-gov-uk philip-clegg 120-tb-web-archive link: >- https://blog.nationalarchives.gov.uk/blog/move-120-tb-web-archive-cloud-two-weeks/ link_title: How to move a 120 TB web archive to the cloud in two weeks source: >- via Library and Archives Canada’s [_Governance and Recordkeeping Around The World_ January 2019 issue](https://www.bac-lac.gc.ca/eng/about-us/publications/governance-recordkeeping-world/Pages/2019/January2019.aspx) date: 2019-01-12T21:58:17.401Z published: true --- The UK’s National Archives transferred its 1.4 billion document, 120 TB Government Web Archive to the cloud—in two weeks. > With this ensemble of 72 hard drives, two custom-built PCs and two AWS Snowballs, the entire process took just two weeks – not bad for more than two decades of internet history! A great explanation of the benefits of cloud storage: > Cloud can also make web-based services faster and more reliable. Put in the simplest terms, physical hardware – like servers and hard drives – can be overloaded or fail. Cloud infrastructure, on the other-hand, tends to have a higher level of redundancy built-in – so if there’s ever a problem with a hard drive, server or even data centre, your services can simply be resumed elsewhere with minimal disruption. Sometimes (usually) the right approach is a combination of building your own tools and using powerful open source libraries: > We struggled to find an existing tool that would meet our specific need for indexing a large number of small files, so we built something called WarpPipe. This allowed us to index all The National Archives’ documents in just ten hours – far below the timeframe of six to eight weeks we were told it would take with one of the most popular big data processing tools. > > The search functionality itself is provided by Elasticsearch, which substantially improves on The National Archives’ previous search engine in terms of speed, flexibility and reliability. We now update the index once a month rather than once a quarter, for example, so it’s much faster for new archive content to show up in search results.
{ "content_hash": "8513fec00e2ddf41f2e614d8ece55c6b", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 413, "avg_line_length": 85.72, "alnum_prop": 0.7909472701819878, "repo_name": "lchski/lucascherkewski.com", "id": "f07a67341ee6a6988d011c7739d665463d45ba74", "size": "2171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_links/2019-01-12-17-07-nationalarchives-gov-uk-philip-clegg-120-tb-web-archive.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8436" }, { "name": "HTML", "bytes": "30188" }, { "name": "JavaScript", "bytes": "2360" }, { "name": "Ruby", "bytes": "623" }, { "name": "Shell", "bytes": "1176" } ], "symlink_target": "" }
require 'rubygems' require 'fileutils' require 'sinatra' require 'mixlib/shellout' require 'chef' require 'chef/provisioning' require 'cheffish' require 'chef/config' require 'chef/knife' require 'chef/run_list/run_list_item' require 'cheffish/basic_chef_client' require 'cheffish/server_api' require 'chef/knife' require 'chef/config_fetcher' require 'chef/log' require 'chef/application' require 'chef/provisioning/registry/data_handler/for_api' require 'chef/provisioning/registry/chef_registry_spec' # APP_ROOT = File.expand_path('..', File.dirname(__FILE__)) unless defined? APP_ROOT APP_ROOT = ENV['REGISTRY_APP_ROOT'] configure do set :bind, '0.0.0.0' end post '/v1/registry' do registry_path = ::File.expand_path("#{APP_ROOT}/.chef/provisioning/registry") FileUtils.mkdir_p(registry_path) datafile = params[:data] payload = datafile[:tempfile].read data_handler = Chef::Provisioning::Registry::DataHandler::ForApi.new(payload, registry_path) if data_handler.keyname && !::File.exists?(data_handler.keyname) if data_handler.ssh_key_value ::File.open(data_handler.keyname, 'wb') do |file| file.write(data_handler.ssh_key_value) end ::File.chmod(00600, data_handler.keyname) end end ## # Setup Config config_file_path = ::File.expand_path("#{APP_ROOT}/.chef/knife.rb") chef_config = Chef::Config config_fetcher = Chef::ConfigFetcher.new(config_file_path) config_content = config_fetcher.read_config chef_config.from_string(config_content, config_file_path) config = Cheffish.profiled_config(chef_config) config[:local_mode] = true chef_server = Cheffish.default_chef_server(config) ## # Action Handler # TODO make right action_handler = Chef::Provisioning::ActionHandler.new ## # Chef Registry Spec registry_spec = Chef::Provisioning::Registry::ChefRegistrySpec.new(data_handler.api_hash, chef_server) ## # Save # TODO get respect_inline working. to file only for now # # registry_spec.save_data_bag(action_handler) registry_spec.save_file(action_handler) # registry_spec.save(action_handler) # This Saves to Both "\n OUT \n Payload Recieved is: \n\n#{payload}\n ChefRegistrySpec inspect is: \n\n#{registry_spec.inspect} \n DataHandler is \n\n#{data_handler.inspect}\n" end
{ "content_hash": "d53dbf0b09f4b9ec61cb9f683c5f7fe7", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 157, "avg_line_length": 30.573333333333334, "alnum_prop": 0.7221979938944614, "repo_name": "double-z/chef-provisioning-registry", "id": "d480d0aec2ab11bca10c314cc0138ee90a4d0ef8", "size": "2293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/chef/provisioning/registry/api.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "84304" } ], "symlink_target": "" }
namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo v8_test_variadic_constructor_arguments_wrapper_type_info = { gin::kEmbedderBlink, V8TestVariadicConstructorArguments::DomTemplate, nullptr, "TestVariadicConstructorArguments", nullptr, WrapperTypeInfo::kWrapperTypeObjectPrototype, WrapperTypeInfo::kObjectClassId, WrapperTypeInfo::kNotInheritFromActiveScriptWrappable, }; #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestVariadicConstructorArguments.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // platform/bindings/ScriptWrappable.h. const WrapperTypeInfo& TestVariadicConstructorArguments::wrapper_type_info_ = v8_test_variadic_constructor_arguments_wrapper_type_info; // not [ActiveScriptWrappable] static_assert( !std::is_base_of<ActiveScriptWrappableBase, TestVariadicConstructorArguments>::value, "TestVariadicConstructorArguments inherits from ActiveScriptWrappable<>, but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); static_assert( std::is_same<decltype(&TestVariadicConstructorArguments::HasPendingActivity), decltype(&ScriptWrappable::HasPendingActivity)>::value, "TestVariadicConstructorArguments is overriding hasPendingActivity(), but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); namespace test_variadic_constructor_arguments_v8_internal { static void Constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestVariadicConstructorArguments_ConstructorCallback"); ExceptionState exception_state(info.GetIsolate(), ExceptionState::kConstructionContext, "TestVariadicConstructorArguments"); Vector<double> args; args = ToImplArguments<IDLDouble>(info, 0, exception_state); if (exception_state.HadException()) return; TestVariadicConstructorArguments* impl = TestVariadicConstructorArguments::Create(args); v8::Local<v8::Object> wrapper = info.Holder(); wrapper = impl->AssociateWithWrapper(info.GetIsolate(), V8TestVariadicConstructorArguments::GetWrapperTypeInfo(), wrapper); V8SetReturnValue(info, wrapper); } CORE_EXPORT void ConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestVariadicConstructorArguments_Constructor"); if (!info.IsConstructCall()) { V8ThrowException::ThrowTypeError( info.GetIsolate(), ExceptionMessages::ConstructorNotCallableAsFunction("TestVariadicConstructorArguments")); return; } if (ConstructorMode::Current(info.GetIsolate()) == ConstructorMode::kWrapExistingObject) { V8SetReturnValue(info, info.Holder()); return; } test_variadic_constructor_arguments_v8_internal::Constructor(info); } } // namespace test_variadic_constructor_arguments_v8_internal static void InstallV8TestVariadicConstructorArgumentsTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { // Initialize the interface object's template. V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8TestVariadicConstructorArguments::GetWrapperTypeInfo()->interface_name, v8::Local<v8::FunctionTemplate>(), V8TestVariadicConstructorArguments::kInternalFieldCount); interface_template->SetCallHandler(test_variadic_constructor_arguments_v8_internal::ConstructorCallback); interface_template->SetLength(0); v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instance_template); v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. // Custom signature V8TestVariadicConstructorArguments::InstallRuntimeEnabledFeaturesOnTemplate( isolate, world, interface_template); } void V8TestVariadicConstructorArguments::InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instance_template); v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. // Custom signature } v8::Local<v8::FunctionTemplate> V8TestVariadicConstructorArguments::DomTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world) { return V8DOMConfiguration::DomClassTemplate( isolate, world, const_cast<WrapperTypeInfo*>(V8TestVariadicConstructorArguments::GetWrapperTypeInfo()), InstallV8TestVariadicConstructorArgumentsTemplate); } bool V8TestVariadicConstructorArguments::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->HasInstance(V8TestVariadicConstructorArguments::GetWrapperTypeInfo(), v8_value); } v8::Local<v8::Object> V8TestVariadicConstructorArguments::FindInstanceInPrototypeChain( v8::Local<v8::Value> v8_value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain( V8TestVariadicConstructorArguments::GetWrapperTypeInfo(), v8_value); } TestVariadicConstructorArguments* V8TestVariadicConstructorArguments::ToImplWithTypeCheck( v8::Isolate* isolate, v8::Local<v8::Value> value) { return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr; } } // namespace blink
{ "content_hash": "92625d6697dbfc40cec7b3df22581672", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 248, "avg_line_length": 45.5531914893617, "alnum_prop": 0.7835902226373969, "repo_name": "endlessm/chromium-browser", "id": "24d62a9983e2bd5c1533cb67debfbbd2297c7f69", "size": "7731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/blink/renderer/bindings/tests/results/core/v8_test_variadic_constructor_arguments.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
'use strict'; var http = require('http'); var https = require('https'); var fs = require('fs'); var path = require('path'); var parse = require('./parse.js'); function f(name, mode, config) { name = name[name.length - 1] === '/' ? name : name + '/'; mode = mode || 'json'; config = config || f.config; return function external() { var argList = [].slice.call(arguments); var callback = function() {}; var params; var payload; var headers; var req; var pkgjson; var fnjson; var fn; var env; var responded = false; if (typeof argList[argList.length - 1] === 'function') { callback = argList.pop(); } if (mode === 'json') { headers = {'Content-Type': 'application/json'}; params = parse.fromArgList(argList); payload = new Buffer(JSON.stringify(params)); } else if (mode === 'command') { headers = {'Content-Type': 'application/json'}; params = parse.fromString(argList[0]); payload = new Buffer(JSON.stringify(params)); } else if (mode === 'file') { if (!argList[0] instanceof Buffer) { return callback(new Error('Expecting Buffer for function mode: ' + mode)); } headers = {'Content-Type': 'application/octet-stream'}; params = parse.fromArgList([]); payload = argList[0]; } else { return callback(new Error('Invalid function mode: ' + mode)); } // if it's a string and the first character is a period... if (typeof name === 'string' && name[0] === '.') { try { let fnpath = path.join(process.cwd(), 'f', name, 'index.js'); let fnjpath = path.join(process.cwd(), 'f', name, 'function.json'); if (!config.local.cache) { delete require.cache[require.resolve(fnpath)]; delete require.cache[require.resolve(fnjpath)]; } name = require(fnpath); name.json = require(fnjpath); } catch (e) { callback(new Error('Could not find local function "' + name + '"')); return true; } } // if it's a function, it's being called locally if (typeof name === 'function') { params.env = process.env.ENV || 'dev'; params.service = '.'; params.remoteAddress = '::1'; params.buffer = payload; return name(params, (err, result, headers) => { if (err) { return callback(err); } headers = headers || {}; headers = typeof headers === 'object' ? headers : {}; let oheaders = (name.json && name.json.http && name.json.http.headers) || {}; oheaders = typeof oheaders === 'object' ? oheaders : {}; headers = Object.assign(oheaders, headers); return callback(err, result, headers); }); } // Throw error if invalid function if (!name || typeof name !== 'string') { callback(new Error('Invalid function name')); return true; } req = [http, https][(config.gateway.port === 443) | 0].request({ host: config.gateway.host, method: 'POST', headers: headers, port: config.gateway.port, path: config.gateway.path + name, agent: false }, function (res) { var buffers = []; res.on('data', function (chunk) { buffers.push(chunk); }); res.on('end', function () { var response = Buffer.concat(buffers); var contentType = res.headers['content-type'] || ''; if (contentType === 'application/json') { response = response.toString(); try { response = JSON.parse(response); } catch(e) { response = null; } } else if (contentType.match(/^text\/.*$/i)) { response = response.toString(); } // Prevent req error responded = true; if (((res.statusCode / 100) | 0) !== 2) { return callback(new Error(response)); } else { return callback(null, response, res.headers); } }); }); req.on('error', function(err) { if (responded) { return; } callback(err); }); req.write(payload); req.end(); return; } }; f.config = { gateway: { host: 'f.stdlib.com', port: 443, path: '/' }, local: { cache: true } }; module.exports = f;
{ "content_hash": "110457743a3fbce2ae992d999b1ad67b", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 85, "avg_line_length": 26.390243902439025, "alnum_prop": 0.5418207024029574, "repo_name": "poly/f", "id": "5ef328463bf4e88adbbd3eca464fe1061737fe7e", "size": "4328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/f.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10218" } ], "symlink_target": "" }
<?php class HomeController extends BaseController { /* |-------------------------------------------------------------------------- | Default Home Controller |-------------------------------------------------------------------------- | | You may wish to use controllers instead of, or in addition to, Closure | based routes. That's great! Here is an example controller method to | get you started. To route to this controller, just add the route: | | Route::get('/', 'HomeController@showWelcome'); | */ public function showWelcome() { return View::make('hello'); } public function showLogin() { // show the form return View::make('login'); } public function doLogin() { // validate the info, create rules for the inputs $rules = array( 'email' => 'required|email', // make sure the email is an actual email 'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters ); // run the validation rules on the inputs from the form $validator = Validator::make(Input::all(), $rules); // if the validator fails, redirect back to the form if ($validator->fails()) { return Redirect::to('login') ->withErrors($validator) // send back all errors to the login form ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form } else { $inputEmail = Input::get('email'); $inputPassword = Input::get('password'); if (Auth::attempt(array('EmailAddress' => $inputEmail, 'Password' => $inputPassword))) { } else { echo('Fail'); } } } public function doLogout() { Auth::logout(); // log the user out of our application return Redirect::to('login'); // redirect the user to the login screen } public function showGraph() { $raw_data = SiteSpectrumData::where('sitespectrumid', '=', 1000)->orderby('frequency')->get(); $count = count($raw_data); $data = array($count); for ($i = 0; $i < $count; $i++) { $item = $raw_data[$i]; $value = new ChartValue(); $value->x = $item->frequency; $value->y = 20*log10($item->readingmagnitude); $data[$i] = $value; } $view = View::make('graph', array('data' => $data)); return $view; } }
{ "content_hash": "3e3975058439cbb6d378fb507117611b", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 119, "avg_line_length": 25.488888888888887, "alnum_prop": 0.5919790758500436, "repo_name": "SidWatch/SidWatchServer", "id": "42b395ad6532fa005351e6c7fba90dd364e89cba", "size": "2294", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/SidWatchServer/app/controllers/HomeController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "161" }, { "name": "PHP", "bytes": "85424" }, { "name": "Shell", "bytes": "191" } ], "symlink_target": "" }
<?php namespace Omnipay\Common\Message; use Mockery as m; use Money\Currency; use Money\Money; use Omnipay\Common\CreditCard; use Omnipay\Common\ItemBag; use Omnipay\Tests\TestCase; class AbstractRequestTest extends TestCase { /** @var AbstractRequest */ protected $request; public function setUp() { $this->request = m::mock('\Omnipay\Common\Message\AbstractRequest')->makePartial(); $this->request->initialize(); } /** * Allow changing a protected property using reflections. * * @param $property * @param bool|true $value */ private function changeProtectedProperty($property, $value = true) { $reflection = new \ReflectionClass($this->request); $reflection_property = $reflection->getProperty($property); $reflection_property->setAccessible(true); $reflection_property->setValue($this->request, $value); $reflection_property->setAccessible(false); } public function testConstruct() { $this->request = new AbstractRequestTest_MockAbstractRequest($this->getHttpClient(), $this->getHttpRequest()); $this->assertSame(array(), $this->request->getParameters()); } public function testInitializeWithParams() { $this->assertSame($this->request, $this->request->initialize(array('amount' => '1.23'))); $this->assertSame('1.23', $this->request->getAmount()); } /** * @expectedException \Omnipay\Common\Exception\RuntimeException * @expectedExceptionMessage Request cannot be modified after it has been sent! */ public function testInitializeAfterRequestSent() { $this->request = new AbstractRequestTest_MockAbstractRequest($this->getHttpClient(), $this->getHttpRequest()); $this->request->send(); $this->request->initialize(); } public function testCard() { // no type checking on card parameter $card = new CreditCard; $this->assertSame($this->request, $this->request->setCard($card)); $this->assertSame($card, $this->request->getCard()); } public function testSetCardWithArray() { // passing array should create CreditCard object $this->assertSame($this->request, $this->request->setCard(array('number' => '1234'))); $card = $this->request->getCard(); $this->assertInstanceOf('\Omnipay\Common\CreditCard', $card); $this->assertSame('1234', $card->getNumber()); } public function testToken() { $this->assertSame($this->request, $this->request->setToken('12345')); $this->assertSame('12345', $this->request->getToken()); } public function testCardReference() { $this->assertSame($this->request, $this->request->setCardReference('12345')); $this->assertSame('12345', $this->request->getCardReference()); } public function testAmount() { $this->assertSame($this->request, $this->request->setAmount('2.00')); $this->assertSame('2.00', $this->request->getAmount()); } public function testAmountWithFloat() { $this->assertSame($this->request, $this->request->setAmount(2.0)); $this->assertSame('2.00', $this->request->getAmount()); } public function testAmountWithEmpty() { $this->assertSame($this->request, $this->request->setAmount(null)); $this->assertSame(null, $this->request->getAmount()); } public function testAmountZeroFloat() { $this->assertSame($this->request, $this->request->setAmount(0.0)); $this->assertSame('0.00', $this->request->getAmount()); } public function testAmountZeroString() { $this->assertSame($this->request, $this->request->setAmount('0.000000')); $this->assertSame('0.00', $this->request->getAmount()); } /** * @expectedException \Omnipay\Common\Exception\InvalidRequestException * @expectedExceptionMessage A zero amount is not allowed. */ public function testAmountZeroNotAllowed() { $this->changeProtectedProperty('zeroAmountAllowed', false); $this->request->setAmount('0.00'); $this->request->getAmount(); } // See https://github.com/thephpleague/omnipay-common/issues/69 public function testAmountPrecision() { // The default precision for PHP is 6 decimal places. ini_set('precision', 6); $this->assertSame($this->request, $this->request->setAmount('67.10')); $this->assertSame('67.10', $this->request->getAmount()); // At 17 decimal places, 67.10 will echo as 67.09999... // This is *why* PHP sets the default precision at 6. ini_set('precision', 17); $this->assertSame('67.10', $this->request->getAmount()); $this->assertSame($this->request, $this->request->setAmount('67.01')); $this->assertSame('67.01', $this->request->getAmount()); $this->assertSame($this->request, $this->request->setAmount('0.10')); $this->assertSame('0.10', $this->request->getAmount()); $this->assertSame($this->request, $this->request->setAmount('0.01')); $this->assertSame('0.01', $this->request->getAmount()); } // See https://github.com/thephpleague/omnipay-common/issues/143 public function testAmountPrecisionLargeNumbers() { $this->request->setCurrency('VND'); $this->assertSame($this->request, $this->request->setAmount('103500000')); $this->assertSame('103500000', $this->request->getAmount()); } /** * @expectedException \Omnipay\Common\Exception\InvalidRequestException * * We still want to catch obvious fractions of the minor units that are * not precision errors at a much lower level. */ public function testAmountPrecisionTooHigh() { $this->assertSame($this->request, $this->request->setAmount('123.005')); $this->assertSame('123.005', $this->request->getAmount()); } public function testGetAmountNoDecimals() { $this->assertSame($this->request, $this->request->setCurrency('JPY')); $this->assertSame($this->request, $this->request->setAmount('1366')); $this->assertSame('1366', $this->request->getAmount()); } /** * @expectedException \Omnipay\Common\Exception\InvalidRequestException */ public function testGetAmountNoDecimalsRounding() { // There will not be any rounding; the amount is sent as requested or not at all. $this->assertSame($this->request, $this->request->setAmount('136.5')); $this->assertSame($this->request, $this->request->setCurrency('JPY')); $this->request->getAmount(); } public function testGetAmountInteger() { $this->assertSame($this->request, $this->request->setAmount('13.66')); $this->assertSame(1366, $this->request->getAmountInteger()); } public function testGetAmountIntegerNull() { $this->assertSame($this->request, $this->request->setAmount(null)); $this->assertSame(null, $this->request->getAmountInteger()); } public function testSetAmountInteger() { $this->assertSame($this->request, $this->request->setAmountInteger(1366)); $this->assertSame(1366, $this->request->getAmountInteger()); $this->assertSame('13.66', $this->request->getAmount()); } public function testGetAmountIntegerNoDecimals() { $this->assertSame($this->request, $this->request->setCurrency('JPY')); $this->assertSame($this->request, $this->request->setAmount('1366')); $this->assertSame(1366, $this->request->getAmountInteger()); } /** * @expectedException \InvalidArgumentException */ public function testAmountThousandsSepThrowsException() { $this->assertSame($this->request, $this->request->setAmount('1,234.00')); $this->request->getAmount(); } /** * @expectedException \InvalidArgumentException */ public function testAmountInvalidFormatThrowsException() { $this->assertSame($this->request, $this->request->setAmount('1.234.00')); $this->request->getAmount(); } /** * @expectedException \Omnipay\Common\Exception\InvalidRequestException */ public function testAmountNegativeStringThrowsException() { $this->assertSame($this->request, $this->request->setAmount('-123.00')); $this->request->getAmount(); } /** * @expectedException \Omnipay\Common\Exception\InvalidRequestException */ public function testAmountNegativeFloatThrowsException() { $this->assertSame($this->request, $this->request->setAmount(-123.00)); $this->request->getAmount(); } public function testMoney() { $money = new Money(12345, new Currency('EUR')); $this->assertSame($this->request, $this->request->setMoney($money)); $this->request->validate('amount', 'currency'); $this->assertSame('123.45', $this->request->getAmount()); $this->assertSame(12345, $this->request->getAmountInteger()); $this->assertSame('EUR', $this->request->getCurrency()); } public function testCurrency() { $this->assertSame($this->request, $this->request->setCurrency('USD')); $this->assertSame('USD', $this->request->getCurrency()); } public function testCurrencyLowercase() { $this->assertSame($this->request, $this->request->setCurrency('usd')); $this->assertSame('USD', $this->request->getCurrency()); } public function testCurrencyNull() { $this->assertSame($this->request, $this->request->setCurrency(null)); $this->assertNull($this->request->getCurrency()); } public function testCurrencyNumeric() { $this->assertSame($this->request, $this->request->setCurrency('USD')); $this->assertSame('840', $this->request->getCurrencyNumeric()); } public function testCurrencyNumericNull() { $this->assertSame($this->request, $this->request->setCurrency(null)); $this->assertSame(null, $this->request->getCurrencyNumeric()); } public function testCurrencyNumericUnkown() { $this->assertSame($this->request, $this->request->setCurrency('UNKNOWN')); $this->assertSame(null, $this->request->getCurrencyNumeric()); } public function testCurrencyDecimals() { $this->assertSame($this->request, $this->request->setCurrency('JPY')); $this->assertSame(0, $this->request->getCurrencyDecimalPlaces()); } public function testCurrencyDecimalsDefault() { $this->assertSame(2, $this->request->getCurrencyDecimalPlaces()); } public function testFormatCurrency() { $this->assertSame('1234.00', $this->request->formatCurrency(1234)); } public function testFormatCurrencyNoDecimals() { $this->request->setCurrency('JPY'); $this->assertSame('1234', $this->request->formatCurrency(1234)); } public function testDescription() { $this->assertSame($this->request, $this->request->setDescription('Cool product')); $this->assertSame('Cool product', $this->request->getDescription()); } public function testTransactionId() { $this->assertSame($this->request, $this->request->setTransactionId(87)); $this->assertSame(87, $this->request->getTransactionId()); } public function testTransactionReference() { $this->assertSame($this->request, $this->request->setTransactionReference('xyz')); $this->assertSame('xyz', $this->request->getTransactionReference()); } public function testItemsArray() { $this->assertSame($this->request, $this->request->setItems(array( array('name' => 'Floppy Disk'), array('name' => 'CD-ROM'), ))); $itemBag = $this->request->getItems(); $this->assertInstanceOf('\Omnipay\Common\ItemBag', $itemBag); $items = $itemBag->all(); $this->assertSame('Floppy Disk', $items[0]->getName()); $this->assertSame('CD-ROM', $items[1]->getName()); } public function testItemsBag() { $itemBag = new ItemBag; $itemBag->add(array('name' => 'Floppy Disk')); $this->assertSame($this->request, $this->request->setItems($itemBag)); $this->assertSame($itemBag, $this->request->getItems()); } public function testClientIp() { $this->assertSame($this->request, $this->request->setClientIp('127.0.0.1')); $this->assertSame('127.0.0.1', $this->request->getClientIp()); } public function testReturnUrl() { $this->assertSame($this->request, $this->request->setReturnUrl('https://www.example.com/return')); $this->assertSame('https://www.example.com/return', $this->request->getReturnUrl()); } public function testCancelUrl() { $this->assertSame($this->request, $this->request->setCancelUrl('https://www.example.com/cancel')); $this->assertSame('https://www.example.com/cancel', $this->request->getCancelUrl()); } public function testNotifyUrl() { $this->assertSame($this->request, $this->request->setNotifyUrl('https://www.example.com/notify')); $this->assertSame('https://www.example.com/notify', $this->request->getNotifyUrl()); } public function testIssuer() { $this->assertSame($this->request, $this->request->setIssuer('some-bank')); $this->assertSame('some-bank', $this->request->getIssuer()); } public function testPaymentMethod() { $this->assertSame($this->request, $this->request->setPaymentMethod('ideal')); $this->assertSame('ideal', $this->request->getPaymentMethod()); } public function testInitializedParametersAreSet() { $params = array('testMode' => 'success'); $this->request->initialize($params); $this->assertSame($this->request->getTestMode(), 'success'); } public function testGetParameters() { $this->request->setTestMode(true); $this->request->setToken('asdf'); $expected = array( 'testMode' => true, 'token' => 'asdf', ); $this->assertEquals($expected, $this->request->getParameters()); } /** * @expectedException \Omnipay\Common\Exception\RuntimeException * @expectedExceptionMessage Request cannot be modified after it has been sent! */ public function testSetParameterAfterRequestSent() { $this->request = new AbstractRequestTest_MockAbstractRequest($this->getHttpClient(), $this->getHttpRequest()); $this->request->send(); $this->request->setCurrency('PHP'); } public function testCanValidateExistingParameters() { $this->request->setTestMode(true); $this->request->setToken('asdf'); $this->assertNull($this->request->validate('testMode', 'token')); } public function testCanValidateAmountInteger() { $this->request->setAmountInteger(1); $this->assertNull($this->request->validate('amount')); } /** * @expectedException \Omnipay\Common\Exception\InvalidRequestException */ public function testInvalidParametersThrowsException() { $this->request->setTestMode(true); $this->request->validate('testMode', 'token'); } public function testNoCurrencyReturnedIfCurrencyNotSet() { $this->assertNull($this->request->getCurrencyNumeric()); } public function testSend() { $response = m::mock('\Omnipay\Common\Message\ResponseInterface'); $data = array('request data'); $this->request->shouldReceive('getData')->once()->andReturn($data); $this->request->shouldReceive('sendData')->once()->with($data)->andReturn($response); $this->assertSame($response, $this->request->send()); } /** * @expectedException \Omnipay\Common\Exception\RuntimeException * @expectedExceptionMessage You must call send() before accessing the Response! */ public function testGetResponseBeforeRequestSent() { $this->request = new AbstractRequestTest_MockAbstractRequest($this->getHttpClient(), $this->getHttpRequest()); $this->request->getResponse(); } public function testGetResponseAfterRequestSent() { $this->request = new AbstractRequestTest_MockAbstractRequest($this->getHttpClient(), $this->getHttpRequest()); $this->request->send(); $response = $this->request->getResponse(); $this->assertInstanceOf('\Omnipay\Common\Message\ResponseInterface', $response); } } class AbstractRequestTest_MockAbstractRequest extends AbstractRequest { public function getData() {} public function sendData($data) { $this->response = m::mock('\Omnipay\Common\Message\AbstractResponse'); } }
{ "content_hash": "8aeac372c2b79fe4599e5d766cd1569f", "timestamp": "", "source": "github", "line_count": 507, "max_line_length": 118, "avg_line_length": 33.65680473372781, "alnum_prop": 0.6302742616033755, "repo_name": "xola/omnipay-common", "id": "f4d751b301d4d995c9f5a52699b67cfbe7056d30", "size": "17064", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Omnipay/Common/Message/AbstractRequestTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "165843" } ], "symlink_target": "" }
@interface BHCollectionViewController : UICollectionViewController <UICollectionViewDataSource, UICollectionViewDelegate> @end
{ "content_hash": "5dd5c14a20e81bc96dd9e66b18d458f5", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 121, "avg_line_length": 42.666666666666664, "alnum_prop": 0.890625, "repo_name": "Akhrameev/LinkingProverbs", "id": "638de8e4a17fcafb8a69b1fb0e43c3359c45fc78", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LinkedProverbs/CollectionView/BHCollectionViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "299" }, { "name": "Objective-C", "bytes": "65299" }, { "name": "Ruby", "bytes": "80" } ], "symlink_target": "" }
import React, { Component } from 'react' import { Icon } from 'semantic-ui-react' class Logo extends Component { render () { return ( <div><Icon name='checked calendar' /> EachDay</div> ) } } export default Logo
{ "content_hash": "facb83bcb49ea11da5f1f01c628501f0", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 57, "avg_line_length": 19.333333333333332, "alnum_prop": 0.6379310344827587, "repo_name": "bcongdon/EachDay", "id": "02e80a314ca22bce9db484b1d48285c0056a7e16", "size": "232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/Logo.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "517" }, { "name": "HTML", "bytes": "489" }, { "name": "JavaScript", "bytes": "87297" }, { "name": "Mako", "bytes": "494" }, { "name": "Python", "bytes": "51507" }, { "name": "Shell", "bytes": "92" } ], "symlink_target": "" }
void pcap_data_handler( u_char *args, const struct pcap_pkthdr *header, const u_char *packet ) { return; }
{ "content_hash": "c33241a8786491ef63a88b91e87822f5", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 35, "avg_line_length": 16.428571428571427, "alnum_prop": 0.6695652173913044, "repo_name": "hagosan8547/tcpdump-data", "id": "4a5fc2de5d9f72252b721def62881f97d578ec01", "size": "142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pcap_data_handler.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "11553" }, { "name": "Makefile", "bytes": "872" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace iTunesSearch.Library.Models { [DataContract] public class Album { [DataMember(Name = "artistId")] public long ArtistId { get; set; } [DataMember(Name = "collectionId")] public long CollectionId { get; set; } [DataMember(Name = "amgArtistId")] public long AMGArtistId { get; set; } [DataMember(Name = "artistName")] public string ArtistName { get; set; } [DataMember(Name = "collectionName")] public string CollectionName { get; set; } [DataMember(Name = "collectionCensoredName")] public string CollectionCensoredName { get; set; } [DataMember(Name = "artistViewUrl")] public string ArtistViewUrl { get; set; } [DataMember(Name = "collectionViewUrl")] public string CollectionViewUrl { get; set; } [DataMember(Name = "artworkUrl60")] public string ArtworkUrl60 { get; set; } [DataMember(Name = "artworkUrl100")] public string ArtworkUrl100 { get; set; } [DataMember(Name = "collectionPrice")] public double CollectionPrice { get; set; } [DataMember(Name = "releaseDate")] public string ReleaseDate { get; set; } [DataMember(Name = "collectionExplicitness")] public string CollectionExplicitness { get; set; } [DataMember(Name = "trackCount")] public int TrackCount { get; set; } [DataMember(Name = "country")] public string Country { get; set; } [DataMember(Name = "currency")] public string Currency { get; set; } [DataMember(Name = "primaryGenreName")] public string PrimaryGenreName { get; set; } [DataMember(Name = "copyright")] public string Copyright { get; set; } } }
{ "content_hash": "da200771907b69d55ab9cff93f74af27", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 58, "avg_line_length": 29.253731343283583, "alnum_prop": 0.6198979591836735, "repo_name": "danesparza/iTunesSearch", "id": "19043c34d53c8571fada6ca6961b8cde6d356117", "size": "1962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iTunesSearch.Library/Models/Album.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "71058" } ], "symlink_target": "" }
class ModifyProviderAccountsForNewMessageSubsystem < ActiveRecord::Migration def self.up remove_column :provider_accounts, :msg_server_uri rescue nil remove_column :provider_accounts, :in_queue remove_column :provider_accounts, :out_queue remove_column :provider_accounts, :msg_access_key remove_column :provider_accounts, :msg_secret_key remove_column :provider_accounts, :msg_account_id add_column :provider_accounts, :messaging_uri, :string, :default => '', :null => false add_column :provider_accounts, :messaging_username, :string, :default => '', :null => false add_column :provider_accounts, :messaging_password, :string, :default => '', :null => false add_column :provider_accounts, :messaging_startup, :string, :default => 'startup', :null => false add_column :provider_accounts, :messaging_shutdown, :string, :default => 'shutdown', :null => false add_column :provider_accounts, :messaging_info, :string, :default => 'info', :null => false add_column :provider_accounts, :messaging_request, :string, :default => 'request', :null => false add_column :provider_accounts, :messaging_control, :string, :default => 'control', :null => false end def self.down remove_column :provider_accounts, :messaging_uri remove_column :provider_accounts, :messaging_username remove_column :provider_accounts, :messaging_password remove_column :provider_accounts, :messaging_startup remove_column :provider_accounts, :messaging_shutdown remove_column :provider_accounts, :messaging_info remove_column :provider_accounts, :messaging_request remove_column :provider_accounts, :messaging_control add_column :provider_accounts, :in_queue, :string, :default => '', :null => false add_column :provider_accounts, :out_queue, :string, :default => '', :null => false add_column :provider_accounts, :msg_access_key, :string, :default => '', :null => false add_column :provider_accounts, :msg_secret_key, :string, :default => '', :null => false add_column :provider_accounts, :msg_account_id, :string, :default => '', :null => false end end
{ "content_hash": "0bcd4f7e01ad4643358082e3824b3b01", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 103, "avg_line_length": 60.94444444444444, "alnum_prop": 0.6864175022789426, "repo_name": "vadimj/nimbul", "id": "09f82f9c547a1e551110e464172186f6e10fe195", "size": "2194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20100515055310_modify_provider_accounts_for_new_message_subsystem.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "30043" }, { "name": "Ruby", "bytes": "1150171" }, { "name": "Shell", "bytes": "3233" } ], "symlink_target": "" }