text
stringlengths 2
1.04M
| meta
dict |
---|---|
sudo yum update -y
sudo yum install -y vim tree
sudo systemctl disable firewalld
sudo systemctl stop firewalld
sudo systemctl disable NetworkManager
sudo systemctl stop NetworkManager
sudo systemctl enable network
sudo systemctl start network
sudo yum -y install epel-release
sudo curl -L -o /etc/yum.repos.d/delorean.repo http://buildlogs.centos.org/centos/7/cloud/x86_64/rdo-trunk-master-tripleo/delorean.repo
sudo curl -L -o /etc/yum.repos.d/delorean-deps.repo http://trunk.rdoproject.org/centos7/delorean-deps.repo
# sudo curl -L -o /etc/yum.repos.d/delorean-current.repo http://trunk.rdoproject.org/centos7/current/delorean.repo
# sudo sed -i 's/\[delorean\]/\[delorean-current\]/' /etc/yum.repos.d/delorean-current.repo
# sudo curl -L -o /etc/yum.repos.d/delorean-deps.repo http://trunk.rdoproject.org/centos7/delorean-deps.repo
# sudo curl -L -o /etc/yum.repos.d/delorean-liberty.repo https://trunk.rdoproject.org/centos7-liberty/current/delorean.repo
# sudo curl -L -o /etc/yum.repos.d/delorean-deps-liberty.repo http://trunk.rdoproject.org/centos7-liberty/delorean-deps.repo
sudo yum -y install yum-plugin-priorities
sudo yum install -y python-tripleoclient
sudo cp /usr/share/instack-undercloud/undercloud.conf.sample ~/undercloud.conf
export DIB_INSTALLTYPE_puppet_modules=source
export USE_DELOREAN_TRUNK=1
export DELOREAN_TRUNK_REPO="http://buildlogs.centos.org/centos/7/cloud/x86_64/rdo-trunk-master-tripleo/"
export DELOREAN_REPO_FILE="delorean.repo"
openssl genrsa -out privkey.pem 2048
openssl req \
-new \
-x509 \
-key privkey.pem \
-days 365 \
-subj "/C=US/ST=Virginia/L=Springfield/O=Dis/CN=triple0.oooo2" \
-out cacert.pem
cat cacert.pem privkey.pem > undercloud.pem
sudo mkdir /etc/pki/instack-certs
sudo cp undercloud.pem /etc/pki/instack-certs
sudo semanage fcontext -a -t etc_t "/etc/pki/instack-certs(/.*)?"
sudo restorecon -R /etc/pki/instack-certs
sudo cp cacert.pem /etc/pki/ca-trust/source/anchors/
sudo update-ca-trust extract
openstack undercloud install
export USE_DELOREAN_TRUNK=1
export DELOREAN_TRUNK_REPO="http://buildlogs.centos.org/centos/7/cloud/x86_64/rdo-trunk-master-tripleo/"
export DELOREAN_REPO_FILE="delorean.repo"
openstack overcloud image build --all
openstack overcloud image upload
| {
"content_hash": "f3a1d200ae79af696ae98e14f93b2754",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 135,
"avg_line_length": 44.3921568627451,
"alnum_prop": 0.7756183745583038,
"repo_name": "lindison/tripleo_vagrant",
"id": "3efaa67802abcc3c96832120ace2c415735bb31d",
"size": "2264",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tripleO_env/scripts/install_latest_undercloud.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "32410"
},
{
"name": "Shell",
"bytes": "44441"
}
],
"symlink_target": ""
} |
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
.PHONY : .NOTPARALLEL
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/evelina/Downloads/eigen-eigen-b30b87236a1b
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target install
install: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install
# Special rule for the target install
install/fast: preinstall/fast
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install/fast
# Special rule for the target install/local
install/local: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
.PHONY : install/local
# Special rule for the target install/local
install/local/fast: install/local
.PHONY : install/local/fast
# Special rule for the target install/strip
install/strip: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..."
/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake
.PHONY : install/strip
# Special rule for the target install/strip
install/strip/fast: install/strip
.PHONY : install/strip/fast
# Special rule for the target list_install_components
list_install_components:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Devel\" \"Unspecified\""
.PHONY : list_install_components
# Special rule for the target list_install_components
list_install_components/fast: list_install_components
.PHONY : list_install_components/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target test
test:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..."
/usr/bin/ctest --force-new-ctest-process $(ARGS)
.PHONY : test
# Special rule for the target test
test/fast: test
.PHONY : test/fast
# The main all target
all: cmake_check_build_system
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build/CMakeFiles /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build/demos/CMakeFiles/progress.marks
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(MAKE) -f CMakeFiles/Makefile2 demos/all
$(CMAKE_COMMAND) -E cmake_progress_start /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(MAKE) -f CMakeFiles/Makefile2 demos/clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(MAKE) -f CMakeFiles/Makefile2 demos/preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(MAKE) -f CMakeFiles/Makefile2 demos/preinstall
.PHONY : preinstall/fast
# clear depends
depend:
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
# Convenience name for target.
demos/CMakeFiles/demos.dir/rule:
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(MAKE) -f CMakeFiles/Makefile2 demos/CMakeFiles/demos.dir/rule
.PHONY : demos/CMakeFiles/demos.dir/rule
# Convenience name for target.
demos: demos/CMakeFiles/demos.dir/rule
.PHONY : demos
# fast build rule for target.
demos/fast:
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(MAKE) -f demos/CMakeFiles/demos.dir/build.make demos/CMakeFiles/demos.dir/build
.PHONY : demos/fast
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... demos"
@echo "... edit_cache"
@echo "... install"
@echo "... install/local"
@echo "... install/strip"
@echo "... list_install_components"
@echo "... rebuild_cache"
@echo "... test"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
cd /home/evelina/Downloads/eigen-eigen-b30b87236a1b/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
| {
"content_hash": "1599bc029a35a45bf7de552a0ce01b63",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 255,
"avg_line_length": 34.38341968911917,
"alnum_prop": 0.7132308619650392,
"repo_name": "evelinad/eigen",
"id": "18071140fe30d9a8d4c9f661b05feb240bcfbf3f",
"size": "6798",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/demos/Makefile",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "181649"
},
{
"name": "C++",
"bytes": "5499590"
},
{
"name": "CMake",
"bytes": "1976576"
},
{
"name": "FORTRAN",
"bytes": "1459075"
},
{
"name": "HTML",
"bytes": "3589"
},
{
"name": "Makefile",
"bytes": "2720826"
},
{
"name": "Python",
"bytes": "8750"
},
{
"name": "Shell",
"bytes": "18938"
},
{
"name": "Tcl",
"bytes": "2588"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>YUI: Split Button on Hover</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/reset-fonts-grids/reset-fonts-grids.css">
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/assets/skins/sam/skin.css">
<link rel="stylesheet" href="http://blog.davglass.com/wp-content/themes/davglass/style.css" type="text/css">
<link rel="stylesheet" type="text/css" href="http://us.js2.yimg.com/us.js.yimg.com/i/ydn/yuiweb/css/dpsyntax-min-11.css">
<style type="text/css" media="screen">
p, h2 {
margin: 1em;
}
</style>
</head>
<body class="yui-skin-sam">
<div id="davdoc" class="yui-t7">
<div id="hd"><h1 id="header"><a href="http://blog.davglass.com/">YUI: Split Button on Hover</a></h1></div>
<div id="bd">
<input type="submit" id="splitbutton1" name="splitbutton1_button" value="Split Button 1">
<select id="splitbutton1select" name="splitbutton1select" multiple>
<option value="0">One</option>
<option value="1">Two</option>
<option value="2">Three</option>
</select>
<h2>The HTML</h2>
<textarea name="code" class="HTML">
<input type="submit" id="splitbutton1" name="splitbutton1_button" value="Split Button 1">
<select id="splitbutton1select" name="splitbutton1select" multiple>
<option value="0">One</option>
<option value="1">Two</option>
<option value="2">Three</option>
</select>
</textarea>
<h2>The Javascript</h2>
<textarea name="code" class="JScript">
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event;
var oSplitButton1 = new YAHOO.widget.Button("splitbutton1", {
type: "split",
menu: "splitbutton1select"
});
oSplitButton1.on('mouseover', function(ev) {
var tar = Event.getTarget(ev);
this._showMenu(ev);
});
})();
</textarea>
</div>
<div id="ft"> </div>
</div>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/utilities/utilities.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/container/container_core-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/menu/menu-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/button/button-min.js"></script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/i/ydn/yuiweb/js/dpsyntax-min-2.js"></script>
<script type="text/javascript" src="../js/toolseffects-min.js"></script>
<script type="text/javascript" src="../js/davglass.js"></script>
<script type="text/javascript">
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event;
var oSplitButton1 = new YAHOO.widget.Button("splitbutton1", {
type: "split",
menu: "splitbutton1select"
});
oSplitButton1.on('mouseover', function(ev) {
var tar = Event.getTarget(ev);
this._showMenu(ev);
});
dp.SyntaxHighlighter.HighlightAll('code');
})();
</script>
</body>
</html>
| {
"content_hash": "e36279f1dfa10e42f2de5af8ba86366f",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 128,
"avg_line_length": 40.20987654320987,
"alnum_prop": 0.6306416948111759,
"repo_name": "davglass/yui-examples",
"id": "84ebc837547c8af1224a9900a0061db526c6b442",
"size": "3257",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "button13/index.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "3246114"
},
{
"name": "PHP",
"bytes": "1692414"
},
{
"name": "Shell",
"bytes": "2077"
}
],
"symlink_target": ""
} |
Documentation
=============
- [Home](http://oo3d.richplastow.com/)
| {
"content_hash": "b1de18190b307e33cbd8e8903ab181f7",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 38,
"avg_line_length": 17,
"alnum_prop": 0.5735294117647058,
"repo_name": "richplastow/oo3d",
"id": "eec799b3d7ffcff5684dd6bb7105b645972f350c",
"size": "68",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "doc/00-documentation.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "231218"
},
{
"name": "HTML",
"bytes": "110835"
},
{
"name": "JavaScript",
"bytes": "13798"
}
],
"symlink_target": ""
} |
<?php
/**
* * Created by mtils on 01.01.2022 at 15:48.
**/
namespace Ems\Http\Psr;
use Ems\Core\Exceptions\UnsupportedParameterException;
use Ems\Core\Filesystem\FileStream;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
use function call_user_func;
use function move_uploaded_file;
use function php_sapi_name;
use const UPLOAD_ERR_OK;
class UploadedFile implements UploadedFileInterface
{
/**
* @var StreamInterface
*/
private $stream;
/**
* @var int
*/
private $error;
/**
* @var int
*/
private $size = -1;
/**
* @var string|null
*/
private $clientFilename = '';
/**
* @var string|null
*/
private $clientMediaType = '';
/**
* @var callable
*/
private $mover;
/**
* @var callable
*/
private static $defaultMover;
public function __construct(StreamInterface $stream, $size, int $error, string $clientFilename = null, string $clientMediaType=null)
{
$this->stream = $stream;
$this->size = $size;
$this->error = $error;
$this->clientFilename = $clientFilename;
$this->clientMediaType = $clientMediaType;
}
public function getStream() : StreamInterface
{
return $this->stream;
}
public function getSize()
{
return $this->size;
}
public function getError() : int
{
return $this->error;
}
public function getClientFilename()
{
return $this->clientFilename;
}
public function getClientMediaType()
{
return $this->clientMediaType;
}
/**
* To be honest...please do not use this method. For me, it makes no sense
* to have such a functionality in a value object. It will work to be compliant
* to psr but a custom filesystem should also be possible...
*
* @param $targetPath
* @return void
*/
public function moveTo($targetPath)
{
call_user_func($this->getMover(), $this, $targetPath);
}
/**
* @return callable
*/
public function getMover(): callable
{
if (!$this->mover) {
return self::getDefaultMover();
}
return $this->mover;
}
/**
* @param callable $mover
* @return UploadedFile
*/
public function setMover(callable $mover): UploadedFile
{
$this->mover = $mover;
return $this;
}
/**
* Get or create the default mover for all UploadedFileInstances
*
* @return callable
*/
public static function getDefaultMover() : callable
{
if (self::$defaultMover) {
return self::$defaultMover;
}
self::$defaultMover = function (UploadedFile $file, $targetPath) {
$stream = $file->getStream();
if (!$stream instanceof FileStream) {
throw new UnsupportedParameterException("The default implementation only works with FileStream");
}
if (php_sapi_name() === 'cli') {
rename((string)$stream->url(), $targetPath);
return;
}
move_uploaded_file((string)$stream->url(), $targetPath);
};
return self::$defaultMover;
}
/**
* Set the default mover for all created UploadedFile instances.
*
* @param callable $mover
* @return void
*/
public static function setDefaultMover(callable $mover)
{
self::$defaultMover = $mover;
}
protected function isError() : bool
{
return $this->error !== UPLOAD_ERR_OK;
}
} | {
"content_hash": "ce3d521357c80e1078b74af92894eece",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 136,
"avg_line_length": 21.797619047619047,
"alnum_prop": 0.5715456034953578,
"repo_name": "mtils/php-ems",
"id": "04bccb12602aea8a13a3f77772d08f25913da7e4",
"size": "3662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Ems/Http/Psr/UploadedFile.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "4490502"
},
{
"name": "Shell",
"bytes": "1138"
}
],
"symlink_target": ""
} |
<div class="container">
<div class="row">
<div class="col-12 text-center">
<button type="button" class="btn btn-default" ng-click="vm.newBot()">Add Bot</button>
</div>
</div>
<div class="spacer"></div>
<div id="bot-list" ui-sortable="vm.sortOpts" ng-model="vm.bots">
<div ng-repeat="bot in vm.bots" class="bot__row moveable" ng-class="{ 'collapsed': !bot.expanded }" data-bot-id="{{bot._id}}">
<div class="bot__collapse-expand clickable" ng-click="bot.expanded = !bot.expanded">
<i class="glyphicon glyphicon-minus" ng-show="bot.expanded"></i>
<i class="glyphicon glyphicon-plus" ng-hide="bot.expanded"></i>
</div>
<div class="bot__img-container">
<img class="bot__img" ng-src="{{bot.imageUrl}}" ng-show="bot.imageUrl" />
<button class="btn btn-sm btn-default" ng-hide="bot.isUser" data-toggle="modal" data-target="#edit-image-modal" ng-click="vm.editBotImage(bot)">{{bot.imageUrl ? 'Edit' : 'Add'}} Image</button>
</div>
<div class="bot__body">
<div class="row">
<div class="col-xs-9">
<form class="bot__title form-group" ng-submit="(editBotname = false) || vm.save(bot)">
<div ng-hide="editBotname">
<h3 ng-class="{ clickable: !bot.isUser }" ng-click="editBotname = !bot.isUser">{{bot.botname}}</h3>
</div>
<div ng-show="editBotname">
<input
class="form-control"
type="text"
name="botname" id="botname-input"
placeholder="Bot Name"
ng-model="bot.botname"
ng-blur="editBotname = false"
focus-on="editBotname"
/>
<input type="submit" ng-hide="true" />
</div>
</form>
</div>
<div class="col-xs-3 text-right">
<button
type="button"
class="btn btn-sm"
ng-hide="bot.isUser"
ng-class="{ 'btn-default': !deleteHover, 'btn-danger': deleteHover }"
ng-mouseenter="deleteHover = true"
ng-mouseleave="deleteHover = false"
ng-click="vm.delete(bot)">
<i class="glyphicon glyphicon-remove"></i>
</button>
<label ng-show="bot.isUser" class="bot__user-label">YOU</label>
</div>
</div>
<form ng-submit="vm.send(bot)" ng-show="bot.expanded">
<div class="row form-group">
<div class="col-xs-3">
<label>Post to</label>
<select class="form-control" name="type" id="type-select" ng-change="vm.save(bot)" ng-model="bot.type" ng-model-options="{ debounce: 500 }">
<option ng-repeat="type in ['User', 'Channel', 'Group']" value="{{type | lowercase}}">{{type}}</option>
</select>
</div>
<div class="col-xs-4" ng-show="bot.type == 'user'">
<label>Users</label>
<select
name="user" id="user-select"
class="form-control"
ng-model="bot.channel"
ng-change="vm.save(bot)"
ng-model-options="{ debounce: 500 }"
ng-options="user.id as user.name for user in vm.users">
</select>
</div>
<div class="col-xs-4" ng-show="bot.type == 'user'">
<label>Post to slackbot or IM?</label>
<label class="radio-inline">
<input
type="radio"
name="userChannel"
ng-checked="bot.postAsSlackbot"
ng-click="(bot.postAsSlackbot = true) || vm.save(bot)"
/>slackbot
</label>
<label class="radio-inline">
<input
type="radio"
name="userChannel"
ng-checked="!bot.postAsSlackbot"
ng-click="(bot.postAsSlackbot = false) || vm.save(bot)"
/>IM
</label>
</div>
<div class="col-xs-4" ng-show="bot.type == 'channel'">
<label>Channels</label>
<select
name="channel" id="channel-select"
class="form-control"
ng-model="bot.channel"
ng-change="vm.save(bot)"
ng-model-options="{ debounce: 500 }"
ng-options="channel.id as channel.name for channel in vm.channels">
</select>
</div>
<div class="col-xs-4" ng-show="bot.type == 'group'">
<label>Groups</label>
<select
name="group" id="group-select"
class="form-control"
ng-model="bot.channel"
ng-change="vm.save(bot)"
ng-model-options="{ debounce: 500 }"
ng-options="group.id as group.name for group in vm.groups">
</select>
</div>
</div>
<div class="row form-group">
<div class="col-xs-10">
<label>Message</label>
<input
class="form-control"
type="text"
name="message" id="message-input"
placeholder="Enter message here..."
ng-model="bot.message"
/>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<p class="clickable text-muted" ng-click="bot.attachments = {}" ng-hide="bot.attachments"><em>Add attachment</em></p>
<p class="clickable text-muted" ng-click="bot.attachments = null" ng-show="bot.attachments"><em>Remove attachment</em></p>
</div>
</div>
<div ng-show="bot.attachments">
<div class="row form-group">
<div class="col-xs-12">
<label>Image</label>
<div class="bot__attachment-img-container">
<img class="bot__img" ng-show="bot.attachments.imageUrl" ng-src="{{bot.attachments.imageUrl}}" />
</div>
</div>
<div class="col-xs-12">
<button type="button" class="btn btn-xs btn-default" data-toggle="modal" data-target="#edit-image-modal" ng-click="vm.editAttachmentImage(bot)">{{bot.attachments.imageUrl ? 'Edit' : 'Add'}} Image</button>
</div>
</div>
<div class="row form-group">
<div class="col-xs-6">
<label>Image Fallback</label>
<input
class="form-control"
type="text"
name="fallback" id="fallback-input"
placeholder="Image fallback text..."
ng-model="bot.attachments.fallback"
/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="edit-image-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span>×</span></button>
<h4 class="modal-title">Edit Image URL</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input
type="text"
name="imageUrl" id="image-url-input"
class="form-control"
placeholder="Image URL..."
ng-model="imageUrlValue "
/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal" ng-click="vm.modalSubmit()">Remove Image</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" data-dismiss="modal" ng-click="vm.modalSubmit(imageUrlValue)">Save</button>
</div>
</div>
</div>
</div>
| {
"content_hash": "9ca112c0b5d11845deae3c725dea6826",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 234,
"avg_line_length": 51.055837563451774,
"alnum_prop": 0.40326108570292307,
"repo_name": "gpanders/slackbots",
"id": "6f243c2849027f7e12c68efcc47193e82bd1a038",
"size": "10058",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/bots/bots.module.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3037"
},
{
"name": "HTML",
"bytes": "12352"
},
{
"name": "JavaScript",
"bytes": "52281"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>sum-of-two-square: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.0 / sum-of-two-square - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
sum-of-two-square
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-06-28 21:48:48 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-28 21:48:48 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/sum-of-two-square"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/SumOfTwoSquare"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: number theory" "category: Mathematics/Arithmetic and Number Theory/Number theory" "date: 2004-12-13" ]
authors: [ "Laurent Thery" ]
bug-reports: "https://github.com/coq-contribs/sum-of-two-square/issues"
dev-repo: "git+https://github.com/coq-contribs/sum-of-two-square.git"
synopsis: "Numbers equal to the sum of two square numbers"
description: """
A proof that a number n can be written as the
sum of two square numbers if and only if each prime factor p of n
that is equal to 3 modulo 4 has its exponent in the decomposition of n
that is even."""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/sum-of-two-square/archive/v8.6.0.tar.gz"
checksum: "md5=2f23a824697ab8c4d635f22f1cb42733"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-sum-of-two-square.8.6.0 coq.8.8.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0).
The following dependencies couldn't be met:
- coq-sum-of-two-square -> coq < 8.7~ -> ocaml < 4.02.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-sum-of-two-square.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "ddd800fd9de7ea0e18e94e31d4050e46",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 159,
"avg_line_length": 42.59649122807018,
"alnum_prop": 0.5490115321252059,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "8b1776c406c1d7d880617186fc85df2d3ffcb6b7",
"size": "7309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.8.0/sum-of-two-square/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
/**
* Xi
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled with this
* package in the file LICENSE.
*
* @category Xi
* @package Zend
* @license http://www.opensource.org/licenses/BSD-3-Clause New BSD License
*/
namespace Xi\Zend\Auth\Condition;
/**
* Authentication adapter condition for Doctrine 2+ ORM
*
* @category Xi
* @package Zend
* @subpackage Auth
* @author Mikko Hirvonen <[email protected]>
*/
class DoctrineORMCondition
{
/**
* @var string
*/
private $condition;
/**
* @var array
*/
private $parameters;
/**
* @param string $condition
* @param array $parameters
* @return DoctrineORMCondition
*/
public function __construct($condition, array $parameters)
{
$this->condition = $condition;
$this->parameters = $parameters;
}
/**
* @return string
*/
public function getCondition()
{
return $this->condition;
}
/**
* @return array
*/
public function getParameters()
{
return $this->parameters;
}
}
| {
"content_hash": "59f5acc55704369ece44e791973ced14",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 79,
"avg_line_length": 18.215384615384615,
"alnum_prop": 0.5743243243243243,
"repo_name": "xi-project/xi-zend",
"id": "b455f3536881f5a289eaf7b1200ac3254c583d86",
"size": "1184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/Xi/Zend/Auth/Condition/DoctrineORMCondition.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "14628"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "dcf1291e4da44f550f3cf27e83cbd78c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "4290d83bf1db21b11ac60395b2c48ab2b128730c",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Chenopodiaceae/Chenopodium/Chenopodium melanospermum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import { Component, OnInit } from '@angular/core';
import { UserService } from './../../../core/user/user.service';
@Component({
selector: 'paas-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
public user;
constructor(
private userService: UserService
) { }
ngOnInit() {
this.user = this.userService.user;
}
}
| {
"content_hash": "9e03ba1228a0a890c27b3a393593d1ee",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 64,
"avg_line_length": 21.5,
"alnum_prop": 0.6697674418604651,
"repo_name": "GonikDaniel/pizza-PaaS",
"id": "1b4fa4f630c3efdaaf77d42581bbde2e010b7b8d",
"size": "430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/admin/layout/navbar/navbar.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "293179"
},
{
"name": "HTML",
"bytes": "48624"
},
{
"name": "JavaScript",
"bytes": "2119"
},
{
"name": "TypeScript",
"bytes": "84258"
}
],
"symlink_target": ""
} |
#ifndef NEK_TYPE_TRAITS_PROPAGATE_CV_HPP
#define NEK_TYPE_TRAITS_PROPAGATE_CV_HPP
namespace nek
{
template <class Source, class Destination>
struct propagate_cv
{
using type = Destination;
};
template <class Source, class Destination>
struct propagate_cv<Source const, Destination>
{
using type = Destination const;
};
template <class Source, class Destination>
struct propagate_cv<Source volatile, Destination>
{
using type = Destination volatile;
};
template <class Source, class Destination>
struct propagate_cv<Source const volatile, Destination>
{
using type = const volatile Destination;
};
template <class Source, class Destination>
using propagate_cv_t = typename propagate_cv<Source, Destination>::type;
}
#endif
| {
"content_hash": "9e99d82e40ab54bdc68be41d4b4d82ec",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 76,
"avg_line_length": 24.5,
"alnum_prop": 0.6794717887154862,
"repo_name": "nekko1119/nek",
"id": "02bd1ad1f04f76138757e9a1592a706a712d49ef",
"size": "835",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "nek/type_traits/propagate_cv.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "313297"
},
{
"name": "CMake",
"bytes": "5084"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>ajaxForm</title>
</head>
<body>
<div id="page-wrapper">
<a onclick="javascript:history.go(-1);" href1="../examples/index.html" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-arrow-left"></span></a>
<a href="https://github.com/tlianglstyle/JZUI/blob/master/src/app/Form/AjaxForm.html" class="btn btn-default btn-sm pull-right">查看源码</a>
<br><br>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default">
<div class="panel-heading"><b>Form</b>
</div>
<div class="panel-body">
<form id="form" method="post" data-submit=".btn-primary">
<div class="form-group"><label>姓名:</label>
<input name="username" placeholder="请输入姓名" data-rule-required="true" data-msg-required="姓名为必填项" type="text" class="form-control">
</div>
<div class="form-group"><label>输入密码:</label>
<input name="password" id="userinfo_password" placeholder="请输入密码" data-rule-required="true" data-msg-required="姓名为必填项" type="password" class="form-control">
</div>
<div class="form-group"><label>重复密码:</label>
<input name="confirm_password" equalto="#userinfo_password" data-msg-equalto="两次密码不一致" placeholder="请输入内容" data-rule-required="true" data-msg-required="姓名为必填项" type="password" class="form-control">
</div>
<div class="form-group"><label>性别:</label>
<input name="gender" placeholder="请输入性别" data-rule-required="true" data-msg-required="姓名为必填项" type="text" class="form-control">
</div>
<div class="form-group"><button type="submit" class="btn btn-primary">提交</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass : 'iradio_flat-green'
})
JZ.onWindowLoad(function () {
$('pre').addClass('prettyprint');
prettyPrint();
})
</script>
<script>
var form = JZ.Form({
//type:'form',
form:'#form',
url:'/mock/data.json',//TODO:更改为提交地址. 如:/user/addAction',
beginSubmit:function(_submit){
if(confirm('确认要提交吗?')){
return true;
}
},
success:function(data){
alert('已提交。');
},
error:function(data){
console.log(data);
}
});
//form.setUrl("");
</script>
</body>
</html>
| {
"content_hash": "e6b21020b75e2d1c6db21246d3759bbd",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 210,
"avg_line_length": 35.02739726027397,
"alnum_prop": 0.5815408682049277,
"repo_name": "tlianglstyle/JZUI_V2",
"id": "8ec6e6a5ed44dfe222df3df3281d2f87bcf74fbc",
"size": "2741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JZUI/dist/app/Form/AjaxForm.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "602548"
},
{
"name": "HTML",
"bytes": "1806017"
},
{
"name": "JavaScript",
"bytes": "2332461"
},
{
"name": "PHP",
"bytes": "622"
}
],
"symlink_target": ""
} |
@echo off
pushd %~dp0
"%VS120COMNTOOLS%..\IDE\mstest" /test:Microsoft.Protocols.TestSuites.MS_ASHTTP.S01_HTTPPOSTPositive.MSASHTTP_S01_TC11_CommandCode_FolderRelatedCommands /testcontainer:..\..\MS-ASHTTP\TestSuite\bin\Debug\MS-ASHTTP_TestSuite.dll /runconfig:..\..\MS-ASHTTP\MS-ASHTTP.testsettings /unique
pause | {
"content_hash": "f13e62526a8322465d6b5ec6d991ab4d",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 284,
"avg_line_length": 78,
"alnum_prop": 0.8012820512820513,
"repo_name": "OfficeDev/Interop-TestSuites",
"id": "f913d86fb0dcdc40d450816de24ad376e3488573",
"size": "312",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ExchangeActiveSync/Source/Scripts/MS-ASHTTP/RunMSASHTTP_S01_TC11_CommandCode_FolderRelatedCommands.cmd",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "1421"
},
{
"name": "Batchfile",
"bytes": "1161743"
},
{
"name": "C",
"bytes": "154398"
},
{
"name": "C#",
"bytes": "161425175"
},
{
"name": "C++",
"bytes": "26321"
},
{
"name": "PowerShell",
"bytes": "1514073"
}
],
"symlink_target": ""
} |
class Solution {
public:
int minMoves(vector<int>& nums) {
return accumulate(begin(nums), end(nums), 0L) - nums.size() * *min_element(begin(nums), end(nums));
}
}; | {
"content_hash": "07c58cd4b51ff606fe25db20ea070643",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 107,
"avg_line_length": 29.833333333333332,
"alnum_prop": 0.6201117318435754,
"repo_name": "pineal/Leetcode_OJ",
"id": "b26f1925301453344058a4003768af63305235af",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cpp/453_Minimum_Moves_To_Equal_Array_Elements.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "340666"
},
{
"name": "Go",
"bytes": "617"
},
{
"name": "Python",
"bytes": "8614"
}
],
"symlink_target": ""
} |
install-infra:
ansible-playbook site.yml
install-web:
cd web ; npm install ; npm start
create-docker-web:
./bin/run-monitord-ui.sh
create-docker-img:
./bin/make-ui.sh
push-docker-img:
./bin/push-monitord-ui.sh
build:
mvn clean install | {
"content_hash": "a6bee220383efdf052233abd09a62597",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 33,
"avg_line_length": 20,
"alnum_prop": 0.7416666666666667,
"repo_name": "BZCareer/monitor.d",
"id": "3adb7abd78ca2ee80b5832fd397fa3895d40a1f6",
"size": "308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "Java",
"bytes": "107699"
},
{
"name": "Makefile",
"bytes": "308"
},
{
"name": "Shell",
"bytes": "11233"
}
],
"symlink_target": ""
} |
import React from 'react'
import Intro from '../views/syllabus/Intro' // 0
import Nound from '../views/syllabus/Nound'
import Definiteness from '../views/syllabus/Definiteness'
import Phrase from '../views/syllabus/Phrase'
import NounPhrase from '../views/syllabus/NounPhrase'
import Adjectivd from '../views/syllabus/Adjectivd' // 5
import NPAdjective from '../views/syllabus/NPAdjective'
import Verbd from '../views/syllabus/Verbd'
import VerbConjugation from '../views/syllabus/VerbConjugation'
import PastForm from '../views/syllabus/PastForm'
import VerbTime from '../views/syllabus/VerbTime' // 10
import VerbPhrase from '../views/syllabus/VerbPhrase'
import Clause from '../views/syllabus/Clause'
import Adverbd from '../views/syllabus/Adverbd'
import Prepositiond from '../views/syllabus/Prepositiond'
import Determinerd from '../views/syllabus/Determinerd'
import Conjunctiond from '../views/syllabus/Conjunctiond'
import Pronound from '../views/syllabus/Pronound'
//import Aspect from '../views/syllabus/Aspect'
//import Sentence from '../views/syllabus/Sentence'
//import Pluralization from '../views/syllabus/Pluralization'
//import VPAspect from '../views/syllabus/VPAspect'
/**
* We have a series of lessons that we want to progress through, in both directions, in a specific order.
*
* We also want to determine a "level". That is, level 0 for the first lesson, level 1 for
* the next lesson, and so on.
*
* We don't want to use a giant switch statement based on a numerical level.
*
* We want to be able to determine if we are presently at the first or last level. This
* affects the lesson navigation UI.
*
* The basic choice is to figure out how to iterate, bi-directionally over some simple data structure
* or to use a more slightly more complicated structure to implement a doubly-linked list. I first attempted choice
* the prior but got bogged down in code that was way too complicated for this simple and limited
* application. Hence my present doubly-linked list approach.
*
*/
// If you change these lessons be sure to review the initialState in AppStore
/*const syllabus = {
intro: {level: 0, comp:Intro, prev:null, next:'nound'},
nound: {level: 1, comp:Nound, prev:'intro', next:'definiteness'},
definiteness: {level: 2, comp:Definiteness, prev:'nound', next:'phrase'},
phrase: {level: 3, comp:Phrase, prev:'definiteness', next:'np'},
np: {level: 4, comp:NounPhrase, prev:'phrase', next:'adjectivd'},
adjectivd: {level: 5, comp:Adjectivd, prev:'np', next:'npAdjective'},
npAdjective: {level: 6, comp:NPAdjective, prev:'adjectivd', next:'verbd'},
verbd: {level: 7, comp:Verbd, prev:'npAdjective', next:'verbConjugation'},
verbConjugation: {level: 8, comp:VerbConjugation, prev:'verbd', next:'pastForm'},
pastForm: {level: 9, comp:PastForm, prev:'verbConjugation', next:'verbTime'},
verbTime: {level:10, comp:VerbTime, prev:'pastForm', next:'vp'},
vp: {level:11, comp:VerbPhrase, prev:'verbTime', next:'clause'},
clause: {level:12, comp:Clause, prev:'vp', next:'adverbd'},
adverbd: {level:13, comp:Adverbd, prev:'clause', next:'prepositiond'},
prepositiond: {level:14, comp:Prepositiond, prev:'adverbd', next:null},
//aspect: {level:12, comp:Aspect, prev:'verbPhrase', next:'clause'},
//sentence: {level:14, comp:Sentence, prev:'clause', next:'pluralization'},
//pluralization: {level:15, comp:Pluralization, prev:'sentence', next:'vpAspect'},
//vpAspect: {level:16, comp:VPAspect, prev:'pluralization', next: null}
// Adverbs as part of verb phrases
}*/
const syllabus = {
intro: {level: 0, comp: Intro, prev: null, next: 'adjectivd'},
adjectivd: {level: 1, comp: Adjectivd, prev: 'intro', next: 'adverbd'},
adverbd: {level: 2, comp: Adverbd, prev: 'adjectivd', next: 'conjunctiond'},
conjunctiond: {level: 3, comp: Conjunctiond, prev: 'adverbd', next: 'determinerd'},
determinerd: {level: 4, comp: Determinerd, prev: 'conjunctiond', next: 'nound'},
nound: {level: 5, comp: Nound, prev: 'determinerd', next: 'prepositiond'},
prepositiond: {level: 6, comp: Prepositiond, prev: 'nound', next: 'pronound'},
pronound: {level: 7, comp: Pronound, prev: 'prepositiond', next: 'verbd'},
verbd: {level: 8, comp: Verbd, prev: 'pronound', next: null}
}
export default syllabus
| {
"content_hash": "c23a43a6e8c6be36fefaaa456e1bf89c",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 116,
"avg_line_length": 59.666666666666664,
"alnum_prop": 0.613926576217079,
"repo_name": "bostontrader/senmaker",
"id": "668dd179ef868ca4e7d3a1fad4c85475a3ebeb8f",
"size": "5012",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/data/Syllabus.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20850"
},
{
"name": "HTML",
"bytes": "500"
},
{
"name": "JavaScript",
"bytes": "657619"
}
],
"symlink_target": ""
} |
<?php namespace App\Ooglee\Application\Listeners;
use Illuminate\Database\Eloquent\Model;
use App\Ooglee\Domain\Contracts\IHandler;
use App\Ooglee\Domain\Entities\User
class SendWelcomeMailListener implements IListener {
/**
* SendWelcomeMailListener implementation
*
*/
/**
* @var Ooglee\Infrastructure\Mailers\IMailer $mailer
*/
private $mailer
/**
* Create a new SendWelcomeEmailListener listener
*
* @param Mailer $mailer
* @return void
*/
public function __construct(IMailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Handle the Event
*
* @param Event $event
* @return void
*/
public function listenerHandle(IEvent $event)
{
$data = [];
$data['view'] = 'emails.welcome';
$data['user'] = $event->user;
$this->mailer->send($data);
}
}
| {
"content_hash": "57425476230f1429c4244b71b35bd831",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 57,
"avg_line_length": 19.32608695652174,
"alnum_prop": 0.6062992125984252,
"repo_name": "RowlandOti/ooglee-usersmodule",
"id": "aea5d494ffa740cb89b35a88a74b154db378e831",
"size": "889",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/OoGlee/Application/Entities/User/Listeners/SendWelcomeMailListener.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "17700"
}
],
"symlink_target": ""
} |
var mongoose = require('mongoose');
var badgeSchema = new mongoose.Schema({
author: 'string',
title: 'string',
consumerKey: 'string',
consumerSecret: 'string',
content: Object,
date: {
type: Date,
default: Date.now
}
});
var userSchema = new mongoose.Schema({
id: 'string',
name: 'string',
imageUrl: 'string',
role: {
type: 'string',
default: 'user' // 'user', 'author' or 'admin'
},
accessTokens: 'mixed', // { <consumerKey>: <accessToken> }
date: {
type: Date,
default: Date.now
}
});
module.exports.init = function (connection) {
module.exports.Badge = connection.model('Badge', badgeSchema);
module.exports.User = connection.model('User', userSchema);
};
| {
"content_hash": "bec054d93e264ebc97020b9b36791eef",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 64,
"avg_line_length": 21.818181818181817,
"alnum_prop": 0.6319444444444444,
"repo_name": "vjrantal/badge-builder",
"id": "1dd197d9602af8a03b4fb1e9706aa49250d90dc8",
"size": "720",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/models/models.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "22006"
},
{
"name": "HTML",
"bytes": "158206"
},
{
"name": "JavaScript",
"bytes": "34407"
},
{
"name": "Shell",
"bytes": "511"
}
],
"symlink_target": ""
} |
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] init];
self.window.frame = [UIScreen mainScreen].bounds;
WBAccount *account = [WBAccountTool account];
if (account) {
[self.window switchRootViewController];
} else {
self.window.rootViewController = [[OAuthViewController alloc] init];
}
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.nyu.xiangyu.Weibo" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Weibo" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Weibo.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
@end
| {
"content_hash": "5a33218ad5e51d51271eb251f99d6105",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 281,
"avg_line_length": 48.030534351145036,
"alnum_prop": 0.7428480610298792,
"repo_name": "Vincent250/My-Weibo-Simulation-Project",
"id": "7d092d06675d7208f91dd6a3cd46070c13b53831",
"size": "6604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Weibo/Weibo/AppDelegate.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "732493"
}
],
"symlink_target": ""
} |
package nl.it.fixx.moknj.repository;
import nl.it.fixx.moknj.domain.core.field.FieldDetail;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface FieldDetailRepository extends MongoRepository<FieldDetail, String> {
}
| {
"content_hash": "e7d5e8da3e47bc1bfc3ad76986c932d9",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 85,
"avg_line_length": 31.3,
"alnum_prop": 0.8434504792332268,
"repo_name": "fixxit/MoknJ",
"id": "645c0cc0ecde77a535ea0050e9629f5247b48096",
"size": "313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/nl/it/fixx/moknj/repository/FieldDetailRepository.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "333693"
}
],
"symlink_target": ""
} |
<#
This script will check to see if there are prereqs and set the flag to deploy them
#>
param(
$sampleFolder = $ENV:SAMPLE_FOLDER,
$prereqTemplateFilenameBicep = $ENV:PREREQ_TEMPLATE_FILENAME_BICEP,
$prereqTemplateFilenameJson = $ENV:PREREQ_TEMPLATE_FILENAME_JSON
)
# checks to see if there are prereqs that need to be deployed and sets the env variable to trigger prereq tasks
$deployPrereqs = Test-Path "$sampleFolder\prereqs\"
Write-Host "##vso[task.setvariable variable=deploy.prereqs]$deployPrereqs"
# Check for a bicep prereq.
$bicepPrereqTemplateFullPath = "$sampleFolder\prereqs\$prereqTemplateFilenameBicep"
$jsonPrereqTemplateFullPath = "$sampleFolder\prereqs\$prereqTemplateFilenameJson"
# if there is a bicep file use it
if(Test-Path -Path $bicepPrereqTemplateFullPath){
$prereqTemplateFullPath = $bicepPrereqTemplateFullPath
}else{
$prereqTemplateFullPath = $jsonPrereqTemplateFullPath
}
Write-Output "Using prereq template: $prereqTemplateFullPath"
if ($deployPrereqs) {
Write-Host "##vso[task.setvariable variable=prereq.template.fullpath]$prereqTemplateFullPath"
}
| {
"content_hash": "54f83b0e3c85f07712926e47dae33784",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 111,
"avg_line_length": 36.03225806451613,
"alnum_prop": 0.7842435094001791,
"repo_name": "nzthiago/azure-quickstart-templates",
"id": "34f1bca845cc140432f9919f5b1ed93e10cefa01",
"size": "1118",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/ci-scripts/Check-Prereqs.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "852"
},
{
"name": "Bicep",
"bytes": "1270200"
},
{
"name": "C#",
"bytes": "13071"
},
{
"name": "CSS",
"bytes": "8505"
},
{
"name": "Dockerfile",
"bytes": "186"
},
{
"name": "Groovy",
"bytes": "1715"
},
{
"name": "HCL",
"bytes": "7632"
},
{
"name": "HTML",
"bytes": "5143"
},
{
"name": "HiveQL",
"bytes": "613"
},
{
"name": "Java",
"bytes": "6880"
},
{
"name": "JavaScript",
"bytes": "1067401"
},
{
"name": "PowerShell",
"bytes": "1185509"
},
{
"name": "Python",
"bytes": "27862"
},
{
"name": "Shell",
"bytes": "1231883"
},
{
"name": "Solidity",
"bytes": "247"
},
{
"name": "TSQL",
"bytes": "66"
},
{
"name": "XSLT",
"bytes": "4429"
}
],
"symlink_target": ""
} |
<?php
namespace Sonata\MediaBundle\Tests\Command;
use Sonata\ClassificationBundle\Model\CategoryManagerInterface;
use Sonata\ClassificationBundle\Model\ContextManagerInterface;
use Sonata\MediaBundle\Command\FixMediaContextCommand;
use Sonata\MediaBundle\Provider\Pool;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Console\Tests\Command\CommandTest;
class FixMediaContextCommandTest extends CommandTest
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject|ContainerInterface
*/
protected $container;
/**
* @var Application
*/
protected $application;
/**
* @var ContainerAwareCommand
*/
protected $command;
/**
* @var CommandTester
*/
protected $tester;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|Pool
*/
private $pool;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|ContextManagerInterface
*/
private $contextManger;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|CategoryManagerInterface
*/
private $categoryManger;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$this->command = new FixMediaContextCommand();
$this->command->setContainer($this->container);
$this->application = new Application();
$this->application->add($this->command);
$this->tester = new CommandTester($this->application->find('sonata:media:fix-media-context'));
$this->pool = $pool = $this->getMockBuilder('Sonata\MediaBundle\Provider\Pool')->disableOriginalConstructor()->getMock();
$this->contextManger = $contextManger = $this->getMock('Sonata\ClassificationBundle\Model\ContextManagerInterface');
$this->categoryManger = $categoryManger = $this->getMockBuilder('Sonata\ClassificationBundle\Entity\CategoryManager')->disableOriginalConstructor()->getMock();
$this->container->expects($this->any())
->method('get')
->will($this->returnCallback(function ($id) use ($pool, $contextManger, $categoryManger) {
switch ($id) {
case 'sonata.media.pool':
return $pool;
case 'sonata.classification.manager.context':
return $contextManger;
case 'sonata.classification.manager.category':
return $categoryManger;
}
return;
}));
}
public function testExecuteWithExisting()
{
$context = array(
'providers' => array(),
'formats' => array(),
'download' => array(),
);
$this->pool->expects($this->any())->method('getContexts')->will($this->returnValue(array('foo' => $context)));
$contextModel = $this->getMock('Sonata\ClassificationBundle\Model\ContextInterface');
$this->contextManger->expects($this->once())->method('findOneBy')->with($this->equalTo(array('id' => 'foo')))->will($this->returnValue($contextModel));
$category = $this->getMock('Sonata\ClassificationBundle\Model\CategoryInterface');
$this->categoryManger->expects($this->once())->method('getRootCategory')->with($this->equalTo($contextModel))->will($this->returnValue($category));
$output = $this->tester->execute(array('command' => $this->command->getName()));
$this->assertRegExp('@Done!@', $this->tester->getDisplay());
$this->assertSame(0, $output);
}
public function testExecuteWithEmptyRoot()
{
$context = array(
'providers' => array(),
'formats' => array(),
'download' => array(),
);
$this->pool->expects($this->any())->method('getContexts')->will($this->returnValue(array('foo' => $context)));
$contextModel = $this->getMock('Sonata\ClassificationBundle\Model\ContextInterface');
$this->contextManger->expects($this->once())->method('findOneBy')->with($this->equalTo(array('id' => 'foo')))->will($this->returnValue($contextModel));
$category = $this->getMock('Sonata\ClassificationBundle\Model\CategoryInterface');
$this->categoryManger->expects($this->once())->method('getRootCategory')->with($this->equalTo($contextModel))->will($this->returnValue(null));
$this->categoryManger->expects($this->once())->method('create')->will($this->returnValue($category));
$this->categoryManger->expects($this->once())->method('save')->with($this->equalTo($category));
$output = $this->tester->execute(array('command' => $this->command->getName()));
$this->assertRegExp('@ > default category for \'foo\' is missing, creating one\s+Done!@', $this->tester->getDisplay());
$this->assertSame(0, $output);
}
public function testExecuteWithNew()
{
$context = array(
'providers' => array(),
'formats' => array(),
'download' => array(),
);
$this->pool->expects($this->any())->method('getContexts')->will($this->returnValue(array('foo' => $context)));
$contextModel = $this->getMock('Sonata\ClassificationBundle\Model\ContextInterface');
$this->contextManger->expects($this->once())->method('findOneBy')->with($this->equalTo(array('id' => 'foo')))->will($this->returnValue(null));
$this->contextManger->expects($this->once())->method('create')->will($this->returnValue($contextModel));
$this->contextManger->expects($this->once())->method('save')->with($this->equalTo($contextModel));
$category = $this->getMock('Sonata\ClassificationBundle\Model\CategoryInterface');
$this->categoryManger->expects($this->once())->method('getRootCategory')->with($this->equalTo($contextModel))->will($this->returnValue(null));
$this->categoryManger->expects($this->once())->method('create')->will($this->returnValue($category));
$this->categoryManger->expects($this->once())->method('save')->with($this->equalTo($category));
$output = $this->tester->execute(array('command' => $this->command->getName()));
$this->assertRegExp('@ > default category for \'foo\' is missing, creating one\s+Done!@', $this->tester->getDisplay());
$this->assertSame(0, $output);
}
}
| {
"content_hash": "c5efe95ab6e1d8d8943e2b8103e4ea06",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 167,
"avg_line_length": 38.319526627218934,
"alnum_prop": 0.6266213712168005,
"repo_name": "Soullivaneuh/SonataMediaBundle",
"id": "7d290735c6b9e8816ea95c9b4253b4b2c127ba6d",
"size": "6723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tests/Command/FixMediaContextCommandTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5154"
},
{
"name": "HTML",
"bytes": "37294"
},
{
"name": "JavaScript",
"bytes": "10949"
},
{
"name": "Makefile",
"bytes": "5879"
},
{
"name": "PHP",
"bytes": "595710"
},
{
"name": "Python",
"bytes": "7893"
},
{
"name": "Shell",
"bytes": "2900"
}
],
"symlink_target": ""
} |
// Fill out your copyright notice in the Description page of Project Settings.
#include "Forge.h"
#include "MeleeCharacter.h"
#include "UsableActor.h"
#include "ForgePlayerController.h"
#include "AnimationDock.h" //*Base Çì´õ·Î °í·Á
#include "Kismet/KismetMathLibrary.h"
AMeleeCharacter::AMeleeCharacter(const FObjectInitializer& ObjectInitializer)
:Super(ObjectInitializer)
{
// Set size for player capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// Don't rotate character to camera direction
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction
GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f);
GetCharacterMovement()->bConstrainToPlane = true;
GetCharacterMovement()->bSnapToPlaneAtStart = true;
// GetCharacterMovement()->JumpZVelocity = 620;
GetCharacterMovement()->bCanWalkOffLedgesWhenCrouching = true;
GetCharacterMovement()->MaxWalkSpeedCrouched = 200;
GetCharacterMovement()->GetNavAgentPropertiesRef().bCanCrouch = true;
// Create a camera boom...
CameraBoomComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoomComp"));
CameraBoomComp->SetupAttachment(RootComponent);
CameraBoomComp->bAbsoluteRotation = true; // Don't want arm to rotate when character does
CameraBoomComp->TargetArmLength = 800.f;
CameraBoomComp->RelativeRotation = FRotator(-60.f, 0.f, 0.f);
CameraBoomComp->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level
// Create a camera...
CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));
CameraComp->SetupAttachment(CameraBoomComp, USpringArmComponent::SocketName);
CameraComp->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Add Cursor //
// Section //
// //
///////////////////
NoiseEmitterComp = CreateDefaultSubobject<UPawnNoiseEmitterComponent>(TEXT("NoiseEmitterComp"));
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
Health = 150.0f;
InteractionRange = 500.0f;
ComboNumber = 1;
}
void AMeleeCharacter::BeginPlay()
{
Super::BeginPlay();
if (!CamShaker)
{
GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Red, TEXT("CamShaker is Null"));
return;
}
}
void AMeleeCharacter::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
}
void AMeleeCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
Super::SetupPlayerInputComponent(InputComponent);
InputComponent->BindAxis("MoveForward", this, &AMeleeCharacter::MoveForward);
InputComponent->BindAxis("MoveRight", this, &AMeleeCharacter::MoveRight);
InputComponent->BindAction("Interaction", IE_Pressed, this, &AMeleeCharacter::Interaction);
InputComponent->BindAction("Attack/Rotate", IE_Pressed, this, &AMeleeCharacter::LeftMouseAction);
}
void AMeleeCharacter::InputReset()
{
//Stop
GetCharacterMovement()->StopMovementImmediately();
//CombatReset
// ³ªÁß¿¡ ÇÕÄ¡ÀÚ..
}
void AMeleeCharacter::MoveForward(float Val)
{
if (Controller && Val != 0.0f)
{
const bool bLimitRotation = (GetCharacterMovement()->IsMovingOnGround() || GetCharacterMovement()->IsFalling());
const FRotator Rotation = /*bLimitRotation ? GetActorRotation() :*/ Controller->GetControlRotation();
const FVector Direction = FRotationMatrix(Rotation).GetScaledAxis(EAxis::X);
AddMovementInput(Direction, Val);
}
}
void AMeleeCharacter::MoveRight(float Val)
{
if (Controller && Val != 0.0f)
{
const FRotator Rotation = /*GetActorRotation()*/ Controller->GetControlRotation();
const FVector Direction = FRotationMatrix(Rotation).GetScaledAxis(EAxis::Y);
AddMovementInput(Direction, Val);
}
}
void AMeleeCharacter::Interaction()
{
InputReset();
const FRotator Rotation = Controller->GetControlRotation();
const FVector Direction = FRotationMatrix(Rotation).GetScaledAxis(EAxis::X);
const FVector TraceStart = GetActorLocation();
const FVector TraceEnd = TraceStart + (Direction * 50.0f);
TArray<FHitResult> HitOuts = TraceSphere(TraceStart, TraceEnd, InteractionRange, this, ECollisionChannel::ECC_WorldDynamic);
AUsableActor* NearActor = nullptr;
float NearLength = 999.0f;
bool bNewInteractiveActor = false;
for (int32 index = 0; index != HitOuts.Num(); ++index)
{
AUsableActor* IActor = Cast<AUsableActor>(HitOuts[index].GetActor());
float Delta = FVector::Dist(TraceStart, IActor->GetActorLocation());
if (NearLength > Delta)
{
NearActor = IActor;
NearLength = Delta;
bNewInteractiveActor = true;
}
}
if (NearActor)
{
if (bNewInteractiveActor)
{
UNavigationSystem* const NavSys = GetWorld()->GetNavigationSystem();
if (NavSys)
{
NavSys->SimpleMoveToLocation(Controller, NearActor->GetActorLocation());
}
}
GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Yellow, NearActor->GetActorLocation().ToString());
GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Yellow, bNewInteractiveActor ? TEXT("true") : TEXT("false"));
}
else
{
GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Red, TEXT("NearActor Null!"));
}
}
void AMeleeCharacter::LeftMouseAction()
{
GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Green, TEXT("L.Click - Rotate"));
AForgePlayerController* PC = Cast<AForgePlayerController>(Controller);
FHitResult Hit;
PC->GetHitResultUnderCursor(ECC_Visibility, false, Hit);
const FRotator Rot = UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), Hit.Location);
const FRotator FixRot = FRotator(0.0f, Rot.Yaw, 0.0f);
SetActorRotation(FixRot);
if (PC)
{
if (PC->GetFocusedUsableActor())
{
GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Green, TEXT("L.Click - Attack"));
ComboAttack();
}
}
}
void AMeleeCharacter::SetCamShakeAmount(float NewAmount)
{
CamShakeAmount = NewAmount;
}
void AMeleeCharacter::CameraShaking()
{
if (CamShaker)
{
AForgePlayerController* PC = Cast<AForgePlayerController>(Controller);
if (PC)
{
PC->ClientPlayCameraShake(CamShaker, CamShakeAmount);
}
}
}
void AMeleeCharacter::ResetCombat()
{
Attacking = false;
ChainAttack = false;
ComboNumber = 1;
RegenOn();
}
void AMeleeCharacter::ComboAttack()
{
if (IsAlive())
{
RegenOff();
// bUseControllerRotationYaw = true;
if (IsAttacking())
{
ChainAttack = true;
}
else
{
Attacking = true;
SwordCombo();
}
}
}
void AMeleeCharacter::SwordCombo()
{
// ³ªÁß¿¡ Âɰ³ÀÚ.. ÀÏ´Ü ÇϵåÄÚµù
switch (ComboNumber)
{
case 1:
SetCurrentAnim(AnimDock->Attack01);
LaunchAmount = 600.0f;
SetCamShakeAmount(0.3f);
SetDamages(15.0f, 18.0f);
break;
case 2:
SetCurrentAnim(AnimDock->Attack02);
LaunchAmount = 1000.0f;
SetCamShakeAmount(0.4f);
SetDamages(15.0f, 18.0f);
break;
case 3:
SetCurrentAnim(AnimDock->Attack03);
LaunchAmount = 600.0f;
SetCamShakeAmount(0.7f);
SetDamages(15.0f, 18.0f);
break;
}
ComboNumber++;
PlayAnimMontage(CurrentAnim);
}
void AMeleeCharacter::ChainCombo()
{
if (ChainAttack)
{
ChainAttack = false;
SwordCombo();
}
}
float AMeleeCharacter::GetLastNoiseLoudness() const
{
return LastNoiseLoudness;
}
float AMeleeCharacter::GetLastMakeNoiseTime() const
{
return LastMakeNoiseTime;
}
void AMeleeCharacter::MakePawnNoise(float Loudness)
{
} | {
"content_hash": "13b3f4d7cb92f7c1f8b3d5ad67e79527",
"timestamp": "",
"source": "github",
"line_count": 298,
"max_line_length": 125,
"avg_line_length": 24.812080536912752,
"alnum_prop": 0.7372193670543684,
"repo_name": "Turtle-Corder/Forge",
"id": "d6fcb0e30e47593a48212ba2ef543f7ecfa93da2",
"size": "7394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Forge/Source/Forge/private/MeleeCharacter.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "213"
},
{
"name": "C#",
"bytes": "1267"
},
{
"name": "C++",
"bytes": "44719"
}
],
"symlink_target": ""
} |
//
// SkillViewController.m
// JianGuo
//
// Created by apple on 17/7/24.
// Copyright © 2017年 ningcol. All rights reserved.
//
#import "SkillViewController.h"
#import "SkillsDetailViewController.h"
#import "WebViewController.h"
#import "MineChatViewController.h"
#import "PostSkillViewController.h"
#import "RealNameNewViewController.h"
#import "JGHTTPClient+Skill.h"
#import "JGHTTPClient+Mine.h"
#import "JGHTTPClient+Home.h"
#import "MineIconCell.h"
#import "SkillsCell.h"
#import "SkillExpertCell.h"
#import "CityModel.h"
#import "SchoolModel.h"
#import "SkillListModel.h"
#import "ImagesModel.h"
#import "SkillExpertModel.h"
#import "SDCycleScrollView.h"
#import "DOPDropDownMenu.h"
#import "DismissingAnimator.h"
#import "PresentingAnimator.h"
@interface SkillViewController () <DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,SDCycleScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UICollectionViewDelegateFlowLayout,SkillExpertBoardDelegate,UIDynamicAnimatorDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIButton *confirmB;
/** 物理仿真器 */
@property (nonatomic,strong) UIDynamicAnimator *animator;
@property (weak, nonatomic) IBOutlet SDCycleScrollView *bannerView;
@property (nonatomic, strong) DOPDropDownMenu *selectMenu;
/** 数据源数组 */
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSMutableArray *cityArr;
@property (nonatomic,strong) NSMutableArray *schoolArr;
@property (nonatomic,strong) NSMutableArray *imagesScrollArr;
@property (nonatomic,strong) NSMutableArray *expertModelArr;
@property (nonatomic,copy) NSString *cityCode;
@property (nonatomic,copy) NSString *schoolId;
@property (nonatomic,strong) NSString *orderType;
@property (nonatomic,strong) NSString *sex;
@end
@implementation SkillViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self == [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
self.cityArr = JGKeyedUnarchiver(JGCityArr);
CityModel *model = self.cityArr.firstObject;
[JGHTTPClient searchSchoolByName:nil cityCode:model.code Success:^(id responseObject) {
[SVProgressHUD dismiss];
if ([responseObject[@"code"] integerValue] == 200) {
self.schoolArr = [SchoolModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
SchoolModel *school = [[SchoolModel alloc] init];
school.id = @"0";
school.name = @"全部学校";
[self.schoolArr insertObject:school atIndex:0];
[self.selectMenu reloadData];
}
} failure:^(NSError *error) {
SchoolModel *school = [[SchoolModel alloc] init];
school.id = @"0";
school.name = @"全部学校";
self.schoolArr = [NSMutableArray array];
[self.schoolArr insertObject:school atIndex:0];
[self.selectMenu reloadData];
[SVProgressHUD dismiss];
}];
// [NotificationCenter addObserver:self selector:@selector(clickNotification:) name:kNotificationClickNotification object:nil];
}
return self;
}
-(void)requestWithCount:(NSString *)count
{
JGSVPROGRESSLOAD(@"加载中...");
[JGHTTPClient getSkillListWithSchoolId:self.schoolId
cityCode:self.cityCode keywords:nil orderBy:self.orderType type:nil sex:self.sex tagId:nil userId:nil pageCount:count Success:^(id responseObject) {
[SVProgressHUD dismiss];
[self.tableView.mj_header endRefreshing];
[self.tableView.mj_footer endRefreshing];
JGLog(@"%@",responseObject);
if (count.integerValue>1) {//上拉加载
if ([[SkillListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]] count] == 0) {
[self showAlertViewWithText:@"没有更多数据" duration:1];
return ;
}
NSMutableArray *indexPaths = [NSMutableArray array];
for (SkillListModel *model in [SkillListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]]) {
[self.dataArr addObject:model];
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:self.dataArr.count-1 inSection:0];
[indexPaths addObject:indexPath];
}
[_tableView reloadData];
return;
}else{
self.dataArr = [SkillListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
}
} failure:^(NSError *error) {
[SVProgressHUD dismiss];
[self.tableView.mj_header endRefreshing];
[self.tableView.mj_footer endRefreshing];
[self showAlertViewWithText:NETERROETEXT duration:1];
}];
}
-(void)getSkillExperts
{
[JGHTTPClient getSkillExpertsListWithCityCode:self.cityCode Success:^(id responseObject) {
if ([responseObject[@"code"]integerValue] == 200) {
self.expertModelArr = [SkillExpertModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
} failure:^(NSError *error) {
}];
}
-(void)refreshBanner
{
[JGHTTPClient getImgsOfScrollviewWithCategory:@"3" Success:^(id responseObject) {
if (responseObject) {
if ([responseObject[@"code"] integerValue] == 200) {
NSMutableArray *images = [NSMutableArray array];
[[ImagesModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
ImagesModel *model = obj;
[images addObject:model.image];
}];
self.imagesScrollArr = [ImagesModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
self.bannerView.imageURLStringsGroup = images;
}
}
} failure:^(NSError *error) {
}];
}
- (IBAction)confirmSkillExpert:(UIButton *)sender {
if (![self checkExistPhoneNum]) {
[self gotoCodeVC];
return;
}
if (USER.status.intValue == 1){
[self showAlertViewWithText:@"请您先去实名认证" duration:1];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
RealNameNewViewController *realNameVC = [[RealNameNewViewController alloc] init];
realNameVC.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:realNameVC animated:YES];
});
return;
}
PostSkillViewController *postSkillVC = [[PostSkillViewController alloc] init];
postSkillVC.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:postSkillVC animated:YES];
// WebViewController *webVC = [[WebViewController alloc]init] ;
// webVC.url = @"https://jinshuju.net/f/BoMqQH";
// webVC.hidesBottomBarWhenPushed = YES;
// [self.navigationController pushViewController:webVC animated:YES];
}
-(void)clickPersonIcon:(id)model
{
SkillExpertModel *_model = model;
MineChatViewController *mineVC = [[MineChatViewController alloc] init];
mineVC.hidesBottomBarWhenPushed = YES;
mineVC.userId = [NSString stringWithFormat:@"%ld",_model.uid];
[self.navigationController pushViewController:mineVC animated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
// self.navigationItem.title = @"技能详情";
self.cityCode = @"0";
self.schoolId = @"0";
self.sex = @"0";
self.orderType = @"createTime";
self.tableView.backgroundColor = BACKCOLORGRAY;
[self initMenu];
[self configSDCycleView];
self.headerView.height = SCREEN_W*336/750+10;
self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
pageCount = 0;
NSString *title = [self.selectMenu titleForRowAtIndexPath:[DOPIndexPath indexPathWithCol:0 row:0]];
if (title.length==0) {
self.cityArr = JGKeyedUnarchiver(JGCityArr);
[self.selectMenu reloadData];
}
[self refreshBanner];
[self getSkillExperts];
[self requestWithCount:@"1"];
}];
self.tableView.mj_footer = ({
MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
pageCount = ((int)(self.dataArr.count-1)/10) + ((int)((self.dataArr.count-1)/10)>=1?1:2) + (((self.dataArr.count-1)%10)>0&&(self.dataArr.count-1)>10?1:0);
[self requestWithCount:[NSString stringWithFormat:@"%ld",pageCount]];
}];
footer;
});
[self.tableView.mj_header beginRefreshing];
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// [self addDynamicAnimator];
// });
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// self.confirmB.hidden = NO;
}
//配置筛选控件
-(void)initMenu{
self.selectMenu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:44];
self.selectMenu.delegate = self;
self.selectMenu.dataSource = self;
self.selectMenu.textSelectedColor = GreenColor;
if (SCREEN_W == 320) {
self.selectMenu.fontSize = 12;
}
}
-(void)configSDCycleView
{
self.bannerView.localizationImageNamesGroup = @[@"kobe",@"kobe",@"kobe"];
//设置pageControl位置
self.bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
self.bannerView.delegate = self;
// 自定义分页控件小圆标颜色
self.bannerView.currentPageDotColor = YELLOWCOLOR;
self.bannerView.pageDotColor = WHITECOLOR;
[self.bannerView setShowPageControl:YES];
self.bannerView.pageControlDotSize = CGSizeMake(100, 20);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
return 190;
}
else
return 335;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return section == 0?44:0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 0) {
return self.selectMenu;
}
return nil;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataArr.count+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
SkillExpertCell *cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([SkillExpertCell class]) owner:nil options:nil].lastObject;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.dataArr = self.expertModelArr;
cell.delegate = self;
return cell;
}
SkillsCell *cell = [SkillsCell cellWithTableView:tableView];
cell.model = self.dataArr[indexPath.row-1];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row>0) {
SkillListModel *model = self.dataArr[indexPath.row-1];
SkillsCell *cell = (SkillsCell *)[tableView cellForRowAtIndexPath:indexPath];
SkillsDetailViewController *detailVC = [[SkillsDetailViewController alloc] init];
detailVC.callBack = ^(NSInteger collectionStatus){
model.isFavourite = collectionStatus;
[cell.collectionB setBackgroundImage:[UIImage imageNamed:collectionStatus?@"heart":@"stars1"] forState:UIControlStateNormal];
};
detailVC.skillId = [NSString stringWithFormat:@"%ld",model.skillId];
detailVC.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:detailVC animated:YES];
}
}
#pragma mark DOPDropDownMenuDataSource (三方筛选控件代理方法)
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{//有几列
return 4;
}
- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{//哪一列有几行
if (column == 0) {
return self.cityArr.count;
}else if (column == 1){
return self.schoolArr.count;
}else if (column == 2){
return 3;
}else {
return 2;
}
}
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{//设置哪一列的哪一行 的名字
if (indexPath.column == 0) {
CityModel *model = self.cityArr[indexPath.row];
return model.cityName;
} else if (indexPath.column == 1){
SchoolModel *model = self.schoolArr[indexPath.row];
return model.name;
} else if (indexPath.column == 2){
NSArray *titleArr = @[@"不限男女",@"只看女",@"只看男 "];
return titleArr[indexPath.row];
} else {
NSArray *titleArr = @[@"最新",@"最热"];
return titleArr[indexPath.row];
}
}
#pragma mark - DOPDropDownMenuDelegate
- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{//选择第几行执行什么操作
if (indexPath.column == 0) {
CityModel *model = self.cityArr[indexPath.row];
self.cityCode = model.code;
self.schoolId = @"0";
[self getSchoolsByCityCode:model.code];
[self getSkillExperts];
[self.selectMenu selectIndexPath:[DOPIndexPath indexPathWithCol:1 row:0] triggerDelegate:NO];
[USERDEFAULTS setInteger:indexPath.row forKey:@"row"];
[USERDEFAULTS setInteger:indexPath.column forKey:@"column"];
} else if (indexPath.column == 1){
SchoolModel *school = self.schoolArr[indexPath.row];
self.schoolId = school.id;
} else if (indexPath.column == 2){
if (indexPath.row == 0) {
self.sex = @"0";//不限男女
}else if (indexPath.row == 1){
self.sex = @"1";//只看女
}else if (indexPath.row == 2){
self.sex = @"2";//只看男
}
} else if (indexPath.column == 3){
if (indexPath.row == 0) {
self.orderType = @"createTime";//最新
}else if (indexPath.row == 1){
self.orderType = @"viewCount";//最热
}
}
[self requestWithCount:@"1"];
}
-(void)getSchoolsByCityCode:(NSString *)cityCode
{
[JGHTTPClient searchSchoolByName:nil cityCode:cityCode Success:^(id responseObject) {
[SVProgressHUD dismiss];
if ([responseObject[@"code"] integerValue] == 200) {
self.schoolArr = [SchoolModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
SchoolModel *school = [[SchoolModel alloc] init];
school.id = @"0";
school.name = @"全部学校";
[self.schoolArr insertObject:school atIndex:0];
// [self.selectMenu reloadData];
}
} failure:^(NSError *error) {
[SVProgressHUD dismiss];
}];
}
#pragma mark - UIViewControllerTransitioningDelegate
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
presentingController:(UIViewController *)presenting
sourceController:(UIViewController *)source
{
PresentingAnimator *animator = [PresentingAnimator new];
animator.scale=1.3;
return animator;
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
return [DismissingAnimator new];
}
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
ImagesModel *model = self.imagesScrollArr[index];
WebViewController *webVC = [[WebViewController alloc] init];
webVC.hidesBottomBarWhenPushed = YES;
webVC.url = model.url;
[self.navigationController pushViewController:webVC animated:YES];
}
- (UIDynamicAnimator *)animator
{
if (!_animator) {
// 创建一个物理仿真器
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.navigationController.view];
_animator.delegate = self;
}
return _animator;
}
-(void)addDynamicAnimator
{
// 创建重力行为x
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] init];
// magnitude越大,速度增长越快
gravity.magnitude = 3;
[gravity addItem:self.confirmB];
// 2.创建碰撞行为
UICollisionBehavior *collision = [[UICollisionBehavior alloc] init];
[collision addItem:self.confirmB];
UIBezierPath *path = [UIBezierPath bezierPathWithRect:
CGRectMake(0,0, self.view.frame.size.width, self.navigationController.view.frame.size.height-49-30)];
[collision addBoundaryWithIdentifier:@"rect" forPath:path];
// 设置碰撞的边界
collision.translatesReferenceBoundsIntoBoundary = YES;
// 3.开始仿真
[self.animator addBehavior:gravity];
[self.animator addBehavior:collision];
}
- (void)dynamicAnimatorDidPause:(UIDynamicAnimator *)animator
{
[animator removeAllBehaviors];
}
@end
| {
"content_hash": "30c2cb7f830eea83a7df91297e1eef92",
"timestamp": "",
"source": "github",
"line_count": 535,
"max_line_length": 286,
"avg_line_length": 33.61869158878505,
"alnum_prop": 0.6467252307350161,
"repo_name": "xueqiulou/Jianguo",
"id": "05038e1eea8fdf357be2a903dce299a758da7fad",
"size": "18349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JianGuo/JianGuo/Home/Controller/SkillViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "37377"
},
{
"name": "C++",
"bytes": "54687"
},
{
"name": "HTML",
"bytes": "4555"
},
{
"name": "Objective-C",
"bytes": "6142119"
},
{
"name": "Objective-C++",
"bytes": "124423"
},
{
"name": "Ruby",
"bytes": "882"
},
{
"name": "Shell",
"bytes": "9276"
}
],
"symlink_target": ""
} |
package edu.berkeley.nlp.sequence.stationary;
import java.util.Arrays;
import edu.berkeley.nlp.math.DoubleArrays;
import edu.berkeley.nlp.sequence.SequenceModel;
import fig.basic.NumUtils;
public class StationaryForwardBackward {
boolean DEBUG = true;
int MAX_LENGTH ;
int numStates;
double[][] alphas;
double[][] betas;
StationarySequenceModel seqModel;
int obsLength;
double normConstant ;
double[][] nodePotentials;
double[] alphaScalingFactors;
double[] betaScalingFactors;
double[][] edgePosteriors;
double[][] nodePosteriors;
int[][] allowableForwardTransitions;
int[][] allowableBackwardTransitions;
private final double[][] edgeForwardPotentials;
private final double[][] edgeBackwardPotentials;
public StationaryForwardBackward(StationarySequenceModel seqModel) {
this.seqModel = seqModel;
numStates = seqModel.getNumStates();
MAX_LENGTH = seqModel.getMaximumSequenceLength();
alphas = new double[MAX_LENGTH][numStates];
betas = new double[MAX_LENGTH][numStates];
alphaScalingFactors = new double[MAX_LENGTH];
betaScalingFactors = new double[MAX_LENGTH];
nodePotentials = new double[MAX_LENGTH][numStates];
nodePosteriors = new double[MAX_LENGTH][numStates];
allowableForwardTransitions = seqModel.getAllowableForwardTransitions();
allowableBackwardTransitions = seqModel.getAllowableBackwardTransitions();
edgeForwardPotentials = seqModel.getForwardEdgePotentials();
edgeBackwardPotentials = seqModel.getBackwardEdgePotentials();
edgePosteriors = new double[numStates][];
for (int s=0; s < numStates; ++s) {
edgePosteriors[s] = new double[allowableForwardTransitions[s].length];
}
}
public void setInput(StationarySequenceInstance seqInstance) {
setInput(seqInstance,false);
}
public void setInput(StationarySequenceInstance seqInstance, boolean viterbi) {
assert seqInstance.getSequenceLength() < seqModel.getMaximumSequenceLength();
this.obsLength = seqInstance.getSequenceLength();
this.normConstant = 0.0;
clearArrays();
seqInstance.fillNodePotentials(nodePotentials);
forwardPass();
if (!viterbi) {
backwardPass();
computePosteriors();
}
}
private void clearArrays() {
for (int i=0; i < obsLength; ++i) {
Arrays.fill(nodePotentials[i],0.0);
Arrays.fill(nodePosteriors[i],0.0);
}
for (int i=0; i < numStates; ++i) {
Arrays.fill(edgePosteriors[i],0.0);
}
Arrays.fill(alphaScalingFactors,0.0);
Arrays.fill(betaScalingFactors,0.0);
}
// SCALING
public static final double SCALE = Math.exp(100);
public static final double LOG_SCALE = Math.log(SCALE);
// Note: e^709 is the largest double java can handle.
private static double getScaleFactor(double logScale) {
if (logScale == 0.0) return 1.0;
if (logScale == 1.0) return SCALE;
if (logScale == 2.0) return SCALE * SCALE;
if (logScale == 3.0) return SCALE * SCALE * SCALE;
if (logScale == -1.0) return 1.0 / SCALE;
if (logScale == -2.0) return 1.0 / SCALE / SCALE;
if (logScale == -3.0) return 1.0 / SCALE / SCALE / SCALE;
return Math.pow(SCALE, logScale);
}
public double getLogNormalizationConstant() {
return normConstant;
}
public double[][] getNodeMarginals() {
return nodePosteriors;
}
public double[][] getEdgeMarginalSums() {
return edgePosteriors;
}
public int[] viterbiDecode() {
int[][] backPointers = new int[obsLength][numStates];
for (int pos=1; pos < obsLength; ++pos) {
for (int state=0; state < numStates; ++state) {
int argMax = -1;
double max = Double.NEGATIVE_INFINITY;
int[] beforeStates = allowableBackwardTransitions[state];
for (int beforeStateIndex=0; beforeStateIndex < beforeStates.length; ++beforeStateIndex) {
int beforeState = beforeStates[beforeStateIndex];
double delta = alphas[pos-1][beforeState] * edgeBackwardPotentials[state][beforeStateIndex] * nodePotentials[pos][state];
if (delta > max) {
argMax = beforeState;
max = delta;
}
}
backPointers[pos][state] = argMax;
}
}
int[] path = new int[obsLength];
path[obsLength-1] = DoubleArrays.argMax(alphas[obsLength-1]);
for (int i=obsLength-2; i >= 0; --i) {
path[i] = backPointers[i+1][path[i+1]];
}
return path;
}
public int[] nodePosteriorDecode() {
int[] path = new int[obsLength];
for (int i=0; i < obsLength; ++i) {
path[i] = DoubleArrays.argMax(nodePosteriors[i]);
}
return path;
}
private void forwardPass() {
for (int pos=0; pos < obsLength; ++pos) {
double max = Double.NEGATIVE_INFINITY;
if (pos==0) {
for (int state=0; state < numStates; ++state) {
alphas[pos][state] = nodePotentials[pos][state];
if (alphas[pos][state] > max) max = alphas[pos][state];
}
} else {
for (int state=0; state < numStates; ++state) {
double alpha = 0.0;
if (nodePotentials[pos][state] > 0) {
int[] beforeStates = allowableBackwardTransitions[state];
for (int beforeStateIndex=0; beforeStateIndex < beforeStates.length; ++beforeStateIndex) {
int beforeState = beforeStates[beforeStateIndex];
alpha += alphas[pos-1][beforeState] * edgeBackwardPotentials[state][beforeStateIndex];
}
alpha *= nodePotentials[pos][state];
}
if (alpha > max) max = alpha;
alphas[pos][state] = alpha;
}
}
if (max == 0.0 || Double.isInfinite(max)) {
throw new RuntimeException(String.format("The alphas[%d] has max=%.3f",pos,max));
}
//LOG SCALE
int logScale = 0;
double scale = 1.0;
while (max > SCALE) {
max /= SCALE;
scale *= SCALE;
logScale += 1;
}
while (max > 0.0 && max < 1.0 / SCALE) {
max *= SCALE;
scale /= SCALE;
logScale -= 1;
}
if (logScale != 0) {
for (int label=0; label < numStates; ++label) {
alphas[pos][label] /= scale;
}
}
if (pos ==0) {
alphaScalingFactors[pos] = logScale;
} else {
alphaScalingFactors[pos] = alphaScalingFactors[pos-1] + logScale;
}
}
}
private void backwardPass() {
for (int pos=obsLength-1; pos >= 0; --pos) {
double max = 0.0;
if (pos == obsLength-1) {
for (int label=0; label < numStates; ++label) {
betas[pos][label] = nodePotentials[pos][label];
if (betas[pos][label] > max) max = betas[pos][label];
}
} else {
for (int state =0; state < numStates; ++state) {
double beta = 0.0;
if (nodePotentials[pos][state] > 0.0) {
//Loop over following States
int[] nextStates = allowableForwardTransitions[state];
for (int nextStateIndex=0; nextStateIndex < nextStates.length; ++nextStateIndex) {
int nextState = nextStates[nextStateIndex];
beta += edgeForwardPotentials[state][nextStateIndex] * betas[pos+1][nextState];
}
beta *= nodePotentials[pos][state];
}
if (beta > max) max = beta;
betas[pos][state] = beta;
}
}
int logScale = 0;
double scale = 1.0;
while (max > SCALE) {
max /= SCALE;
scale *= SCALE;
logScale += 1;
}
while (max > 0.0 && max < 1.0 / SCALE) {
max *= SCALE;
scale /= SCALE;
logScale -= 1;
}
if (logScale != 0) {
for (int label=0; label < numStates; ++label) {
betas[pos][label] /= scale;
}
}
if (pos == obsLength-1) {
betaScalingFactors[pos] = logScale;
} else {
betaScalingFactors[pos] = betaScalingFactors[pos+1] + logScale;
}
}
}
public double[][] getAlphas() {
return alphas;
}
public double[][] getBetas () {
return betas;
}
private void computePosteriors() {
double z = DoubleArrays.add(alphas[obsLength-1]);
double z_scale = alphaScalingFactors[obsLength-1];
if (z == 0.0) { throw new RuntimeException("Forward-Backward: No non-zero label sequences"); };
for (int i = 0; i+1 < obsLength; i++) {
double[] cur_betas = betas[i+1];
double beta_scale = betaScalingFactors[i+1];
double alpha_scale = alphaScalingFactors[i];
double posterior_scale = alpha_scale + beta_scale - z_scale;
double exp_scale = getScaleFactor(posterior_scale);
assert Math.abs(posterior_scale) <= 3.0 : "Exp scale is " + posterior_scale;
for (int s = 0; s < numStates; s++) {
int[] nextLabels = allowableForwardTransitions[s];
double alpha_s = alphas[i][s];
if (alpha_s == 0.0) continue;
double nodeSum = 0.0;
double x = alpha_s / z;
for (int tIndex=0; tIndex < nextLabels.length; ++tIndex) {
int t = nextLabels[tIndex];
double beta_t = cur_betas[t];
if (beta_t == 0.0) continue;
double unscaled_posterior = x * edgeForwardPotentials[s][tIndex] * beta_t ;
double edgePosterior = unscaled_posterior * exp_scale;
edgePosteriors[s][tIndex] += edgePosterior;
nodeSum += edgePosterior;
}
nodePosteriors[i][s] = nodeSum;
}
}
for (int t = 0; t < numStates; t++) {
double alpha_t = alphas[obsLength-1][t];
if (alpha_t == 0.0) continue;
double beta_t = betas[obsLength-1][t];
double beta_scale = betaScalingFactors[obsLength-1];
double alpha_scale = alphaScalingFactors[obsLength-1];
double unscaled_posterior = alpha_t * beta_t / (z * nodePotentials[obsLength-1][t]);
double posterior_scale = alpha_scale + beta_scale - z_scale;
double exp_scale = getScaleFactor(posterior_scale);
double nodePosterior = unscaled_posterior * exp_scale;
nodePosteriors[obsLength-1][t] = nodePosterior;
}
normConstant = z_scale * LOG_SCALE + Math.log(z);
if (DEBUG) {
probCheck();
}
}
private double relativeDiff(double a, double b) {
double diff = Math.abs(a-b);
return diff / Math.max(a, b);
}
@SuppressWarnings("unused")
private void probCheck() {
//Test Probability
for (int pos=0; pos < obsLength; ++pos) {
double nodeSum = 0.0;
double edgeSum = 0.0;
for (int l=0; l < nodePosteriors[pos].length; ++l) nodeSum += nodePosteriors[pos][l];
if (relativeDiff(1.0, nodeSum) > 1.0e-2) {
throw new RuntimeException("Node Sum: " + nodeSum + " not 1.0 for " + pos);
}
}
double edgeSum = 0;
for (int label=0; label < numStates; ++label) {
int[] nextLabels = allowableForwardTransitions[label];
for(int nextLabelIndex=0; nextLabelIndex < edgePosteriors[label].length; ++nextLabelIndex) {
edgeSum += edgePosteriors[label][nextLabelIndex];
}
}
if (relativeDiff(obsLength-1.0,edgeSum) > 1.0e-2) {
throw new RuntimeException("Failed ProbCheck: Edge Sum: " + edgeSum + " for " + obsLength);
}
}
}
| {
"content_hash": "3e4fa1d6b024985c0171163949c1f38b",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 126,
"avg_line_length": 29.56373937677054,
"alnum_prop": 0.6557110003832887,
"repo_name": "blodstone/CCS590v2",
"id": "28157546a5d540a71933861f21357a957a4da4ad",
"size": "10436",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "collinsHead/edu/berkeley/nlp/sequence/stationary/StationaryForwardBackward.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "173"
},
{
"name": "Java",
"bytes": "3073135"
},
{
"name": "Python",
"bytes": "113621"
}
],
"symlink_target": ""
} |
package com.kotcrab.vis.editor.module.editor;
import com.google.common.eventbus.Subscribe;
import com.kotcrab.vis.editor.event.EventBusExceptionEvent;
import com.kotcrab.vis.editor.module.EventBusSubscriber;
import com.kotcrab.vis.editor.ui.toast.DetailsToast;
/** @author Kotcrab */
@EventBusSubscriber
public class EventBusExceptionMonitorModule extends EditorModule {
private ToastModule toastModule;
@Subscribe
public void handleEventBusException (EventBusExceptionEvent event) {
toastModule.show(new DetailsToast("Internal exception occurred", event.exception));
}
}
| {
"content_hash": "c57b47b7d0400c639302f0fee51fb1c9",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 85,
"avg_line_length": 30.68421052631579,
"alnum_prop": 0.8216123499142367,
"repo_name": "intrigus/VisEditor",
"id": "a8fdb29e53533825773b2018359d3e58e29f545f",
"size": "1184",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Editor/src/com/kotcrab/vis/editor/module/editor/EventBusExceptionMonitorModule.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1252"
},
{
"name": "Java",
"bytes": "2479594"
}
],
"symlink_target": ""
} |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'excel2003_style07.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.image_dir = test_dir + 'images/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {'xl/drawings/drawing1.xml':
['<xdr:cNvPr', '<a:picLocks',
'<a:srcRect/>', '<xdr:spPr',
'<a:noFill/>']}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename, {'excel2003_style': True})
worksheet = workbook.add_worksheet()
worksheet.insert_image('B3', self.image_dir + 'yellow.jpg',
{'x_offset': 4, 'y_offset': 3})
workbook.close()
self.assertExcelEqual()
| {
"content_hash": "e20c8761b47e95830dba217002a95896",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 73,
"avg_line_length": 31.05128205128205,
"alnum_prop": 0.5590421139554087,
"repo_name": "jkyeung/XlsxWriter",
"id": "ed1560b5c39d993e9d69f6c04f64ea4ad0151955",
"size": "1384",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xlsxwriter/test/comparison/test_excel2003_style07.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "5113"
},
{
"name": "CSS",
"bytes": "16544"
},
{
"name": "HTML",
"bytes": "13100"
},
{
"name": "Makefile",
"bytes": "7819"
},
{
"name": "Perl",
"bytes": "3504"
},
{
"name": "Python",
"bytes": "2430294"
},
{
"name": "Shell",
"bytes": "6064"
}
],
"symlink_target": ""
} |
package encoding
import (
"github.com/apache/arrow/go/v8/arrow/memory"
"github.com/apache/arrow/go/v8/parquet"
"github.com/apache/arrow/go/v8/parquet/internal/utils"
"golang.org/x/xerrors"
)
// DeltaLengthByteArrayEncoder encodes data using by taking all of the byte array lengths
// and encoding them in front using delta encoding, followed by all of the binary data
// concatenated back to back. The expected savings is from the cost of encoding the lengths
// and possibly better compression in the data which will no longer be interleaved with the lengths.
//
// This encoding is always preferred over PLAIN for byte array columns where possible.
//
// For example, if the data was "Hello", "World", "Foobar", "ABCDEF" the encoded data would be:
// DeltaEncoding(5, 5, 6, 6) "HelloWorldFoobarABCDEF"
type DeltaLengthByteArrayEncoder struct {
encoder
lengthEncoder *DeltaBitPackInt32Encoder
}
// Put writes the provided slice of byte arrays to the encoder
func (enc *DeltaLengthByteArrayEncoder) Put(in []parquet.ByteArray) {
lengths := make([]int32, len(in))
totalLen := int(0)
for idx, val := range in {
lengths[idx] = int32(val.Len())
totalLen += val.Len()
}
enc.lengthEncoder.Put(lengths)
enc.sink.Reserve(totalLen)
for _, val := range in {
enc.sink.UnsafeWrite(val)
}
}
// PutSpaced is like Put, but the data is spaced out according to the bitmap provided and is compressed
// accordingly before it is written to drop the null data from the write.
func (enc *DeltaLengthByteArrayEncoder) PutSpaced(in []parquet.ByteArray, validBits []byte, validBitsOffset int64) {
if validBits != nil {
data := make([]parquet.ByteArray, len(in))
nvalid := spacedCompress(in, data, validBits, validBitsOffset)
enc.Put(data[:nvalid])
} else {
enc.Put(in)
}
}
// Type returns the underlying type which is handled by this encoder, ByteArrays only.
func (DeltaLengthByteArrayEncoder) Type() parquet.Type {
return parquet.Types.ByteArray
}
// FlushValues flushes any remaining data and returns the final encoded buffer of data
// or returns nil and any error encountered.
func (enc *DeltaLengthByteArrayEncoder) FlushValues() (Buffer, error) {
ret, err := enc.lengthEncoder.FlushValues()
if err != nil {
return nil, err
}
defer ret.Release()
data := enc.sink.Finish()
defer data.Release()
output := bufferPool.Get().(*memory.Buffer)
output.ResizeNoShrink(ret.Len() + data.Len())
copy(output.Bytes(), ret.Bytes())
copy(output.Bytes()[ret.Len():], data.Bytes())
return poolBuffer{output}, nil
}
// DeltaLengthByteArrayDecoder is a decoder for handling data produced by the corresponding
// encoder which expects delta packed lengths followed by the bytes of data.
type DeltaLengthByteArrayDecoder struct {
decoder
mem memory.Allocator
lengths []int32
}
// Type returns the underlying type which is handled by this encoder, ByteArrays only.
func (DeltaLengthByteArrayDecoder) Type() parquet.Type {
return parquet.Types.ByteArray
}
func (d *DeltaLengthByteArrayDecoder) Allocator() memory.Allocator { return d.mem }
// SetData sets in the expected data to the decoder which should be nvalues delta packed lengths
// followed by the rest of the byte array data immediately after.
func (d *DeltaLengthByteArrayDecoder) SetData(nvalues int, data []byte) error {
dec := DeltaBitPackInt32Decoder{
deltaBitPackDecoder: &deltaBitPackDecoder{
decoder: newDecoderBase(d.encoding, d.descr),
mem: d.mem}}
if err := dec.SetData(nvalues, data); err != nil {
return err
}
d.lengths = make([]int32, nvalues)
dec.Decode(d.lengths)
return d.decoder.SetData(nvalues, data[int(dec.bytesRead()):])
}
// Decode populates the passed in slice with data decoded until it hits the length of out
// or runs out of values in the column to decode, then returns the number of values actually decoded.
func (d *DeltaLengthByteArrayDecoder) Decode(out []parquet.ByteArray) (int, error) {
max := utils.MinInt(len(out), d.nvals)
for i := 0; i < max; i++ {
out[i] = d.data[:d.lengths[i]:d.lengths[i]]
d.data = d.data[d.lengths[i]:]
}
d.nvals -= max
d.lengths = d.lengths[max:]
return max, nil
}
// DecodeSpaced is like Decode, but for spaced data using the provided bitmap to determine where the nulls should be inserted.
func (d *DeltaLengthByteArrayDecoder) DecodeSpaced(out []parquet.ByteArray, nullCount int, validBits []byte, validBitsOffset int64) (int, error) {
toread := len(out) - nullCount
values, _ := d.Decode(out[:toread])
if values != toread {
return values, xerrors.New("parquet: number of values / definition levels read did not match")
}
return spacedExpand(out, nullCount, validBits, validBitsOffset), nil
}
| {
"content_hash": "e32a8ee745fca0bcc4190af729e63967",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 146,
"avg_line_length": 35.484848484848484,
"alnum_prop": 0.7391118701964133,
"repo_name": "laurentgo/arrow",
"id": "24d751fa77e1ab6b482b60d13230ce46293af419",
"size": "5480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "go/parquet/internal/encoding/delta_length_byte_array.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "73655"
},
{
"name": "Awk",
"bytes": "3683"
},
{
"name": "Batchfile",
"bytes": "32252"
},
{
"name": "C",
"bytes": "328114"
},
{
"name": "C#",
"bytes": "419434"
},
{
"name": "C++",
"bytes": "7254875"
},
{
"name": "CMake",
"bytes": "401649"
},
{
"name": "CSS",
"bytes": "3946"
},
{
"name": "Dockerfile",
"bytes": "42193"
},
{
"name": "FreeMarker",
"bytes": "2274"
},
{
"name": "Go",
"bytes": "364102"
},
{
"name": "HTML",
"bytes": "23047"
},
{
"name": "Java",
"bytes": "2296962"
},
{
"name": "JavaScript",
"bytes": "84850"
},
{
"name": "Lua",
"bytes": "8741"
},
{
"name": "M4",
"bytes": "8713"
},
{
"name": "MATLAB",
"bytes": "9068"
},
{
"name": "Makefile",
"bytes": "44853"
},
{
"name": "Meson",
"bytes": "36931"
},
{
"name": "Objective-C",
"bytes": "7559"
},
{
"name": "PLpgSQL",
"bytes": "56995"
},
{
"name": "Perl",
"bytes": "3799"
},
{
"name": "Python",
"bytes": "1548489"
},
{
"name": "R",
"bytes": "155922"
},
{
"name": "Ruby",
"bytes": "682150"
},
{
"name": "Rust",
"bytes": "1609482"
},
{
"name": "Shell",
"bytes": "251436"
},
{
"name": "Thrift",
"bytes": "137291"
},
{
"name": "TypeScript",
"bytes": "932690"
}
],
"symlink_target": ""
} |
@class DatePickerTextField;
@protocol DatePickerTextFieldDelegate <NSObject>
-(void)datePickerTextField:(DatePickerTextField*)field changed:(NSDate*)date;
@end
@interface DatePickerTextField : UITextField
@property(nonatomic,weak)IBOutlet id<DatePickerTextFieldDelegate> dateDelegate;
@property(nonatomic,strong)UIDatePicker * datePicker;
@property(nonatomic,strong)NSString * displayFormat;
@end
| {
"content_hash": "0cc6e5e23dfc8af2aac0570e4974d6e7",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 79,
"avg_line_length": 33.333333333333336,
"alnum_prop": 0.8375,
"repo_name": "qonceptual/QwikHttp",
"id": "948661d5e56d730cd3c1e65c18016d5e39055bdc",
"size": "511",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Example/Pods/SeaseAssist/Pod/Classes/DatePickerTextField.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "224180"
},
{
"name": "Ruby",
"bytes": "1792"
},
{
"name": "Shell",
"bytes": "16724"
},
{
"name": "Swift",
"bytes": "54892"
}
],
"symlink_target": ""
} |
FROM alpine:3.8
ARG TRANSMISSION_VERSION
LABEL maintainer='Pierre GINDRAUD <[email protected]>'
ENV SMTP_PORT=25
ENV SMTP_STARTTLS=no
ENV SMTP_SSL=no
#ENV SMTP_USERNAME=SASL_USERNAME
#ENV SMTP_PASSWORD=SASL_PASSWORD
#ENV SMTP_SERVER
# Install dependencies
RUN apk --no-cache add \
curl \
jq \
ssmtp \
transmission-daemon=$TRANSMISSION_VERSION \
tzdata
# Create the working filetree
RUN mkdir -p \
/config \
/downloads/complete \
/downloads/incomplete \
/watch \
&& chown transmission:transmission \
/config \
/downloads \
/downloads/complete \
/downloads/incomplete \
/watch \
&& chgrp transmission /etc/ssmtp /etc/ssmtp/ssmtp.conf \
&& chmod g+w /etc/ssmtp /etc/ssmtp/ssmtp.conf \
&& ln -s /config/timezone /etc/timezone \
&& ln -s /config/localtime /etc/localtime
# copy local files
COPY root/ /
# ports and volumes
EXPOSE 9091/tcp 51413/tcp 51413/udp
VOLUME ["/config", "/downloads", "/watch"]
WORKDIR /downloads
USER transmission:transmission
HEALTHCHECK --interval=5s --timeout=3s --retries=3 \
CMD curl --connect-timeout 1 --max-time 2 --silent --fail http://localhost:9091 || exit 1
COPY /entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
CMD ["/usr/bin/transmission-daemon", "--config-dir", "/config", "--watch-dir", "/watch", "--foreground"]
| {
"content_hash": "2fef84125d7571ab2c168ca445bd2999",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 104,
"avg_line_length": 24.87272727272727,
"alnum_prop": 0.6681286549707602,
"repo_name": "Turgon37/docker-transmission",
"id": "1d5f97c8c74d8a593c570bbae81d8b96a42c8e82",
"size": "1368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1368"
},
{
"name": "Shell",
"bytes": "10523"
}
],
"symlink_target": ""
} |
- Create a git repository: `git init`
- Add this repository on a remote git url (github for example).
- Configure the shipitfile with the remote repository url and the server IP address if you haven't done it yet.
- Launch deploy script:
```bash
./node_modules/.bin/shipit staging deploy
```
If deployment fails, it maybe because npm install requires a lot of memory. To bypass this issue, [add some swap file](https://www.cyberciti.biz/faq/linux-add-a-swap-file-howto/)
| {
"content_hash": "92154bbb4ba63e1a90844fe95b5d3eb4",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 178,
"avg_line_length": 39.583333333333336,
"alnum_prop": 0.751578947368421,
"repo_name": "tcheymol/generator-loopback-ansible",
"id": "74965e9e0d75a2614ba1b11fd2f330e986cfc6ce",
"size": "494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "generators/app/templates/doc/deployment.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "15907"
},
{
"name": "PLpgSQL",
"bytes": "117"
},
{
"name": "Ruby",
"bytes": "1872"
},
{
"name": "Shell",
"bytes": "701"
}
],
"symlink_target": ""
} |
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'li',
classNames: ['list-group-item todo'],
classNameBindings: ['isHidden:hide'],
isHidden: false,
actions: {
}
});
| {
"content_hash": "aad87ac173a3b15bd05766e167ad8939",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 39,
"avg_line_length": 20.5,
"alnum_prop": 0.6731707317073171,
"repo_name": "dossorio/ember-todo",
"id": "ea32454c5db6ea59601a87922eda9ecac6d23cff",
"size": "205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/components/todo-list-elem.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "81"
},
{
"name": "HTML",
"bytes": "3157"
},
{
"name": "JavaScript",
"bytes": "11149"
}
],
"symlink_target": ""
} |
angular.module('mapboxgl-directive').directive('glVideo', ['mapboxglVideoUtils', function (mapboxglVideoUtils) {
// ToDo: Check
function mapboxGlVideoDirectiveLink (scope, element, attrs, controller) {
if (!controller) {
throw new Error('Invalid angular-mapboxgl-directive controller');
}
var mapboxglScope = controller.getMapboxGlScope();
var videoWatched = function (map, controller, video) {
if (angular.isDefined(video)) {
if (Object.prototype.toString.call(video) === Object.prototype.toString.call({})) {
mapboxglVideoUtils.createVideoByObject(map, video);
controller.addVideoObject(video);
} else if (Object.prototype.toString.call(video) === Object.prototype.toString.call([])) {
video.map(function (eachVideo) {
mapboxglVideoUtils.createVideoByObject(map, eachVideo);
controller.addVideoObject(eachVideo);
});
} else {
throw new Error('Invalid video parameter');
}
}
};
scope.$on('mapboxglMap:styleChanged', function () {
});
controller.getMap().then(function (map) {
mapboxglScope.$watchCollection('glVideo', function (video) {
if (map.loaded()) {
videoWatched(map, controller, video);
} else {
map.on('load', function () {
videoWatched(map, controller, video);
});
}
});
});
}
var directive = {
restrict: 'A',
scope: false,
replace: false,
require: '?^mapboxgl',
link: mapboxGlVideoDirectiveLink
};
return directive;
}]);
| {
"content_hash": "8a3c2e3ef8edb1aaead5471de0c86eff",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 112,
"avg_line_length": 29.28301886792453,
"alnum_prop": 0.6372422680412371,
"repo_name": "Naimikan/angular-mapboxgl-directive",
"id": "565d01ac9d20350dfe834020aaac53d31fcd2399",
"size": "1552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/directives/glVideo.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "69432"
},
{
"name": "HTML",
"bytes": "3853"
},
{
"name": "JavaScript",
"bytes": "93071"
}
],
"symlink_target": ""
} |
@interface baiduMapDemoTests : XCTestCase
@end
@implementation baiduMapDemoTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
@end
| {
"content_hash": "517b6f63a8b351601e61637d5cd678db",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 107,
"avg_line_length": 25.586206896551722,
"alnum_prop": 0.6981132075471698,
"repo_name": "gaoyuexit/BMKMapDemo",
"id": "c7b8ca50f8659f993bf2979ce0d72128993efa8f",
"size": "914",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "baiduMapDemo/baiduMapDemoTests/baiduMapDemoTests.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "181128"
},
{
"name": "Objective-C++",
"bytes": "13199"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "968a051a9bb72a86fa1277e9293f39f5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "f12724152d72ae405d2069fd1c52cc50e631c2b6",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Marantaceae/Calathea/Calathea tinalandia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.CSharp;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Scripting.CSharp.Test
{
public class ScriptTests : TestBase
{
[Fact]
public void TestCreateScript()
{
var script = CSharpScript.Create("1 + 2");
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public void TestGetCompilation()
{
var script = CSharpScript.Create("1 + 2");
var compilation = script.GetCompilation();
Assert.Equal(script.Code, compilation.SyntaxTrees.First().GetText().ToString());
}
[Fact]
public void TestCreateScriptDelegate()
{
// create a delegate for the entire script
var script = CSharpScript.Create("1 + 2");
var fn = script.CreateDelegate();
var value = fn();
Assert.Equal(3, value.Result);
}
[Fact]
public void TestRunScript()
{
var result = CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, result.ReturnValue.Result);
}
[Fact]
public void TestCreateAndRunScript()
{
var script = CSharpScript.Create("1 + 2");
var result = script.RunAsync();
Assert.Same(script, result.Script);
Assert.Equal(3, result.ReturnValue.Result);
}
[Fact]
public void TestEvalScript()
{
var value = CSharpScript.EvaluateAsync("1 + 2");
Assert.Equal(3, value.Result);
}
[Fact]
public void TestRunScriptWithSpecifiedReturnType()
{
var result = CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, result.ReturnValue.Result);
}
[Fact]
public void TestRunVoidScript()
{
var result = CSharpScript.RunAsync("System.Console.WriteLine(0);");
var task = result.ReturnValue;
Assert.Null(task.Result);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do();"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithoutTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do()"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
public class Globals
{
public int X;
public int Y;
}
[Fact]
public void TestRunScriptWithGlobals()
{
var result = CSharpScript.RunAsync("X + Y", new Globals { X = 1, Y = 2 });
Assert.Equal(3, result.ReturnValue.Result);
}
[Fact]
public void TestRunCreatedScriptWithExpectedGlobals()
{
var script = CSharpScript.Create("X + Y").WithGlobalsType(typeof(Globals));
var result = script.RunAsync(new Globals { X = 1, Y = 2 });
Assert.Equal(3, result.ReturnValue.Result);
Assert.Same(script, result.Script);
}
[Fact]
public void TestRunCreatedScriptWithUnexpectedGlobals()
{
var script = CSharpScript.Create("X + Y");
var result = script.RunAsync(new Globals { X = 1, Y = 2 });
Assert.Equal(3, result.ReturnValue.Result);
// the end state of running the script should be based on a different script instance because of the globals
// not matching the original script definition.
Assert.NotSame(script, result.Script);
}
[Fact]
public void TestRunScriptWithScriptState()
{
// run a script using another scripts end state as the starting state (globals)
var result = CSharpScript.RunAsync("int X = 100;");
var result2 = CSharpScript.RunAsync("X + X", result);
Assert.Equal(200, result2.ReturnValue.Result);
}
[Fact]
public void TestRepl()
{
string[] submissions = new[]
{
"int x = 100;",
"int y = x * x;",
"x + y"
};
object input = null;
ScriptState<object> result = null;
foreach (var submission in submissions)
{
result = CSharpScript.RunAsync(submission, input);
input = result;
}
Assert.Equal(10100, result.ReturnValue.Result);
}
#if TODO // https://github.com/dotnet/roslyn/issues/3720
[Fact]
public void TestCreateMethodDelegate()
{
// create a delegate to a method declared in the script
var state = CSharpScript.Run("int Times(int x) { return x * x; }");
var fn = state.CreateDelegate<Func<int, int>>("Times");
var result = fn(5);
Assert.Equal(25, result);
}
#endif
[Fact]
public void TestGetScriptVariableAfterRunningScript()
{
var result = CSharpScript.RunAsync("int x = 100;");
var globals = result.Variables.Names.ToList();
Assert.Equal(1, globals.Count);
Assert.Equal(true, globals.Contains("x"));
Assert.Equal(true, result.Variables.ContainsVariable("x"));
Assert.Equal(100, (int)result.Variables["x"].Value);
}
[Fact]
public void TestBranchingSubscripts()
{
// run script to create declaration of M
var result1 = CSharpScript.RunAsync("int M(int x) { return x + x; }");
// run second script starting from first script's end state
// this script's new declaration should hide the old declaration
var result2 = CSharpScript.RunAsync("int M(int x) { return x * x; } M(5)", result1);
Assert.Equal(25, result2.ReturnValue.Result);
// run third script also starting from first script's end state
// it should not see any declarations made by the second script.
var result3 = CSharpScript.RunAsync("M(5)", result1);
Assert.Equal(10, result3.ReturnValue.Result);
}
}
}
| {
"content_hash": "acb7e03d82d4bc1273b0e4c328970a26",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 120,
"avg_line_length": 32.2877358490566,
"alnum_prop": 0.5693206720233748,
"repo_name": "poizan42/roslyn",
"id": "bdabcf59317d948f09b2d9c7dcea3806f9d86c30",
"size": "7007",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Scripting/CSharpTest/ScriptTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9424"
},
{
"name": "C#",
"bytes": "72744591"
},
{
"name": "C++",
"bytes": "3744"
},
{
"name": "F#",
"bytes": "421"
},
{
"name": "PowerShell",
"bytes": "8067"
},
{
"name": "Shell",
"bytes": "8222"
},
{
"name": "Visual Basic",
"bytes": "58514898"
}
],
"symlink_target": ""
} |
module.exports = function getErrorHandler() {
return function errorHandler(err, req, res, next) {
let code = 500, error = 'Internal Server Error';
// Mongoose Validation Error?
if (err.name === 'ValidationError' || err.name === 'CastError') {
code = 400;
error = err.name;
}
// is this one of our errors?
else if (err.code) {
// by convention, we're passing in an object
// with a code property === http statusCode
// and a error property === message to display
code = err.code;
error = err.error;
console.log(err.code, err.error);
}
// or something unexpected?
else {
console.log(err);
}
res.status(code).send({ error });
};
}; | {
"content_hash": "25104e4e2f734771c3f06ab29be3a851",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 73,
"avg_line_length": 30.925925925925927,
"alnum_prop": 0.5149700598802395,
"repo_name": "krogseng/server",
"id": "db01149db89af93875c9e3b6a51302cd00cbab51",
"size": "835",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/error-handler.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "464"
},
{
"name": "JavaScript",
"bytes": "22457"
}
],
"symlink_target": ""
} |
package net.sf.uadetector.internal.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import net.sf.uadetector.exception.CanNotOpenStreamException;
/**
* This class is intended to provide URL utility functions that encapsulate the checked exceptions like
* {@link MalformedURLException} during the construction of an URL or the {@link IOException} while opening a stream to
* an {@code URL}.
*
* @author André Rouél
*/
public class UrlUtil {
/**
* Creates an {@code URL} instance from the given {@code String} representation.<br>
* <br>
* This method tunnels a {@link MalformedURLException} by an {@link IllegalArgumentException}.
*
* @param url
* {@code String} representation of an {@code URL}
* @return new {@code URL} instance
* @throws IllegalArgumentException
* if the given argument is {@code null}
* @throws IllegalArgumentException
* if the string representation of the given URL is invalid and a {@link MalformedURLException} occurs
*/
public static final URL build(final String url) {
if (url == null) {
throw new IllegalArgumentException("Argument 'url' must not be null.");
}
URL ret = null;
try {
ret = new URL(url);
} catch (final MalformedURLException e) {
throw new IllegalArgumentException("The given string is not a valid URL: " + url, e);
}
return ret;
}
/**
* Tries to open an {@link InputStream} to the given {@link URL}.
*
* @param url
* URL which should be opened
* @return opened stream
* @throws IllegalArgumentException
* if the given argument is {@code null}
* @throws CanNotOpenStreamException
* if no stream to the given {@code URL} can be established
*/
public static final InputStream open(final URL url) {
if (url == null) {
throw new IllegalArgumentException("Argument 'url' must not be null.");
}
final InputStream ret;
try {
ret = url.openStream();
} catch (final IOException e) {
throw new CanNotOpenStreamException(url.toString());
}
return ret;
}
/**
* Reads the content of the passed {@link URL} as string representation.
*
* @param url
* URL to <em>UAS data</em>
* @param charset
* the character set in which the data should be read
* @return content as {@code String}
* @throws IllegalArgumentException
* if any of the given arguments is {@code null}
* @throws CanNotOpenStreamException
* if no stream to the given {@code URL} can be established
* @throws IOException
* if an I/O error occurs
*/
public static String read(final URL url, final Charset charset) throws IOException {
if (url == null) {
throw new IllegalArgumentException("Argument 'url' must not be null.");
}
if (charset == null) {
throw new IllegalArgumentException("Argument 'charset' must not be null.");
}
final InputStream inputStream = open(url);
BufferedReader reader = null;
final StringBuilder buffer = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(inputStream, charset));
buffer.append(readAll(reader));
} finally {
if (reader != null) {
reader.close();
}
inputStream.close();
}
return buffer.toString();
}
/**
* Reads the entire contents via the given {@link Reader} as string.
*
* @param reader
* {@code Reader} to read the entire contents
* @return the read contents as string
* @throws IOException
* If an I/O error occurs
*/
private static String readAll(final Reader reader) throws IOException {
final StringBuilder buffer = new StringBuilder();
int cp;
while ((cp = reader.read()) != -1) {
buffer.append((char) cp);
}
return buffer.toString();
}
/**
* Gets the URL to a given {@code File}.
*
* @param file
* file to be converted to a URL
* @return an URL to the passed file
* @throws IllegalStateException
* if no URL can be resolved to the given file
*/
public static URL toUrl(final File file) {
if (file == null) {
throw new IllegalArgumentException("Argument 'file' must not be null.");
}
URL url = null;
try {
url = file.toURI().toURL();
} catch (final MalformedURLException e) {
throw new IllegalStateException("Can not construct an URL for passed file.", e);
}
return url;
}
/**
* <strong>Attention:</strong> This class is not intended to create objects from it.
*/
private UrlUtil() {
// This class is not intended to create objects from it.
}
}
| {
"content_hash": "0ec5f83846f09f5bb6f2d71b9183f580",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 119,
"avg_line_length": 29.32515337423313,
"alnum_prop": 0.6669456066945607,
"repo_name": "jolros/uadetector",
"id": "fbd810d4916b4d618aab15ab58375f1f20f3235b",
"size": "5534",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/uadetector-core/src/main/java/net/sf/uadetector/internal/util/UrlUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "667077"
},
{
"name": "JavaScript",
"bytes": "410"
}
],
"symlink_target": ""
} |
(function() {
"use strict";
var DEFAULT_ROUTE = 'about';
var template = document.querySelector('#t');
var ajax, pages, scaffold;
var cache = {};
template.pages = [
{name: 'About', hash: 'about', url: '//www.html5rocks.com/en/tutorials/webcomponents/shadowdom/'},
{name: 'Resumé', hash: 'resume', url: '//www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/'},
{name: 'Blog', hash: 'blog', url: '//www.html5rocks.com/en/tutorials/webcomponents/shadowdom-301/'},
{name: 'Bookmarks', hash: 'bookmarks', url: '//www.html5rocks.com/en/tutorials/webcomponents/customelements/'}
];
template.addEventListener('template-bound', function(e) {
scaffold = document.querySelector('#scaffold');
ajax = document.querySelector('#ajax');
pages = document.querySelector('#pages');
var keys = document.querySelector('#keys');
// Allow selecting pages by num keypad. Dynamically add
// [1, template.pages.length] to key mappings.
var keysToAdd = Array.apply(null, template.pages).map(function(x, i) {
return i + 1;
}).reduce(function(x, y) {
return x + ' ' + y;
});
keys.keys += ' ' + keysToAdd;
this.route = this.route || DEFAULT_ROUTE; // Select initial route.
});
template.keyHandler = function(e, detail, sender) {
var pages = document.querySelector('#pages');
// Select page by num key.
var num = parseInt(detail.key);
if (!isNaN(num) && num <= this.pages.length) {
pages.selectIndex(num - 1);
return;
}
switch (detail.key) {
case 'left':
case 'up':
pages.selectPrevious();
break;
case 'right':
case 'down':
pages.selectNext();
break;
case 'space':
detail.shift ? pages.selectPrevious() : pages.selectNext();
break;
}
};
template.menuItemSelected = function(e, detail, sender) {
if (detail.isSelected) {
// Need to wait one rAF so <core-ajax> has it's URL set.
this.async(function() {
if (!cache[ajax.url]) {
ajax.go();
}
scaffold.closeDrawer();
});
}
};
template.ajaxLoad = function(e, detail, sender) {
e.preventDefault(); // prevent link navigation.
};
template.onResponse = function(e, detail, sender) {
var article = detail.response.querySelector('#article-content');
article.querySelector('.byline').remove();
// Fix up image paths to not be local.
[].forEach.call(article.querySelectorAll('img'), function(img) {
img.setAttribute('src', img.src);
});
var html = article.innerHTML;
cache[ajax.url] = html; // Primitive caching by URL.
this.injectBoundHTML(html, pages.selectedItem.firstElementChild);
};
})(); | {
"content_hash": "be4c6489e3335a3e1953edbf82ba6535",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 112,
"avg_line_length": 27.1875,
"alnum_prop": 0.6498084291187739,
"repo_name": "iheartcake/single-page-app",
"id": "d0fbec895340dd8ea50b901a2f772e63c6ffa0c4",
"size": "2611",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1377"
},
{
"name": "HTML",
"bytes": "3985"
},
{
"name": "JavaScript",
"bytes": "2611"
}
],
"symlink_target": ""
} |
require 'net/http'
require 'json'
class Oohlalog::Counter
def initialzie
end
def increment(code,counter=1)
Thread.new do
begin
request = Net::HTTP::Post.new("/api/counter/increment?apiKey=#{Oohlalog.api_key}&incr=#{counter}",{'Content-Type' =>'application/json'})
http_net = Net::HTTP.new(Oohlalog.host, Oohlalog.port)
http_net.read_timeout = 5
http_net.start {|http| http.request(request) }
rescue
# puts "Oohlalog Exception**:"
end
end
end
end
| {
"content_hash": "cae523bbd0a561e29fa2e62160040709",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 144,
"avg_line_length": 24.904761904761905,
"alnum_prop": 0.6328871892925431,
"repo_name": "oohlalog/oohlalog_ruby",
"id": "331b3d45ce4aebb73f4ba8d0e2693d7742696490",
"size": "523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/oohlalog/counter.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6937"
}
],
"symlink_target": ""
} |
./dependencies.sh
docker build -t gr2/cppbuilder .
| {
"content_hash": "96e4df3ea6edbab237359378b40aa570",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 32,
"avg_line_length": 17.333333333333332,
"alnum_prop": 0.75,
"repo_name": "Justewi/CentralTrafficLightManagement",
"id": "0744586d3cf75a2f81b82124f5c8d8398615c843",
"size": "65",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lightControler/docker_builder/build.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "11547"
},
{
"name": "CMake",
"bytes": "301"
},
{
"name": "Java",
"bytes": "22951"
},
{
"name": "Python",
"bytes": "1798"
},
{
"name": "Shell",
"bytes": "4224"
}
],
"symlink_target": ""
} |
package com.google.cloud.automl.v1.samples;
// [START automl_v1_generated_AutoMl_GetModel_Modelname_sync]
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Model;
import com.google.cloud.automl.v1.ModelName;
public class SyncGetModelModelname {
public static void main(String[] args) throws Exception {
syncGetModelModelname();
}
public static void syncGetModelModelname() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (AutoMlClient autoMlClient = AutoMlClient.create()) {
ModelName name = ModelName.of("[PROJECT]", "[LOCATION]", "[MODEL]");
Model response = autoMlClient.getModel(name);
}
}
}
// [END automl_v1_generated_AutoMl_GetModel_Modelname_sync]
| {
"content_hash": "dab7ed920d23d612a55e7536524fef34",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 100,
"avg_line_length": 39.785714285714285,
"alnum_prop": 0.744165170556553,
"repo_name": "googleapis/java-automl",
"id": "4ec35c77513df38ee17ca5ac65126d373b7d9b7f",
"size": "1709",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "samples/snippets/generated/com/google/cloud/automl/v1/automl/getmodel/SyncGetModelModelname.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "11675388"
},
{
"name": "Python",
"bytes": "918"
},
{
"name": "Shell",
"bytes": "22269"
}
],
"symlink_target": ""
} |
"""
Custom Authenticator to use generic OAuth2 with JupyterHub
"""
import json
import os
import base64
import tornado
from tornado.auth import OAuth2Mixin
from tornado import gen, web
from tornado.httputil import url_concat
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from jupyterhub.auth import LocalAuthenticator
from traitlets import Unicode, Dict
from .oauth2 import OAuthLoginHandler, OAuthenticator
# Support github.com and github enterprise installations
#GITHUB_HOST = os.environ.get('GITHUB_HOST') or 'github.com'
#if GITHUB_HOST == 'github.com':
# GITHUB_API = 'api.github.com/user'
#else:
# GITHUB_API = '%s/api/v3/user' % GITHUB_HOST
class GenericEnvMixin(OAuth2Mixin):
_OAUTH_AUTHORIZE_URL = os.environ.get('OAUTH2_AUTHORIZE_URL', '')
_OAUTH_ACCESS_TOKEN_URL = os.environ.get('OAUTH2_TOKEN_URL', '')
class GenericLoginHandler(OAuthLoginHandler, GenericEnvMixin):
pass
class GenericOAuthenticator(OAuthenticator):
login_service = "GenericOAuth2"
login_handler = GenericLoginHandler
userdata_url = Unicode(
os.environ.get('OAUTH2_USERDATA_URL', ''),
config=True,
help="Userdata url to get user data login information"
)
username_key = Unicode(
os.environ.get('OAUTH2_USERNAME_KEY', 'user_name'),
config=True,
help="Userdata username key from returned json for USERDATA_URL"
)
userdata_params = Dict(
os.environ.get('OAUTH2_USERDATA_PARAMS', {}),
help="Userdata params to get user data login information"
).tag(config=True)
userdata_method = Unicode(
os.environ.get('OAUTH2_USERDATA_METHOD', 'GET'),
config=True,
help="Userdata method to get user data login information"
)
token_url = Unicode(
os.environ.get('OAUTH2_TOKEN_URL', 'GET'),
config=True,
help="Userdata method to get user data login information"
)
@gen.coroutine
def authenticate(self, handler, data=None):
code = handler.get_argument("code", False)
if not code:
raise web.HTTPError(400, "oauth callback made without a token")
# TODO: Configure the curl_httpclient for tornado
http_client = AsyncHTTPClient()
params = dict(
redirect_uri=self.get_callback_url(handler),
code=code,
grant_type='authorization_code'
)
url = url_concat(self.token_url, params)
b64key = base64.b64encode(
bytes(
"{}:{}".format(self.client_id, self.client_secret),
"utf8"
)
)
headers = {
"Accept": "application/json",
"User-Agent": "JupyterHub",
"Authorization": "Basic {}".format(b64key.decode("utf8"))
}
proxy_host = os.environ.get('HTTP_PROXY_HOST', '')
port = os.environ.get('HTTP_PROXY_PORT', '')
if proxy_host and port:
proxy_port = int(port)
req = HTTPRequest(url,
method="POST",
headers=headers,
body='', # Body is required for a POST...
proxy_host=proxy_host,
proxy_port=proxy_port
)
else:
req = HTTPRequest(url,
method="POST",
headers=headers,
body=''
)
resp = yield http_client.fetch(req)
resp_json = json.loads(resp.body.decode('utf8', 'replace'))
access_token = resp_json['access_token']
token_type = resp_json['token_type']
# Determine who the logged in user is
headers = {
"Accept": "application/json",
"User-Agent": "JupyterHub",
"Authorization": "{} {}".format(token_type, access_token)
}
url = url_concat(self.userdata_url, self.userdata_params)
if proxy_host and port:
proxy_port = int(port)
req = HTTPRequest(url,
method="GET",
headers=headers,
proxy_host=proxy_host,
proxy_port=proxy_port
)
else:
req = HTTPRequest(url,
method="GET",
headers=headers
)
resp = yield http_client.fetch(req)
resp_json = json.loads(resp.body.decode('utf8', 'replace'))
if resp_json.get(self.username_key):
return resp_json[self.username_key]
class LocalGenericOAuthenticator(LocalAuthenticator, GenericOAuthenticator):
"""A version that mixes in local system user creation"""
pass
| {
"content_hash": "f4900f696ae14911d74a96fa5973bd12",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 76,
"avg_line_length": 30.575,
"alnum_prop": 0.5598937040065413,
"repo_name": "santi81/oauthenticator",
"id": "02bcf15e1419335cb85c027c47a6a4b0488c8f4b",
"size": "4892",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "oauthenticator/generic.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "656"
},
{
"name": "Python",
"bytes": "67606"
},
{
"name": "Shell",
"bytes": "270"
}
],
"symlink_target": ""
} |
package ru.elazarev.list;
/**
* Class to detect cycles in linked list.
* @param <T> type of elements in linked list
* @author Eugene Lazarev mailto([email protected])
* @since 02.06.17
*/
public class CycleDetector<T> {
/**
* Returns true if linked list head has cycles.
* @param head linked list to check
* @return true or false
*/
public boolean hasCycle(Node<T> head) {
if (head == null) {
return false;
}
int i = 0;
Node<T> node = head;
while (node.getNext() != null) {
if (hasCycle(i, head, node.getNext())) {
return true;
}
node = node.getNext();
i++;
}
return false;
}
/**
* Checks that node is in range from 0 to index.
* @param index end of range to check
* @param head linked list of nodes
* @param node node to find
* @return true if node in range and false else
*/
private boolean hasCycle(int index, Node<T> head, Node<T> node) {
int i = 0;
while (head != null && i < index) {
if (node == head) {
return true;
}
head = head.getNext();
i++;
}
return false;
}
}
/**
* Linked list node.
* @param <T> type of elements to contain
*/
class Node<T> {
/**
* Value of node.
*/
private T value;
/**
* Ref to next node in list.
*/
private Node<T> next;
/**
* Default constructor.
* @param value value of new node
*/
Node(T value) {
this.value = value;
}
/**
* Getter to value field.
* @return value field
*/
public T getValue() {
return value;
}
/**
* Setter to value field.
* @param value new value
*/
public void setValue(T value) {
this.value = value;
}
/**
* Getter for next field.
* @return next field
*/
public Node<T> getNext() {
return next;
}
/**
* Setter for next field.
* @param next new next field
*/
public void setNext(Node<T> next) {
this.next = next;
}
}
| {
"content_hash": "bd7cf29138a14ee7ebd5e4712c6049ff",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 69,
"avg_line_length": 20.87735849056604,
"alnum_prop": 0.5020334387708992,
"repo_name": "helycopternicht/elazarev",
"id": "32e154539c727b9dba5dbbe2d36a8e7b724e6644",
"size": "2213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_004/src/main/java/ru/elazarev/list/CycleDetector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "31"
},
{
"name": "Java",
"bytes": "470132"
}
],
"symlink_target": ""
} |
* remove rresult dependency
* use sexplib0 instead of sexplib for mirage-crypto 0.10.4+ compatibility
(the dependency stated sexplib0 since some time, but sexplib was inherited
via mirage-crypto-pk)
## v0.3.9 (2021-08-04)
* use Cstruct.length instead of deprecated Cstruct.len (requires cstruct 6.0.0)
## v0.3.8 (2020-03-15)
* fix crypt function (0.3.7 used the counter wrong, the 0 should be the other half)
## v0.3.7 (2020-03-11)
* use mirage-crypto instead of nocrypto
## 0.3.6 (2019-02-16)
* move build system to dune
## 0.3.5 (2018-08-25)
* remove usage of ppx
## 0.3.4 (2017-11-23)
* prefix modules with "Otr_"
* drop OCaml < 4.03.0 support
## 0.3.3 (2016-07-17)
* improve interop (instance tags) #10
* don't pack anymore
* switch to topkg
## 0.3.2 (2016-05-09)
* use result, 4.03 compatibility
## 0.3.1 (2016-03-21)
* get rid of camlp4, use ppx instead
## 0.3.0 (2015-12-20)
* add `update_config` function to update a session with given parameters
* use Astring instead of Stringext for String functionality
## 0.2.0 (2015-07-02)
* config contains policies and versions, but no longer the DSA key
* DSA key needs to be provided separately in new_session
* own_fingerprint takes a DSA key, not a config
## 0.1.1 (2015-04-25)
* expose full config structure
* handle simultaneous open (both parties send a DH_COMMIT) gracefully
## 0.1.0 (2015-01-24)
* initial release
| {
"content_hash": "78f4d4289e4b24718c181bca9fdf64f4",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 83,
"avg_line_length": 22.26984126984127,
"alnum_prop": 0.7027797576621525,
"repo_name": "hannesm/ocaml-otr",
"id": "bd13186f4a657aee2fac2956f59a5a6eac3ac5ee",
"size": "1428",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "CHANGES.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "OCaml",
"bytes": "87459"
}
],
"symlink_target": ""
} |
id: version-1.9.1-addresses
title: Generating Addresses
original_id: addresses
---
Almost all Bitcoin applications need to generate addresses
for their users somehow. There's a lot going on in getting
a correct bitcoin address, but our APIs make it possible to
to get started with all types of addresses in a matter of
minutes.
## Generating SegWit (bech32) addresses
Generating native SegWit addresses in the bech32 format
is something that all Bitcoin applications should enable,
as it makes the transaction fees less expensive, and also
makes the addresses more readable by humans. However, it
has seen slower than necessary adoption. With Bitcoin-S
you can generate bech32 addresses in four(!) lines of code
(not counting comments and imports), so now there's no
reason to keep using legacy transaction formats.
```scala
// this generates a random private key
val privkey = ECPrivateKey()
// privkey: ECPrivateKey = Masked(ECPrivateKey)
val pubkey = privkey.publicKey
// pubkey: org.bitcoins.crypto.ECPublicKey = ECPublicKey(02f07024f9e977133041d5a7768fcb582385ce5c09b2711f0202e473d23f52ee64)
val segwitAddress = {
// see https://bitcoin.org/en/glossary/pubkey-script
// for reading resources on the details of scriptPubKeys
// pay-to-witness-pubkey-hash scriptPubKey V0
val scriptPubKey = P2WPKHWitnessSPKV0(pubkey)
Bech32Address(scriptPubKey, TestNet3)
}
// segwitAddress: Bech32Address = tb1q3gftc5dytyvj0rssxl8v2xragetulx7fs5gulj
println(segwitAddress.toString)
// tb1q3gftc5dytyvj0rssxl8v2xragetulx7fs5gulj
```
## Generating legacy (base58) addresses
If you need to generate legacy addresses for backwards
compatability reasons, that's also a walk in the park.
Take a look:
```scala
// we're reusing the same private/public key pair
// from before. don't do this in an actual application!
val legacyAddress = P2PKHAddress(pubkey, TestNet3)
// legacyAddress: P2PKHAddress = mt71zJNhcSPkd8mBEgcC21nWYzzHo1JJRK
println(legacyAddress.toString)
// mt71zJNhcSPkd8mBEgcC21nWYzzHo1JJRK
```
| {
"content_hash": "0e8c34dc7ad137bbbbd3964ef9259f1f",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 124,
"avg_line_length": 34.86206896551724,
"alnum_prop": 0.7972304648862513,
"repo_name": "bitcoin-s/bitcoin-s",
"id": "3d4008161d4bb667224a5c17346cae89e2fb0e78",
"size": "2026",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "website/versioned_docs/version-1.9.1/core/addresses.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2266"
},
{
"name": "Dockerfile",
"bytes": "235"
},
{
"name": "Java",
"bytes": "58539"
},
{
"name": "JavaScript",
"bytes": "31763"
},
{
"name": "Scala",
"bytes": "8398379"
},
{
"name": "Shell",
"bytes": "7787"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>nfix: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.0 / nfix - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
nfix
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-07 00:45:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-07 00:45:43 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/nfix"
license: "Proprietary"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Nfix"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:mutual fixpoint functions" "category:Miscellaneous/Coq Extensions" ]
authors: [ "Stéphane Lescuyer <>" ]
bug-reports: "https://github.com/coq-contribs/nfix/issues"
dev-repo: "git+https://github.com/coq-contribs/nfix.git"
synopsis: "Nfix: a Coq extension for fixpoints on nested inductives"
description:
"This plugin provides a syntactic extension that allows one to write mutual fixpoints over nested inductives."
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/nfix/archive/v8.5.0.tar.gz"
checksum: "md5=51342658a19147f3d4eb8f3e005ac475"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-nfix.8.5.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.0).
The following dependencies couldn't be met:
- coq-nfix -> coq < 8.6~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-nfix.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "714c19bd124da58e21ce09304a99fd34",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 159,
"avg_line_length": 41.6144578313253,
"alnum_prop": 0.5392298784018529,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "34461972c78d3b51c59389562437899acc319788",
"size": "6934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.9.0/nfix/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
function [d imFnames]=strings35()
full_fname = 'strings35.mat';
fname = '/media/blandry/LinuxData/crazyflie-tools/logs/cf2/tests0514/strings35.mat';
if (exist(full_fname,'file'))
filename = full_fname;
else
filename = fname;
end
d = load(filename);
| {
"content_hash": "82465b35769da7053e2bbaafa71042e5",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 84,
"avg_line_length": 28.555555555555557,
"alnum_prop": 0.7198443579766537,
"repo_name": "peteflorence/crazyflie-tools",
"id": "c537d9ba46b18787d34c7990f08bc3f67791c27b",
"size": "257",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "logs/cf2/tests0514/strings35.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9573"
},
{
"name": "Limbo",
"bytes": "93"
},
{
"name": "M",
"bytes": "1235"
},
{
"name": "Matlab",
"bytes": "202375"
},
{
"name": "Python",
"bytes": "104885"
},
{
"name": "Shell",
"bytes": "155"
}
],
"symlink_target": ""
} |
/**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highcharts]]
*/
package com.highcharts.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>series<xrange>-point-events</code>
*/
@js.annotation.ScalaJSDefined
class SeriesXrangePointEvents extends com.highcharts.HighchartsGenericObject {
/**
* <p>Callback that fires when starting to drag a point. The mouse event object is
* passed in as an argument. If a drag handle is used, <code>e.updateProp</code> is set to
* the data property being dragged. The <code>this</code> context is the point. See
* <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>
* <p>Requires the <code>draggable-points</code> module.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/dragdrop/drag-xrange">Drag events</a>
* @since 6.2.0
*/
val dragStart: js.UndefOr[js.Function] = js.undefined
/**
* <p>Callback that fires while dragging a point. The mouse event is passed in as
* parameter. The original data can be accessed from <code>e.origin</code>, and the new
* point values can be accessed from <code>e.newPoints</code>. If there is only a single
* point being updated, it can be accessed from <code>e.newPoint</code> for simplicity, and
* its ID can be accessed from <code>e.newPointId</code>. The <code>this</code> context is the point
* being dragged. To stop the default drag action, return false.
* See <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>
* <p>Requires the <code>draggable-points</code> module.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/dragdrop/drag-xrange">Drag events</a>
* @since 6.2.0
*/
val drag: js.UndefOr[js.Function] = js.undefined
/**
* <p>Callback that fires when the point is dropped. The parameters passed are the
* same as for <a href="#plotOptions.series.point.events.drag">drag</a>. To stop the
* default drop action, return false. See
* <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>
* <p>Requires the <code>draggable-points</code> module.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/dragdrop/drag-xrange">Drag events</a>
* @since 6.2.0
*/
val drop: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when a point is clicked. One parameter, <code>event</code>, is passed
* to the function, containing common event information.</p>
* <p>If the <code>series.allowPointSelect</code> option is true, the default
* action for the point's click event is to toggle the point's
* select state. Returning <code>false</code> cancels this action.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-click/">Click marker to alert values</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-click-column/">Click column</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-click-url/">Go to URL</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-point-events-click/">Click marker to display values</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-point-events-click-url/">Go to URL</a>
*/
val click: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the mouse leaves the area close to the point. One
* parameter, <code>event</code>, is passed to the function, containing common
* event information.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-mouseover/">Show values in the chart's corner on mouse over</a>
*/
val mouseOut: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the mouse enters the area close to the point. One
* parameter, <code>event</code>, is passed to the function, containing common
* event information.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-mouseover/">Show values in the chart's corner on mouse over</a>
*/
val mouseOver: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is removed using the <code>.remove()</code> method. One
* parameter, <code>event</code>, is passed to the function. Returning <code>false</code>
* cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-remove/">Remove point and confirm</a>
* @since 1.2.0
*/
val remove: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is selected either programmatically or
* following a click on the point. One parameter, <code>event</code>, is passed
* to the function. Returning <code>false</code> cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-select/">Report the last selected point</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-allowpointselect/">Report select and unselect</a>
* @since 1.2.0
*/
val select: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is unselected either programmatically or
* following a click on the point. One parameter, <code>event</code>, is passed
* to the function.
* Returning <code>false</code> cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-unselect/">Report the last unselected point</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-allowpointselect/">Report select and unselect</a>
* @since 1.2.0
*/
val unselect: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is updated programmatically through the
* <code>.update()</code> method. One parameter, <code>event</code>, is passed to the
* function. The new point options can be accessed through
* <code>event.options</code>. Returning <code>false</code> cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-update/">Confirm point updating</a>
* @since 1.2.0
*/
val update: js.UndefOr[js.Function] = js.undefined
}
object SeriesXrangePointEvents {
/**
* @param dragStart <p>Callback that fires when starting to drag a point. The mouse event object is. passed in as an argument. If a drag handle is used, <code>e.updateProp</code> is set to. the data property being dragged. The <code>this</code> context is the point. See. <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>. <p>Requires the <code>draggable-points</code> module.</p>
* @param drag <p>Callback that fires while dragging a point. The mouse event is passed in as. parameter. The original data can be accessed from <code>e.origin</code>, and the new. point values can be accessed from <code>e.newPoints</code>. If there is only a single. point being updated, it can be accessed from <code>e.newPoint</code> for simplicity, and. its ID can be accessed from <code>e.newPointId</code>. The <code>this</code> context is the point. being dragged. To stop the default drag action, return false.. See <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>. <p>Requires the <code>draggable-points</code> module.</p>
* @param drop <p>Callback that fires when the point is dropped. The parameters passed are the. same as for <a href="#plotOptions.series.point.events.drag">drag</a>. To stop the. default drop action, return false. See. <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>. <p>Requires the <code>draggable-points</code> module.</p>
* @param click <p>Fires when a point is clicked. One parameter, <code>event</code>, is passed. to the function, containing common event information.</p>. <p>If the <code>series.allowPointSelect</code> option is true, the default. action for the point's click event is to toggle the point's. select state. Returning <code>false</code> cancels this action.</p>
* @param mouseOut <p>Fires when the mouse leaves the area close to the point. One. parameter, <code>event</code>, is passed to the function, containing common. event information.</p>
* @param mouseOver <p>Fires when the mouse enters the area close to the point. One. parameter, <code>event</code>, is passed to the function, containing common. event information.</p>
* @param remove <p>Fires when the point is removed using the <code>.remove()</code> method. One. parameter, <code>event</code>, is passed to the function. Returning <code>false</code>. cancels the operation.</p>
* @param select <p>Fires when the point is selected either programmatically or. following a click on the point. One parameter, <code>event</code>, is passed. to the function. Returning <code>false</code> cancels the operation.</p>
* @param unselect <p>Fires when the point is unselected either programmatically or. following a click on the point. One parameter, <code>event</code>, is passed. to the function.. Returning <code>false</code> cancels the operation.</p>
* @param update <p>Fires when the point is updated programmatically through the. <code>.update()</code> method. One parameter, <code>event</code>, is passed to the. function. The new point options can be accessed through. <code>event.options</code>. Returning <code>false</code> cancels the operation.</p>
*/
def apply(dragStart: js.UndefOr[js.Function] = js.undefined, drag: js.UndefOr[js.Function] = js.undefined, drop: js.UndefOr[js.Function] = js.undefined, click: js.UndefOr[js.Function] = js.undefined, mouseOut: js.UndefOr[js.Function] = js.undefined, mouseOver: js.UndefOr[js.Function] = js.undefined, remove: js.UndefOr[js.Function] = js.undefined, select: js.UndefOr[js.Function] = js.undefined, unselect: js.UndefOr[js.Function] = js.undefined, update: js.UndefOr[js.Function] = js.undefined): SeriesXrangePointEvents = {
val dragStartOuter: js.UndefOr[js.Function] = dragStart
val dragOuter: js.UndefOr[js.Function] = drag
val dropOuter: js.UndefOr[js.Function] = drop
val clickOuter: js.UndefOr[js.Function] = click
val mouseOutOuter: js.UndefOr[js.Function] = mouseOut
val mouseOverOuter: js.UndefOr[js.Function] = mouseOver
val removeOuter: js.UndefOr[js.Function] = remove
val selectOuter: js.UndefOr[js.Function] = select
val unselectOuter: js.UndefOr[js.Function] = unselect
val updateOuter: js.UndefOr[js.Function] = update
com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesXrangePointEvents {
override val dragStart: js.UndefOr[js.Function] = dragStartOuter
override val drag: js.UndefOr[js.Function] = dragOuter
override val drop: js.UndefOr[js.Function] = dropOuter
override val click: js.UndefOr[js.Function] = clickOuter
override val mouseOut: js.UndefOr[js.Function] = mouseOutOuter
override val mouseOver: js.UndefOr[js.Function] = mouseOverOuter
override val remove: js.UndefOr[js.Function] = removeOuter
override val select: js.UndefOr[js.Function] = selectOuter
override val unselect: js.UndefOr[js.Function] = unselectOuter
override val update: js.UndefOr[js.Function] = updateOuter
})
}
}
| {
"content_hash": "416efa4150d707aa93b9e5af5db4bfff",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 654,
"avg_line_length": 75.87037037037037,
"alnum_prop": 0.7273614840126922,
"repo_name": "Karasiq/scalajs-highcharts",
"id": "0b35ef86e0fcd07e84af6b3987c91ca59fb5cc78",
"size": "12291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/highcharts/config/SeriesXrangePointEvents.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "131509301"
}
],
"symlink_target": ""
} |
describe("Common date formater", function () {
beforeEach(module("app"));
describe("dateFormater service", function() {
var service;
beforeEach(inject(function ($injector) {
service = $injector.get("dateFormater");
}));
it("exists", function() {
expect(service).not.toBe(null);
expect(service).not.toBe(undefined);
});
it("can formate date", function() {
//arange
var nonFormatedDate = "2015-03-20T01:35:18.167";
var formatedDate = "20/03/2015 - 01:35:18";
//act
var actual = service.formateDate(nonFormatedDate);
//assert
expect(actual).toEqual(formatedDate);
});
});
}); | {
"content_hash": "0c7ad90d747fd2ce1a8d071773b1d767",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 62,
"avg_line_length": 27.392857142857142,
"alnum_prop": 0.529335071707953,
"repo_name": "Social-Projects/PrompterPro",
"id": "7b615989504b1ac332d9c076a2b1cf1fc2ccad68",
"size": "769",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Main/SoftServe.ITA.PrompterPro/PrompterPro.WebApplication/app/UnitTests/Common/services/dateFormaterTest.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "123"
},
{
"name": "C#",
"bytes": "313428"
},
{
"name": "CSS",
"bytes": "15440"
},
{
"name": "HTML",
"bytes": "21178"
},
{
"name": "JavaScript",
"bytes": "848144"
},
{
"name": "Smalltalk",
"bytes": "47548"
}
],
"symlink_target": ""
} |
var shrink = require('cortex-shrinkwrap');
var path = require('path');
var semver = require('semver');
var cortexJson = require('read-cortex-json');
var Walker = require('./lib/walker');
var _ = require('underscore');
var events = require('events');
var util = require('util');
var builder = new events.EventEmitter();
builder.pickVersion = function (modules, callback) {
var self = this;
var conflict = false;
var mods = {};
for (var name in modules) {
var module = modules[name];
var versions = Object.keys(module);
var version_to_choose = null;
versions.forEach(function (version) {
var v = semver.parse(version);
if (!version_to_choose) {
version_to_choose = version;
} else {
var parsed = semver.parse(version_to_choose);
if (parsed.major == v.major) {
// error
conflict = true;
} else if (parsed.minor == v.minor) {
// warn
self.emit("warn", util("multi minor version %s@%s <-> %s@%s", name, version, name, version_to_choose_raw));
if (parsed.minor < v.minor) {
version_to_choose = version;
}
}
}
});
mods[name] = modules[name][version_to_choose];
mods[name].version = version_to_choose;
}
if (conflict) {
callback("multi major version!");
} else {
callback(null, mods);
}
}
builder.get = function (options, callback) {
var self = this;
var cwd = options.cwd || process.cwd();
var cache_root = options.cache_root
cortexJson.enhanced(cwd, function (err, cortex_json) {
if (err) {
return callback(err);
}
var traveller = shrink.shrinktree(cortex_json, cache_root, {
stableOnly: false
}, function (err, tree) {
if (err) {
return callback(err);
}
var walker = new Walker(traveller);
walker.walk(tree, function (err, modules) {
if (err) {
return callback(err);
}
self.pickVersion(modules, function (err, mods) {
if (err) {
return callback(err);
}
callback(null, mods);
});
});
});
});
}
module.exports = builder; | {
"content_hash": "2a9518f88966b017672aa3643b903b1b",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 117,
"avg_line_length": 25.313953488372093,
"alnum_prop": 0.5718879191548002,
"repo_name": "cortexjs/cortex-css-builder",
"id": "842464e4bccc6913ee03d6308c77544f90d42b1e",
"size": "2198",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4564"
}
],
"symlink_target": ""
} |
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Prometheus Dummy Exporter is a testing utility that exposes a prometheus format metric of constant value.
// The metric is exposed at a port that can be configured with flag 'port'
// Metric name and value can be specified with flags 'metric-name' and 'metric-value'.
func main() {
metricName := flag.String("metric-name", "foo", "custom metric name")
metricValue := flag.Int64("metric-value", 0, "custom metric value")
port := flag.Int64("port", 8080, "port to expose metrics on")
flag.Parse()
// [START gke_custom_metrics_prometheus_exporter]
// [START container_custom_metrics_prometheus_exporter]
metric := prometheus.NewGauge(
prometheus.GaugeOpts{
Name: *metricName,
Help: "Custom metric",
},
)
prometheus.MustRegister(metric)
metric.Set(float64(*metricValue))
http.Handle("/metrics", promhttp.Handler())
log.Printf("Starting to listen on :%d", *port)
err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
// [END container_custom_metrics_prometheus_exporter]
// [END gke_custom_metrics_prometheus_exporter]
log.Fatal("Failed to start serving metrics: %v", err)
}
| {
"content_hash": "3abe04405b90a0a3f2dcde12dfd43e6d",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 108,
"avg_line_length": 31.170731707317074,
"alnum_prop": 0.7237871674491393,
"repo_name": "GoogleCloudPlatform/kubernetes-engine-samples",
"id": "a4870ebc63360bb7922f51fddc8bd33510ac0b30",
"size": "1835",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "custom-metrics-autoscaling/prometheus-to-sd/prometheus_dummy_exporter.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "2726"
},
{
"name": "Dockerfile",
"bytes": "17562"
},
{
"name": "Go",
"bytes": "25649"
},
{
"name": "HCL",
"bytes": "6779"
},
{
"name": "HTML",
"bytes": "2856"
},
{
"name": "Java",
"bytes": "675"
},
{
"name": "JavaScript",
"bytes": "1914"
},
{
"name": "PHP",
"bytes": "1594"
},
{
"name": "Procfile",
"bytes": "18"
},
{
"name": "Python",
"bytes": "29836"
},
{
"name": "Ruby",
"bytes": "216"
},
{
"name": "Shell",
"bytes": "13206"
}
],
"symlink_target": ""
} |
#ifndef COHEAR_TUNNEL_H__
#define COHEAR_TUNNEL_H__
#include "detail/TunnelCallbackDescription.h"
#include "detail/TunnelSlot.h"
namespace chr {
/**
* A callback-slot pair, that simply forward any signal that is compatible with
* SignalType from a receiver to a sender. Usage:
*
* // the receiver to listen for signals
* Receiver receiver;
* // the sender to forward the signal to
* Sender sender;
*
* Tunnel<A> tunnel;
*
* receiver.registerCallback(tunnel.getCallback());
* sender.registerSlot(tunnel.getSlot());
*
* Tunnels come with no additional costs for sending signals, they just connect
* all compatible slots that are connected to the receiver with all compatible
* callbacks that are connected to the sender.
*/
template <typename SignalType>
class Tunnel {
public:
/**
* Create and return a new tunnel callback description that forwards to the
* slot of this tunnel.
*/
CallbackDescription* getCallback() {
return new detail::TunnelCallbackDescription<SignalType>(&_slot);
}
/**
* Get a reference to the output slot of this tunnel.
*/
detail::TunnelSlot& getSlot() {
return _slot;
}
private:
detail::TunnelSlot _slot;
};
} // namespace chr
#endif // COHEAR_TUNNEL_H__
| {
"content_hash": "925740877460c5f60454a512ae7287b7",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 80,
"avg_line_length": 21.894736842105264,
"alnum_prop": 0.7067307692307693,
"repo_name": "funkey/cohear",
"id": "a999557aaeb73fb96614a5a0103410fb916a5aa7",
"size": "1248",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Tunnel.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "45784"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="Maven: org.jboss.profileservice:jboss-profileservice-plugins:0.2.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/profileservice/jboss-profileservice-plugins/0.2.2/jboss-profileservice-plugins-0.2.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/profileservice/jboss-profileservice-plugins/0.2.2/jboss-profileservice-plugins-0.2.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/profileservice/jboss-profileservice-plugins/0.2.2/jboss-profileservice-plugins-0.2.2-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "15f372e82b3baf806c19e6a4f98eaf80",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 154,
"avg_line_length": 52.84615384615385,
"alnum_prop": 0.710334788937409,
"repo_name": "YaelMendes/jboss-eap-quickstarts",
"id": "65fa50728adf3969c18e49f0f38ec667d4df9319",
"size": "687",
"binary": false,
"copies": "1",
"ref": "refs/heads/7.0.x-develop",
"path": "ejb-remote/.idea/libraries/Maven__org_jboss_profileservice_jboss_profileservice_plugins_0_2_2.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "311660"
},
{
"name": "HTML",
"bytes": "235227"
},
{
"name": "Java",
"bytes": "1693650"
},
{
"name": "JavaScript",
"bytes": "1815914"
},
{
"name": "Ruby",
"bytes": "5168"
},
{
"name": "Shell",
"bytes": "11933"
}
],
"symlink_target": ""
} |
"""
URL scraping API.
This module contains utility functions to extract (scrape) URLs from data.
Currently only HTML and plain text data are supported.
"""
__license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: [email protected]
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
__all__ = [
# Generic entry point.
"extract",
# Specific parsers for each data format.
"extract_from_text",
"extract_from_html",
# Helper functions.
"is_link",
]
from .web_utils import parse_url, urldefrag, urljoin
from BeautifulSoup import BeautifulSoup
from warnings import warn
import re
from codecs import decode
from chardet import detect
#------------------------------------------------------------------------------
# URL detection regex, by John Gruber.
# http://daringfireball.net/2010/07/improved_regex_for_matching_urls
_re_url_readable = re.compile(r"""(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""", re.I)
#------------------------------------------------------------------------------
# Wrappers for URIs in plain text
# http://www.w3.org/Addressing/URL/url-spec.txt
_re_url_rfc = re.compile(r"""\\<([^\\>]+\\:\\/\\/[^\\>]+)\\>""", re.I)
#------------------------------------------------------------------------------
def is_link(url, base_url):
"""
Determines if an URL is a link to another resource.
:param url: URL to test.
:type url: str
:param base_url: Base URL for the current document.
Must not contain a fragment.
:type base_url: str
:returns: True if the URL points to another page or resource,
False otherwise.
:rtype: bool
"""
try:
# Parse the URL. If it can't be parsed, it's not a link.
parsed = parse_url(url, base_url)
# URLs that point to the same page
# in a different fragment are not links.
parsed.fragment = ""
if parsed.url == base_url:
return False
# All other URLs are links.
return True
# On any parsing error assume it's not a link.
except Exception:
return False
#------------------------------------------------------------------------------
def extract_from_text(text, base_url = None, only_links = True):
"""
Extract URLs from text.
Implementation notes:
- Unicode URLs are currently not supported.
:param text: Text.
:type text: str
:param base_url: Base URL for the current document.
If not specified, relative URLs are ignored.
:type base_url: str
:param only_links: If True, only extract links to other resources.
If False, extract all URLs.
:type only_links: bool
:returns: Extracted URLs.
:rtype: set(str)
"""
# Trivial case.
if not text:
return set()
# Check the type.
if not isinstance(text, basestring):
raise TypeError("Expected string, got %r instead" % type(text))
# Set where the URLs will be collected.
result = set()
# Remove the fragment from the base URL.
if base_url:
base_url = urldefrag(base_url)[0]
# Look for URLs using regular expressions.
for regex in (_re_url_rfc, _re_url_readable):
for url in regex.findall(text):
url = url[0]
# Skip if we've already seen it.
if url in result:
continue
# XXX FIXME
# Make sure the text is really ASCII text.
# We don't support Unicode yet.
try:
url = str(url)
except Exception:
warn("Unicode URLs not yet supported: %r" % url)
continue
# If a base URL was given...
if base_url:
# Canonicalize the URL.
# Discard it on parse error.
try:
url = urljoin(base_url, url.strip())
except Exception:
continue
# Skip if we've already seen it.
if url in result:
continue
# Discard URLs that are not links to other pages or resources,
# and URLs we've already seen.
if only_links and (url in result or
not is_link(url, base_url = base_url)):
continue
# If a base URL was NOT given...
else:
# Discard relative URLs.
# Also discard them on parse error.
try:
parsed = parse_url(url)
if not parsed.scheme or not parsed.netloc:
continue
except Exception:
raise
continue
# Add the URL to the set.
result.add(url)
# Return the set of collected URLs.
return result
#------------------------------------------------------------------------------
def extract_forms_from_html(raw_html, base_url):
"""
Extract forms info from HTML.
:param raw_html: Raw HTML data.
:type raw_html: str
:param base_url: Base URL for the current document.
:type base_url: str
:returns: Extracted form info.
:rtype: list((URL, METHOD, list({ "name" : PARAM_NAME, "value" : PARAM_VALUE, "type" : PARAM_TYPE})))
"""
# Set where the URLs will be collected.
result = list()
result_append = result.append
# Remove the fragment from the base URL.
base_url = urldefrag(base_url)[0]
# Parse the raw HTML.
bs = BeautifulSoup(decode(raw_html, detect(raw_html)["encoding"]))
for form in bs.findAll("form"):
target = form.get("action", None)
method = form.get("method", "POST").upper()
if not target:
continue
try:
target = str(target)
except Exception:
warn("Unicode URLs not yet supported: %r" % target)
continue
# Canonicalize the URL.
try:
target = urljoin(base_url, target.strip())
except Exception:
continue
form_params = []
form_params_append = form_params.append
for params in form.findAll("input"):
if params.get("type") == "submit":
continue
form_params_append({
"name": params.get("name", "NAME"),
"value": params.get("value", "VALUE"),
"type": params.get("type", "TYPE")})
# Add to results
result_append((target, method, form_params))
return result
#------------------------------------------------------------------------------
def extract_from_html(raw_html, base_url, only_links = True):
"""
Extract URLs from HTML.
Implementation notes:
- The current implementation is fault tolerant, meaning it will try
to extract URLs even if the HTML is malformed and browsers wouldn't
normally see those links. This may therefore result in some false
positives.
- HTML5 tags are supported, including tags not currently supported by
any major browser.
:param raw_html: Raw HTML data.
:type raw_html: str
:param base_url: Base URL for the current document.
:type base_url: str
:param only_links: If True, only extract links to other resources.
If False, extract all URLs.
:type only_links: bool
:returns: Extracted URLs.
:rtype: set(str)
"""
# Set where the URLs will be collected.
result = set()
add_result = result.add
# Remove the fragment from the base URL.
base_url = urldefrag(base_url)[0]
# Parse the raw HTML.
bs = BeautifulSoup(decode(raw_html, detect(raw_html)["encoding"]),
convertEntities = BeautifulSoup.ALL_ENTITIES)
# Some sets of tags and attributes to look for.
href_tags = {"a", "link", "area"}
src_tags = {"script", "img", "iframe", "frame", "embed", "source", "track"}
param_names = {"movie", "href", "link", "src", "url", "uri"}
# Iterate once through all tags...
for tag in bs.findAll():
# Get the tag name, case insensitive.
name = tag.name.lower()
# Extract the URL from each tag that has one.
url = None
if name in href_tags:
url = tag.get("href", None)
elif name in src_tags:
url = tag.get("src", None)
elif name == "param":
name = tag.get("name", "").lower().strip()
if name in param_names:
url = tag.get("value", None)
##elif name == "form":
## url = tag.get("action", None)
elif name == "object":
url = tag.get("data", None)
elif name == "applet":
url = tag.get("code", None)
elif name == "meta":
name = tag.get("name", "").lower().strip()
if name == "http-equiv":
content = tag.get("content", "")
p = content.find(";")
if p >= 0:
url = content[ p + 1 : ]
elif name == "base":
url = tag.get("href", None)
if url is not None:
# XXX FIXME
# Unicode URLs are not supported.
try:
url = str(url)
except Exception:
warn("Unicode URLs not yet supported: %r" % url)
continue
# Update the base URL.
try:
base_url = urljoin(base_url, url.strip(),
allow_fragments = False)
except Exception:
continue
# If we found an URL in this tag...
if url is not None:
# XXX FIXME
# Unicode URLs are not supported.
try:
url = str(url)
except Exception:
warn("Unicode URLs not yet supported: %r" % url)
continue
# Canonicalize the URL.
try:
url = urljoin(base_url, url.strip())
except Exception:
continue
# Discard URLs that are not links to other pages or resources.
if not only_links or is_link(url, base_url = base_url):
# Add the URL to the set.
add_result(url)
# Return the set of collected URLs.
return result
#------------------------------------------------------------------------------
def extract(raw_data, content_type, base_url, only_links = True):
"""
Extract URLs from raw data.
Implementation notes:
- Unicode URLs are currently not supported.
- The current implementation is fault tolerant, meaning it will try
to extract URLs even if the HTML is malformed and browsers wouldn't
normally see those links. This may therefore result in some false
positives.
- HTML5 tags are supported, including tags not currently supported by
any major browser.
:param raw_data: Raw data.
:type raw_data: str
:param content_type: MIME content type.
:type content_type: str
:param base_url: Base URL for the current document.
:type base_url: str
:param only_links: If True, only extract links to other resources.
If False, extract all URLs.
:type only_links: bool
:returns: Extracted URLs.
:rtype: set(str)
"""
# Sanitize the content type.
content_type = content_type.strip().lower()
if ";" in content_type:
content_type = content_type[ content_type.find(";") : ].strip()
# HTML parser.
if content_type == "text/html":
urls = extract_from_html(raw_data, base_url, only_links)
urls.update( extract_from_text(raw_data, base_url, only_links) )
return urls
# Generic plain text parser.
if content_type.startswith("text/"):
return extract_from_text(raw_data, base_url, only_links)
# Unsupported content type.
return set()
| {
"content_hash": "f892502bede03f4a73373d1cdd34bc92",
"timestamp": "",
"source": "github",
"line_count": 427,
"max_line_length": 248,
"avg_line_length": 30.271662763466043,
"alnum_prop": 0.540151632368869,
"repo_name": "JeyZeta/Dangerous",
"id": "b459f3f2cae4b7df43d3d5e9ad81212429cf58ed",
"size": "12983",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "Dangerous/Golismero/golismero/api/net/scraper.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "13260"
},
{
"name": "C",
"bytes": "12851"
},
{
"name": "C++",
"bytes": "3174"
},
{
"name": "CSS",
"bytes": "267451"
},
{
"name": "HTML",
"bytes": "2686153"
},
{
"name": "JavaScript",
"bytes": "1356956"
},
{
"name": "Lua",
"bytes": "14436"
},
{
"name": "Makefile",
"bytes": "11190"
},
{
"name": "Objective-C",
"bytes": "998"
},
{
"name": "PHP",
"bytes": "619"
},
{
"name": "PLpgSQL",
"bytes": "536"
},
{
"name": "Perl",
"bytes": "263365"
},
{
"name": "Python",
"bytes": "16669102"
},
{
"name": "Roff",
"bytes": "9828"
},
{
"name": "Ruby",
"bytes": "503"
},
{
"name": "Shell",
"bytes": "6691"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="{{ site.lang | default: "en-US" }}">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<link href='https://fonts.googleapis.com/css?family=Chivo:900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">
<link rel="stylesheet" type="text/css" href="{{ '/assets/css/print.css' | relative_url }}" media="print">
<link rel="shortcut icon" type="image/png" href="/assets/imgs/logo.png"/>
<title>{{ site.title | default: site.github.repository_name }} by {{ site.github.owner_name }}</title>
</head>
<body>
<div id="container">
<div class="inner">
<header>
<h1>{{ page.title | default: site.title | default: site.github.repository_name }}</h1>
<h2>{{ page.description | default: site.description | default: site.github.project_tagline }}</h2>
</header>
<section id="downloads" class="clearfix">
{% if site.show_downloads %}
<a href="{{ site.github.zip_url }}" id="download-zip" class="button"><span>Download .zip</span></a>
<a href="{{ site.github.tar_url }}" id="download-tar-gz" class="button"><span>Download .tar.gz</span></a>
{% endif %}
{% if site.github.is_project_page %}
<a href="{{ site.github.repository_url }}" id="view-on-github" class="button"><span>View on GitHub</span></a>
{% else %}
<a href="{{ site.github.owner_url }}" id="view-on-github" class="button"><span>View on GitHub</span></a>
{% endif %}
</section>
<hr>
<section id="main_content">
{{ content }}
</section>
<footer>
{% if site.github.is_project_page %}
{{ site.title | default: site.github.repository_name }} is maintained by <a href="{{ site.github.owner_url }}">{{ site.github.owner_name }}</a><br>
{% endif %}
This page was generated by <a href="https://pages.github.com">GitHub Pages</a>.
</footer>
</div>
</div>
{% if site.google_analytics %}
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '{{ site.google_analytics }}', 'auto');
ga('send', 'pageview');
</script>
{% endif %}
</body>
</html> | {
"content_hash": "5ae2f98c1f279df306f0c5163740f13f",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 157,
"avg_line_length": 46.06896551724138,
"alnum_prop": 0.5815868263473054,
"repo_name": "isortegah/isortegah.github.io",
"id": "4299a652a5b277e31fbad245be1b2c120d9e2ad6",
"size": "2672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_layouts/defaults.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "32872"
},
{
"name": "HTML",
"bytes": "170479"
},
{
"name": "Ruby",
"bytes": "3217"
},
{
"name": "SCSS",
"bytes": "36"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: HP
* Date: 09/03/2016
* Time: 12:59 AM
*/
namespace RbacUserDoctrineOrm\Authentication\Storage;
use Doctrine\ORM\EntityManagerInterface;
use RbacUserDoctrineOrm\Domain\AbstractRbacUser;
use RbacUserDoctrineOrm\Domain\Role;
use Zend\Authentication\Storage\StorageInterface;
use Zend\Stdlib\ArrayUtils;
use ZfcUser\Options\ModuleOptions;
class ZfcUserDoctrineStorageDelegator implements StorageInterface
{
/**
* @var StorageInterface
*/
private $wrappedStorage;
/**
* @var EntityManagerInterface
*/
private $em;
/**
*
* @var ModuleOptions
*/
private $zfcUserModuleOptions;
public function __construct(StorageInterface $wrappedStorage, EntityManagerInterface $em, ModuleOptions $zfcUserModuleOptions)
{
$this->wrappedStorage = $wrappedStorage;
$this->em = $em;
$this->zfcUserModuleOptions = $zfcUserModuleOptions;
}
public function isEmpty()
{
return $this->wrappedStorage->isEmpty();
}
public function read()
{
return $this->wrappedStorage->read();
}
public function write($contents)
{
$this->_write($contents);
}
/**
* @param AbstractRbacUser $contents
* @return void
*/
private function _write(AbstractRbacUser $contents){
/* @var $user AbstractRbacUser */
$user = $contents;
if ( !$this->em->contains($user)){
$user = $this->em->find($this->zfcUserModuleOptions->getUserEntityClass(), $contents->getId());
$this->_write($user);
}
$allGrantedRoles = [];
$todoRoles = new \ArrayIterator($user->getDbRoles()->getValues());
$todoRoles->rewind();
while ($todoRoles->valid()){
/* @var $role Role */
$role = $todoRoles->current();
if ( !array_key_exists($role->getName(), $allGrantedRoles)){
$permissions = $role->getPermissions();
if( !$permissions->isInitialized() ){
$permissions->initialize();
}
$allGrantedRoles[$role->getName()] = $role;
foreach ($role->getChildren()->getValues() as $childRole) {
$todoRoles->append($childRole);
}
}
$todoRoles->next();
}
$user = $this->em->detach($user);
$roles = $user->getDbRoles();
$roles->unwrap()->clear();
$roles->setDirty(true);
$roles->setInitialized(false);
$user->_setAllGrantedRoles( ArrayUtils::merge($allGrantedRoles, $user->getProviderRoles()) );
$this->wrappedStorage->write($user);
}
public function clear()
{
$this->wrappedStorage->clear();
}
}
| {
"content_hash": "77b394b2595dd7d4b5fe54b4716dff90",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 131,
"avg_line_length": 26.78095238095238,
"alnum_prop": 0.5807254623044097,
"repo_name": "evilband7/RbacUserDoctrineOrm",
"id": "9851eb35e616d0c02b30fad4bc80bd15a5221ed5",
"size": "2812",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RbacUserDoctrineOrm/src/RbacUserDoctrineOrm/Authentication/Storage/ZfcUserDoctrineStorageDelegator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "936"
},
{
"name": "PHP",
"bytes": "14133"
}
],
"symlink_target": ""
} |
& | {
"content_hash": "bf49803a716571e8acf4c7036a83987c",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 4,
"avg_line_length": 4,
"alnum_prop": 0.75,
"repo_name": "krosenvold/nekohtml",
"id": "73df8425620edc76908db5bed2d6cf1e8638b320",
"size": "4",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "data/test085.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "482744"
}
],
"symlink_target": ""
} |
<!--
Copyright 2014 Google Inc. 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.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<!-- Shown in the schedule to indicate how many sessions are available on that particular time slot. -->
<plurals name="schedule_block_subtitle">
<item quantity="other">사용 가능한 세션 <xliff:g id="number_of_sessions">%1$d</xliff:g>개</item>
</plurals>
<!-- Shows as a notification on the system bar to alert user that some of their sessions are about to begin. -->
<plurals name="session_notification_text">
<item quantity="other">및 다른 <xliff:g id="num_sessions">%2$d</xliff:g>개가 <xliff:g id="remaining_time">%1$d</xliff:g>분에 시작합니다.</item>
</plurals>
<!-- Shown as a notification on the system bar to alert user that some of their sessions are about to begin. -->
<plurals name="session_notification_ticker">
<item quantity="other">%d 세션을 시작하려 합니다.</item>
</plurals>
<!-- Title for the notification that alerts the user that some of their sessions are about to begin. -->
<plurals name="session_notification_title">
<item quantity="other">
<xliff:g id="num_sessions">%2$d</xliff:g>개 세션이 <xliff:g id="remaining_time">%1$d</xliff:g>분에 시작합니다.</item>
</plurals>
<!-- Shown in the 'About' window of the app. -->
<string name="about_body"><b>GDG DevFest Omsk 2014</b><br> 버전 %s<br><br> <a href=http://m.google.com/utos>서비스 계약</a><br><br> <a href=http://www.google.com/policies/privacy/>개인 정보 취급 방침</a></string>
<!-- Shown as a link in the About screen of the app; user can click to see the EULA. -->
<string name="about_eula">최종 사용자 사용권 계약</string>
<!-- Shown as a link in the About screen of the app; user can click it to see the licenses. -->
<string name="about_licenses">오픈소스 라이센스</string>
<!-- Label on a button that the user clicks to accept a license agreement. -->
<string name="accept">수락</string>
<!-- Label on a button that, when clicked, allows user to add an account to the device. -->
<string name="add_account">계정 추가</string>
<!-- Label on a button that, when clicked, adds the currently displayed session to their schedule. -->
<string name="add_to_schedule">일정에 추가</string>
<!-- Accessibility description for a button that, when clicked, adds the currently
displayed session to the user's schedule. -->
<string name="add_to_schedule_desc">일정에 세션을 추가하는 버튼</string>
<!-- Shown in a drop-down list on the main screen, indicating that all conference sessions
are being displayed. -->
<string name="all_sessions">모든 세션</string>
<!-- Shown in a drop-down list on the main screen, indicating that all conference themes
are being displayed. Themes are major categories for sessions (the themes are Design,
Develop and Distribute). -->
<string name="all_themes">모든 테마</string>
<!-- Shown in a drop-down list on the main screen, indicating that all conference topics
are being displayed. Topics are major categories for sessions (example topics are: Android,
Chrome, Google APIs, Wearables, etc). -->
<string name="all_topics">모든 주제</string>
<!-- Shown in a drop-down list on the main screen, indicating that all session types
are being displayed. Some examples of session types are: session, office hours, code lab. -->
<string name="all_types">모든 유형</string>
<!-- Shown in a drop-down list on the Video Library screen, indicating that videos from all
GDG DevFest Omsk years are being displayed. -->
<string name="all_years">모든 년도</string>
<!-- Label on a button that is one possible answer to the question "Are you attending the
conference in person in Omsk or remotely via livestream?" -->
<string name="attending_in_person">직접 참석</string>
<!-- Label on a button that is one possible answer to the question "Are you attending the
conference in person in Omsk or remotely via livestream?" -->
<string name="attending_remotely">원격 연결</string>
<!-- Label on a button that allows the user to browse GDG DevFest Omsk Extended events that they
might be interested in attending. -->
<string name="browse_events">이벤트 가져오기</string>
<!-- Label on a button that allows the user to see what conference sessions are available
at a particular time. -->
<string name="browse_sessions">세션 가져오기...</string>
<!-- Shown on Configure WiFi dialog, instructing user on what button to click. -->
<string name="calltoaction_wifi_configure"><br><br>계속하려면 \'Wi-Fi 네트워크 추가\'를 누릅니다.</string>
<!-- Shown on Configure WiFi dialog, instructing user on what button to click. -->
<string name="calltoaction_wifi_settings"><br><br>Wi-Fi를 사용하려면 \'Wi-Fi 설정 열기\'를 누릅니다.</string>
<!-- Accessibility description for a button that allows the user to close a session details pane. -->
<string name="close_detail_pane">세부 정보 창 닫기</string>
<!-- Label on a button that allows the user to cancel an operation before it starts. For
example, this may be a button on a dialog that says "This will delete your data." -->
<string name="cancel">취소</string>
<!-- Text on a warning box that appears to warn the user they are viewing data that hasn't
been updated by the server recently, so it might be out of date.-->
<string name="data_stale_warning">지금 보고 계신 데이터는 업데이트 되지 않은 정보입니다.</string>
<!-- Shown as the title of the user's schedule for today -->
<string name="day_title_today">오늘</string>
<!-- Shown as the title of the user's schedule for tomorrow -->
<string name="day_title_tomorrow">내일</string>
<!-- Shown as the title of the user's schedule for yesterday -->
<string name="day_title_yesterday">어제</string>
<!-- Label on a button that the user clicks to decline something (for example, a license
agreement). -->
<string name="decline">거부</string>
<!-- Menu item that brings up the application's About screen -->
<string name="description_about">정보</string>
<!-- Menu item that allows user to add a session to their schedule -->
<string name="description_add_schedule">일정에 추가</string>
<!-- Menu item that allows the user to send feedback about the application to Google. This
says 'App Feedback' to clarify that it's feedback about the application, and not about a
session. -->
<string name="description_app_feedback">앱 피드백</string>
<!-- Menu item that allows the user to send feedback about the application to Google -->
<string name="description_app_feedback_old">피드백</string>
<!-- Menu item that, when clicked, shows the captions on a video. -->
<string name="description_captions">자막</string>
<!-- Menu item that allows user to configure the conference WiFi on their device. -->
<string name="description_configure_wifi">Wi-Fi 구성</string>
<!-- Menu item that takes the user to a page that shows a list of GDG DevFest Omsk Extended events. -->
<string name="description_i_o_extended">GDG DevFest Omsk 확장</string>
<!-- Menu item that takes the user to the conference venue map screen -->
<string name="description_map">지도</string>
<!-- Menu item that allows user to turn on or turn off the output of a video to a
second screen. -->
<string name="description_presentation">화면 출력 전환</string>
<!-- Menu item that allows user to reload the data in the current screen so they see
the most up-to-date version from the server. -->
<string name="description_refresh">새로 고침</string>
<!-- Menu item that allows the user to remove the currently session from their schedule. -->
<string name="description_remove_schedule">일정에서 제거</string>
<!-- Menu item that allows the user to start a search for a session by name. After clicking,
they type in their search query. -->
<string name="description_search">검색</string>
<!-- Menu item that takes the user to the application's Settings screen -->
<string name="description_settings">설정</string>
<!-- Explanation of wifi setup that appears in the WiFi setup dialog box. -->
<string name="description_setup_wifi_body">직접 참석했기 때문에 이 장치가 회의 Wi-Fi 네트워크를 액세스하도록 설정할 수 있습니다 (5Ghz). 지금 Wi-Fi를 구성하면 네트워크 혼잡을 피할 수 있습니다.</string>
<!-- Menu item that allows user to share the currently displayed session. Sharing can be done
by email, social networks, etc. -->
<string name="description_share">공유</string>
<!-- Menu item that allows the user to view the Google+ stream about a particular topic. This
appears as a menu item on a Sesssion screen, and opens the Google+ app to show the Google+
posts about that session's topic. -->
<string name="description_social_stream">Google+ 스트림 보기</string>
<!-- Accessibility description saying that the app's navigation drawer has been closed -->
<string name="drawer_close">내비게이션 서랍 닫힘</string>
<!-- Accessibility description saying that the app's navigation drawer has been opened -->
<string name="drawer_open">내비게이션 서랍 열기</string>
<!-- Shown when trying to watch a video of a session, alerting user that no captions are
available for that video. -->
<string name="empty_captions">이 세션에서 자막을 찾을 수 없습니다.</string>
<!-- Shown on the Session page, alerting user that no details could be found for that session. -->
<string name="empty_session_detail">세션 세부 정보가 없습니다.</string>
<!-- Shown on the session search page, alerting user that no conference sessions could be found. -->
<string name="empty_sessions">세션이 없습니다.</string>
<!-- Shown on several screens alerting user that no data is being shown because a background
data synchronization is still in progress. Data will show as soon as the sync ends. -->
<string name="empty_waiting_for_sync">동기화를 기다리는 중...</string>
<!-- Shown on a widget that normally displays upcoming sessions. This is shown after the
conference, when there are no more sessions to show. -->
<string name="empty_widget_text">예정된 세션이 더 이상 없습니다.\n내년에 뵙겠습니다!</string>
<!-- Shown on a widget instructing user how to start using the widget. -->
<string name="empty_widget_text_signed_out">앱에 로그인해 사용을 시작하려면 위에 있는 GDG DevFest Omsk 2014 로고를 누릅니다.</string>
<!-- Shown as a header on a list of sessions to indicate that the sessions that appear on that
group have already ended. -->
<string name="ended_sessions">종료된 세션</string>
<!-- Label for a button that, when clicked, allows the user to send their feedback (ratings
and comments) about a particular session. -->
<string name="give_feedback">예</string>
<!-- Error message that shows when the user tries to use the app without a Google account
configured on their device. -->
<string name="google_account_required_message">이 애플리케이션을 사용하려면 장치에 하나 이상의 Google 계정이 있어야 합니다.</string>
<!-- Title for an error message that appears when the user tries to use the app without
a Google account configured on their device. -->
<string name="google_account_required_title">Google 계정 필요</string>
<!-- List dropdown item on the Video Library screen allowing the user to choose to see
the videos from a particular year of GDG DevFest Omsk. -->
<string name="google_i_o_year">GDG DevFest Omsk <xliff:g id="year">%1$d</xliff:g>
</string>
<!-- Label on a button that the user can click to dismiss an reminder or information message.
For example "To scan an attendee's badge, hold your phone close to the badge for a few
seconds." -->
<string name="got_it">확인</string>
<!-- Short text appended to the end of the session subtitle when the session will be live
streamed. Constrained to 10 chars because the session subtitle should be small enough to fit
into the explore cards. [CHAR_LIMIT=10] -->
<string name="live_available">생방송</string>
<!-- Short text appended to the end of the session subtitle when the session is currently being
streamed. Also used in a "LIVE" badge overlay that shows up on top of the session card.
Constrained because the session subtitle should be small enough to fit into the
explore cards. [CHAR_LIMIT=10] -->
<string name="live_now">생방송 중</string>
<!-- Message presented while data is loading in Explore view -->
<string name="loading">로드 중...</string>
<!-- Message shown in an error bar when user could not be logged in. [CHAR_LIMIT=75] -->
<string name="login_failed_text">오류가 발생하여 세션 정보를 동기화 하지 못했습니다.</string>
<!-- Button to retry a failed login attempt [CHAR_LIMIT=2 lines of 9 characters].
If using multiple lines, separate them with "\n" ("Tentar\nde novo" for example)
-->
<string name="login_failed_text_retry">다시 시도</string>
<!-- Message shown in a popup to request a mandatory upgrade -->
<string name="mandatory_update_error">애플리케이션이 이전 버전입니다. 계속 사용하려면 업그레이드해야 합니다.</string>
<!-- Message shown in a popup to indicate that there is a mandatory upgrade -->
<string name="update_available">Google Play에서 이 애플리케이션의 새 버전을 사용할 수 있습니다.</string>
<!-- Message shown in a map popup to indicate the next session.
Param %1$s: time of the next session
Param %2$s: title of the next session
-->
<string name="map_at"><b>%2$s</b> 시간:<br>%1$s</string>
<!-- Indicator shown when there is no upcoming session in a room -->
<string name="map_infowindow_text_empty">-</string>
<!-- Message shown in a map popup to indicate the current session.
Param %1$s: title of the next session
-->
<string name="map_now_playing">재생 중:<br><b>%1$s</b></string>
<!-- Clickable text in the map popup that leads to sessions in a room -->
<string name="map_touch_to_see_session">세션을 보려면 누릅니다.</string>
<!-- Text on a button that allows the user to browse more sessions -->
<string name="more_sessions">세션 더 보기</string>
<!-- Accessibility description for tab that shows the attendee's schedule for a given day. -->
<string name="my_schedule_tab_desc_a11y">
<xliff:g id="day">%1$s</xliff:g>일 일정을 보려면 누릅니다.</string>
<!-- Accessibility announcement to alert user that they are now viewing their schedule of a given day. -->
<string name="my_schedule_page_desc_a11y">
<xliff:g id="day">%1$s</xliff:g>일 일정을 표시합니다.</string>
<!-- Accessibility description for navigation drawer -->
<string name="navdrawer_description_a11y">내비게이션 서랍. 이 서랍에는 애플리케이션의 다양한 화면을 보관할 수 있는 단추가 있습니다.</string>
<!-- Menu item to send feedback about the app [CHAR_LIMIT=20] -->
<string name="navdrawer_item_app_feedback">앱 피드백</string>
<!-- Accessibility description for menu item to send feedback about the app -->
<string name="navdrawer_item_app_feedback_a11y">앱 피드백</string>
<!-- Menu item to open the Experts screen [CHAR_LIMIT=20] -->
<string name="navdrawer_item_experts_directory">전문가</string>
<!-- Accessibility description for menu item to open the Experts screen. -->
<string name="navdrawer_item_experts_directory_a11y">전문가 디렉토리</string>
<!-- Menu item to open the Explore screen [CHAR_LIMIT=20] -->
<string name="navdrawer_item_explore">탐색</string>
<!-- Accessibility description for menu item to open the Explore screen. -->
<string name="navdrawer_item_explore_a11y">GDG DevFest Omsk 탐색</string>
<!-- Menu item to open the Map screen [CHAR_LIMIT=20] -->
<string name="navdrawer_item_map">지도</string>
<!-- Menu item to open the My Schedule screen [CHAR_LIMIT=20] -->
<string name="navdrawer_item_my_schedule">내 일정</string>
<!-- Menu item to open the People I've Met screen [CHAR_LIMIT=20] -->
<string name="navdrawer_item_people_ive_met">만난 사람</string>
<!-- Accessibility description of item to open the People I've Met screen -->
<string name="navdrawer_item_people_ive_met_a11y">만난 사람</string>
<!-- Menu item to open the Settings screen [CHAR_LIMIT=20] -->
<string name="navdrawer_item_settings">설정</string>
<!-- Menu item to start the Sign In flow [CHAR_LIMIT=20] -->
<string name="navdrawer_item_sign_in">로그인</string>
<!-- Menu item to open a screen that lists GDG DevFest Omsk related hashtags. Each hashtag, when clicked, will
open Google+ stream of posts that uses the hashtag [CHAR_LIMIT=20] -->
<string name="navdrawer_item_social">소셜</string>
<!-- Menu item to open a list of current and past GDG DevFest Omsk videos [CHAR_LIMIT=20] -->
<string name="navdrawer_item_video_library">비디오 라이브러리</string>
<!-- Text indicator that appears below the user's name, showing that they are
attending the conference in person in Omsk. -->
<string name="navdrawer_status_attending_in_person">GDG DevFest Omsk에 직접 참석</string>
<!-- Text indicator that appears below the user's name, showing that they are
attending the conference remotely via live streaming. -->
<string name="navdrawer_status_attending_remotely">GDG DevFest Omsk에 원격으로 참석</string>
<!-- Message shown in a toast (popup) when the user clicks to change the active account but
there is no network connection -->
<string name="no_connection_cant_login">로그인할 수 없습니다. 네트워크 연결을 확인하십시오.</string>
<!-- Message shown in the session explorer when the user applies a filter that results no
session -->
<string name="no_matching_sessions">일치하는 세션이 없습니다.</string>
<!-- Message shown in the session explorer when the user selects a time slot that has no
session -->
<string name="no_matching_sessions_in_interval">이 시간 슬롯에서 사용할 수 있는 세션이 없습니다.</string>
<!-- Message shown in the video library when the user applies a filter that results no video -->
<string name="no_matching_videos">일치하는 비디오가 없습니다.</string>
<!-- Button of a card in session or session explorer that dismiss the card.
One sample of such card is "How was this session? We would love to hear your feedback" with
"Give feedback" and "No, thanks" as buttons. [CHAR_LIMIT=20]-->
<string name="no_thanks">아니오. 괜찮습니다.</string>
<!-- Button of a popup that shows up when the user has no Google account registered in the
device. The popup says that the user needs to have at least one Google account registered in the
device to be able to use the app. [CHAR_LIMIT=20] -->
<string name="not_now">지금 하지 않음</string>
<!-- Number in a scale of 1 to 5 used to rate a session [CHAR_LIMIT=2]-->
<string name="number_1">1</string>
<!-- Number in a scale of 1 to 5 used to rate a session [CHAR_LIMIT=2]-->
<string name="number_2">2</string>
<!-- Number in a scale of 1 to 5 used to rate a session [CHAR_LIMIT=2]-->
<string name="number_3">3</string>
<!-- Number in a scale of 1 to 5 used to rate a session [CHAR_LIMIT=2]-->
<string name="number_4">4</string>
<!-- Number in a scale of 1 to 5 used to rate a session [CHAR_LIMIT=2]-->
<string name="number_5">5</string>
<!-- A single button shown on informative popups, like EULA, open source licenses and About -->
<string name="ok">확인</string>
<!-- Header for a group of sessions in Session Explorer that don't fit into other tag-based groups -->
<string name="others">기타</string>
<!-- An application permission (this permission allows the application to modify the Google
GDG DevFest Omsk schedule data). Shows on a permissions dialog screen. -->
<string name="permission_write">GDG DevFest Omsk 일정 데이터 수정</string>
<!-- Description of the Google+ +1 button for accessibility screen readers -->
<string name="plus_one_description_standard">하나를 더하려면 누릅니다.</string>
<!-- Title in the Settings screen for the setting that enables sending of anonymous usage
statistics to Google. This title will be accompanied by a longer description
of the setting, so it does not need to be too verbose. [CHAR_LIMIT=40] -->
<string name="pref_analytics_enabled_title">사용 통계 익명으로 전송</string>
<!-- Description in the Settings screen for the setting that enables sending of anonymous usage
statistics to Google. -->
<string name="pref_analytics_enabled_description">이 옵션을 선택하면 사용 통계가 익명으로 Google에 전송됩니다.</string>
<!-- Summary in the Settings screen for the "I will be at GDG DevFest Omsk" option -->
<string name="pref_attendee_at_venue_description">확인 표시를 하면 모든 세션과 현장 이벤트가 표시됩니다.\n확인 표시를 하지 않으면 생방송 세션만 표시됩니다.</string>
<!-- Title in the Settings screen for the "I will be at GDG DevFest Omsk" option -->
<string name="pref_attendee_at_venue_title">GDG DevFest Omsk에 있습니다!</string>
<!-- Summary in the Settings screen for the "Show local times" option -->
<string name="pref_local_times_description">확인 표시를 하면 장치에 설정된 지역 시간으로 시간이 표시됩니다. 확인 표시를 하지 않으면 회의의 지역 시간인 PDT로 시간이 표시됩니다.</string>
<!-- Title in the Settings screen for the "Show local times" option -->
<string name="pref_local_times_title">지역 시간 표시</string>
<!-- Summary in the Settings screen for the "Notify me to send feedback about my sessions" option -->
<string name="pref_notify_feedback_description">확인 표시를 하면 선택한 세션에 대한 피드백을 요청하는 알림 메시지가 표시됩니다.</string>
<!-- Title in the Settings screen for the "Notify me to send feedback about my sessions" option -->
<string name="pref_notify_feedback_title">피드백 보내기 알림</string>
<!-- Summary in the Settings screen for the "Notify me when my sessions are about to begin" option -->
<string name="pref_notify_starred_sessions_description">확인 표시를 하면 선택한 세션이 시작될 때 알림 메시지가 표시됩니다.</string>
<!-- Title in the Settings screen for the "Notify me when my sessions are about to begin" option -->
<string name="pref_notify_starred_sessions_title">세션 시작 알림</string>
<!-- Title in the Settings screen for the "Synchronize my schedule with Google Calendar" option -->
<string name="pref_sync_with_calendar_description">확인 표시를 하면 선택한 세션이 Google 캘린더에 자동으로 동기화됩니다.</string>
<!-- Summary in the Settings screen for the "Synchronize my schedule with Google Calendar" option -->
<string name="pref_sync_with_calendar_title">구글 캘린더와 동기화</string>
<!-- Text of a card shown in the session explorer that asks the user if he wants to see GDG DevFest Omsk
extended events in his area. "Browse events" and "No, thanks" are the buttons shown in the card -->
<string name="question_i_o_extended">귀하의 지역 근처에서 열리는 GDG DevFest Omsk 확장 이벤트에 대한 추가 정보를 알고 싶나요?</string>
<!-- Text of a card shown in the session explorer that asks the user if he will be attending GDG DevFest Omsk
in person or remotely. "Remotely" and "In person" are the buttons shown in the card -->
<string name="question_local_or_remote">샌프란시스코에서 열리는 GDG DevFest Omsk에 원격 또는 직접 참가하시겠습니까?</string>
<!-- Text of a card shown in the session explorer after GDG DevFest Omsk has started that asks the user if
he wants to configure the WiFi. "Yes!" and "No, thanks" are the buttons shown in the card -->
<string name="question_setup_wifi_after_i_o_start">GDG DevFest Omsk에 오셨습니다! 지금 회의 WiFi를 구성하시겠습니까?</string>
<!-- Text of a card shown in the session explorer before GDG DevFest Omsk has started that asks the user if
he wants to configure the WiFi. "Yes!" and "No, thanks" are the buttons shown in the card -->
<string name="question_setup_wifi_before_i_o_start">GDG DevFest Omsk가 다가오고 있습니다. 지금 회의 WiFi를 구성하시겠습니까?</string>
<!-- Section title for videos related to a particular event session -->
<string name="related_videos">관련 비디오</string>
<!-- Button text indicating the session is in the user's schedule -->
<string name="remove_from_schedule">일정</string>
<!-- Accessibility content description for button used to remove the session from the user's schedule -->
<string name="remove_from_schedule_desc">일정에서 세션을 제거하는 단추입니다.</string>
<!-- Button label allowing users to retry a failed operation -->
<string name="retry">다시 시도</string>
<!-- Text hint that shows when a session is in conflict with a session already on the user's schedule -->
<string name="schedule_conflict_with_previous">(충돌)</string>
<!-- Indicates the ending block of a session time. Used in a text fragment like "8:00 AM to 9:00 AM" [CHAR_LIMIT=4 (excluding placeholders)]-->
<string name="schedule_end_time">- <xliff:g id="endTime">%1$s</xliff:g>
</string>
<!-- -->
<string name="schedule_session_subtitle">
<xliff:g id="speakers">%1$s</xliff:g>\n<xliff:g id="room">%2$s</xliff:g>
</string>
<!-- Hint that the user can search across sessions -->
<string name="search_hint">세션 검색</string>
<!-- Search label that shows the type of data being searched for when the user clicks the
Search button. -->
<string name="search_label">GDG DevFest Omsk 세션</string>
<!-- A fragment of text appended to a Google calendar event indicating it was added by this application -->
<string name="session_calendar_suffix">- GDG DevFest Omsk Android 앱이 추가함</string>
<!-- Accessibility text announced as a response to pressing a button to add a session to the schedule. -->
<string name="session_details_a11y_session_added">일정에 세션이 추가되었습니다.</string>
<!-- Accessibility text announced as a response to pressing a button to remove a session from the schedule. -->
<string name="session_details_a11y_session_removed">일정에서 세션이 제거되었습니다.</string>
<!-- A session feedback option indicating the content was too advanced -->
<string name="session_feedback_advanced">너무 빠름</string>
<!-- A session feedback option indicating the content was too basic -->
<string name="session_feedback_basic">너무 기초적</string>
<!-- Session feedback section title -->
<string name="session_feedback_content">내용:</string>
<!-- A positive overall session feedback option -->
<string name="session_feedback_great">대단합니다!</string>
<!-- A negative overall session feedback option -->
<string name="session_feedback_notgreat">그냥 그래요.</string>
<!-- Notification text asking the user to provide feedback for a particular session -->
<string name="session_feedback_notification_text">%1$s에 대한 피드백 제공</string>
<!-- Notification ticker text asking the user to provide session feedback -->
<string name="session_feedback_notification_ticker">세션 피드백 제공</string>
<!-- A negative relevance session feedback option -->
<string name="session_feedback_notrel">적절하지 않음</string>
<!-- A session feedback section label asking for any other feedback. It indicates the user should not add personal information -->
<string name="session_feedback_other">우리가 더 알아야 할 것이 있습니까?\n(덧글에 개인 정보를 입력하지 마십시오.)</string>
<!-- A positive speaker quality session feedback option -->
<string name="session_feedback_outstanding">아주 좋습니다.</string>
<!-- A negative speaker quality session feedback option -->
<string name="session_feedback_poor">좋지 않습니다.</string>
<!-- A positive relevance session feedback option -->
<string name="session_feedback_rel">적당합니다.</string>
<!-- A session feedback section label asking for the session's relevance to the user's projects -->
<string name="session_feedback_relevance">이 세션이 귀하의 프로젝트에 얼마나 적절한가요?</string>
<!-- A session feedback section label asking for the speaker's quality -->
<string name="session_feedback_speaker_quality">발표자 수준:</string>
<!-- Button text for submitting session feedback -->
<string name="session_feedback_submitlink">피드백 제출</string>
<!-- Hint for adding other session feedback -->
<string name="session_feedback_tell_us">알려 주십시오!</string>
<!-- Text indicating the session has ended -->
<string name="session_finished">종료됨</string>
<!-- Card text asking the user to provide session feedback -->
<string name="session_give_feedback_message">이 세션은 어떠셨나요? 세션 피드백을 보내시겠습니까?</string>
<!-- Link text for the user to watch a live video stream of the session -->
<string name="session_link_livestream">생방송 보기</string>
<!-- Link text taking the user to the session's Google Moderator page -->
<string name="session_link_moderator">중재자</string>
<!-- Link text taking the user to the session's notes page -->
<string name="session_link_notes">공식 주석</string>
<!-- Link text taking the user to the session's slides page -->
<string name="session_link_pdf">슬라이드</string>
<!-- Link text taking the user to the session's YouTube page -->
<string name="session_link_youtube">YouTube 비디오</string>
<!-- Text indicating additional session links -->
<string name="session_links">더 보기</string>
<!-- Card text indicating the session is being broadcast right now and is available on live stream -->
<string name="session_live_now_message">이 세션은 지금 실시간으로 방송됩니다! 라이브 스트림으로 시청하시겠습니까?</string>
<!-- Short text indicating the session's live stream is live -->
<string name="session_livestream_block">라이브!</string>
<!-- Tab text on the session livestream to view captions -->
<string name="session_livestream_captions">자막</string>
<!-- Toast error message indicating an issue with the YouTube player -->
<string name="session_livestream_error_init">YouTube 플레이어를 초기화하는 도중 오류가 발생했습니다. (%1$s)</string>
<!-- Toast error message indicating an issue with YouTube playback -->
<string name="session_livestream_error_playback">라이브 스트림을 로드하는 도중 오류가 발생했습니다. 나중에 다시 시도하십시오.</string>
<!-- Tab text on the session livestream to view info -->
<string name="session_livestream_info">정보</string>
<!-- Hint for a play/pause video button -->
<string name="session_livestream_play_pause">재생/일시 정지</string>
<!-- Actionbar title for GDG DevFest Omsk Live -->
<string name="session_livestream_title">GDG DevFest Omsk 라이브</string>
<!-- Notification text that a session is starting in some number of minutes -->
<string name="session_notification_text_1">
<xliff:g id="remaining_time">%1$d</xliff:g>분에 시작합니다.</string>
<!-- Short text indicating that the session is currently happening -->
<string name="session_now">지금</string>
<!-- A session feedback section label asking the user to rate the session overall -->
<string name="session_rating_label">이 세션을 전체적으로 평가:</string>
<!-- Label for a session section listing the requirements for the session -->
<string name="session_requirements">요구 사항</string>
<!-- Label for a session section listing the presenters at the session -->
<string name="session_speakers">발표자</string>
<!-- Subtitle of a session indicating time interval and room number -->
<string name="session_subtitle">
<xliff:g id="room">%2$s</xliff:g>의 <xliff:g id="time">%1$s</xliff:g>
</string>
<!-- Short subtitle for a session indicating time interval -->
<string name="session_subtitle_short">
<xliff:g id="time">%1$s</xliff:g>
</string>
<!-- Button text indicating the user would like us to set up wifi access -->
<string name="setup_wifi_yes">예!</string>
<!-- Re-share template text indicating the user is watching GDG DevFest Omsk Live -->
<string name="share_livestream_template">GDG DevFest Omsk 라이브 시청: <xliff:g id="hashtags">%2$s</xliff:g> <xliff:g id="url">%3$s</xliff:g>의 \'<xliff:g id="title">%1$s</xliff:g>\'</string>
<!-- Re-share template text indicating the user is at a particular session -->
<string name="share_template">
<xliff:g id="hashtags">%2$s</xliff:g> <xliff:g id="url">%3$s</xliff:g>의 \'<xliff:g id="title">%1$s</xliff:g>\' 확인</string>
<!-- Notification action text for snoozing the notification for some number of minutes -->
<string name="snooze_x_min">
<xliff:g id="remaining_time">%1$d</xliff:g>분 지연되고 있습니다.</string>
<!-- Introductory text for a screen that shows several hashtags the user can click on to
see the corresponding stream on the Google+ application. -->
<string name="social_intro">Google+에서 대화에 참여하려면 해시 태그를 클릭합니다.</string>
<!-- Speaker image content description -->
<string name="speaker_googleplus_profile">Google+ 프로필: <xliff:g id="speakername">%1$s</xliff:g>
</string>
<!-- Short text label indicating a grouping of themes -->
<string name="themes">테마</string>
<!-- Text indicating the session is going to start in some number of minutes -->
<string name="time_hint_about_to_start_min">이 세션은 <xliff:g id="minutes">%1$d</xliff:g>분 내에 시작합니다.</string>
<!-- Text indicating the session is going to start in less than 1 minute -->
<string name="time_hint_about_to_start_shortly">이 세션이 시작됩니다. (1분 이내)</string>
<!-- Text indicating the session has ended -->
<string name="time_hint_session_ended">이 세션이 종료됩니다.</string>
<!-- Text indicating the session just started -->
<string name="time_hint_started_just">이 세션이 진행 중입니다! (방금 시작됨)</string>
<!-- Text indicating the session is in progress but has not completed -->
<string name="time_hint_started_min">이 세션이 진행 중입니다! (<xliff:g id="minutes">%1$d</xliff:g>분 전에 시작됨)</string>
<!-- Explanation text shown below the user's schedule clarifying the timezone used for display.
For example, 'All times shown in UTC-7' -->
<string name="times_shown_in_tz">모든 시간은 <xliff:g id="timezone">%1$s</xliff:g>(으)로 표시됩니다.</string>
<!-- Title text for dialog screen about the application -->
<string name="title_about">정보</string>
<!-- Navigation bar text for exploring the sessions -->
<string name="title_explore">탐색</string>
<!-- Navigation bar text for the map -->
<string name="title_map">지도</string>
<!-- Navigation bar text for viewing the user's schedule -->
<string name="title_my_schedule">내 일정</string>
<!-- Navigation bar text for viewing Office Hours -->
<string name="title_office_hours">근무 시간</string>
<!-- Map breadcrumb text for navigating company showcase entries -->
<string name="title_sandbox_detail">회사 정보</string>
<!-- Label for Search screen, that allows users to search for sessions. -->
<string name="title_search">검색</string>
<!-- Map breadcrumb text for navigating session entries -->
<string name="title_session_detail">세션 정보</string>
<!-- Label for SessionFeedback activity -->
<string name="title_session_feedback">세션 피드백</string>
<!-- Label for Settings activity -->
<string name="title_settings">설정</string>
<!-- Chooser dialog text when the user is selecting an application with which to share something -->
<string name="title_share">공유:</string>
<!-- Label for Social activity -->
<string name="title_stream">스트림</string>
<!-- Label for VideoLibrary activity -->
<string name="title_video_library">비디오 라이브러리</string>
<!-- Label for exploration category which groups session topics -->
<string name="topics">주제</string>
<!-- Label for exploration category which groups session types -->
<string name="types">유형</string>
<!-- Text for a session subtitle indicating it does not have a room specified -->
<string name="unknown_room">(지정되지 않은 회의실)</string>
<!-- Label on a button that, when clicked, will let the user update the application to
a newer version. -->
<string name="update_app">앱 업데이트</string>
<!-- Text for a button which allows the user to watch this particular session on live stream. -->
<string name="watch_now">지금 시청!</string>
<!-- Medium-length welcome text indicating the subsequent text is important legal information -->
<string name="welcome_text">시작하기 전에 이 앱 사용과 관련된 중요한 법률 정보를 읽으시기 바랍니다. 1분이면 다 읽을 수 있습니다!</string>
<!-- Short text welcoming the user to the application -->
<string name="welcome_to_google_i_o_app">GDG DevFest Omsk 앱을 시작합니다!</string>
<!-- Text for a button which will add a wi-fi network -->
<string name="wifi_dialog_button_configure">WiFi 네트워크 추가</string>
<!-- Text for a button which will open the user's Wi-Fi settings -->
<string name="wifi_dialog_button_settings">WiFi 설정 열기</string>
<!-- Toast failure message if the user's wifi couldn't be updated -->
<string name="wifi_install_error_message">WiFi 구성을 업데이트할 수 없습니다.</string>
<string name="experts_directory_all_cities">모든 도시</string>
<string name="experts_directory_all_countries">모든 국가</string>
<string name="experts_directory_attending">GDG DevFest Omsk 참석</string>
<string name="experts_directory_header_body">구글 개발자 전문가(GDE) 타이틀은 하나 이상의 구글 기술 분야에 대해 상당한 전문 지식을 보유하고 있고 그것을 개발자 커뮤니티와 공유하는 훌륭한 개발자들을 공인합니다. 구글 개발자 전문가들은 권위자이고 멘토이며 전도자입니다. 그들은 지침서와 코드 샘플을 만들고 책과 블로그를 씁니다. 동영상을 게시하고 커뮤니티 프로젝트를 추진하며 크고 작은 행사에 참여하고 있습니다. 이러한 독립 개발자들은 구글의 기술을 이용하여 일하며 전 세계 개발자 커뮤니티에 자신의 실제 경험과 지식을 제공합니다.</string>
<string name="experts_directory_header_dismiss">확인</string>
<string name="experts_directory_header_title">구글 개발자 전문가에 대하여</string>
<string name="explore_attending_in_person_toast">직접 GDG DevFest Omsk 참석(설정에서 변경할 수 있습니다)</string>
<string name="explore_attending_remotely_toast">원격으로 GDG DevFest Omsk 참석(설정에서 변경할 수 있습니다)</string>
<string name="go_to_settings">설정으로 이동</string>
<string name="map_infowindow_partner_seemore">더 자세한 내용을 보려면 터치하세요</string>
<string name="map_nearby_button">근처</string>
<string name="more_information">추가 정보</string>
<string name="nearby_eula_header">PhysicalWeb 실험</string>
<string name="no_matching_partner">일치하는 파트너가 없습니다.</string>
<string name="no_nearby_urls">귀하의 지역에 PhysicalWeb 비콘이 없습니다. 회의 동안 모스콘의 관심 지역 근처에 있을 때 다시 시도하십시오.</string>
<string name="people_ive_met_delete">삭제</string>
<string name="people_ive_met_delete_confirmation">정말로 목록에서 이 사람을 삭제하시겠습니까?</string>
<string name="people_ive_met_dummy_badge">이 배지는 구글플러스 프로필에 대한 링크를 포함하고 있지 않습니다</string>
<string name="people_ive_met_edit_note_title">참고 사항</string>
<string name="people_ive_met_empty">귀하는 아직 누구의 배지도 스캔하지 않았습니다. 다른 참석자와 연락처 정보를 교환하고자 하는 경우, 몇 초 동안 그 사람의 배지에 기기를 대고 있으면 그 사람의 구글플러스 프로필이 이 목록에 추가됩니다(NFC 필요).</string>
<string name="people_ive_met_header">귀하가 배지를 스캔한 참석자:</string>
<string name="people_ive_met_note">참고 사항</string>
<string name="physical_web_bluetooth_off">이 기능은 Bluetooth를 필요로 하는데, 기기의 Bluetooth가 꺼져 있습니다. 이 기능을 사용하시려면 기기 설정 화면에서 Bluetooth를 활성화하십시오.</string>
<string name="physicalweb_intro_text">이 탭은 귀하의 현재 위치(예를 들어, 협력사 웹사이트, 앱, 데모 및 대화형 콘텐츠)에 가까이 있는 회의 기능과 관련 있는 콘텐츠에 대한 링크를 표시할 수 있습니다. 이를 위해서 앱은 태그를 찾기 위해 귀하의 주위에 대한 Bluetooth 저전력(LE) 스캔을 수행하고 처리를 위해 그 정보를 구글 서버로 전송할 것입니다. 일단 활성화되면 기기의 Bluetooth가 켜져 있는 한 이 기능이 행사 내내 계속됩니다. 기능을 해제하려면 앱의 설정 메뉴로 가거나 기기에서 Bluetooth를 비활성화하십시오. 이것은 완성 제품이 아니고 Bluetooth 저전력(BLE) 실험용이기 때문에 제대로 작동하지 않을 수 있다는 점을 유념하시기 바랍니다. 네트워크 연결이 약하거나 끊어진 경우 또는 너무 많은 간섭이 있는 경우 작동하지 않을 수도 있습니다.\n\n지금 이 기능을 활성화하시겠습니까?</string>
<string name="physicalweb_intro_title">PhysicalWeb 실험</string>
<string name="pref_nearby_summary">이 옵션을 선택하면 Map 화면에서 PhysicalWeb Bluetooth 저전력 실험이 활성화되는데 이 기능은 귀하와 가까이 있는 PhysicalWeb 태그를 보여주기 위해 Bluetooth 저전력 스캔을 수행합니다(Bluetooth 필요).</string>
<string name="pref_nearby_title">PhysicalWeb 실험을 활성화</string>
<string name="title_experts_directory">전문가</string>
<string name="title_people_ive_met">내가 만난 사람들</string>
</resources>
| {
"content_hash": "87e351b1b2b4b49d7c523ffc1becec9f",
"timestamp": "",
"source": "github",
"line_count": 760,
"max_line_length": 490,
"avg_line_length": 52.40263157894737,
"alnum_prop": 0.6918846984382062,
"repo_name": "GDGMiageGiLab/devfest-app",
"id": "eba2e9d45352a1ecc4acd7bab989170c05d27c79",
"size": "45150",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "android/src/main/res/values-ko/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.druid.indexing.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.jaxrs.smile.SmileMediaTypes;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.druid.indexer.TaskLocation;
import org.apache.druid.indexer.TaskStatus;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.IOE;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.Request;
import org.apache.druid.java.util.http.client.response.StringFullResponseHandler;
import org.apache.druid.java.util.http.client.response.StringFullResponseHolder;
import org.apache.druid.segment.realtime.firehose.ChatHandlerResource;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.joda.time.Duration;
import org.joda.time.Period;
import javax.annotation.Nullable;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* Abstract class to communicate with index tasks via HTTP. This class provides interfaces to serialize/deserialize
* data and send an HTTP request.
*/
public abstract class IndexTaskClient implements AutoCloseable
{
public static class NoTaskLocationException extends RuntimeException
{
public NoTaskLocationException(String message)
{
super(message);
}
}
public static class TaskNotRunnableException extends RuntimeException
{
public TaskNotRunnableException(String message)
{
super(message);
}
}
public static final int MAX_RETRY_WAIT_SECONDS = 10;
private static final EmittingLogger log = new EmittingLogger(IndexTaskClient.class);
private static final String BASE_PATH = "/druid/worker/v1/chat";
private static final int MIN_RETRY_WAIT_SECONDS = 2;
private static final int TASK_MISMATCH_RETRY_DELAY_SECONDS = 5;
private final HttpClient httpClient;
private final ObjectMapper objectMapper;
private final TaskInfoProvider taskInfoProvider;
private final Duration httpTimeout;
private final RetryPolicyFactory retryPolicyFactory;
private final ListeningExecutorService executorService;
public IndexTaskClient(
HttpClient httpClient,
ObjectMapper objectMapper,
TaskInfoProvider taskInfoProvider,
Duration httpTimeout,
String callerId,
int numThreads,
long numRetries
)
{
this.httpClient = httpClient;
this.objectMapper = objectMapper;
this.taskInfoProvider = taskInfoProvider;
this.httpTimeout = httpTimeout;
this.retryPolicyFactory = initializeRetryPolicyFactory(numRetries);
this.executorService = MoreExecutors.listeningDecorator(
Execs.multiThreaded(
numThreads,
StringUtils.format(
"IndexTaskClient-%s-%%d",
StringUtils.encodeForFormat(callerId)
)
)
);
}
private static RetryPolicyFactory initializeRetryPolicyFactory(long numRetries)
{
// Retries [numRetries] times before giving up; this should be set long enough to handle any temporary
// unresponsiveness such as network issues, if a task is still in the process of starting up, or if the task is in
// the middle of persisting to disk and doesn't respond immediately.
return new RetryPolicyFactory(
new RetryPolicyConfig()
.setMinWait(Period.seconds(MIN_RETRY_WAIT_SECONDS))
.setMaxWait(Period.seconds(MAX_RETRY_WAIT_SECONDS))
.setMaxRetryCount(numRetries)
);
}
protected HttpClient getHttpClient()
{
return httpClient;
}
protected RetryPolicy newRetryPolicy()
{
return retryPolicyFactory.makeRetryPolicy();
}
protected <T> T deserialize(String content, JavaType type) throws IOException
{
return objectMapper.readValue(content, type);
}
protected <T> T deserialize(String content, TypeReference<T> typeReference) throws IOException
{
return objectMapper.readValue(content, typeReference);
}
protected <T> T deserialize(String content, Class<T> typeReference) throws IOException
{
return objectMapper.readValue(content, typeReference);
}
protected <T> T deserializeMap(String content, Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass)
throws IOException
{
return deserialize(content, objectMapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass));
}
protected <T> T deserializeNestedValueMap(
String content,
Class<? extends Map> mapClass,
Class<?> keyClass,
Class<? extends Map> valueMapClass,
Class<?> valueMapClassKey,
Class<?> valueMapClassValue
)
throws IOException
{
TypeFactory factory = objectMapper.getTypeFactory();
return deserialize(
content,
factory.constructMapType(
mapClass,
factory.constructType(keyClass),
factory.constructMapType(valueMapClass, valueMapClassKey, valueMapClassValue)
)
);
}
protected byte[] serialize(Object value) throws JsonProcessingException
{
return objectMapper.writeValueAsBytes(value);
}
protected <T> ListenableFuture<T> doAsync(Callable<T> callable)
{
return executorService.submit(callable);
}
protected boolean isSuccess(StringFullResponseHolder responseHolder)
{
return responseHolder.getStatus().getCode() / 100 == 2;
}
@VisibleForTesting
protected void checkConnection(String host, int port) throws IOException
{
new Socket(host, port).close();
}
protected StringFullResponseHolder submitRequestWithEmptyContent(
String taskId,
HttpMethod method,
String encodedPathSuffix,
@Nullable String encodedQueryString,
boolean retry
) throws IOException, ChannelException, NoTaskLocationException
{
return submitRequest(taskId, null, method, encodedPathSuffix, encodedQueryString, new byte[0], retry);
}
/**
* To use this method, {@link #objectMapper} should be a jsonMapper.
*/
protected StringFullResponseHolder submitJsonRequest(
String taskId,
HttpMethod method,
String encodedPathSuffix,
@Nullable String encodedQueryString,
byte[] content,
boolean retry
) throws IOException, ChannelException, NoTaskLocationException
{
return submitRequest(
taskId,
MediaType.APPLICATION_JSON,
method,
encodedPathSuffix,
encodedQueryString,
content,
retry
);
}
/**
* To use this method, {@link #objectMapper} should be a smileMapper.
*/
protected StringFullResponseHolder submitSmileRequest(
String taskId,
HttpMethod method,
String encodedPathSuffix,
@Nullable String encodedQueryString,
byte[] content,
boolean retry
) throws IOException, ChannelException, NoTaskLocationException
{
return submitRequest(
taskId,
SmileMediaTypes.APPLICATION_JACKSON_SMILE,
method,
encodedPathSuffix,
encodedQueryString,
content,
retry
);
}
private Request createRequest(
String taskId,
TaskLocation location,
String path,
@Nullable String encodedQueryString,
HttpMethod method,
@Nullable String mediaType,
byte[] content
) throws MalformedURLException
{
final String host = location.getHost();
final String scheme = location.getTlsPort() >= 0 ? "https" : "http";
final int port = location.getTlsPort() >= 0 ? location.getTlsPort() : location.getPort();
// Use URL constructor, not URI, since the path is already encoded.
// The below line can throw a MalformedURLException, and this method should return immediately without rety.
final URL serviceUrl = new URL(
scheme,
host,
port,
encodedQueryString == null ? path : StringUtils.format("%s?%s", path, encodedQueryString)
);
final Request request = new Request(method, serviceUrl);
// used to validate that we are talking to the correct worker
request.addHeader(ChatHandlerResource.TASK_ID_HEADER, StringUtils.urlEncode(taskId));
if (content.length > 0) {
request.setContent(Preconditions.checkNotNull(mediaType, "mediaType"), content);
}
return request;
}
/**
* Sends an HTTP request to the task of the specified {@code taskId} and returns a response if it succeeded.
*/
private StringFullResponseHolder submitRequest(
String taskId,
@Nullable String mediaType, // nullable if content is empty
HttpMethod method,
String encodedPathSuffix,
@Nullable String encodedQueryString,
byte[] content,
boolean retry
) throws IOException, ChannelException, NoTaskLocationException
{
final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy();
while (true) {
String path = StringUtils.format("%s/%s/%s", BASE_PATH, StringUtils.urlEncode(taskId), encodedPathSuffix);
Optional<TaskStatus> status = taskInfoProvider.getTaskStatus(taskId);
if (!status.isPresent() || !status.get().isRunnable()) {
throw new TaskNotRunnableException(
StringUtils.format(
"Aborting request because task [%s] is not runnable",
taskId
)
);
}
final TaskLocation location = taskInfoProvider.getTaskLocation(taskId);
if (location.equals(TaskLocation.unknown())) {
throw new NoTaskLocationException(StringUtils.format("No TaskLocation available for task [%s]", taskId));
}
final Request request = createRequest(
taskId,
location,
path,
encodedQueryString,
method,
mediaType,
content
);
StringFullResponseHolder response = null;
try {
// Netty throws some annoying exceptions if a connection can't be opened, which happens relatively frequently
// for tasks that happen to still be starting up, so test the connection first to keep the logs clean.
checkConnection(request.getUrl().getHost(), request.getUrl().getPort());
response = submitRequest(request);
int responseCode = response.getStatus().getCode();
if (responseCode / 100 == 2) {
return response;
} else if (responseCode == 400) { // don't bother retrying if it's a bad request
throw new IAE("Received 400 Bad Request with body: %s", response.getContent());
} else {
throw new IOE("Received status [%d] and content [%s]", responseCode, response.getContent());
}
}
catch (IOException | ChannelException e) {
// Since workers are free to move tasks around to different ports, there is a chance that a task may have been
// moved but our view of its location has not been updated yet from ZK. To detect this case, we send a header
// identifying our expected recipient in the request; if this doesn't correspond to the worker we messaged, the
// worker will return an HTTP 404 with its ID in the response header. If we get a mismatching task ID, then
// we will wait for a short period then retry the request indefinitely, expecting the task's location to
// eventually be updated.
final Duration delay;
if (response != null && response.getStatus().equals(HttpResponseStatus.NOT_FOUND)) {
String headerId = StringUtils.urlDecode(
response.getResponse().headers().get(ChatHandlerResource.TASK_ID_HEADER)
);
if (headerId != null && !headerId.equals(taskId)) {
log.warn(
"Expected worker to have taskId [%s] but has taskId [%s], will retry in [%d]s",
taskId,
headerId,
TASK_MISMATCH_RETRY_DELAY_SECONDS
);
delay = Duration.standardSeconds(TASK_MISMATCH_RETRY_DELAY_SECONDS);
} else {
delay = retryPolicy.getAndIncrementRetryDelay();
}
} else {
delay = retryPolicy.getAndIncrementRetryDelay();
}
final String urlForLog = request.getUrl().toString();
if (!retry) {
// if retry=false, we probably aren't too concerned if the operation doesn't succeed (i.e. the request was
// for informational purposes only) so don't log a scary stack trace
log.info("submitRequest failed for [%s], with message [%s]", urlForLog, e.getMessage());
throw e;
} else if (delay == null) {
log.warn(e, "Retries exhausted for [%s], last exception:", urlForLog);
throw e;
} else {
try {
final long sleepTime = delay.getMillis();
log.warn(
"Bad response HTTP [%s] from [%s]; will try again in [%s] (body/exception: [%s])",
(response != null ? response.getStatus().getCode() : "no response"),
urlForLog,
new Duration(sleepTime).toString(),
(response != null ? response.getContent() : e.getMessage())
);
Thread.sleep(sleepTime);
}
catch (InterruptedException e2) {
Thread.currentThread().interrupt();
e.addSuppressed(e2);
throw new RuntimeException(e);
}
}
}
catch (NoTaskLocationException e) {
log.info(
"No TaskLocation available for task [%s], this task may not have been assigned to a worker yet "
+ "or may have already completed",
taskId
);
throw e;
}
catch (Exception e) {
log.warn(e, "Exception while sending request");
throw e;
}
}
}
private StringFullResponseHolder submitRequest(Request request) throws IOException, ChannelException
{
try {
log.debug("HTTP %s: %s", request.getMethod().getName(), request.getUrl().toString());
return httpClient.go(request, new StringFullResponseHandler(StandardCharsets.UTF_8), httpTimeout).get();
}
catch (Exception e) {
throw throwIfPossible(e);
}
}
/**
* Throws if it's possible to throw the given Throwable.
* <p>
* - The input throwable shouldn't be null.
* - If Throwable is an {@link ExecutionException}, this calls itself recursively with the cause of ExecutionException.
* - If Throwable is an {@link IOException} or a {@link ChannelException}, this simply throws it.
* - If Throwable is an {@link InterruptedException}, this interrupts the current thread and throws a RuntimeException
* wrapping the InterruptedException
* - Otherwise, this simply returns the given Throwable.
* <p>
* Note that if the given Throable is an ExecutionException, this can return the cause of ExecutionException.
*/
private RuntimeException throwIfPossible(Throwable t) throws IOException, ChannelException
{
Preconditions.checkNotNull(t, "Throwable shoulnd't null");
if (t instanceof ExecutionException) {
if (t.getCause() != null) {
return throwIfPossible(t.getCause());
} else {
return new RuntimeException(t);
}
}
if (t instanceof IOException) {
throw (IOException) t;
}
if (t instanceof ChannelException) {
throw (ChannelException) t;
}
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
throw new RuntimeException(t);
}
Throwables.propagateIfPossible(t);
return new RuntimeException(t);
}
@Override
public void close()
{
executorService.shutdownNow();
}
}
| {
"content_hash": "f82f109405b4ea2e57398c33b0c09d3c",
"timestamp": "",
"source": "github",
"line_count": 472,
"max_line_length": 121,
"avg_line_length": 35.25635593220339,
"alnum_prop": 0.6847545219638242,
"repo_name": "mghosh4/druid",
"id": "a42e83d2baea1b01f18c2fbd955569fa70142831",
"size": "17448",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "indexing-service/src/main/java/org/apache/druid/indexing/common/IndexTaskClient.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "5360"
},
{
"name": "CSS",
"bytes": "3878"
},
{
"name": "Dockerfile",
"bytes": "8766"
},
{
"name": "HTML",
"bytes": "2536"
},
{
"name": "Java",
"bytes": "34944606"
},
{
"name": "JavaScript",
"bytes": "59220"
},
{
"name": "Makefile",
"bytes": "659"
},
{
"name": "PostScript",
"bytes": "5"
},
{
"name": "Python",
"bytes": "66994"
},
{
"name": "R",
"bytes": "17002"
},
{
"name": "Roff",
"bytes": "3617"
},
{
"name": "SCSS",
"bytes": "109536"
},
{
"name": "Shell",
"bytes": "81730"
},
{
"name": "Smarty",
"bytes": "3517"
},
{
"name": "Stylus",
"bytes": "7682"
},
{
"name": "TeX",
"bytes": "399468"
},
{
"name": "Thrift",
"bytes": "1003"
},
{
"name": "TypeScript",
"bytes": "1224966"
}
],
"symlink_target": ""
} |
/***************
* PROGRAM: Scenario
* NAME: sci.cpp
* DESCRIPTION: interface to Scenario (tm) modeler
* AUTHORS: Andreas Heumann & Mike Hesser
* HISTORY:
* DATE NAME COMMENT
* 21.02.97 ah initial release
* 03.05.97 ah added sciCreateSurface(), sciFreeAll()
* 12.05.97 ah added sciLoadMaterial(), sciSaveMaterial(), sciDeleteSurface()
* 21.05.97 ah added sciGetMaterialThumbNail()
* 22.05.97 ah added sciUpdateThumbNail(), sciBrowserClear()
* 04.06.97 ah added sciAssignSurface()
* 29.07.97 ah added sciSetActiveObjects()
* 29.08.97 ah added sciAssignSurfaceToSelectedObjects(), sciChangeSurface()
* 17.09.97 ah added sciReadResFile()
***************/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifdef __AMIGA__
#include <pragma/dos_lib.h>
#endif
#ifndef SCI_H
#include "sci.h"
#endif
#ifndef UNDO_H
#include "undo.h"
#endif
#ifndef GLOBALS_H
#include "globals.h"
#endif
#ifndef PROJECT_H
#include "project.h"
#endif
#ifndef SPHERE_H
#include "sphere.h"
#endif
#ifndef BOX_H
#include "box.h"
#endif
#ifndef PLANE_H
#include "plane.h"
#endif
#ifndef CYLINDER_H
#include "cylinder.h"
#endif
#ifndef CONE_H
#include "cone.h"
#endif
#ifndef CSG_H
#include "csg.h"
#endif
#ifndef SOR_H
#include "sor.h"
#endif
#ifndef LIGHT_H
#include "light.h"
#endif
#ifndef MESH_H
#include "mesh.h"
#endif
#ifndef PREFS_H
#include "prefs.h"
#endif
#ifndef MOUSE_H
#include "mouse.h"
#endif
#ifndef __AMIGA__
#ifndef CAMVIEW_H
#include "CamView.h"
#endif
#endif
#ifndef UTILITY_H
#include "utility.h"
#endif
#ifndef BRUSH_H
#include "brush.h"
#endif
#ifndef TEXTURE_H
#include "texture.h"
#endif
static DISPLAY *display;
#ifdef __AMIGA__
#ifndef MUIUTILITY_H
#include "muiutility.h"
#endif
#ifdef __MIXEDBINARY__
void WriteLog(void*, char*);
#endif // __MIXEDBINARY__
static Object *drawarea, *browser, *material, *main;
#define REDRAW() MUI_Redraw(drawarea, MADF_DRAWUPDATE);
#define CLEAR_SELECTED() DoMethod(drawarea, MUIM_Draw_RemoveSelected);
#define REDRAW_SELECTED() DoMethod(drawarea,MUIM_Draw_RedrawSelected);
#define REDRAW_DIRTY() DoMethod(drawarea,MUIM_Draw_RedrawDirty);
#define REDRAW_CURRENTVIEW() DoMethod(drawarea,MUIM_Draw_RedrawCurrentView);
#else
extern char szWorkingDirectory[256];
static CCamView *pCamView;
#define REDRAW() pCamView->Redraw(REDRAW_ALL, FALSE);
#define CLEAR_SELECTED() pCamView->Redraw(REDRAW_REMOVE_SELECTED, FALSE);
#define REDRAW_SELECTED() pCamView->Redraw(REDRAW_SELECTED, FALSE);
#define REDRAW_DIRTY() pCamView->Redraw(REDRAW_DIRTY, FALSE);
#define REDRAW_CURRENTVIEW() pCamView->Redraw(REDRAW_CURRENT_VIEW, FALSE);
#endif
#ifdef __AMIGA__
/*************
* DESCRIPTION: call this function before you use the interface
* INPUT: d drawarea
* b browser
* mm material manager
* mw main window
* OUTPUT: -
*************/
void sciInit(Object *d, Object *b, Object *mm, Object *mw)
{
ASSERT(d && b && mm && mw);
drawarea = d;
browser = b;
material = mm;
main = mw;
}
/*************
* DESCRIPTION: call this function after the window is opened
* INPUT: -
* OUTPUT: -
*************/
void sciInitDisplay()
{
ASSERT(drawarea);
GetAttr(MUIA_Draw_DisplayPtr, drawarea, (ULONG*)&display);
}
/*************
* DESCRIPTION: Get a thumb nail image for the specified surface
* INPUT: surf
* OUTPUT: image object or NULL if none found
*************/
Object *sciGetMaterialThumbNail(SURFACE *surf)
{
return (Object*)DoMethod(material, MUIM_Material_GetThumbNail, surf);
}
/*************
* DESCRIPTION: Avoid the material manager from updating its display
* while adding items. Call this function is you want to add many
* material items. This avoids the display from flickering. After you
* have added the materials you HAVE to call sciMaterialExitChange().
* INPUT: none
* OUTPUT: none
*************/
void sciMaterialInitChange()
{
DoMethod(material, MUIM_Material_InitChange);
}
/*************
* DESCRIPTION: Start rendering
* INPUT: none
* OUTPUT: FALSE if failed
*************/
BOOL sciRender()
{
return(DoMethod(main, MUIM_MainWindow_Render));
}
/*************
* DESCRIPTION: Let the material manager update its display after
* adding items
* INPUT: none
* OUTPUT: none
*************/
void sciMaterialExitChange()
{
DoMethod(material, MUIM_Material_ExitChange);
}
#else
/*************
* DESCRIPTION: call this function before you use the interface
* INPUT: v camera view
* OUTPUT: -
*************/
void sciInit(CCamView *pView)
{
pCamView = pView;
display = pCamView->pDisplay;
}
#endif
/*************
* DESCRIPTION: Reset scene to default
* INPUT: display current display
* OUTPUT: -
*************/
void sciNew()
{
SURFACE *surf;
// set title to 'untitled'
SetProjectName("untitled");
sciBrowserClear();
// free undo buffer
FreeUndo();
// remove all objects
FreeObjects();
// free all surfaces
FreeSurfaces();
// and create the default surface
surf = sciCreateSurface(SURF_DEFAULTNAME);
surf->flags |= SURF_DEFAULT;
#ifdef __AMIGA__
DoMethod(material, MUIM_Material_FreeMaterials);
#else
pCamView->pMatView->FreeMaterials();
#endif
global.ToDefaults();
display->ToDefaults();
display->view->ToDefaults();
SetProjectChanged(FALSE);
REDRAW();
sciBrowserBuild();
}
/*************
* DESCRIPTION: Open a new scene
* INPUT: name name of scene to load
* OUTPUT: error string or NULL if all went ok
*************/
char *sciOpen(char *name)
{
char *err;
SURFACE *surf;
// set the new project name
SetProjectName(name);
sciBrowserClear();
// free undo buffer
FreeUndo();
// then remove all objects
FreeObjects();
// free all surfaces
FreeSurfaces();
// and create the default surface
surf = sciCreateSurface(SURF_DEFAULTNAME);
surf->flags |= SURF_DEFAULT;
#ifdef __AMIGA__
DoMethod(material, MUIM_Material_FreeMaterials);
sciMaterialInitChange();
#else
pCamView->pMatView->FreeMaterials();
#endif
// and load new project
err = ProjectLoad(name, display);
#ifdef __AMIGA__
sciMaterialExitChange();
#endif
if(err)
return err;
DeselectAll();
display->SetMultiView(display->multiview);
REDRAW();
sciBrowserBuild();
return NULL;
}
/*************
* DESCRIPTION: Save the current scene
* INPUT: name name of scene to save
* OUTPUT: error string or NULL if all went ok
*************/
char *sciSave(char *name)
{
char *err, buffer[256];
// save project
err = ProjectSave(name, display);
if(err)
return err;
// set the new project name
SetProjectName(name);
// set output picture name if no is set
if(!global.renderdpic)
{
strcpy(buffer, name);
#ifdef __AMIGA__
*PathPart(buffer) = 0;
#else
DirPart(buffer, buffer, 255);
#endif
AddPart(buffer, "pic0001", 255);
global.SetRenderdPic(buffer);
}
return NULL;
}
/*************
* DESCRIPTION: Undo the last operation
* INPUT: -
* OUTPUT: -
*************/
void sciUndo()
{
switch(Undo())
{
case UNDO_NOUNDO:
utility.Request("Nothing to undo");
break;
case UNDO_FAILED:
utility.Request("Undo failed. Not enough memory.");
break;
case UNDO_OK_REDRAW:
REDRAW();
break;
}
SetProjectChanged(TRUE);
sciBrowserBuild();
}
/*************
* DESCRIPTION: Redo the last operation
* INPUT: -
* OUTPUT: -
*************/
void sciRedo()
{
switch(Redo())
{
case UNDO_NOREDO:
utility.Request("Nothing to redo");
break;
case UNDO_FAILED:
utility.Request("Redo failed. Not enough memory.");
break;
case UNDO_OK_REDRAW:
REDRAW();
break;
}
SetProjectChanged(TRUE);
sciBrowserBuild();
}
/*************
* DESCRIPTION: Cut selected objects to paste buffer (active camera is excluded)
* INPUT: camera active camera
* OUTPUT: -
*************/
void sciCut(CAMERA *camera)
{
if(!Cut(camera))
utility.Request("Not enough memory");
CLEAR_SELECTED();
// redraw the camera if it was cleared
if(camera->selected)
{
camera->flags |= OBJECT_DIRTY;
REDRAW_DIRTY();
}
SetProjectChanged(TRUE);
sciBrowserBuild();
}
/*************
* DESCRIPTION: Copy selected objects to paste buffer
* INPUT: -
* OUTPUT: -
*************/
void sciCopy()
{
if(!Copy())
utility.Request("Not enough memory");
}
/*************
* DESCRIPTION: Paste objects from paste buffer
* INPUT: -
* OUTPUT: -
*************/
void sciPaste()
{
DeselectAll();
if(!Paste())
utility.Request("Not enough memory");
REDRAW();
SetProjectChanged(TRUE);
sciBrowserBuild();
}
/*************
* DESCRIPTION: Delete selected objects (active camera is excluded)
* INPUT: camera active camera
* mode mode (copy of display->editmode)
* OUTPUT: -
*************/
void sciDelete(CAMERA *camera, ULONG mode)
{
DeleteSelected(camera, mode);
CLEAR_SELECTED();
// redraw the camera if it was deleted
if(camera->selected)
camera->flags |= OBJECT_DIRTY;
REDRAW_DIRTY();
SetProjectChanged(TRUE);
sciBrowserBuild();
}
/*************
* DESCRIPTION: Select all objects
* INPUT: -
* OUTPUT: -
*************/
void sciSelectAll()
{
SelectAll();
REDRAW_DIRTY();
sciBrowserBuild();
}
/*************
* DESCRIPTION: Deselect all selected objects
* INPUT: -
* OUTPUT: -
*************/
void sciDeselectAll()
{
DeselectAll();
REDRAW_DIRTY();
sciBrowserBuild();
}
/*************
* DESCRIPTION: Select next object
* INPUT: -
* OUTPUT: -
*************/
void sciSelectNext()
{
SelectNext();
REDRAW_DIRTY();
sciBrowserBuild();
}
/*************
* DESCRIPTION: Select previous object
* INPUT: -
* OUTPUT: -
*************/
void sciSelectPrev()
{
SelectPrev();
REDRAW_DIRTY();
sciBrowserBuild();
}
/*************
* DESCRIPTION: Select an object by it's name
* INPUT: name
* multi if TRUE multiselect is enabled
* OUTPUT: TRUE if found, else FALSE
*************/
BOOL sciSelectByName(char *name, BOOL multi)
{
OBJECT *obj;
obj = GetObjectByName(name);
if(obj)
{
if(!multi)
DeselectAll();
obj->Select();
return TRUE;
}
return FALSE;
}
/*************
* DESCRIPTION: Redraw
* INPUT: -
* OUTPUT: -
*************/
void sciRedraw()
{
REDRAW();
}
/*************
* DESCRIPTION: Redraw current view
* INPUT: -
* OUTPUT: -
*************/
void sciRedrawCurrentView()
{
REDRAW_CURRENTVIEW();
}
/*************
* DESCRIPTION: Set active camera to position of virtual camera
* INPUT: view current view
* OUTPUT: -
*************/
void sciCamera2Viewer(VIEW *view)
{
view->Camera2Viewer(display->camera);
REDRAW();
SetProjectChanged(TRUE);
}
/*************
* DESCRIPTION: Group currently selected objects
* INPUT: -
* OUTPUT: FALSE if failed (less than two objects selected) else TRUE
*************/
BOOL sciGroupObjects()
{
if(!GroupObjects())
return FALSE;
REDRAW_DIRTY();
SetProjectChanged(TRUE);
sciBrowserBuild();
return TRUE;
}
/*************
* DESCRIPTION: UnGroup currently selected objects
* INPUT: -
* OUTPUT: -
*************/
void sciUnGroupObjects()
{
UnGroupObjects();
CLEAR_SELECTED();
REDRAW_DIRTY();
SetProjectChanged(TRUE);
sciBrowserBuild();
}
/*************
* DESCRIPTION: Load an object
* INPUT: name file name
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciLoadObject(char *name)
{
char *err;
DeselectAll();
err = LoadObject(name);
if(err)
{
utility.Request("%s\n%s", err, GetLoadError());
return FALSE;
}
REDRAW_DIRTY();
SetProjectChanged(TRUE);
sciBrowserBuild();
return TRUE;
}
/*************
* DESCRIPTION: Save selected object(s)
* INPUT: name file name
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciSaveObject(char *name)
{
FILE *f;
char *err;
f = fopen(name,"r");
if(f)
{
fclose(f);
if(!utility.AskRequest("File '%s' already exists. Overwrite?", name))
return FALSE;
}
err = SaveObject(name);
if(err)
{
utility.Request("%s\n%s", err, GetLoadError());
return FALSE;
}
REDRAW_DIRTY();
SetProjectChanged(TRUE);
sciBrowserBuild();
return TRUE;
}
/*************
* DESCRIPTION: Create a new object
* INPUT: type type of object to create (OBJECT_xxx)
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciCreateObject(int type)
{
OBJECT *obj;
UNDO_CREATE *undo;
switch(type)
{
case OBJECT_SPHERE:
obj = new SPHERE;
break;
case OBJECT_BOX:
obj = new BOX;
break;
case OBJECT_PLANE:
obj = new PLANE;
break;
case OBJECT_POINTLIGHT:
obj = new POINT_LIGHT;
break;
case OBJECT_SPOTLIGHT:
obj = new SPOT_LIGHT;
break;
case OBJECT_DIRECTIONALLIGHT:
obj = new DIRECTIONAL_LIGHT;
break;
case OBJECT_CAMERA:
obj = new CAMERA;
break;
case OBJECT_MESH:
obj = new MESH;
break;
case OBJECT_CYLINDER:
obj = new CYLINDER;
break;
case OBJECT_CONE:
obj = new CONE;
break;
case OBJECT_CSG:
obj = new CSG;
break;
case OBJECT_SOR:
obj = new SOR;
break;
}
if(!obj)
return FALSE;
// create surface for visible objects
if((type == OBJECT_SPHERE) ||
(type == OBJECT_BOX) ||
(type == OBJECT_PLANE) ||
(type == OBJECT_MESH) ||
(type == OBJECT_CYLINDER) ||
(type == OBJECT_CONE) ||
(type == OBJECT_SOR))
{
obj->surf = GetSurfaceByName(SURF_DEFAULTNAME);
if(!obj->surf)
{
obj->surf = sciCreateSurface(SURF_DEFAULTNAME);
if(!obj->surf)
{
delete obj;
return FALSE;
}
sciAddMaterial(obj->surf);
}
else
{
if(!sciAssignSurface(obj->surf, obj))
{
delete obj;
return FALSE;
}
}
}
obj->selected = TRUE;
DeselectAll();
obj->Append();
obj->IsFirstSelected();
undo = new UNDO_CREATE;
if(undo)
{
if(undo->AddCreated(obj))
undo->Add();
else
delete undo;
}
REDRAW_DIRTY();
SetProjectChanged(TRUE);
sciBrowserAddObject(obj);
return TRUE;
}
/*************
* DESCRIPTION: Load preferences
* INPUT: -
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciLoadPrefs()
{
BOOL success;
FreePrefs();
#ifdef __AMIGA__
success = PrefsLoad("prefs/Scenario.prf");
#else
char szBuf[256];
sprintf(szBuf, "%s\\prefs\\Scenario.prf", szWorkingDirectory);
success = PrefsLoad(szBuf);
#endif
if(success)
GetColorPrefs();
return success;
}
/*************
* DESCRIPTION: Save preferences
* INPUT: -
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciSavePrefs()
{
SetColorPrefs();
#ifdef __AMIGA__
return PrefsSave("prefs/Scenario.prf");
#else
char szBuf[256];
sprintf(szBuf, "%s\\prefs\\Scenario.prf", szWorkingDirectory);
return PrefsSave(szBuf);
#endif
}
/*************
* DESCRIPTION: focus objects
* INPUT: view current view
* all TRUE: whole scene FALSE: only selected objects
* OUTPUT: -
*************/
void sciFocus(VIEW *view, BOOL all)
{
if(Focus(view, all))
REDRAW_CURRENTVIEW();
}
/*************
* DESCRIPTION: zooms in one step
* INPUT: view current view
* OUTPUT: -
*************/
void sciZoomIn(VIEW *view)
{
ZoomIn(view);
REDRAW_CURRENTVIEW();
}
/*************
* DESCRIPTION: zooms out one step
* INPUT: view current view
* OUTPUT: -
*************/
void sciZoomOut(VIEW *view)
{
ZoomOut(view);
REDRAW_CURRENTVIEW();
}
/*************
* DESCRIPTION: update
* INPUT: obj object to be updated
* OUTPUT: -
*************/
void sciBrowserUpdate(OBJECT *obj)
{
#ifdef __AMIGA__
DoMethod(browser, MUIM_BrowserTree_Update, obj);
#else
pCamView->pBrowserView->Build();
#endif
}
/*************
* DESCRIPTION: add a new created object to the end of the list
* INPUT: obj object to be added
* OUTPUT: -
*************/
void sciBrowserAddObject(OBJECT *obj)
{
#ifdef __AMIGA__
DoMethod(browser, MUIM_BrowserTree_AddObject, obj);
#else
pCamView->pBrowserView->Build();
#endif
}
/*************
* DESCRIPTION: build complete browser hierarchie
* INPUT: -
* OUTPUT: -
*************/
void sciBrowserBuild()
{
#ifdef __AMIGA__
DoMethod(browser, MUIM_BrowserTree_Build);
#else
pCamView->pBrowserView->Build();
#endif
}
/*************
* DESCRIPTION: clear browser
* INPUT: -
* OUTPUT: -
*************/
void sciBrowserClear()
{
#ifdef __AMIGA__
DoMethod(browser, MUIM_BrowserTree_Clear);
#else
pCamView->pBrowserView->Clear();
#endif
}
/*************
* DESCRIPTION: Create a new surface.
* INPUT: name name of surface
* OUTPUT: created surface
*************/
SURFACE *sciCreateSurface(char *name)
{
SURFACE *surf;
surf = new SURFACE;
if(!surf)
return NULL;
if(!surf->SetName(name))
{
delete surf;
return NULL;
}
surf->Add();
return surf;
}
/*************
* DESCRIPTION: Delete a surface.
* INPUT: surf surface to delete
* OUTPUT: -
*************/
void sciDeleteSurface(SURFACE *surf)
{
surf->Remove();
}
/*************
* DESCRIPTION: Assign a surface to an object. Local brushes and textures
* are created.
* INPUT: surf surface to assign
* obj obj to assign surface to
* OUTPUT: FALSE if failed
*************/
BOOL sciAssignSurface(SURFACE *surf, OBJECT *obj)
{
BRUSH *brush;
BRUSH_OBJECT *brushobj;
TEXTURE *texture;
TEXTURE_OBJECT *textureobj;
int type;
type = obj->GetType();
if((type == OBJECT_CSG) || (type == OBJECT_CAMERA) || (type == OBJECT_POINTLIGHT) || (type == OBJECT_SPOTLIGHT) || (type == OBJECT_DIRECTIONALLIGHT))
return TRUE;
// remove old brushes
obj->RemoveBrushes();
// create brushes
brush = surf->brush;
while(brush)
{
brushobj = new BRUSH_OBJECT;
if(!brushobj)
return FALSE;
brushobj->brush = brush;
obj->AddBrushTop(brushobj);
brush = (BRUSH*)brush->GetNext();
}
// remove old textures
obj->RemoveTextures();
// create textures
texture = surf->texture;
while(texture)
{
textureobj = new TEXTURE_OBJECT;
if(!textureobj)
return FALSE;
textureobj->texture = texture;
obj->AddTextureTop(textureobj);
texture = (TEXTURE*)texture->GetNext();
}
obj->surf = surf;
sciBrowserUpdate(obj);
return TRUE;
}
/*************
* DESCRIPTION: Assign a surface to all selected objects.
* INPUT: surf surface to assign
* OUTPUT: FALSE if failed
*************/
typedef struct
{
SURFACE *surf;
BOOL success;
} AssignSurfaceToSelectedObjectsData;
static void AssignSurfaceToSelectedObjectsCB(OBJECT *obj, void *data)
{
if(obj)
{
if(obj->surf)
{
if(!sciAssignSurface(((AssignSurfaceToSelectedObjectsData*)data)->surf, obj))
((AssignSurfaceToSelectedObjectsData*)data)->success = FALSE;
}
}
}
BOOL sciAssignSurfaceToSelectedObjects(SURFACE *surf)
{
AssignSurfaceToSelectedObjectsData data;
data.surf = surf;
data.success = TRUE;
GetSelectedObjects(AssignSurfaceToSelectedObjectsCB, &data, 0);
return data.success;
}
/*************
* DESCRIPTION: Change the surface of objects with a specified surface.
* INPUT: from objects with this surface are changed
* to this surface is assigned to the object
* OUTPUT: -
*************/
typedef struct
{
SURFACE *from, *to;
} ChangeSurfaceData;
static void ChangeSurfaceCB(OBJECT *obj, void *data)
{
if(obj)
{
if(obj->surf == ((ChangeSurfaceData*)data)->from)
sciAssignSurface(((ChangeSurfaceData*)data)->to, obj);
}
}
void sciChangeSurface(SURFACE *from, SURFACE *to)
{
ChangeSurfaceData data;
data.from = from;
data.to = to;
GetObjects(ChangeSurfaceCB, &data, 0);
}
/*************
* DESCRIPTION: Add a surface to the material manager.
* INPUT: surf surface
* OUTPUT: -
*************/
void sciAddMaterial(SURFACE *surf)
{
// add new created surface to material manager
#ifdef __AMIGA__
DoMethod(material, MUIM_Material_AddMaterial, surf);
#else
pCamView->pMatView->AddMaterial(surf);
#endif
SetProjectChanged(TRUE);
}
/*************
* DESCRIPTION: Remove a surface from the material manager. It's tested before if the
* surface is used by an object.
* INPUT: surf surface
* test_used TRUE -> test if surface is used and refuse deleting when used
* OUTPUT: FALSE if failed
*************/
BOOL sciRemoveMaterial(SURFACE *surf, BOOL test_used)
{
OBJECT *obj;
if(test_used)
{
obj = IsSurfaceUsed(surf);
if(obj)
{
utility.Request("Can't delete Surface because it is used by %s.", obj->GetName());
return FALSE;
}
}
// is requester open?
if(surf->win)
{
#ifdef __AMIGA__
// close requester
SetAttrs(surf->win, MUIA_Window_Open, FALSE, TAG_DONE);
DoMethod(app, OM_REMMEMBER, surf->win);
MUI_DisposeObject(surf->win);
surf->win = NULL;
#else
// Mike: Dialog schließen
#endif
}
#ifdef __AMIGA__
DoMethod(material, MUIM_Material_RemoveMaterial, surf);
#endif
SetProjectChanged(TRUE);
return TRUE;
}
/*************
* DESCRIPTION: free all scenario data
* INPUT: -
* OUTPUT: -
*************/
void sciFreeAll()
{
FreeUndo();
FreeObjects();
FreePrefs();
FreeSurfaces();
}
/*************
* DESCRIPTION: open material requester
* INPUT: surf surface to open requester on
* OUTPUT: -
*************/
void sciOpenMaterialRequ(SURFACE *surf)
{
#ifdef __AMIGA__
DoMethod(main, MUIM_MainWindow_OpenMaterialRequ, surf);
#else
pCamView->MaterialDlg(surf, NULL);
#endif
}
/*************
* DESCRIPTION: pop up a file requester and ask for a material file and
* load it
* INPUT: surf surface to store loaded material to
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciLoadMaterial(SURFACE *surf)
{
char *err;
char file[256];
BRUSH *brush, *bnext;
TEXTURE *texture, *tnext;
if(utility.FileRequ(file, FILEREQU_MATERIAL, 0))
{
// free all brushes and textures
brush = surf->brush;
while(brush)
{
bnext = (BRUSH*)brush->GetNext();
delete brush;
brush = bnext;
}
surf->brush = NULL;
texture = surf->texture;
while(texture)
{
tnext = (TEXTURE*)texture->GetNext();
delete texture;
texture = tnext;
}
surf->texture = NULL;
err = surf->Load(file);
if(err)
{
utility.Request(err);
return FALSE;
}
SetProjectChanged(TRUE);
}
else
return FALSE;
return TRUE;
}
/*************
* DESCRIPTION: pop up a file requester and ask for a material file name and
* save it
* INPUT: surf surface to store
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciSaveMaterial(SURFACE *surf)
{
char *err;
char file[256];
if(utility.FileRequ(file, FILEREQU_MATERIAL, FILEREQU_SAVE))
{
err = surf->Save(file);
if(err)
{
utility.Request(err);
return FALSE;
}
}
else
return FALSE;
return TRUE;
}
/*************
* DESCRIPTION: pop up a file requester and ask for a light file and
* load it
* INPUT: light light to store data to
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciLoadLight(LIGHT *light)
{
char *err;
char file[256];
if(utility.FileRequ(file, FILEREQU_LIGHT, 0))
{
err = light->Load(file);
if(err)
{
utility.Request(err);
return FALSE;
}
SetProjectChanged(TRUE);
}
else
return FALSE;
return TRUE;
}
/*************
* DESCRIPTION: pop up a file requester and ask for a light file name and
* save it
* INPUT: light light to store
* OUTPUT: FALSE if failed else TRUE
*************/
BOOL sciSaveLight(LIGHT *light)
{
char *err;
char file[256];
if(utility.FileRequ(file, FILEREQU_LIGHT, FILEREQU_SAVE))
{
err = light->Save(file);
if(err)
{
utility.Request(err);
return FALSE;
}
}
else
return FALSE;
return TRUE;
}
/*************
* DESCRIPTION: Update the thumb nail gfx of a surface of a browser item
* INPUT: surf surface
* OUTPUT: -
*************/
void sciUpdateThumbNail(SURFACE *surf)
{
#ifdef __AMIGA__
DoMethod(browser, MUIM_BrowserTree_UpdateThumbNail, surf);
#endif
}
/*************
* DESCRIPTION: test if there is a light source in the scene
* INPUT: none
* OUTPUT: TRUE if a light is found
*************/
static void TestForLight(OBJECT *obj, void *lights)
{
ASSERT(lights);
if(obj)
{
switch(obj->GetType())
{
case OBJECT_POINTLIGHT:
case OBJECT_SPOTLIGHT:
case OBJECT_DIRECTIONALLIGHT:
*((BOOL*)lights) = TRUE;
break;
}
}
}
BOOL sciTestForLight()
{
BOOL lights;
lights = FALSE;
GetObjects(TestForLight, &lights, 0);
return lights;
}
/*************
* DESCRIPTION: set the position, size and alignment of the selected object(s)
* INPUT: undo undo object with all objects to set
* object primary object
* newpos
* poslocal if TRUE position change is in model coordinates
* newsize
* sizelocal if TRUE size change is in model coordinates
* newalign
* alignlocal if TRUE alignment change is in model coordinates
* OUTPUT: -
*************/
void sciSetActiveObjects(UNDO_TRANSFORM *undo, OBJECT *object,
VECTOR *newpos, BOOL poslocal, VECTOR *newsize, BOOL sizelocal, VECTOR *newalign, BOOL alignlocal)
{
VECTOR pos, orient_x, orient_y, orient_z;
BOOL oldposlocal, oldalignlocal, oldsizelocal;
MATRIX m;
ASSERT(undo && object && newpos && newsize && newalign);
oldposlocal = display->localpos;
display->localpos = poslocal;
oldalignlocal = display->localalign;
display->localalign = alignlocal;
oldsizelocal = display->localsize;
display->localsize = sizelocal;
// update the axis values in the undo object
// (maybe another requester changed the object after
// we opened our requester)
undo->UpdateObjects();
object->GetObjectMatrix(&m);
m.GenerateAxis(&orient_x, &orient_y, &orient_z, &pos);
// change position
if(poslocal)
display->pos = *newpos;
else
VecSub(newpos, &pos, &display->pos);
// change size
SetVector(&display->size,
newsize->x / object->size.x,
newsize->y / object->size.y,
newsize->z / object->size.z);
// change alignment
display->align.x = newalign->x - object->align.x;
display->align.y = newalign->y - object->align.y;
display->align.z = newalign->z - object->align.z;
newalign->y = -newalign->y;
CalcOrient(newalign, &display->orient_x, &display->orient_y, &display->orient_z);
if(!alignlocal)
InvOrient(&display->orient_x, &display->orient_y, &display->orient_z, &display->orient_x, &display->orient_y, &display->orient_z);
undo->SetObjects(display);
display->localpos = oldposlocal;
display->localalign = oldalignlocal;
display->localsize = oldsizelocal;
}
/*************
* DESCRIPTION: Read the resolutions from the a preset file. This routine allocates an array of
* description strings and resolution values and fills in the values it reads from a ASCII file.
* The last string in the string array is followed by a NULL-pointer. After you dont't need the
* strings any more you have to free each single string AND the array which holds the pointers AND
* the array with the resolution values.
* INPUT: resolutions pointer to a pointer to a array with pointers to resolution strings (WOW!)
* res pointer to pointer to a array of resolution values (x-y pairs)
* OUTPUT: FALSE if failed
*************/
BOOL sciReadResFile(char ***resolutions, ULONG **res)
{
FILE *f;
int amount, cur, i;
char buffer[256], *s;
ASSERT(resolutions && res);
#ifdef __AMIGA__
f = fopen("prefs/res.dat","rb");
#else
f = fopen("prefs\\res.dat","rb");
#endif
if(!f)
return FALSE;
amount = 0;
while(fgets(buffer, 256, f))
amount++;
*resolutions = new char*[amount+1];
if(!resolutions)
{
fclose(f);
return FALSE;
}
*res = new ULONG[2*amount];
if(!*res)
{
delete resolutions;
fclose(f);
return FALSE;
}
fseek(f, 0, SEEK_SET);
cur = 0;
while(fgets(buffer, 256, f))
{
(*resolutions)[cur] = new char[strlen(buffer)+1];
if(!(*resolutions)[cur])
{
for(i=0; i<cur; i++)
delete resolutions[i];
delete resolutions;
delete res;
fclose(f);
return FALSE;
}
strtok(buffer, ",");
strcpy((*resolutions)[cur], buffer);
s = strtok(NULL, ",");
(*res)[cur*2] = atol(s);
s = strtok(NULL, ",");
(*res)[cur*2+1] = atol(s);
cur++;
}
(*resolutions)[amount] = NULL;
fclose(f);
return TRUE;
}
/*************
* DESCRIPTION: Join selected mesh objects
* INPUT: -
* OUTPUT: FALSE if failed
*************/
typedef struct
{
OBJECT *to;
} MeshJoinData;
static void MeshJoinCB(OBJECT *obj, void *data)
{
if(obj)
{
if((obj != ((MeshJoinData*)data)->to) && (obj->selected) && (obj->GetType() == OBJECT_MESH))
((MESH*)(((MeshJoinData*)data)->to))->Join(((MESH*)obj));
}
}
BOOL sciMeshJoin()
{
OBJECT *selobj = NULL;
MeshJoinData data;
GetActiveObjects(&selobj);
if(!selobj)
{
utility.Request("No object selected.");
return FALSE;
}
if(selobj->GetType() != OBJECT_MESH)
{
utility.Request("First selected object has to be a mesh.");
return FALSE;
}
data.to = selobj;
GetObjects(MeshJoinCB, &data, 0);
REDRAW();
return TRUE;
}
/*************
* DESCRIPTION: all menu functions come through this function
* INPUT: method
* OUTPUT: -
*************/
BOOL sciDoMethod(int method)
{
OBJECT *active;
ASSERT(display);
switch(method)
{
case SCIM_SETRENDERWINDOW:
if(display->editmode & EDIT_SELBOX)
display->editmode &= ~EDIT_SELBOX;
else
{
display->editmode |= EDIT_SELBOX;
display->boxmode = BOXMODE_RENDERWINDOW;
}
break;
case SCIM_SELECTBYBOX:
if(display->editmode & EDIT_SELBOX)
display->editmode &= ~EDIT_SELBOX;
else
{
utility.CheckMenuItem(MENU_SETRENDERWINDOW, FALSE);
display->editmode |= EDIT_SELBOX;
display->boxmode = BOXMODE_SELECT;
}
break;
case SCIM_OBJECT2SCENE:
GetActiveObjects(&active, FALSE);
if(active)
{
if(active->GetType() == OBJECT_MESH)
{
((MESH*)active)->ToScene();
delete active;
sciBrowserBuild();
REDRAW();
}
}
break;
case SCIM_GRIDONOFF:
display->grid = !display->grid;
REDRAW();
SetProjectChanged(TRUE);
break;
case SCIM_GRIDSNAP:
display->gridsnap = !display->gridsnap;
SetProjectChanged(TRUE);
break;
case SCIM_SHOWNAMES:
display->name_disp = !display->name_disp;
REDRAW();
break;
case SCIM_SHOWALL:
display->filter_flags = FILTER_ALL;
REDRAW();
utility.CheckMenuItem(MENU_SHOWCAMERA, TRUE);
utility.CheckMenuItem(MENU_SHOWBRUSHES, TRUE);
utility.CheckMenuItem(MENU_SHOWTEXTURES, TRUE);
utility.CheckMenuItem(MENU_SHOWLIGHT, TRUE);
utility.CheckMenuItem(MENU_SHOWMESH, TRUE);
utility.CheckMenuItem(MENU_SHOWSPHERE, TRUE);
utility.CheckMenuItem(MENU_SHOWBOX, TRUE);
utility.CheckMenuItem(MENU_SHOWCYLINDER, TRUE);
utility.CheckMenuItem(MENU_SHOWCONE, TRUE);
utility.CheckMenuItem(MENU_SHOWSOR, TRUE);
utility.CheckMenuItem(MENU_SHOWPLANE, TRUE);
utility.CheckMenuItem(MENU_SHOWCSG, TRUE);
break;
case SCIM_SHOWBRUSHES:
display->filter_flags ^= FILTER_BRUSH;
if(!(display->filter_flags & FILTER_BRUSH))
DeselectBrushes();
REDRAW();
break;
case SCIM_SHOWTEXTURES:
display->filter_flags ^= FILTER_TEXTURE;
if(!(display->filter_flags & FILTER_TEXTURE))
DeselectTextures();
REDRAW();
break;
case SCIM_SHOWCAMERA:
display->filter_flags ^= FILTER_CAMERA;
REDRAW();
break;
case SCIM_SHOWLIGHT:
display->filter_flags ^= FILTER_LIGHT;
REDRAW();
break;
case SCIM_SHOWMESH:
display->filter_flags ^= FILTER_MESH;
REDRAW();
break;
case SCIM_SHOWSPHERE:
display->filter_flags ^= FILTER_SPHERE;
REDRAW();
break;
case SCIM_SHOWBOX:
display->filter_flags ^= FILTER_BOX;
REDRAW();
break;
case SCIM_SHOWCYLINDER:
display->filter_flags ^= FILTER_CYLINDER;
REDRAW();
break;
case SCIM_SHOWCONE:
display->filter_flags ^= FILTER_CONE;
REDRAW();
break;
case SCIM_SHOWSOR:
display->filter_flags ^= FILTER_SOR;
REDRAW();
break;
case SCIM_SHOWPLANE:
display->filter_flags ^= FILTER_PLANE;
REDRAW();
break;
case SCIM_SHOWCSG:
display->filter_flags ^= FILTER_CSG;
REDRAW();
break;
case SCIM_UNDO:
sciUndo();
break;
case SCIM_REDO:
sciRedo();
break;
case SCIM_CUT:
sciCut(display->camera);
break;
case SCIM_COPY:
sciCopy();
break;
case SCIM_PASTE:
sciPaste();
break;
case SCIM_DELETE:
sciDelete(display->camera, display->editmode);
break;
case SCIM_EDITMOVEOBJECT:
display->editmode &= ~EDIT_MASK;
display->editmode |= EDIT_MOVE | EDIT_OBJECT;
break;
case SCIM_EDITROTATEOBJECT:
display->editmode &= ~EDIT_MASK;
display->editmode |= EDIT_ROTATE | EDIT_OBJECT;
break;
case SCIM_EDITSCALEOBJECT:
display->editmode &= ~EDIT_MASK;
display->editmode |= EDIT_SCALE | EDIT_OBJECT;
break;
case SCIM_EDITMOVEWORLD:
display->editmode &= ~(EDIT_MASK | EDIT_OBJECT);
display->editmode |= EDIT_MOVE;
break;
case SCIM_EDITROTATEWORLD:
display->editmode &= ~(EDIT_MASK | EDIT_OBJECT);
display->editmode |= EDIT_ROTATE;
break;
case SCIM_EDITSCALEWORLD:
display->editmode &= ~(EDIT_MASK | EDIT_OBJECT);
display->editmode |= EDIT_SCALE;
break;
case SCIM_VIEWCAMERA:
display->view->viewmode = VIEW_CAMERA;
display->view->SetCamera(display->camera);
REDRAW_CURRENTVIEW();
// enable Set Render Window menu item
utility.EnableMenuItem(MENU_SETRENDERWINDOW, TRUE);
utility.CheckMenuItem(MENU_VIEWCAMERA, TRUE);
break;
case SCIM_VIEWFRONT:
display->view->viewmode = VIEW_FRONT;
REDRAW_CURRENTVIEW();
// disable Set Render Window menu item
utility.EnableMenuItem(MENU_SETRENDERWINDOW, FALSE);
utility.CheckMenuItem(MENU_VIEWFRONT, TRUE);
break;
case SCIM_VIEWRIGHT:
display->view->viewmode = VIEW_RIGHT;
REDRAW_CURRENTVIEW();
// disable Set Render Window menu item
utility.EnableMenuItem(MENU_SETRENDERWINDOW, FALSE);
utility.CheckMenuItem(MENU_VIEWRIGHT, TRUE);
break;
case SCIM_VIEWTOP:
display->view->viewmode = VIEW_TOP;
REDRAW_CURRENTVIEW();
// disable Set Render Window menu item
utility.EnableMenuItem(MENU_SETRENDERWINDOW, FALSE);
utility.CheckMenuItem(MENU_VIEWTOP, TRUE);
break;
case SCIM_VIEWPERSP:
display->view->viewmode = VIEW_PERSP;
display->view->SetVirtualCamera();
REDRAW_CURRENTVIEW();
// disable Set Render Window menu item
utility.EnableMenuItem(MENU_SETRENDERWINDOW, FALSE);
utility.CheckMenuItem(MENU_VIEWPERSP, TRUE);
break;
case SCIM_VIEWQUAD:
display->SetMultiView(!display->multiview);
REDRAW();
utility.CheckMenuItem(MENU_VIEWQUAD, display->multiview);
break;
case SCIM_TOGGLEACTIVEX:
display->active ^= ACTIVE_X;
break;
case SCIM_TOGGLEACTIVEY:
display->active ^= ACTIVE_Y;
break;
case SCIM_TOGGLEACTIVEZ:
display->active ^= ACTIVE_Z;
break;
case SCIM_SETACTIVEX:
display->active |= ACTIVE_X;
break;
case SCIM_SETACTIVEY:
display->active |= ACTIVE_Y;
break;
case SCIM_SETACTIVEZ:
display->active |= ACTIVE_Z;
break;
case SCIM_UNSETACTIVEX:
display->active &= ~ACTIVE_X;
break;
case SCIM_UNSETACTIVEY:
display->active &= ~ACTIVE_Y;
break;
case SCIM_UNSETACTIVEZ:
display->active &= ~ACTIVE_Z;
break;
case SCIM_DISPLAYBBOX:
display->SetDisplayMode(DISPLAY_BBOX);
REDRAW();
break;
case SCIM_DISPLAYWIRE:
display->SetDisplayMode(DISPLAY_WIRE);
REDRAW();
break;
case SCIM_DISPLAYSOLID:
display->SetDisplayMode(DISPLAY_SOLID);
REDRAW();
break;
case SCIM_EDIT_LOCAL:
display->localpos = !display->localpos;
display->localalign = !display->localalign;
display->localsize = !display->localsize;
break;
case SCIM_EDITPOINTS:
if(display->editmode & EDIT_EDITPOINTS)
{
OBJECT *selobj;
GetActiveObjects(&selobj, TRUE);
if(selobj)
{
// free selected point buffers
selobj->FreeSelectedPoints();
}
display->editmode &= ~(EDIT_EDITPOINTS | EDIT_MESH);
}
else
{
display->editmode |= EDIT_EDITPOINTS | EDIT_MESH;
}
REDRAW_SELECTED();
break;
case SCIM_ADDPOINTS:
if(display->editmode & EDIT_ADDPOINTS)
{
OBJECT *selobj;
GetActiveObjects(&selobj, TRUE);
if(selobj)
selobj->FreeSelectedPoints();
display->editmode &= ~(EDIT_ADDPOINTS | EDIT_MESH);
}
else
display->editmode |= EDIT_ADDPOINTS | EDIT_MESH;
REDRAW_SELECTED();
break;
case SCIM_EDITEDGES:
if(display->editmode & EDIT_EDITEDGES)
{
OBJECT *selobj;
GetActiveObjects(&selobj, TRUE);
if(selobj)
{
// free selected point buffers
selobj->FreeSelectedPoints();
}
display->editmode &= ~(EDIT_EDITEDGES | EDIT_MESH);
}
else
{
display->editmode |= EDIT_EDITEDGES | EDIT_MESH;
}
REDRAW_SELECTED();
break;
case SCIM_ADDEDGES:
if(display->editmode & EDIT_ADDEDGES)
{
OBJECT *selobj;
GetActiveObjects(&selobj, TRUE);
if(selobj)
selobj->FreeSelectedPoints();
display->editmode &= ~(EDIT_ADDEDGES | EDIT_MESH);
}
else
{
display->editmode |= EDIT_ADDEDGES | EDIT_MESH;
}
REDRAW_SELECTED();
break;
case SCIM_EDITFACES:
if(display->editmode & EDIT_EDITFACES)
{
OBJECT *selobj;
GetActiveObjects(&selobj, TRUE);
if(selobj)
{
// free selected point buffers
selobj->FreeSelectedPoints();
}
display->editmode &= ~(EDIT_EDITFACES | EDIT_MESH);
}
else
{
display->editmode |= EDIT_EDITFACES | EDIT_MESH;
}
REDRAW_SELECTED();
break;
case SCIM_ADDFACES:
if(display->editmode & EDIT_ADDFACES)
{
OBJECT *selobj;
GetActiveObjects(&selobj, TRUE);
if(selobj)
selobj->FreeSelectedPoints();
display->editmode &= ~(EDIT_ADDFACES | EDIT_MESH);
}
else
{
display->editmode |= EDIT_ADDFACES | EDIT_MESH;
}
REDRAW_SELECTED();
break;
case SCIM_SELALL:
sciSelectAll();
break;
case SCIM_DESELALL:
sciDeselectAll();
break;
case SCIM_SELNEXT:
sciSelectNext();
break;
case SCIM_SELPREV:
sciSelectPrev();
break;
case SCIM_REDRAW:
sciRedraw();
break;
case SCIM_REDRAW_CURRENT_VIEW:
sciRedrawCurrentView();
break;
case SCIM_CAMERA2VIEWER:
sciCamera2Viewer(display->view);
break;
case SCIM_GROUP:
return sciGroupObjects();
break;
case SCIM_UNGROUP:
sciUnGroupObjects();
break;
case SCIM_ZOOMFIT:
sciFocus(display->view, TRUE);
break;
case SCIM_FOCUS:
sciFocus(display->view, FALSE);
break;
case SCIM_ZOOMIN:
sciZoomIn(display->view);
break;
case SCIM_ZOOMOUT:
sciZoomOut(display->view);
break;
case SCIM_CREATEBOX:
return sciCreateObject(OBJECT_BOX);
break;
case SCIM_CREATESPHERE:
return sciCreateObject(OBJECT_SPHERE);
break;
case SCIM_CREATECYLINDER:
return sciCreateObject(OBJECT_CYLINDER);
break;
case SCIM_CREATECONE:
return sciCreateObject(OBJECT_CONE);
break;
case SCIM_CREATESOR:
return sciCreateObject(OBJECT_SOR);
break;
case SCIM_CREATEPLANE:
return sciCreateObject(OBJECT_PLANE);
break;
case SCIM_CREATEPOINTLIGHT:
return sciCreateObject(OBJECT_POINTLIGHT);
break;
case SCIM_CREATESPOTLIGHT:
return sciCreateObject(OBJECT_SPOTLIGHT);
break;
case SCIM_CREATEDIRECTIONALLIGHT:
return sciCreateObject(OBJECT_DIRECTIONALLIGHT);
break;
case SCIM_CREATECAMERA:
return sciCreateObject(OBJECT_CAMERA);
break;
case SCIM_CREATECSG:
return sciCreateObject(OBJECT_CSG);
break;
case SCIM_CREATEAXIS:
return sciCreateObject(OBJECT_MESH);
break;
case SCIM_MESHJOIN:
return sciMeshJoin();
default:
return FALSE;
}
return TRUE;
}
static char *ErrorMessage(rsiCONTEXT *rc, rsiResult err)
{
static char buffer[256];
if(rc)
{
PPC_STUB(rsiGetErrorMsg)(CTXT, buffer, err);
PPC_STUB(rsiCleanup)(CTXT);
PPC_STUB(rsiSetLogCB)(CTXT, (void (*)(void*, char*))NULL);
PPC_STUB(rsiSetUpdateStatusCB)(CTXT, (void (*)(void*, float, float, int, int, rsiSMALL_COLOR*))NULL);
PPC_STUB(rsiSetCheckCancelCB)(CTXT, (BOOL (*)(void*))NULL);
PPC_STUB(rsiSetCooperateCB)(CTXT, (void (*)(void*))NULL);
PPC_STUB(rsiFreeContext)(CTXT);
return buffer;
}
return NULL;
}
/*************
* DESCRIPTION: transfer the data and initialize the render context
* INPUT: LogCB
* UpdateStatusCB
* CheckCancelCB
* CooperateCB
* data
* rc
* OUTPUT: error string
*************/
char *sciRenderInit(void (*LogCB)(void*, char*), void (*UpdateStatusCB)(void*, float, float, int, int, rsiSMALL_COLOR*),
BOOL (*CheckCancelCB)(void*), void (*CooperateCB)(void*), void *data, rsiCONTEXT **rc)
{
rsiResult err;
PREFS p;
*rc = NULL;
err = PPC_STUB(rsiCreateContext)(CTXT);
if(err)
return ErrorMessage(*rc, err);
err = PPC_STUB(rsiSetUserData)(*rc, data);
if(err)
return ErrorMessage(*rc, err);
LogCB(*rc, "Transfering data");
#ifdef __MIXEDBINARY__
err = ppcSetCallbacks(*rc);
if(err)
return ErrorMessage(*rc, err);
#else
err = PPC_STUB(rsiSetLogCB)(*rc, LogCB);
if(err)
return ErrorMessage(*rc, err);
err = PPC_STUB(rsiSetUpdateStatusCB)(*rc, UpdateStatusCB);
if(err)
return ErrorMessage(*rc, err);
err = PPC_STUB(rsiSetCheckCancelCB)(*rc, CheckCancelCB);
if(err)
return ErrorMessage(*rc, err);
err = PPC_STUB(rsiSetCooperateCB)(*rc, CooperateCB);
if(err)
return ErrorMessage(*rc, err);
#endif // __MIXEDBINARY__
err = global.ToRSI(*rc);
if(err)
return ErrorMessage(*rc, err);
p.id = ID_OBJP;
if(p.GetPrefs())
{
err = PPC_STUB(rsiSetObjectPath)(*rc, (char*)p.data);
if(err)
{
p.data = NULL;
return ErrorMessage(*rc, err);
}
}
p.id = ID_BRSP;
if(p.GetPrefs())
{
err = PPC_STUB(rsiSetBrushPath)(*rc, (char*)p.data);
if(err)
{
p.data = NULL;
return ErrorMessage(*rc, err);
}
}
p.id = ID_TXTP;
if(p.GetPrefs())
{
err = PPC_STUB(rsiSetTexturePath)(*rc, (char*)p.data);
if(err)
{
p.data = NULL;
return ErrorMessage(*rc, err);
}
}
p.data = NULL;
err = ToRSI(*rc, display->camera);
if(err)
return ErrorMessage(*rc, err);
if(global.enablearea)
{
err = PPC_STUB(rsiSetRenderField)(*rc, (int)(global.xres * global.xmin),
(int)(global.yres * global.ymin),
(int)(global.xres * global.xmax)-1,
(int)(global.yres * global.ymax)-1);
if(err)
return ErrorMessage(*rc, err);
}
return NULL;
}
/*************
* DESCRIPTION: render the scene
* INPUT: rc
* OUTPUT: error string
*************/
char *sciRender(rsiCONTEXT *rc)
{
ULONG flags, quality;
PREFS p;
rsiResult err;
UBYTE *scr;
flags = 0;
if(global.quick)
flags |= rsiFRenderQuick;
if(global.randjit)
flags |= rsiFRenderRandomJitter;
err = PPC_STUB(rsiRender)(CTXT, &scr,
rsiTRenderFlags,flags,
rsiTDone);
if(err)
{
PPC_STUB(rsiCleanup)(CTXT);
return ErrorMessage(rc, err);
}
p.id = ID_JPEG;
if(p.GetPrefs())
quality = *(ULONG*)(p.data);
else
quality = 70;
p.data = NULL;
if(global.renderdpic)
{
if(global.renderdpic[0])
{
err = PPC_STUB(rsiSavePicture)(CTXT, global.renderdpic,
rsiTPicType, global.picformat,
rsiTPicJPEGQuality, quality,
rsiTDone);
}
}
if(err)
return ErrorMessage(rc, err);
err = PPC_STUB(rsiCleanup)(CTXT);
if(err)
return ErrorMessage(rc, err);
// reset callback functions
PPC_STUB(rsiSetLogCB)(CTXT, (void (*)(void*, char*))NULL);
PPC_STUB(rsiSetUpdateStatusCB)(CTXT, (void (*)(void*, float, float, int, int, rsiSMALL_COLOR*))NULL);
PPC_STUB(rsiSetCheckCancelCB)(CTXT, (BOOL (*)(void*))NULL);
PPC_STUB(rsiSetCooperateCB)(CTXT, (void (*)(void*))NULL);
PPC_STUB(rsiFreeContext)(CTXT);
return NULL;
}
| {
"content_hash": "1862f978c8080d800a23d51b3d607911",
"timestamp": "",
"source": "github",
"line_count": 2087,
"max_line_length": 150,
"avg_line_length": 21.244849065644466,
"alnum_prop": 0.629482610852993,
"repo_name": "privatosan/RayStorm",
"id": "8416affdf5d3bae6805cee282350c89d0fb8b6e6",
"size": "44338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Scenario/CommonScenario/sci.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "60980"
},
{
"name": "C",
"bytes": "4170609"
},
{
"name": "C++",
"bytes": "4169265"
},
{
"name": "Objective-C",
"bytes": "50761"
},
{
"name": "Parrot",
"bytes": "147029"
},
{
"name": "Perl",
"bytes": "37"
},
{
"name": "Scilab",
"bytes": "2596"
},
{
"name": "Shell",
"bytes": "180"
}
],
"symlink_target": ""
} |
<div class="drop-lines"></div>
| {
"content_hash": "6624fcfe8d1f29fc20e83b59274ddc11",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 30,
"avg_line_length": 16,
"alnum_prop": 0.625,
"repo_name": "psr1919plus21/myd3",
"id": "717f0eea3f10351953717365b6792521e48f8745",
"size": "32",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "markup/components/drop-lines/drop-lines.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "54885"
},
{
"name": "HTML",
"bytes": "58146"
},
{
"name": "JavaScript",
"bytes": "1469891"
}
],
"symlink_target": ""
} |
A simple sample for the usage of UnityEditor.AnimationMode api set.
scrapped from [here](http://forum.unity3d.com/threads/sample-mecanim-animations-in-editor.262973/).
| {
"content_hash": "37c2de355b09eff973d4c8c338ece418",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 99,
"avg_line_length": 56.333333333333336,
"alnum_prop": 0.7988165680473372,
"repo_name": "kimsama/Unity-AnimationMode-Sample",
"id": "489f467224eb3f45de85d63d51679ba923f10b1e",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2363"
}
],
"symlink_target": ""
} |
package de.grafelhaft.winespray.acrecontrol;
import org.junit.Before;
import org.junit.Test;
import static de.grafelhaft.winespray.acrecontrol.Constants.EARTH_RADIUS;
import static org.junit.Assert.*;
/**
* Created by @author Markus Graf (Grafelhaft) on 03.02.2017.
*/
public class LocationConverterTest {
private static final double EARTH_RADIUS = 6378.388;
@Test
public void convertGps() throws Exception {
final IPoint point = new Point(90, 90);
IPoint apoint = approxMeterSphere(point);
IPoint bpoint = LocationConverter.approxDegreeSphere(apoint);
IPoint cpoint = new Point(EARTH_RADIUS * (Math.PI/180) * point.x(), EARTH_RADIUS * (Math.PI/180) * Math.cos(Math.toRadians(point.x())) * point.y());
assertEquals(point.x(), bpoint.x(), 0);
assertEquals(point.y(), bpoint.y(), 0);
}
public static Point approxMeterSphere(IPoint point) {
double lat = point.x();
double lng = point.y();
double distLat = EARTH_RADIUS * (Math.PI/180) * lat;
double distLng = EARTH_RADIUS * /*(Math.PI/180) **/ Math.acos(Math.pow(Math.sin(Math.toRadians(lat)), 2) + Math.pow(Math.cos(Math.toRadians(lat)), 2) * Math.cos(Math.toRadians(lng)));
//double distLng = EARTH_RADIUS * /*(Math.PI/180)* */ Math.acos(Math.sin(Math.toRadians(lat)) * Math.sin(Math.toRadians(lat)) + Math.cos(Math.toRadians(lat)) * Math.cos(Math.toRadians(lat)) * Math.cos(Math.toRadians(lng)));
return new Point(distLat, distLng);
}
} | {
"content_hash": "261c1fd43563ccadd44b7156e47619e5",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 231,
"avg_line_length": 39.94736842105263,
"alnum_prop": 0.66600790513834,
"repo_name": "Grafelhaft/WineSpray",
"id": "9d868ea7554111de6ef0d379cf19c25c891c2390",
"size": "1518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Acrecontrol/acrecontrol/src/test/java/de/grafelhaft/winespray/acrecontrol/LocationConverterTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "476757"
}
],
"symlink_target": ""
} |
#ifndef TANGO_VIDEO_OVERLAY_VIDEO_OVERLAY_APP_H_
#define TANGO_VIDEO_OVERLAY_VIDEO_OVERLAY_APP_H_
#include <atomic>
#include <jni.h>
#include <memory>
#include <mutex>
#include <tango_client_api.h> // NOLINT
#include <tango-gl/util.h>
#include <tango-video-overlay/yuv_drawable.h>
#include <tango-gl/video_overlay.h>
namespace tango_video_overlay {
// VideoOverlayApp handles the application lifecycle and resources.
class VideoOverlayApp {
public:
// Constructor and deconstructor.
VideoOverlayApp();
~VideoOverlayApp();
enum TextureMethod {
kYUV,
kTextureId
};
// YUV data callback.
void OnFrameAvailable(const TangoImageBuffer* buffer);
// Initialize Tango Service, this function starts the communication
// between the application and Tango Service.
// The activity object is used for checking if the API version is outdated.
int TangoInitialize(JNIEnv* env, jobject caller_activity);
// Setup the configuration file for the Tango Service. We'll also se whether
// we'd like auto-recover enabled.
int TangoSetupConfig();
// Connect to the Tango Service.
// This function will start the Tango Service pipeline, in this case, it will
// start the video overlay update.
int TangoConnect();
// Disconnect from Tango Service, release all the resources that the app is
// holding from Tango Service.
void TangoDisconnect();
// Allocate OpenGL resources for rendering, mainly initializing the Scene.
void InitializeGLContent();
// Setup the view port width and height.
void SetViewPort(int width, int height);
// Main render loop.
void Render();
// Release all OpenGL resources that allocate from the program.
void FreeGLContent();
// Set texture method.
void SetTextureMethod(int method) {
current_texture_method_ = static_cast<TextureMethod>(method);
}
private:
// Tango configration file, this object is for configuring Tango Service setup
// before connect to service. For example, we set the flag
// config_enable_auto_recovery based user's input and then start Tango.
TangoConfig tango_config_;
// video_overlay_ render the camera video feedback onto the screen.
tango_gl::VideoOverlay* video_overlay_drawable_;
YUVDrawable* yuv_drawable_;
TextureMethod current_texture_method_;
std::vector<uint8_t> yuv_buffer_;
std::vector<uint8_t> yuv_temp_buffer_;
std::vector<GLubyte> rgb_buffer_;
std::atomic<bool> is_yuv_texture_available_;
std::atomic<bool> swap_buffer_signal_;
std::mutex yuv_buffer_mutex_;
size_t yuv_width_;
size_t yuv_height_;
size_t yuv_size_;
size_t uv_buffer_offset_;
void AllocateTexture(GLuint texture_id, int width, int height);
void RenderYUV();
void RenderTextureId();
};
} // namespace tango_video_overlay
#endif // TANGO_VIDEO_OVERLAY_VIDEO_OVERLAY_APP_H_
| {
"content_hash": "82932a32ed5a16a7a0e3ee5fa8f20e9c",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 80,
"avg_line_length": 28.575757575757574,
"alnum_prop": 0.7299399080947331,
"repo_name": "hamidb/tango-examples-c",
"id": "1a05c26e217be57b41c6c0aa37e0a445547bf27b",
"size": "3445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "video-overlay-jni-example/app/src/main/jni/tango-video-overlay/video_overlay_app.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "498415"
},
{
"name": "Java",
"bytes": "140152"
},
{
"name": "Makefile",
"bytes": "25814"
}
],
"symlink_target": ""
} |
<div class="commentable" voteable voteable-type="Comment">
<div ng-hide="loggedIn()">
Please <span login-link></span> or <span register-link></span> to comment on this bill
</div>
<div ng-show="loggedIn()">
<div class="add-comment">
<textarea ng-model="formComment.body" placeholder="Add Comment..." cols="20" rows="2"></textarea>
<div class="buttons">
<button class="save btn btn-primary" ng-click="createComment()">Save</button>
</div>
</div>
</div>
<div class="comment clearfix" ng-repeat="comment in comments | orderBy:score " ng-include=" '/templates/commentable/comment' " timeago time-selector="time.timeago"></div>
</div>
| {
"content_hash": "a50eb28dc052cdf06b90f8210f398290",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 172,
"avg_line_length": 45.266666666666666,
"alnum_prop": 0.6612665684830633,
"repo_name": "nazar/parlmnt",
"id": "dbd47bef50897aa9bc02618a330ebdde3140b28f",
"size": "679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/templates/commentable/commentable.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "127696"
},
{
"name": "Ruby",
"bytes": "124891"
}
],
"symlink_target": ""
} |
import Express from 'express';
import registerMiddlewares from './lib/middleware.js';
import dbInit from '../db/index.js';
import passport from './lib/passport.js';
import { register } from './lib/auth/local.js';
export default function createRouter() {
return dbInit()
.then((db) => {
const router = new Express.Router();
registerMiddlewares(router);
router.get('/session', (req, res) => {
// This kinda looks silly
res.send(req.user || {});
});
router.post('/session', passport.authenticate('local'), (req, res) => {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.send(req.user || {});
});
router.delete('/session', (req, res) => {
req.logout();
res.send({});
});
router.all('/user/auth/local', (req, res) => {
register(req, req.query, (err) => {
if (err) return res.status(500).send(err.message);
res.send(req.user || {});
});
});
router.get('/search', (req, res) => {
res.send({});
});
router.use((req, res) => {
res.sendStatus(404);
});
return router;
});
}
| {
"content_hash": "8a81eefee65e76133ff59e28b93bcc79",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 75,
"avg_line_length": 29.525,
"alnum_prop": 0.5715495342929721,
"repo_name": "GrooshBene/shellscripts",
"id": "f72e3ad547c92390a71a7957d9a38979d15719f9",
"size": "1181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/api/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6142"
},
{
"name": "JavaScript",
"bytes": "42626"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<head>
<title>Alarm Control</title>
<link rel="apple-touch-icon" sizes="180x180" href="{{ url_for('static', filename='apple-touch-icon.png') }}">
<link rel="icon" type="image/png" sizes="32x32" href="{{ url_for('static', filename='favicon-32x32.png') }}">
<link rel="icon" type="image/png" sizes="16x16" href="{{ url_for('static', filename='favicon-16x16.png') }}">
<link rel="manifest" href="{{ url_for('static', filename='manifest.json') }}">
<link rel="mask-icon" href="{{ url_for('static', filename='safari-pinned-tab.svg') }}" color="#000000">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
<meta name="msapplication-config" content="{{ url_for('static', filename='browserconfig.xml') }}">
<meta name="theme-color" content="#ffffff">
<script>
function myFunction() {
var i = document.createElement("input");
i.setAttribute("type", "time");
var stuff = i.type !== "text";
var foo = document.getElementById("browser_specific_input");
if(stuff == true) {
var element = document.createElement("input");
element.name = "usr_time";
element.type = "time";
foo.appendChild(element);
} else {
var result = document.createElement("span");
var hours = document.createElement("select");
hours.name = "hour"
hours.setAttribute("id", "hour");
for (var h=1; h<25; h++) {
var option = document.createElement("option");
option.setAttribute("value", h);
option.appendChild(document.createTextNode(h));
hours.appendChild(option);
}
var minutes = document.createElement("select");
minutes.setAttribute("name", "minute")
minutes.setAttribute("id", "minute");
for (var m=0; m<60; m++) {
var option = document.createElement("option");
option.setAttribute("value", m);
option.appendChild(document.createTextNode(m));
minutes.appendChild(option);
}
result.appendChild(hours);
result.appendChild(document.createTextNode(" : "));
result.appendChild(minutes);
foo.appendChild(result);
}
}
</script>
</head>
<body style="background-color:#181818;color:white;" link="blue" vlink="blue" alink="red" onload="myFunction()">
<h1>Alarm Control</h1>
<h2>Page last reloaded at: {{ time }}   <a href="{{ url_for('alarm_control') }}">Reload</a></h2>
<h3>Alarm {{ alarm_on_or_off }} {{ alarm_time }}</h3>
<form action="{{ url_for('alarm_control') }}" method=Post>
Alarm time:
<br>
<div id="browser_specific_input">
</div>
<br>
<br>
Alarm Set:
<br>
<input type="radio" name="on_or_off" value="1" checked> On<br>
<input type="radio" name="on_or_off" value="0"> Off<br>
<br>
<input type="submit">
</form>
<h4><a href="{{ url_for('control') }}">Back to control panel</a></h4>
</body>
</html>
| {
"content_hash": "d0c8d433d4fc053397e80ee9d799c689",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 111,
"avg_line_length": 37.25675675675676,
"alnum_prop": 0.6463547334058759,
"repo_name": "mhar9000/Clock-Pi",
"id": "27ab543b6321997c92e3775349e29518242b2cd5",
"size": "2757",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Web/templates/alarm.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "6844"
},
{
"name": "HTML",
"bytes": "8820"
},
{
"name": "Python",
"bytes": "79439"
},
{
"name": "Shell",
"bytes": "13241"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
android:drawable="@drawable/abc_spinner_ab_disabled_holo_light" />
<item android:state_pressed="true"
android:drawable="@drawable/abc_spinner_ab_pressed_holo_light" />
<item android:state_pressed="false" android:state_focused="true"
android:drawable="@drawable/abc_spinner_ab_focused_holo_light" />
<item android:drawable="@drawable/abc_spinner_ab_default_holo_light" />
</selector>
<!-- From: file:/D:/Foheart/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/20.0.0/res/drawable/abc_spinner_ab_holo_light.xml --> | {
"content_hash": "cb735c8f489d2918929c0df3fb43a2ce",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 151,
"avg_line_length": 52.19230769230769,
"alnum_prop": 0.7170228445099485,
"repo_name": "FlushOut/foheart",
"id": "daaf9722a66f0cee75109b18ecabed7868c5f914",
"size": "1357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mobile/Foheart/app/build/intermediates/res/debug/drawable/abc_spinner_ab_holo_light.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "1242"
},
{
"name": "Java",
"bytes": "766431"
},
{
"name": "PHP",
"bytes": "71805"
}
],
"symlink_target": ""
} |
// Copyright 2016-present the Material Components for iOS 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.
#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIKit.h>
#import "MaterialElevation.h"
#import "MaterialInk.h"
#import "MaterialRipple.h"
#import "MaterialShadow.h"
#import "MaterialShadowElevations.h"
#import "MaterialShapes.h"
API_DEPRECATED_BEGIN("🤖👀 Use branded M3CButton instead. "
"See go/material-ios-buttons/gm2-migration for more details. "
"This has go/material-ios-migrations#scriptable-potential 🤖👀.",
ios(12, 12))
/**
A Material flat, raised or floating button.
All buttons display animated ink splashes when the user interacts with the button.
The title color of the button set to have an accessible contrast ratio with the button's
background color. To ensure this works for flat buttons (with transparent background), the caller
is responsible for setting (and updating, if necessary) the button's underlyingColor property.
All buttons set the exclusiveTouch property to YES by default, which prevents users from
simultaneously interacting with a button and other UI elements.
@see https://material.io/go/design-buttons
*/
@interface MDCButton : UIButton <MDCElevatable, MDCElevationOverriding>
/** The ripple style of the button. */
@property(nonatomic, assign) MDCRippleStyle rippleStyle;
/**
The color of the ripple.
@note Defaults to a transparent black.
*/
@property(nonatomic, strong, null_resettable) UIColor *rippleColor;
/**
The maximum radius the ripple can expand to.
@note This property is ignored if @c rippleStyle is set to @c MDCRippleStyleBounded.
@note Defaults to 0.
*/
@property(nonatomic, assign) CGFloat rippleMaximumRadius;
/**
This property determines if an @c MDCButton should use the @c MDCInkView behavior or not.
By setting this property to @c YES, @c MDCStatefulRippleView is used to provide the user visual
touch feedback, instead of the legacy @c MDCInkView.
@note Defaults to @c NO.
*/
@property(nonatomic, assign) BOOL enableRippleBehavior;
/**
The alpha value that will be applied when the button is disabled. Most clients can leave this as
the default value to get a semi-transparent button automatically.
*/
@property(nonatomic) CGFloat disabledAlpha;
/**
If true, converts the button title to uppercase. Changing this property to NO will update the
current title string.
Default is YES.
*/
@property(nonatomic, getter=isUppercaseTitle) BOOL uppercaseTitle UI_APPEARANCE_SELECTOR;
/**
A Boolean value that determines whether the visible area is centered in the bounds of the view.
If set to YES, the visible area is centered in the bounds of the view, which is often used to
configure invisible tappable area. If set to NO, the visible area fills its bounds. This property
doesn't affect the result of @c sizeThatFits:.
The default value is @c NO.
*/
@property(nonatomic, assign) BOOL centerVisibleArea;
/**
The edges of this guide are constrained to equal the edges of the visible area
when @c centerVisibleArea is @c YES.
@note If centerVisibleArea is @c NO then visibleAreaLayoutGuide is nil.
*/
@property(nonatomic, readonly, strong, nullable) UILayoutGuide *visibleAreaLayoutGuide;
/**
The default content edge insets of the button. They are set at initialization time.
*/
@property(nonatomic, readonly) UIEdgeInsets defaultContentEdgeInsets;
/**
The offset (in points) of the button's inkView or rippleView (depending on which is being used -
see @c enableRippleBehavior)
Default is CGSizeZero.
*/
@property(nonatomic) CGSize inkViewOffset;
/**
The inset or outset margins for the rectangle surrounding the button’s ripple.
*/
@property(nonatomic, assign) UIEdgeInsets rippleEdgeInsets;
/**
The minimum size of the button’s alignment rect. If either the height or width are non-positive
(negative or zero), they will be ignored and that axis will adjust to its content size.
Defaults to CGSizeZero.
*/
@property(nonatomic, assign) CGSize minimumSize UI_APPEARANCE_SELECTOR;
/**
The maximum size of the button’s alignment rect. If either the height or width are non-positive
(negative or zero), they will be ignored and that axis will adjust to its content size. Setting a
maximum size may result in image clipping or text truncation.
Defaults to CGSizeZero.
*/
@property(nonatomic, assign) CGSize maximumSize UI_APPEARANCE_SELECTOR;
/**
Setting this property to @c YES when the button's @c titleLabel is multi-line (i.e. when @c
numberOfLines is not equal to 1) will result in the button inferring what its size should be and
then setting both the @c minimumSize and @c maximumSize to that value. Setting this property back
to @c NO will result in @c maximumSize and @c minimumSize being reset to @c CGSizeZero.
In both Manual Layout and Auto Layout environments the inferred height is a function of the width.
In an Auto Layout environment the width will depend on the constraints placed on the view. In a
Manual Layout environment the current width will be assumed to be the preferred width, so it is
important to make sure the button's width is set to an appropriate value before turning this flag
on. In an Auto Layout environment, the view will likely resize itself as needed when this flag is
turned on. In a Manual Layout environment, you will likely have to call @c -sizeToFit after turning
this flag on.
Defaults to NO.
*/
@property(nonatomic, assign) BOOL inferMinimumAndMaximumSizeWhenMultiline;
/**
The apparent background color as seen by the user, i.e. the color of the view behind the button.
The underlying color hint is used by buttons to calculate accessible title text colors when in
states with transparent background colors. The hint is used whenever the button changes state such
that the background color changes, for example, setting the background color or disabling the
button.
For flat buttons, this is the color of both the surrounding area and the button's background.
For raised and floating buttons, this is the color of view underneath the button.
The default is nil. If left unset, buttons will likely have an incorrect appearance when
disabled. Additionally, flat buttons might have text colors with low accessibility.
*/
@property(nonatomic, strong, nullable) UIColor *underlyingColorHint;
/**
The shape generator used to define the button's shape.
When the shapeGenerator is nil, MDCButton will use the default underlying layer with
its default settings.
@note If a layer property is explicitly set after the shapeGenerator has been set,
it can lead to unexpected behavior.
@note When @c centerVisibleArea is set to YES, this property can no longer be set.
Default value for shapeGenerator is nil.
*/
@property(nullable, nonatomic, strong) id<MDCShapeGenerating> shapeGenerator;
/**
A block that is invoked when the MDCButton receives a call to @c
traitCollectionDidChange:. The block is called after the call to the superclass.
*/
@property(nonatomic, copy, nullable) void (^traitCollectionDidChangeBlock)
(MDCButton *_Nonnull button, UITraitCollection *_Nullable previousTraitCollection);
/**
A color used as the button's @c backgroundColor for @c state.
@param state The state.
@return The background color.
*/
- (nullable UIColor *)backgroundColorForState:(UIControlState)state;
/**
A color used as the button's @c backgroundColor.
If left unset or reset to nil for a given state, then a default blue color is used.
@param backgroundColor The background color.
@param state The state.
*/
- (void)setBackgroundColor:(nullable UIColor *)backgroundColor
forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
/* Convenience for `setBackgroundColor:backgroundColor forState:UIControlStateNormal`. */
- (void)setBackgroundColor:(nullable UIColor *)backgroundColor;
/** Sets the enabled state with optional animation. */
- (void)setEnabled:(BOOL)enabled animated:(BOOL)animated;
/**
Returns the elevation for a particular control state.
The default values depend on the kind of button, for example, flat buttons in the
UIControlStateNormal state have zero elevation.
@param state The control state to retrieve the elevation.
@return The elevation for the requested state.
*/
- (MDCShadowElevation)elevationForState:(UIControlState)state;
/**
Sets the elevation for a particular control state.
@param elevation The elevation to set.
@param state The state to set.
*/
- (void)setElevation:(MDCShadowElevation)elevation forState:(UIControlState)state;
/**
A color used as the button's @c borderColor for @c state.
@param state The state.
@return The border color.
*/
- (nullable UIColor *)borderColorForState:(UIControlState)state;
/**
Sets the border color for a particular control state. Sets the @c borderColor of the layer.
@param borderColor The border color to set.
@param state The state to set.
*/
- (void)setBorderColor:(nullable UIColor *)borderColor
forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
/**
A color used as the button's imageView tint color @c imageTintColor for @c state.
If no image tint color has been set for a given state, the returned value will fall back to the
value set for UIControlStateNormal.
setting @c tintColor will clear these values.
@param state The state.
@return The tint color.
*/
- (nullable UIColor *)imageTintColorForState:(UIControlState)state;
/**
Sets the image view tint color for a particular control state.
If left unset or reset to nil for a given state, it falls back to UIControlStateNormal setting.
@param imageTintColor The imageView tint color to set.
@param state The state to set.
*/
- (void)setImageTintColor:(nullable UIColor *)imageTintColor forState:(UIControlState)state;
/**
The value set for the button's @c borderWidth for @c state.
@param state The state.
@return The border width.
*/
- (CGFloat)borderWidthForState:(UIControlState)state;
/**
Sets the border width for a particular control state. Sets the @c borderWidth of the layer.
@param borderWidth The border width to set.
@param state The state to set.
*/
- (void)setBorderWidth:(CGFloat)borderWidth forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
/**
Sets this button's layer's shadowColor for the specified control state.
During initialization, the value for @c UIControlStateNormal is set to the value of this button's
layer's @c shadowColor. Providing a @c nil value for @c shadowColor will remove the shadow color
mapping for the specified state.
If the color is not set for a specified state, the default behavior is to use the color associated
with @c UIControlStateNormal. If the color for @c UIControlStateNormal is not set, then @c nil will
be used.
@param shadowColor The shadow color to use for the specified state.
@param state The state that uses the specified color. The possible values are described in
@c UIControlState.
*/
- (void)setShadowColor:(nullable UIColor *)shadowColor
forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
/**
The color used as this button's layer's @c shadowColor for the specified control state.
During initialization, the value for @c UIControlStateNormal is set to the value of this view's
layer's @c shadowColor.
If the color is not set for a specified state, the default behavior is to use the color associated
with @c UIControlStateNormal. If the color for @c UIControlStateNormal has not been set, then
@c nil is returned.
@param state The state that uses the shadow color. The possible values are described in
@c UIControlState.
@return The shadow color for the specified state. If no shadow color has been set for the
specific state, this method returns the shadow color associated with the
@c UIControlStateNormal state.
@return The shadow color.
*/
- (nullable UIColor *)shadowColorForState:(UIControlState)state;
#pragma mark - Enabling multi-line layout
/**
When enabled, makes use of constraints to enable the title label to wrap to multiple lines.
Note: this property does not currently support buttons with images. Enabling this property when an
image is present will result in undefined behavior.
Default value is NO.
*/
@property(nonatomic, assign) BOOL layoutTitleWithConstraints;
#pragma mark - UIButton changes
/**
From UIButton's documentation: "If you subclass UIButton, this method does not return an instance
of your subclass. If you want to create an instance of a specific subclass, you must alloc/init
the button directly."
*/
+ (nonnull instancetype)buttonWithType:(UIButtonType)buttonType NS_UNAVAILABLE;
@end
@interface MDCButton (ToBeDeprecated)
/**
Enables the state-based font behavior of the receiver.
If @c NO, then @c titleFont:forState: and @c setTitleFont:forState: have no effect. Defaults to
@c YES.
@note This API will eventually be deprecated and removed.
*/
@property(nonatomic, assign) BOOL enableTitleFontForState;
/**
The inset margins for the rectangle surrounding all of the button’s visual representation.
Use this property when you wish to have the touch target (frame) be larger than the
visible content.
A positive value shrinks the visible area of the button. A negative value expands the visible area
of the button.
The button uses this property to determine intrinsicContentSize and sizeThatFits:.
@note This API will be deprecated and removed. Consider using @c centerVisibleArea.
Default is UIEdgeInsetsZero.
*/
@property(nonatomic, assign) UIEdgeInsets visibleAreaInsets;
/**
The font used by the button's @c title.
If left unset or reset to nil for a given state, then a default font is used.
@param font The font.
@param state The state.
@note This API will eventually be deprecated and removed.
*/
- (void)setTitleFont:(nullable UIFont *)font forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
/**
The font used by the button's @c title for @c state.
@param state The state.
@return The font.
@note This API will eventually be deprecated and removed.
*/
- (nonnull UIFont *)titleFontForState:(UIControlState)state;
/**
If @c true, @c accessiblityTraits will always include @c UIAccessibilityTraitButton.
If @c false, @c accessibilityTraits will inherit its behavior from @c UIButton.
@note Defaults to true.
@note This API is intended as a migration flag to restore @c UIButton behavior to @c MDCButton. In
a future version, this API will eventually be deprecated and then deleted.
*/
@property(nonatomic, assign) BOOL accessibilityTraitsIncludesButton;
/** The ink style of the button. */
@property(nonatomic, assign) MDCInkStyle inkStyle UI_APPEARANCE_SELECTOR;
/** The ink color of the button. */
@property(nonatomic, strong, null_resettable) UIColor *inkColor UI_APPEARANCE_SELECTOR;
/*
Maximum radius of the button's ink. If the radius <= 0 then half the length of the diagonal of
self.bounds is used. This value is ignored if button's @c inkStyle is set to |MDCInkStyleBounded|.
*/
@property(nonatomic, assign) CGFloat inkMaxRippleRadius UI_APPEARANCE_SELECTOR;
@end
@interface MDCButton (Deprecated)
/**
Insets to apply to the button’s hit area.
Allows the button to detect touches outside of its bounds. A negative value indicates an
extension past the bounds.
Default is UIEdgeInsetsZero.
*/
@property(nonatomic) UIEdgeInsets hitAreaInsets __deprecated_msg("Use centerVisibleArea instead.");
/*
Indicates whether the button should automatically update its font when the device’s
UIContentSizeCategory is changed.
This property is modeled after the adjustsFontForContentSizeCategory property in the
UIContentSizeCategoryAdjusting protocol added by Apple in iOS 10.0.
If set to YES, this button will base its text font on MDCFontTextStyleButton.
Defaults value is NO.
This property will be deprecated and deleted. Instead, please use
titleLabel.adjustsFontForContentSizeCategory and make sure the title font is a
scalable font.
*/
@property(nonatomic, readwrite, setter=mdc_setAdjustsFontForContentSizeCategory:)
BOOL mdc_adjustsFontForContentSizeCategory UI_APPEARANCE_SELECTOR __deprecated_msg(
"Use titleLabel.adjustsFontForContentSizeCategory");
@end
API_DEPRECATED_END
| {
"content_hash": "f6ab93082a5aa3447dc8dfadd1ac698d",
"timestamp": "",
"source": "github",
"line_count": 467,
"max_line_length": 100,
"avg_line_length": 36.21627408993576,
"alnum_prop": 0.7656832022704428,
"repo_name": "material-components/material-components-ios",
"id": "0c097b483dff0451e1f6cd475141b109b2bccf1f",
"size": "16937",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "components/Buttons/src/MDCButton.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "15108"
},
{
"name": "Objective-C",
"bytes": "7907886"
},
{
"name": "Python",
"bytes": "22330"
},
{
"name": "Ruby",
"bytes": "108390"
},
{
"name": "Shell",
"bytes": "118227"
},
{
"name": "Swift",
"bytes": "896400"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.parse.dukehack.activity.PointActivity"
android:background="#e84ce67d">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="95dp"
android:src="@drawable/gift79" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/usernameTxt"
android:layout_marginTop="54dp"
android:hint="Name"
android:textSize="40dp"
android:textColor="#fbfdfd"
android:text="Jack"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50 :)"
android:id="@+id/pointTxt"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:textSize="50dp"
android:textColor="#faf616" />
</RelativeLayout>
<!-- From: file:/C:/Users/IBM_ADMIN/AndroidStudioProjects/dukehack/ParseStarterProject/src/main/res/layout/activity_point.xml --> | {
"content_hash": "f2d9e37bd1dc0b9277237f22e30bf049",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 129,
"avg_line_length": 41.16279069767442,
"alnum_prop": 0.6830508474576271,
"repo_name": "iganbold/dukehack",
"id": "aa0886b0dcd37d3c8c887d097d46d19d0e21afd7",
"size": "1770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ParseStarterProject/build/intermediates/res/merged/debug/layout/activity_point.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1620864"
}
],
"symlink_target": ""
} |
package org.febit.lang.protocal;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.febit.lang.Valued;
@Data
@AllArgsConstructor(staticName = "of")
public class Sort {
private String property;
private Direction direction;
public static Sort asc(String column) {
return of(column, Direction.ASC);
}
public static Sort desc(String column) {
return of(column, Direction.DESC);
}
@JsonIgnore
public boolean isAsc() {
return getDirection() == Direction.ASC;
}
public Direction getDirection() {
return direction != null ? direction : Direction.ASC;
}
@JsonIgnore
public boolean isDesc() {
return getDirection() == Direction.DESC;
}
@Override
public String toString() {
return this.property + ',' + this.direction.getValue();
}
@RequiredArgsConstructor
public enum Direction implements Valued<String> {
ASC("asc"),
DESC("desc"),
;
@Getter
private final String value;
}
}
| {
"content_hash": "9323002cbafcd1df07c2f7d3b51b1f34",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 63,
"avg_line_length": 21.685185185185187,
"alnum_prop": 0.6532877882152007,
"repo_name": "febit/febit-common",
"id": "4f67afa966852447c112efcb5b5df5be5dadedad",
"size": "1791",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "febit-lang/src/main/java/org/febit/lang/protocal/Sort.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "607380"
},
{
"name": "Makefile",
"bytes": "282"
}
],
"symlink_target": ""
} |
//
// NSSet+LCActionSheet.h
// LCActionSheet
//
// Created by Leo on 2016/11/28.
// Copyright © 2016年 Leo(http://LeoDev.me). All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSSet (LCActionSheet)
/**
* Check if set contains the int value.
*/
- (BOOL)lc_contains:(int)num;
@end
| {
"content_hash": "8b1b40ee0c72e1e2cea7fa7e59c8d952",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 65,
"avg_line_length": 17.11111111111111,
"alnum_prop": 0.6688311688311688,
"repo_name": "CQTWProgramme/cqtw",
"id": "849676ae4eb7eb8abe9144fbb6a2291f13e44c14",
"size": "315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pods/LCActionSheet/LCActionSheet/NSSet+LCActionSheet.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "412"
},
{
"name": "Objective-C",
"bytes": "1608694"
}
],
"symlink_target": ""
} |
<?php
/**
* @author Samuel Nogueira <[email protected]>
*/
class BlogController extends BaseController {
public function showIndex()
{
return View::make('blog.index');
}
}
| {
"content_hash": "c27cd629f1bf6f1c23ea7fe862de7897",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 58,
"avg_line_length": 16.083333333333332,
"alnum_prop": 0.694300518134715,
"repo_name": "cientistamaluco/samuelnogueira",
"id": "b07e7be93aa0fe4291abedb3eed188e0b807c7d1",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/BlogController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "149762"
},
{
"name": "JavaScript",
"bytes": "734"
},
{
"name": "PHP",
"bytes": "86275"
}
],
"symlink_target": ""
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bunk
{
public class BulkDocs
{
public BulkDocs(IEnumerable<IDocument> docs)
{
this.Documents = new List<IDocument>(docs);
}
[JsonProperty("docs")]
public List<IDocument> Documents { get; set; }
}
public class BulkDocsResponse : List<BulkDocumentResponse>
{
}
public class BulkDocumentResponse : DocumentResponse
{
[JsonProperty("error")]
public string Error {get;set;}
[JsonProperty("reason")]
public string Reason { get; set; }
}
}
| {
"content_hash": "0c09637b28133db0b90385ddc175ab8a",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 62,
"avg_line_length": 18.763157894736842,
"alnum_prop": 0.6269284712482468,
"repo_name": "dedels/Bunk",
"id": "e63b0b3260ffb9554276b994f0036cec0f904774",
"size": "715",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Bunk/BulkDocs.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "115212"
}
],
"symlink_target": ""
} |
<?php
namespace Helloworld\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class GreetingServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
/*$greetingService = new GreetingService();
$greetingService->setEventManager(
$serviceLocator->get('eventManager')
);
$greetingService->getEventManager()
->attach(
'getGreeting',
function($e) use ($serviceLocator) {
$serviceLocator->get('loggingService')
->onGetGreeting($e);
}
);*/
/*$serviceLocator->get('sharedEventManager')
->attach(
'GreetingService',
'getGreeting',
function($e) use($serviceLocator) {
$serviceLocator->get('loggingService')
->onGetGreeting($e);
}
);
$greetingService = new GreetingService();
return $greetingService;*/
$di = new \Zend\Di\Di();
$di->configure(new \Zend\Di\Config(array(
'definition' => array(
'class' => array(
'Helloworld\Service\GreetingService' => array(
'setLoggingService' => array(
'required' => true
)
)
)
),
'instance' => array(
'preferences' => array(
'Helloworld\Service\LoggingServiceInterface'
=> 'Helloworld\Service\LoggingService'
)
)
)));
$greetingService = $di->get('Helloworld\Service\GreetingService');
return $greetingService;
}
}
| {
"content_hash": "b68086c37a4efad7f987a1ae808442f4",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 78,
"avg_line_length": 36.12903225806452,
"alnum_prop": 0.4205357142857143,
"repo_name": "crysthianophp/zf2extjs-curso",
"id": "1b687df2af126fc5cca85a14a6665ce5567aa835",
"size": "2240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Helloworld/src/Helloworld/Service/GreetingServiceFactory.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "6600"
},
{
"name": "JavaScript",
"bytes": "11057"
},
{
"name": "PHP",
"bytes": "1334975"
},
{
"name": "Perl",
"bytes": "711"
},
{
"name": "Shell",
"bytes": "14"
}
],
"symlink_target": ""
} |
require "cases/helper"
require 'models/post'
require 'models/comment'
require 'models/developer'
require 'models/project'
require 'models/reader'
require 'models/person'
# Dummy class methods to test implicit association scoping.
def Comment.foo() find :first end
def Project.foo() find :first end
class ReadOnlyTest < ActiveRecord::TestCase
fixtures :posts, :comments, :developers, :projects, :developers_projects
def test_cant_save_readonly_record
dev = Developer.find(1)
assert !dev.readonly?
dev.readonly!
assert dev.readonly?
assert_nothing_raised do
dev.name = 'Luscious forbidden fruit.'
assert !dev.save
dev.name = 'Forbidden.'
end
assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save }
assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! }
end
def test_find_with_readonly_option
Developer.find(:all).each { |d| assert !d.readonly? }
Developer.find(:all, :readonly => false).each { |d| assert !d.readonly? }
Developer.find(:all, :readonly => true).each { |d| assert d.readonly? }
end
def test_find_with_joins_option_implies_readonly
# Blank joins don't count.
Developer.find(:all, :joins => ' ').each { |d| assert !d.readonly? }
Developer.find(:all, :joins => ' ', :readonly => false).each { |d| assert !d.readonly? }
# Others do.
Developer.find(:all, :joins => ', projects').each { |d| assert d.readonly? }
Developer.find(:all, :joins => ', projects', :readonly => false).each { |d| assert !d.readonly? }
end
def test_habtm_find_readonly
dev = Developer.find(1)
assert !dev.projects.empty?
assert dev.projects.all?(&:readonly?)
assert dev.projects.find(:all).all?(&:readonly?)
assert dev.projects.find(:all, :readonly => true).all?(&:readonly?)
end
def test_has_many_find_readonly
post = Post.find(1)
assert !post.comments.empty?
assert !post.comments.any?(&:readonly?)
assert !post.comments.find(:all).any?(&:readonly?)
assert post.comments.find(:all, :readonly => true).all?(&:readonly?)
end
def test_has_many_with_through_is_not_implicitly_marked_readonly
assert people = Post.find(1).people
assert !people.any?(&:readonly?)
end
def test_readonly_scoping
Post.with_scope(:find => { :conditions => '1=1' }) do
assert !Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
Post.with_scope(:find => { :joins => ' ' }) do
assert !Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
# Oracle barfs on this because the join includes unqualified and
# conflicting column names
unless current_adapter?(:OracleAdapter)
Post.with_scope(:find => { :joins => ', developers' }) do
assert Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
end
Post.with_scope(:find => { :readonly => true }) do
assert Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
end
def test_association_collection_method_missing_scoping_not_readonly
assert !Developer.find(1).projects.foo.readonly?
assert !Post.find(1).comments.foo.readonly?
end
end
| {
"content_hash": "f2e04d683a75e25e92ba53f57ec7342d",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 101,
"avg_line_length": 32.32710280373832,
"alnum_prop": 0.6582827406764961,
"repo_name": "liquidware/saasy",
"id": "145ae57546020d4d0b11322c155fa0589ef2b3b7",
"size": "3486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/rails/activerecord/test/cases/readonly_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1864"
},
{
"name": "Ruby",
"bytes": "79337"
},
{
"name": "Shell",
"bytes": "81"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: sylvain
* Date: 23/07/2018
* Time: 19:21
*/
use GuzzleHttp\Psr7\Response;
use \Lou117\Core\AbstractController;
use Psr\Http\Message\ResponseInterface;
class TestController extends AbstractController
{
public function foo(): ResponseInterface
{
$response = new Response();
return $response->withHeader("X-Controller-Test", time());
}
public function baz()
{
return null;
}
}
| {
"content_hash": "710c5910ac0591cd7d8e35241536623c",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 66,
"avg_line_length": 18.84,
"alnum_prop": 0.6539278131634819,
"repo_name": "Lou117/core",
"id": "6ddc88b801e6d38c580f21d90ab7fa352b0368c0",
"size": "471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/TestController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "60332"
}
],
"symlink_target": ""
} |
package edu.wpi.disco.plugin;
import edu.wpi.cetask.*;
import edu.wpi.disco.*;
import edu.wpi.disco.lang.*;
/**
* TTSay plugin for utterances for which all inputs known.
*/
public class UtterancePlugin extends AuthorizedPlugin {
private boolean excludeAcceptShould; // see User
@Override
protected boolean isApplicable (Plan plan) {
Task goal = plan.getGoal();
return goal instanceof Utterance && isAuthorizedDefined(plan) &&
( !plan.isOptional() || isAccept(plan) ) &&
( !excludeAcceptShould ||
!(goal instanceof Accept &&
((Accept) goal).getProposal() instanceof Propose.Should) );
}
@Override
public Task newTask (Disco disco, Plan plan) {
Task goal = plan.getGoal();
// better for default formatting of 'yes'
return isAccept(plan) ? new Accept(getDisco(), self(), (Propose) goal) : goal;
}
private boolean isAccept (Plan plan) {
Task goal = plan.getGoal();
Plan focus = getDisco().getFocus();
return goal instanceof Propose && focus != null &&
focus.getGoal() instanceof Accept &&
((Accept) focus.getGoal()).getProposal() instanceof Propose.Should &&
goal.equals(((Propose.Should) ((Accept) focus.getGoal()).getProposal()).getGoal());
}
public UtterancePlugin (Agenda agenda, int priority, boolean excludeAcceptShould) {
super(agenda, priority);
this.excludeAcceptShould = excludeAcceptShould;
}
}
| {
"content_hash": "243bcee4604d4cc6399b4eb20f33d138",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 96,
"avg_line_length": 34.71111111111111,
"alnum_prop": 0.618437900128041,
"repo_name": "charlesrich/Disco",
"id": "f09862af94d81235e30e72f3dc522206f2484885",
"size": "1832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "disco/java/edu/wpi/disco/plugin/UtterancePlugin.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3410"
},
{
"name": "Java",
"bytes": "645938"
},
{
"name": "JavaScript",
"bytes": "1353"
},
{
"name": "Perl",
"bytes": "137778"
},
{
"name": "Shell",
"bytes": "23961"
},
{
"name": "XSLT",
"bytes": "83952"
}
],
"symlink_target": ""
} |
import bot
import sys
from lib import db
from threading import Thread
import time
import imp
import signal
fatal = False
run = True
threads = []
def signal_handler(signal, frame):
print("Caught signal, exiting.")
global run
run = False
bot.run = False
def hup_handler(signal, frame):
print('Reloading from HUP.')
bot.run = False
def runserver(server):
global fatal
while bot.run:
try:
time.sleep(0.01)
with server.runlock:
with db.lock:
server.corerun()
with server.runlock:
with db.lock:
server.dotimers()
except:
print("Fatal Exception!")
import traceback
traceback.print_exc()
fatal = True
break
try:
server.shutdown()
except:
pass
if __name__ == "__main__":
initial = True
for s in [
signal.SIGINT,
signal.SIGTERM,
]:
signal.signal(s, signal_handler)
if hasattr(signal, "SIGHUP"):
signal.signal(signal.SIGHUP, hup_handler)
while run:
if len(sys.argv) > 1:
bot.userdata = sys.argv[1]
bot.createuserdata()
bot.importmodule("%s/config.py" % bot.userdata, r=not initial)
initial = False
bot.run = True
if bot.threads:
print("Starting threads...")
for server in bot.runningservers:
t = Thread(target=runserver, args=(server,))
t.daemon = True
t.start()
threads.append(t)
while True:
if fatal:
bot.run = False
run = False
with db.lock:
db.saveall()
time.sleep(0.01)
if not bot.run:
for thread in threads:
thread.join()
imp.reload(db)
imp.reload(bot)
break
else:
print("Running unthreaded...")
while bot.run:
for server in bot.runningservers:
server.corerun()
server.dotimers()
db.saveall()
time.sleep(0.01)
for server in bot.runningservers:
try:
server.shutdown()
except:
pass
imp.reload(db)
imp.reload(bot)
| {
"content_hash": "9c25e2bde54eaed4489203bc2bff7fbf",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 70,
"avg_line_length": 25.73469387755102,
"alnum_prop": 0.4706582077716098,
"repo_name": "shacknetisp/vepybot",
"id": "74b817378099c0cfb7ca0132a6f2218943f234ec",
"size": "2570",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "run.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "186378"
}
],
"symlink_target": ""
} |
<launch>
<!-- This file makes it easy to include the settings for trajectory execution -->
<!-- Flag indicating whether MoveIt! is allowed to load/unload or switch controllers -->
<arg name="moveit_manage_controllers" default="true"/>
<param name="moveit_manage_controllers" value="$(arg moveit_manage_controllers)"/>
<!-- When determining the expected duration of a trajectory, this multiplicative factor is applied to get the allowed duration of execution -->
<param name="trajectory_execution/allowed_execution_duration_scaling" value="1.2"/> <!-- default 1.2 -->
<!-- Turn off execution duration monitoring -->
<param name="trajectory_execution/execution_duration_monitoring" value="false" />
<!-- Allow more than the expected execution time before triggering a trajectory cancel (applied after scaling) -->
<param name="trajectory_execution/allowed_goal_duration_margin" value="0.5"/> <!-- default 0.5 -->
<!-- Allowed joint-value tolerance for validation that trajectory's first point matches current robot state -->
<!-- <param name="trajectory_execution/allowed_start_tolerance" value="0.01"/> --> <!-- default 0.01 -->
<param name="trajectory_execution/allowed_start_tolerance" value="0.1"/>
<!-- Load the robot specific controller manager; this sets the moveit_controller_manager ROS parameter -->
<arg name="moveit_controller_manager" default="poli2_segway" />
<include file="$(find poli2_full_moveit)/launch/$(arg moveit_controller_manager)_moveit_controller_manager.launch.xml" />
</launch>
| {
"content_hash": "a2a35ba46be3ae543d8e35a807476269",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 145,
"avg_line_length": 67.34782608695652,
"alnum_prop": 0.7269205939315687,
"repo_name": "si-machines/poli2",
"id": "50abd3abc4bb6b6da1a6907bfb9da1df7295c75e",
"size": "1549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "poli2_full_moveit/launch/trajectory_execution.launch.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "17111"
},
{
"name": "C++",
"bytes": "72015"
},
{
"name": "CMake",
"bytes": "25356"
},
{
"name": "Makefile",
"bytes": "9850"
},
{
"name": "Python",
"bytes": "59635"
},
{
"name": "Shell",
"bytes": "6355"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import os.path
from pypi_practices.check_readme import check_readme
from pypi_practices.errors import FileValidationError
from testing.util import assert_raises_with_msg
def test_readme_does_not_exist(tmpdir):
with assert_raises_with_msg(
FileValidationError,
'README.md: File does not exist.\n\n'
'To attempt automatic fixing, run with --fix.'
):
check_readme(tmpdir.strpath)
def test_returns_zero_readme_exists_and_is_correct(tmpdir):
with io.open(os.path.join(tmpdir.strpath, 'README.md'), 'w') as readme:
readme.write('my package\n=========\n')
ret = check_readme(tmpdir.strpath)
assert ret == 0
| {
"content_hash": "811fee5f30d054346741808013603007",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 75,
"avg_line_length": 29.076923076923077,
"alnum_prop": 0.6984126984126984,
"repo_name": "asottile/pypi_practices",
"id": "fc674f83b13397bc18fb30f270dd9b3990efaa34",
"size": "756",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/check_readme_test.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "15985"
}
],
"symlink_target": ""
} |
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from mixer.backend.django import mixer
from organisation.models import DepartmentUser
from .models import Approval
User = get_user_model()
class ApprovalViewsTestCase(TestCase):
client = Client()
def setUp(self):
# Create User and linked DepartmentUser objects.
self.du1 = mixer.blend(DepartmentUser, username=mixer.RANDOM, photo=None)
self.user1 = User.objects.create_user(
username=self.du1.username, email=self.du1.email)
self.user1.set_password('pass')
self.user1.save()
# Log in user1 by default.
self.client.login(username=self.user1.username, password='pass')
self.du2 = mixer.blend(DepartmentUser, username=mixer.RANDOM, photo=None)
self.user2 = User.objects.create_user(
username=self.du2.username, email=self.du2.email)
self.user2.set_password('pass')
self.user2.save()
def test_approval_create_get(self):
"""Test the approval_create GET response
"""
url = reverse('approval_create')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_approval_create_post(self):
"""Test the approval_create POST response
"""
url = reverse('approval_create')
self.assertEqual(Approval.objects.count(), 0)
response = self.client.post(url, {
'approver': self.du2.pk,
'proposal_desc': 'Test approval request',
})
self.assertEqual(response.status_code, 302)
self.assertEqual(Approval.objects.count(), 1)
def test_approval_detail(self):
"""Test the approval_detail view
"""
app = mixer.blend(Approval, approver=self.du2)
url = reverse('approval_detail', kwargs={'pk': app.pk})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_approval_confirm(self):
"""Test the approval_confirm view
"""
app = mixer.blend(Approval, approver=self.du2)
self.assertFalse(app.confirmed_date)
# Log in user2.
self.client.logout()
self.client.login(username=self.user2.username, password='pass')
url = reverse('approval_confirm', kwargs={'guid': app.guid})
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
app = Approval.objects.get(pk=app.pk) # Refresh from db.
self.assertTrue(app.confirmed_date)
| {
"content_hash": "496a7ae0b26548d66ebc00eb2358a702",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 81,
"avg_line_length": 38.411764705882355,
"alnum_prop": 0.6477794793261868,
"repo_name": "rockychen-dpaw/oim-cms",
"id": "83072f414f0a2cf28ae7b77e07fde3a807ded2d3",
"size": "2612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "approvals/test_views.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "33080"
},
{
"name": "HTML",
"bytes": "68403"
},
{
"name": "JavaScript",
"bytes": "141247"
},
{
"name": "Python",
"bytes": "649405"
}
],
"symlink_target": ""
} |
ReSharperExtensions
===================
Important
---------
Due to changes in distribution of extensions for the ReSharper platform, I have created a new repository with an extension supporting ReSharper 9.0 and later: [ReSharper.LiveTemplates](https://github.com/joaroyen/ReSharper.LiveTemplates)
What this project contains
--------------------------
This solution contains Live Templates and macros for [JetBrains ReSharper](http://www.jetbrains.com/resharper/). The following macros are available:
* **ValidIdentifierMacro**: Replaces invalid identifier characters with underscores as you type
* **CapitalizedWordsIdentifierMacro**: Same as ValidIdentifierMacro but capitalizes the first letter in each word
* **DomainAndUsernameMacro**: Returns your domain and username in the form of Domain\Username
The Live Template contains one template with the **mstm** shortcut (MicroSoft Test Method).It allows
you to write test method names as sentences with spaces, and the macro will replace the spaces with underscores as you
type. It also allows you to select an MSTest category and assigns the current user as the owner of the test in a format
compatible with TFS.
See [http://www.joaroyen.com/2010/08/resharpers-live-templates-can-do.html](http://www.joaroyen.com/2010/08/resharpers-live-templates-can-do.html) for more information.
Installation instructions
-------------------------
Alternative 1 is recommended if you have ReSharper 8.0 or later and just want the bits. Alternative 2 is best if you want to tinker with and debug the macros yourself, while alternative 3 if you just want to use the macros in your own templates with ReSharper 7.1 or earlier.
### Alternative 1: Install using ReSharper Extension Manager ###
* Open ReSharper -> Extension manager
* Search for JoarOyen
* Select "JoarOyen.ReSharperExtensions.Macros" if you just wan to use the macros in your own Live Templates
* Select "JoarOyen.ReSharperExtensions.LiveTemplates" if you want both macros and a LiveTemplate with a template for writing MSTest methods. This package depends on the macro package.
### Alternative 2: Build from sources and install Debug build ###
* Download and install [ReSharper 8.0 SDK](http://www.jetbrains.com/resharper/download/index.html). Dependencies on ReSharper SDK for version 8.1 and later are handled by NuGet.
* Open Visual Studio 2012 or 2013 and build the solution in Debug configuration
* Close all instances of Visual Studio
* Run "Deploy.bat" from an elevated command prompt to copy dll and pdb to the ReSharper 8.1 plugins folder for the current user
### Alternative 3: From precompiled package with Release build ###
* Download the latest package for your ReSharper version from my [SkyDrive folder](http://sdrv.ms/XBPFYA).
* Unzip the package to an empty directory.
* Copy JoarOyen.ReSharperPlugIn.dll to the ReSharper N.N plugins folder. This will typically be something like "C:\Users\<USERNAME>\AppData\Local\JetBrains\ReSharper\vN.N\Plugins\JoarOyen\".
* Open the "ReSharperExtensions.sln.DotSettings" file using "ReSharper -> Manage Options..." to inspect the example template
Remarks
-------
* Master is updated to support ReSharper 8.0 and ReSharper 8.1, and requires .NET 4.0 or newer. The macros can therefore only be used in VS2010, VS2012 and VS2013.
* Master will continue to support all versions of ReSharper 8.0 and later as long as it is possible to build every version from one solution.
* Macros that works with previous versions of ReSharper and Visual Studio are available in separate branches for each version of ReSharper.
* The code in this version is built with the ReSharper SDK, and the namespace for the macros has been changed to reflect the new name of the assembly.
* The test project is using NUnit from ReSharper SDK, but uses NuGet for NSubstitute (this dependency should be downloaded automatically).
* The Deploy.bat file must be run with administrative privileges if UAC is enabled
| {
"content_hash": "ddb6eff641dfa926ced0e976c4fcd03b",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 275,
"avg_line_length": 67.20338983050847,
"alnum_prop": 0.7778058007566204,
"repo_name": "joaroyen/ReSharperExtensions",
"id": "b0fbbb02c68a28fb83aec3cff5a3315b63d0e7c3",
"size": "3965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "18149"
},
{
"name": "PowerShell",
"bytes": "195"
},
{
"name": "Shell",
"bytes": "267"
}
],
"symlink_target": ""
} |
package net.floodlightcontroller.loadbalancer;
import java.io.IOException;
import java.util.Collection;
import net.floodlightcontroller.packet.IPv4;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.MappingJsonFactory;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MembersResource extends ServerResource {
protected static Logger log = LoggerFactory.getLogger(MembersResource.class);
@Get("json")
public Collection <LBMember> retrieve() {
ILoadBalancerService lbs =
(ILoadBalancerService)getContext().getAttributes().
get(ILoadBalancerService.class.getCanonicalName());
String memberId = (String) getRequestAttributes().get("member");
if (memberId!=null)
return lbs.listMember(memberId);
else
return lbs.listMembers();
}
@Put
@Post
public LBMember createMember(String postData) {
LBMember member=null;
try {
member=jsonToMember(postData);
log.info("Created New LBMember id:{} Addr:{} PoolID:{} VipId:{}", new Object[]{member.id,IPv4.fromIPv4Address(member.address),member.poolId,member.vipId } );
} catch (IOException e) {
log.error("Could not parse JSON {}", e.getMessage());
}
ILoadBalancerService lbs =
(ILoadBalancerService)getContext().getAttributes().
get(ILoadBalancerService.class.getCanonicalName());
String memberId = (String) getRequestAttributes().get("member");
if (memberId != null)
return lbs.updateMember(member);
else
return lbs.createMember(member);
}
@Delete
public int removeMember() {
String memberId = (String) getRequestAttributes().get("member");
ILoadBalancerService lbs =
(ILoadBalancerService)getContext().getAttributes().
get(ILoadBalancerService.class.getCanonicalName());
return lbs.removeMember(memberId);
}
protected LBMember jsonToMember(String json) throws IOException {
MappingJsonFactory f = new MappingJsonFactory();
JsonParser jp;
LBMember member = new LBMember();
try {
jp = f.createParser(json);
} catch (JsonParseException e) {
throw new IOException(e);
}
jp.nextToken();
if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
throw new IOException("Expected START_OBJECT");
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
throw new IOException("Expected FIELD_NAME");
}
String n = jp.getCurrentName();
jp.nextToken();
if (jp.getText().equals(""))
continue;
if (n.equals("id")) {
member.id = jp.getText();
continue;
} else
if (n.equals("address")) {
member.address = IPv4.toIPv4Address(jp.getText());
continue;
} else
if (n.equals("port")) {
member.port = Short.parseShort(jp.getText());
continue;
} else
if (n.equals("connection_limit")) {
member.connectionLimit = Integer.parseInt(jp.getText());
continue;
} else
if (n.equals("admin_state")) {
member.adminState = Short.parseShort(jp.getText());
continue;
} else
if (n.equals("status")) {
member.status = Short.parseShort(jp.getText());
continue;
} else
if (n.equals("pool_id")) {
member.poolId = jp.getText();
continue;
}
log.warn("Unrecognized field {} in " +
"parsing Members",
jp.getText());
}
jp.close();
return member;
}
}
| {
"content_hash": "20ecc38da971097df6fa019e08d87bda",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 178,
"avg_line_length": 33.11678832116788,
"alnum_prop": 0.5574167952391448,
"repo_name": "rhoybeen/floodlightLB",
"id": "3a81b59759a5207e4f69655273c9f97fd9b72ead",
"size": "5179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/floodlightcontroller/loadbalancer/MembersResource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "181"
},
{
"name": "HTML",
"bytes": "10186"
},
{
"name": "Java",
"bytes": "3923065"
},
{
"name": "JavaScript",
"bytes": "55112"
},
{
"name": "Makefile",
"bytes": "426"
},
{
"name": "Python",
"bytes": "32743"
},
{
"name": "Shell",
"bytes": "5610"
},
{
"name": "Thrift",
"bytes": "7114"
}
],
"symlink_target": ""
} |
import {
ChildEntity,
OneToOne,
JoinColumn,
ManyToMany,
JoinTable,
} from "../../../../src/index"
import { TournamentParticipant } from "./TournamentParticipant"
import { User } from "./User"
@ChildEntity()
export class TournamentSquadParticipant extends TournamentParticipant {
@OneToOne((type) => User, {
eager: true,
})
@JoinColumn()
public owner: User
@ManyToMany((type) => User, {
eager: true,
})
@JoinTable({ name: "tournament_squad_participants" })
public users: User[]
constructor(tournamentSquadParticipant?: { users: User[]; owner: User }) {
super()
if (tournamentSquadParticipant) {
this.users = tournamentSquadParticipant.users
this.owner = tournamentSquadParticipant.owner
}
}
}
| {
"content_hash": "654cd332a517a17bfb25ab0b936d2027",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 78,
"avg_line_length": 24.147058823529413,
"alnum_prop": 0.6236297198538368,
"repo_name": "typeorm/typeorm",
"id": "1e3203f99017ba77eb4ef2b9fcdda552b5b6c676",
"size": "821",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/github-issues/1972/entity/TournamentSquadParticipant.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "580"
},
{
"name": "JavaScript",
"bytes": "16233"
},
{
"name": "Shell",
"bytes": "2208"
},
{
"name": "TypeScript",
"bytes": "8547494"
}
],
"symlink_target": ""
} |
var approvals = require('approvals');
var exec = require('shelljs').exec;
var path = require('path');
describe('when calling the cli', function () {
[
{
testName: 'blank',
cmd: ''
},
{
testName: 'badProjectFile',
cmd: 'badProjectFile.projectx'
},
{
testName: 'help',
cmd: '--help'
}
].forEach(function (item) {
it('should verify command: ' + item.cmd, function () {
this.timeout(5000);
var result = exec(path.join(__dirname, "../bin/index.js") + " " + item.cmd).toString();
var output = result;
// remove version
output = output.replace(/\(v(.*)\)/g, '(v###)');
approvals.verify(__dirname, item.testName, output);
});
});
});
| {
"content_hash": "c4bac10e99aff56f9ab0f8c9c3b6ba7e",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 93,
"avg_line_length": 19.63157894736842,
"alnum_prop": 0.5348525469168901,
"repo_name": "staxmanade/diffXcodeTargets",
"id": "5f8f46bc84d2323fc14a152cd62633ea01bce940",
"size": "746",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/cli.tests.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "9856"
},
{
"name": "Objective-C",
"bytes": "4177"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc (1.8.0_60) on Tue Mar 29 13:02:11 CEST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PThreadFactory (Play! API)</title>
<meta name="date" content="2016-03-29">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PThreadFactory (Play! API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PThreadFactory.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../play/utils/Properties.html" title="class in play.utils"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../play/utils/SmartFuture.html" title="class in play.utils"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?play/utils/PThreadFactory.html" target="_top">Frames</a></li>
<li><a href="PThreadFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">play.utils</div>
<h2 title="Class PThreadFactory" class="title">Class PThreadFactory</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>play.utils.PThreadFactory</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.util.concurrent.ThreadFactory</dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">PThreadFactory</span>
extends java.lang.Object
implements java.util.concurrent.ThreadFactory</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../play/utils/PThreadFactory.html#PThreadFactory-java.lang.String-">PThreadFactory</a></span>(java.lang.String poolName)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.Thread</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../play/utils/PThreadFactory.html#newThread-java.lang.Runnable-">newThread</a></span>(java.lang.Runnable r)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="PThreadFactory-java.lang.String-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PThreadFactory</h4>
<pre>public PThreadFactory(java.lang.String poolName)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="newThread-java.lang.Runnable-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>newThread</h4>
<pre>public java.lang.Thread newThread(java.lang.Runnable r)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>newThread</code> in interface <code>java.util.concurrent.ThreadFactory</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PThreadFactory.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../play/utils/Properties.html" title="class in play.utils"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../play/utils/SmartFuture.html" title="class in play.utils"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?play/utils/PThreadFactory.html" target="_top">Frames</a></li>
<li><a href="PThreadFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><a href="http://guillaume.bort.fr">Guillaume Bort</a> & <a href="http://www.zenexity.fr">zenexity</a> - Distributed under <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2 licence</a>, without any warrantly</small></p>
</body>
</html>
| {
"content_hash": "afbc3b087062a13354765a6e28746bb8",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 391,
"avg_line_length": 34.347517730496456,
"alnum_prop": 0.6455709271112946,
"repo_name": "play1-maven-plugin/play1-maven-plugin.github.io",
"id": "da3cc2ccd27feb9ee6db63da99531c95ca4d441f",
"size": "9686",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "external-apidocs/com/google/code/maven-play-plugin/org/playframework/play/1.3.4/play/utils/PThreadFactory.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "245466"
},
{
"name": "HTML",
"bytes": "161333450"
},
{
"name": "JavaScript",
"bytes": "11578"
}
],
"symlink_target": ""
} |
package techreborn.itemblocks;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import reborncore.common.powerSystem.PowerSystem;
import techreborn.init.ModBlocks;
import techreborn.tiles.storage.TileAdjustableSU;
import java.util.List;
public class ItemBlockAdjustableSU extends ItemBlock {
public ItemBlockAdjustableSU(Block p_i45328_1_) {
super(p_i45328_1_);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World world, List list, ITooltipFlag flag) {
if (!stack.isEmpty() && stack.hasTagCompound()) {
if (stack.getTagCompound().getCompoundTag("tileEntity") != null)
list.add(PowerSystem
.getLocaliszedPower(stack.getTagCompound().getCompoundTag("tileEntity").getInteger("energy")));
}
}
@Override
public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side,
float hitX, float hitY, float hitZ, IBlockState newState) {
if (!world.setBlockState(pos, newState)) {
return false;
}
if (world.getBlockState(pos).getBlock() == block) {
world.getBlockState(pos).getBlock().onBlockPlacedBy(world, pos, newState, player, stack);
}
if (!stack.isEmpty() && stack.hasTagCompound()) {
((TileAdjustableSU) world.getTileEntity(pos))
.readFromNBTWithoutCoords(stack.getTagCompound().getCompoundTag("tileEntity"));
}
return true;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) {
itemList.add(getDropWithNBT(0));
itemList.add(getDropWithNBT(1000000000));
}
public ItemStack getDropWithNBT(double energy) {
NBTTagCompound tileEntity = new NBTTagCompound();
ItemStack dropStack = new ItemStack(ModBlocks.ADJUSTABLE_SU, 1);
writeToNBTWithoutCoords(tileEntity, energy);
dropStack.setTagCompound(new NBTTagCompound());
dropStack.getTagCompound().setTag("tileEntity", tileEntity);
return dropStack;
}
public void writeToNBTWithoutCoords(NBTTagCompound tagCompound, double energy) {
NBTTagCompound data = new NBTTagCompound();
data.setDouble("energy", energy);
tagCompound.setTag("TilePowerAcceptor", data);
tagCompound.setDouble("energy", energy);
tagCompound.setDouble("euChange", 0);
tagCompound.setDouble("euLastTick", 0);
tagCompound.setBoolean("active", false);
}
}
| {
"content_hash": "dd2a81726a6d7f1e4e706b259f77b62a",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 110,
"avg_line_length": 35.51807228915663,
"alnum_prop": 0.7645861601085482,
"repo_name": "drcrazy/TechReborn",
"id": "31384c1ebf56166aabfc7e7070f5246a0cccebb7",
"size": "4139",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.12",
"path": "src/main/java/techreborn/itemblocks/ItemBlockAdjustableSU.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1898942"
}
],
"symlink_target": ""
} |
//
// XMLParserViewController.m
// week11
//
// Created by 이상진 on 2014. 9. 18..
// Copyright (c) 2014년 EntusApps. All rights reserved.
//
#import "XMLParserViewController.h"
#import <sqlite3.h>
@interface XMLParserViewController (){
NSString *tagName,*tagNameInItem,*dbPath;
NSMutableArray *itemsArray,*resultArray;
NSMutableDictionary *itemDict;
sqlite3 *db;
}
@end
@implementation XMLParserViewController
- (void)viewDidLoad {
resultArray = [NSMutableArray new];
[super viewDidLoad];
[self dbPath];
[self loadFromDB];
}
-(NSString *)dbPath
{
if(!dbPath)
{
NSFileManager *fileman = [NSFileManager defaultManager];
NSURL *documentPathURL = [[fileman URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
NSString *databaseFilename = @"newsfeed.db";
dbPath = [[documentPathURL URLByAppendingPathComponent:databaseFilename] path];
if(![fileman fileExistsAtPath:dbPath])
{
NSString *dbSource = [[NSBundle mainBundle] pathForResource:@"newsfeed" ofType:@"db"];
[fileman copyItemAtPath:dbSource toPath:dbPath error:nil];
if (!resultArray.count) {
itemsArray = [NSMutableArray new];
itemDict = [NSMutableDictionary new];
NSURL *url = [NSURL URLWithString:@"http://images.apple.com/main/rss/hotnews/hotnews.rss"];
NSXMLParser *myParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[myParser setDelegate:self];
[myParser parse];
}
}
}
return dbPath;
}
-(NSInteger)loadFromDB{
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:dbPath] == YES) {
sqlite3_stmt *statement;
const char *dbPathInChar = [dbPath UTF8String];
if (sqlite3_open(dbPathInChar, &db) == SQLITE_OK) {
NSMutableArray *colNames = [[NSMutableArray alloc] init];
const char *queryInChar = [@"SELECT * FROM tbl_newsfeed" UTF8String];
const char *queryForColumnNames = [@"PRAGMA TABLE_INFO('tbl_newsfeed')" UTF8String];
if (sqlite3_prepare_v2(db, queryForColumnNames, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *colName = [[NSString alloc] initWithUTF8String:(const char*) sqlite3_column_text(statement, 1)];
[colNames addObject:colName];
}
}
sqlite3_reset(statement);
if (sqlite3_prepare_v2(db, queryInChar, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
for (int i = 0; i < colNames.count; i++) {
NSString * dataForCol = [[NSString alloc] initWithUTF8String:(const char*) sqlite3_column_text(statement, i)];
[data setObject:dataForCol forKey:[colNames objectAtIndex:i]];
}
[resultArray addObject:data];
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
[_tableView reloadData];
NSLog(@"%zd",resultArray.count);
return resultArray.count;
}
#pragma mark - XMLParserDelegate
-(void)parserDidEndDocument:(NSXMLParser *)parser{
for (NSDictionary *dict in itemsArray) {
[self insertNewsFeed:dict];
}
[self loadFromDB];
NSLog(@"%zd,%@",resultArray.count,resultArray);
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"item"]) {
tagName = elementName;
}
else if ([tagName isEqualToString:@"item"]){
tagNameInItem = elementName;
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([tagName isEqualToString:@"item"]) {
if (tagNameInItem) {
itemDict[tagNameInItem] = string;
}
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"item"]) {
tagName = nil;
[itemsArray addObject:[itemDict mutableCopy]];
}
else if ([elementName isEqualToString:tagNameInItem]){
tagNameInItem = nil;
}
}
- (void)insertNewsFeed:(NSDictionary*)dict {
int dbrc;
dbrc=sqlite3_open([dbPath UTF8String], &db);
if (dbrc) {
NSLog(@"couldn't open db");
return;
}
NSString *title = [dict objectForKey:@"title"];
NSString *link = [dict objectForKey:@"link"];
NSString *description = [dict objectForKey:@"description"];
NSString *pubDate = [dict objectForKey:@"pubDate"];
sqlite3_stmt *dbps;
NSString *insertSQLString= [NSString stringWithFormat:@"INSERT INTO \"tbl_newsfeed\" (title, link, description, pubDate) VALUES (\"%@\",\"%@\", \"%@\", \"%@\");",title,link,description,pubDate];
dbrc = sqlite3_prepare_v2(db, [insertSQLString UTF8String], -1, &dbps, NULL);
dbrc = sqlite3_step(dbps);
sqlite3_finalize(dbps);
sqlite3_close(db);
}
#pragma mark - TableViewDelegate&DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [resultArray count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"XMLCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.textLabel.text = [[resultArray objectAtIndex:indexPath.row] objectForKey:@"title"];
cell.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] objectForKey:@"pubDate"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSURL *url = [NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] objectForKey:@"link"]];
[[UIApplication sharedApplication]openURL:url];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
| {
"content_hash": "3fd597488795cabd8c0252535eb73c1c",
"timestamp": "",
"source": "github",
"line_count": 223,
"max_line_length": 198,
"avg_line_length": 31.973094170403588,
"alnum_prop": 0.6286115007012623,
"repo_name": "lsj333610dl/NEXT-1402-iOS-basic",
"id": "0405249307177e21eaef2af2ac32dfffdad578e4",
"size": "7138",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "week11/week11/XMLParserViewController.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "115233"
}
],
"symlink_target": ""
} |
<?php
namespace App\Common\Models\Weixin\Mysql;
use App\Common\Models\Base\Mysql\Base;
class Callbackurls extends Base
{
/**
* 微信-回调地址安全域名
* This model is mapped to the table iweixin_callbackurls
*/
public function getSource()
{
return 'iweixin_callbackurls';
}
} | {
"content_hash": "c56ade6c975f1bae4d6d2f13401ae85c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 61,
"avg_line_length": 17.941176470588236,
"alnum_prop": 0.659016393442623,
"repo_name": "handsomegyr/models",
"id": "a227cd19fb11bae72c1476d8a9933e237d9e5817",
"size": "325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/App/Common/Models/Weixin/Mysql/Callbackurls.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "2561336"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='UTF-8'?>
<identity xmlns="urn:elytron:1.0">
<credentials>
<password algorithm="clear" format="base64">AXdiYWRtaW4=</password>
</credentials>
<attributes>
<attribute name="role" value="user"/>
</attributes></identity> | {
"content_hash": "6b553b21478abfb57f56e273e86cdddc",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 75,
"avg_line_length": 34.75,
"alnum_prop": 0.6402877697841727,
"repo_name": "droolsjbpm/jbpm-console-ng",
"id": "c4816b41c67c847085ae5f9d46debd0e614e8af8",
"size": "278",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "jbpm-wb-case-mgmt/jbpm-wb-case-mgmt-showcase/src/main/config/kie-fs-realm-users/w/b/wbadmin-O5RGCZDNNFXA.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "29326"
},
{
"name": "FreeMarker",
"bytes": "2262"
},
{
"name": "HTML",
"bytes": "55976"
},
{
"name": "Java",
"bytes": "2225396"
},
{
"name": "Visual Basic",
"bytes": "18019"
}
],
"symlink_target": ""
} |
package templates
import (
"text/template"
"github.com/spf13/cobra"
)
// A command group is for grouping together commands
type CommandGroup struct {
// Title for command group shown in help/usage messages
Header string
// List of commands for this group
Commands []*cobra.Command
}
type CommandGroups []CommandGroup
// Add all commands from this group slice to the given command
func (g CommandGroups) AddTo(cmd *cobra.Command) {
for _, group := range g {
for _, sub := range group.Commands {
cmd.AddCommand(sub)
}
}
}
// SetRootUsage sets our own help and usage function messages to the root command
func (g CommandGroups) SetRootUsage(rootCmd *cobra.Command, extraTemplateFunctions *template.FuncMap) {
engine := newTemplateEngine(rootCmd, g, extraTemplateFunctions)
setHelpFlagsToSubCommands(rootCmd)
rootCmd.SetUsageFunc(engine.usageFunc())
rootCmd.SetHelpFunc(engine.helpFunc())
}
func setHelpFlagsToSubCommands(parent *cobra.Command) {
for _, cmd := range parent.Commands() {
if cmd.HasSubCommands() {
setHelpFlagsToSubCommands(cmd)
}
cmd.DisableFlagsInUseLine = true
}
}
| {
"content_hash": "d12bd3828e75a1fb88468e0117b923f1",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 103,
"avg_line_length": 24.844444444444445,
"alnum_prop": 0.7504472271914132,
"repo_name": "knative/client",
"id": "5af9af6ec063fd9e91ac81c3231d0a89d83c368d",
"size": "1718",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "pkg/templates/command_groups.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "832"
},
{
"name": "Go",
"bytes": "2069067"
},
{
"name": "Shell",
"bytes": "35618"
}
],
"symlink_target": ""
} |
package com.xixibase.cache;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import com.xixibase.cache.multi.MultiDeleteItem;
import com.xixibase.cache.multi.MultiUpdateItem;
import junit.framework.TestCase;
public class MultiOperationTest extends TestCase {
private static final String managerName1 = "MultiOperationTest";
private static CacheClient cc1 = null;
private static CacheClientManager mgr1 = null;
static String servers;
static boolean enableSSL = false;
static {
servers = System.getProperty("hosts");
enableSSL = System.getProperty("enableSSL") != null && System.getProperty("enableSSL").equals("true");
if (servers == null) {
try {
InputStream in = new BufferedInputStream(new FileInputStream("test.properties"));
Properties p = new Properties();
p.load(in);
in.close();
servers = p.getProperty("hosts");
enableSSL = p.getProperty("enableSSL") != null && p.getProperty("enableSSL").equals("true");
} catch (IOException e) {
e.printStackTrace();
}
}
String[] serverlist = servers.split(",");
mgr1 = CacheClientManager.getInstance(managerName1);
mgr1.setSocketWriteBufferSize(64 * 1024);
mgr1.initialize(serverlist, enableSSL);
mgr1.enableLocalCache();
}
protected void setUp() throws Exception {
super.setUp();
cc1 = mgr1.createClient();
}
protected void tearDown() throws Exception {
super.tearDown();
assertNotNull(cc1);
cc1.flush();
}
public void testMultiGet() {
String[] allKeys = { "key1", "key2", "key3", "key4", "key5", "key6", "key7" };
String[] setKeys = { "key1", "key3", "key5", "key7" };
for (String key : setKeys) {
cc1.set(key, key + "xixi");
}
ArrayList<String> allKeyList = new ArrayList<String>();
for (String key : allKeys) {
allKeyList.add(key);
}
List<CacheItem> results = cc1.multiGet(allKeyList);
HashMap<String, CacheItem> hm = new HashMap<String, CacheItem>();
for (int i = 0; i < allKeyList.size(); i++) {
hm.put(allKeyList.get(i), results.get(i));
}
assert allKeys.length == results.size();
for (int i = 0; i < setKeys.length; i++) {
String key = setKeys[i];
String val = (String) hm.get(key).getValue();
assertEquals(key + "xixi", val);
}
}
public void testMultiGetError() {
assertNull(cc1.multiGet(null));
ArrayList<String> allKeyList = new ArrayList<String>();
assertEquals(0, cc1.multiGet(allKeyList).size());
String[] allKeys = { "key1", "key2", "key4", "key5", "key6", "key7" };
String[] setKeys = { "key1", "key3", "key5", "key7" };
for (String key : setKeys) {
cc1.set(key, key + "xixi");
}
allKeyList.add(null);
for (String key : allKeys) {
allKeyList.add(key);
}
allKeyList.add(null);
List<CacheItem> results = cc1.multiGet(allKeyList);
HashMap<String, CacheItem> hm = new HashMap<String, CacheItem>();
for (int i = 0; i < allKeyList.size(); i++) {
hm.put(allKeyList.get(i), results.get(i));
}
assertEquals(allKeys.length + 2, results.size());
for (int i = 0; i < setKeys.length; i++) {
String key = setKeys[i];
if (!key.equals("key3")) {
String val = (String) hm.get(key).getValue();
assertEquals(key + "xixi", val);
}
}
}
public void testMultiAdd() {
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
int ret = cc1.multiAdd(multi);
assertEquals(max, ret);
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), values.get(i));
}
}
public void testMultiSet() {
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
int ret = cc1.multiSet(multi);
assertEquals(max, ret);
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), values.get(i));
}
}
public void testMultiReplace() {
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
int ret = cc1.multiSet(multi);
assertEquals(max, ret);
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), values.get(i));
}
ArrayList<MultiUpdateItem> multi2 = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys2 = new ArrayList<String>();
ArrayList<String> values2 = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value2" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi2.add(item);
keys2.add(key);
values2.add(value);
}
ret = cc1.multiReplace(multi2);
assertEquals(max, ret);
List<CacheItem> results2 = cc1.multiGet(keys2);
for (int i = 0; i < max; i++) {
CacheItem item = results2.get(i);
assertEquals(item.getValue(), values2.get(i));
}
}
public void testMultiAppend() {
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
int ret = cc1.multiAdd(multi);
assertEquals(max, ret);
for (int i = 0; i < max; i++) {
multi.get(i).value = "append";
}
ret = cc1.multiAppend(multi);
assertEquals(max, ret);
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), values.get(i) + "append");
}
}
public void testMultiPrepend() {
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
int ret = cc1.multiAdd(multi);
assertEquals(max, ret);
ArrayList<MultiUpdateItem> multi2 = new ArrayList<MultiUpdateItem>();
for (int i = 0; i < max; i++) {
MultiUpdateItem item = new MultiUpdateItem();
item.key = multi.get(i).key;
item.value = "prepend";
multi2.add(item);
}
ret = cc1.multiPrepend(multi2);
assertEquals(max, ret);
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), "prepend" + values.get(i));
assertTrue(item.cacheID != multi.get(i).cacheID);
}
}
public void testMultiDelete() {
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
int ret = cc1.multiAdd(multi);
assertEquals(max, ret);
ArrayList<MultiDeleteItem> md = new ArrayList<MultiDeleteItem>();
for (int i = 0; i < multi.size(); i++) {
MultiUpdateItem item = multi.get(i);
MultiDeleteItem ditem = new MultiDeleteItem();
ditem.key = item.key;
ditem.cacheID = item.cacheID;
md.add(ditem);
}
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), values.get(i));
}
cc1.multiDelete(md);
results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertNull(item);
}
}
public void testMultiFlags() {
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
int ret = cc1.multiAdd(multi);
assertEquals(max, ret);
// ArrayList<MultiUpdateBaseItem> multibase = new ArrayList<MultiUpdateBaseItem>();
// for (int i = 0; i < max; i++) {
// MultiUpdateBaseItem item = new MultiUpdateBaseItem();
// }
ArrayList<MultiDeleteItem> md = new ArrayList<MultiDeleteItem>();
for (int i = 0; i < multi.size(); i++) {
MultiUpdateItem item = multi.get(i);
MultiDeleteItem ditem = new MultiDeleteItem();
ditem.key = item.key;
ditem.cacheID = item.cacheID;
md.add(ditem);
}
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), values.get(i));
}
cc1.multiDelete(md);
results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertNull(item);
}
}
public void testMultiError() {
int ret = cc1.multiAdd(null);
assertEquals(ret, 0);
assertNotNull(cc1.getLastError());
int max = 100;
ArrayList<MultiUpdateItem> multi = new ArrayList<MultiUpdateItem>();
ret = cc1.multiAdd(multi);
assertEquals(ret, 0);
assertNotNull(cc1.getLastError());
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < max; i++) {
String key = Integer.toString(i);
String value = "value" + i;
MultiUpdateItem item = new MultiUpdateItem();
item.key = key;
item.value = value;
multi.add(item);
keys.add(key);
values.add(value);
}
ret = cc1.multiAdd(multi);
assertEquals(max, ret);
ArrayList<MultiDeleteItem> md = new ArrayList<MultiDeleteItem>();
for (int i = 0; i < multi.size(); i++) {
MultiUpdateItem item = multi.get(i);
MultiDeleteItem ditem = new MultiDeleteItem();
ditem.key = item.key;
ditem.cacheID = item.cacheID;
md.add(ditem);
}
List<CacheItem> results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertEquals(item.getValue(), values.get(i));
}
cc1.multiDelete(md);
results = cc1.multiGet(keys);
for (int i = 0; i < max; i++) {
CacheItem item = results.get(i);
assertNull(item);
}
}
}
| {
"content_hash": "df19f36983be44116f2ec146dfc90fcd",
"timestamp": "",
"source": "github",
"line_count": 418,
"max_line_length": 104,
"avg_line_length": 29.69377990430622,
"alnum_prop": 0.6281018369320013,
"repo_name": "yeaya/xixibase",
"id": "d98dd17f9fbac6b8e4b0f3f771fa2ff6edd08963",
"size": "13029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/java/xixibase-client-old/src/test/com/xixibase/cache/MultiOperationTest.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2298"
},
{
"name": "C",
"bytes": "1779427"
},
{
"name": "C++",
"bytes": "583245"
},
{
"name": "CMake",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "806"
},
{
"name": "Groff",
"bytes": "4235"
},
{
"name": "HTML",
"bytes": "17225"
},
{
"name": "Java",
"bytes": "357706"
},
{
"name": "JavaScript",
"bytes": "6677"
},
{
"name": "Makefile",
"bytes": "3602"
},
{
"name": "Perl",
"bytes": "3895"
},
{
"name": "Shell",
"bytes": "2374"
}
],
"symlink_target": ""
} |
using System.Data;
using System.Text;
namespace Carbon.Data
{
using Versioning;
internal class SemanticVersionHandler : DbTypeHandler<SemanticVersion>
{
public override DatumInfo DatumType => DatumInfo.String(100);
public override SemanticVersion Parse(object value) =>
SemanticVersion.Parse((string)value);
public override void SetValue(IDbDataParameter parameter, SemanticVersion value)
{
parameter.Value = ToAlignedString(value);
parameter.DbType = DbType.AnsiString;
}
private static string ToAlignedString(SemanticVersion version)
{
if (version.Major == -1) return "xxxx.xxxx.xxxx";
var sb = new StringBuilder(14);
// support
// 9999 majors
// 9999 minors
// 9999 patches
sb.Append(version.Major.ToString("0000"));
sb.Append('.');
sb.Append(version.Minor == -1 ? "xxxx" : version.Minor.ToString("0000"));
sb.Append('.');
sb.Append(version.Patch == -1 ? "xxxx" : version.Patch.ToString("0000"));
if (version.IsPrerelease)
{
sb.Append('-');
sb.Append(version.Prerelease);
}
return sb.ToString();
}
}
}
// DB Serialization
/// 0001.0001.0000-prerelease | {
"content_hash": "ac53ffabe9ddace7aa54692e2c6fd48a",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 88,
"avg_line_length": 29.08,
"alnum_prop": 0.5447042640990372,
"repo_name": "carbon/Platform",
"id": "673cf93026876c7c5974d1dd25082179c34ba8c7",
"size": "1456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Carbon.Platform.Services/TypeHandlers/SemanticVersionHandler.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "228"
},
{
"name": "C#",
"bytes": "1012961"
},
{
"name": "PowerShell",
"bytes": "2854"
},
{
"name": "Smalltalk",
"bytes": "244"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e6c994a8355f4891398543da99776ebf",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 10.923076923076923,
"alnum_prop": 0.7183098591549296,
"repo_name": "mdoering/backbone",
"id": "b59cc4d2922be0c04cd527be090ad84d5c584837",
"size": "196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Vargolopteris/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
package com.microsoft.alm.client.utils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.TimeZone;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.microsoft.alm.client.model.VssServiceException;
public class JsonHelper {
private final static ObjectMapper objectMapper;
private final static SimpleDateFormat dateFormat;
static {
objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.disable(SerializationFeature.INDENT_OUTPUT);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objectMapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
objectMapper.setSerializationInclusion(Include.NON_NULL);
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); //$NON-NLS-1$
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); //$NON-NLS-1$
objectMapper.setDateFormat(dateFormat);
}
/**
* Get DateFormat
*
* @return DateFormat
*/
public static DateFormat getDateFormat() {
return dateFormat;
}
/**
* Get ObjectMapper
*
* @return ObjectMapper
*/
public static ObjectMapper getObjectMapper() {
return objectMapper;
}
/**
* Map to QueryParameters
*
* @param model
* @return Map<String, String>
*/
public static Map<String, String> toQueryParametersMap(final Object model) {
final ObjectMapper objectMapper = getObjectMapper();
try {
return objectMapper.readValue(
objectMapper.writeValueAsString(model),
new TypeReference<Map<String, String>>() {
});
} catch (final Exception e) {
throw new VssServiceException(e.getMessage(), e);
}
}
}
| {
"content_hash": "ce97cd8f026fa54365c6e74849d98b8f",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 87,
"avg_line_length": 32.66233766233766,
"alnum_prop": 0.6954274353876739,
"repo_name": "Microsoft/vso-httpclient-java",
"id": "58b72e52b96e016260c79581c966ebe5befed328",
"size": "2515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Rest/alm-vss-client/src/main/java/com/microsoft/alm/client/utils/JsonHelper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "760"
},
{
"name": "Java",
"bytes": "4771131"
}
],
"symlink_target": ""
} |
Request Component
-----------------
This contains BLW Libraries HTTP Request classes for making and handling HTTP Requests. All classes are built on the [BLW\HTTP][BLW\HTTP Framework] framework.
A request is either created from a string or manually using [IRequest][] API
##### Inspiration #####
- [Hypertext Transfer Protocol -- HTTP/1.1][RFC 2616]
- [HTTP Authentication: Basic and Digest Access Authentication][RFC 2617]
- [Returning Values from Forms: multipart/form-data][RFC 2388]
- [HTTP State Management Mechanism][RFC 6265]
- [Guzzle][]
- [Artax][]
##### Example: GET: Basics #####
```php
<?php
use BLW\Model\GenericURI as URL;
use BLW\Model\Config\Generic as Config;
use BLW\Model\HTTP\Request\Generic as Request;
use BLW\Model\MIME;
// Create Request
$Request = new Request(IRequest::GET, new Config(array(
'Timeout' => 10, // Abort request after 10 seconds
'MaxRedirects' => 4, // Maximum redirects to follow
'EnableCookies' => true, // Use cookies
)));
// Target
$Request->URI = new URL('http://example.com/get.php?foo=1');
// Add Get var
$Request->URI['query']['bar'] = 1;
// 'http://example.com/get.php?foo=1&bar=1'
// Edit Foo var
$Request->URI['query']['foo'] = 2;
// 'http://example.com/get.php?foo=2&bar=1'
// Change config
$Request->Config['Timeout'] = 30;
// Referer
$Request->Referer = new URL('http://example.com');
// Custom Header
$Request->Headers['Accept'] = $Request->createHeader('Accept', '*/*;q=0.8');
// See results
echo $Request;
?>
```
##### Example: POST: application/x-www-form-urlencoded #####
```php
<?php
use BLW\Model\GenericEmail as Email;
use BLW\Model\GenericURI as URL;
use BLW\Model\GenericFile as File;
use BLW\Model\Config\Generic as Config;
use BLW\Model\HTTP\Request\Generic as Request;
use BLW\Model\MIME;
$Request = new Request(IRequest::GET, new Config(array(
'Timeout' => 10, // Abort request after 10 seconds
'MaxRedirects' => 4, // Maximum redirects to follow
'EnableCookies' => true, // Use cookies
));
// Target
$Request->URI = new URL('http://example.com/post.php?secret=foo');
// Content Type Header
$Request->Headers['Content-Type'] = new MIME\ContentType('application/x-www-form-urlencoded');
// Fields
$Fields = array();
// Field with encoding
$Fields[] = new MIME\Part\Field('name', 'text/html', 'Alexander', 'ASCII');
// Objects implementing `__toString`
$Fields[] = new MIME\Part\Field('email', 'text/html', new Email('[email protected]'));
// Arrays
$Fields[] = new MIME\Part\FormField('info[country]', 'text/plain', 12);
$Fields[] = new MIME\Part\FormField('info[state]', 'text/plain', 27);
// Message Body
$Request->Body['Content'] = new FormData($Fields);
echo strval($Request);
?>
```
##### Example: POST Multipart/Form #####
```php
<?php
use BLW\Model\GenericURI as URL;
use BLW\Model\GenericFile as File;
use BLW\Model\Config\Generic as Config;
use BLW\Model\HTTP\Request\Generic as Request;
use BLW\Model\MIME;
$Request = new Request(IRequest::GET, new Config(array(
'Timeout' => 10, // Abort request after 10 seconds
'MaxRedirects' => 4, // Maximum redirects to follow
'EnableCookies' => true, // Use cookies
));
// Target
$Request->URI = new URL('http://example.com/post.php?secret=foo');
/*
* Note:
* MIME\Section helps to create Content-Type and
* MIME Boundary Headers
*/
$Section = new MIME\Section('multipart/form-data');
// MIME Part header placed in message header
$Request->Headers['Content-Type'] = $Section->createStart();
// Regular text value with encoding
$Request->Body[] = $Section->createBoundary();
$Request->Body[] = new MIME\Part\FormField('name', 'text/plain', 'Alexander', 'UTF-8');
$Request->Body[] = $Section->createBoundary();
$Request->Body[] = new MIME\Part\FormField('email', 'text/plain', '[email protected]', 'UTF-8');
// Arrays
$Request->Body[] = $Section->createBoundary();
$Request->Body[] = new MIME\Part\FormField('info[country]', 'text/plain', 12);
$Request->Body[] = $Section->createBoundary();
$Request->Body[] = new MIME\Part\FormField('info[state]', 'text/plain', 27);
// Files
$Request->Body[] = $Section->createBoundary();
$Request->Body[] = new MIME\Part\FormFile('cv', new File('path/to/file.doc'));
// End MIME Part
$Request->Body[] = $Section->createEnd();
echo $Request;
?>
```
##### Example: RAW #####
```php
<?php
use BLW\Model\HTTP\Request\Generic as Request;
$String = <<<EOT
GET /post.php?foo=1 HTTP/1.1
Host: example.com
....';
$Request = Request::createFromString($String);
?>
```
[RFC 2616]: <https://tools.ietf.org/html/rfc2616> "RFC 2616"
[RFC 2617]: <https://tools.ietf.org/html/rfc2617> "RFC 2617"
[RFC 2388]: <http://tools.ietf.org/html/rfc2388> "RFC 2388"
[RFC 6265]: <http://tools.ietf.org/html/rfc6265> "RFC 6265"
[Guzzle]: <https://github.com/guzzle/guzzle>
[Artax]: <https://github.com/rdlowrey/Artax>
[BLW\HTTP Framework]: <../../../Type/HTTP/>
[IRequest]: <../../../Type/HTTP/IRequest.php>
['bar']: <javascript:;>
['foo']: <javascript:;> | {
"content_hash": "52c1c73c290fb1833f860651fff0c148",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 158,
"avg_line_length": 25.838541666666668,
"alnum_prop": 0.6722434992944971,
"repo_name": "mAsT3RpEE/BLW",
"id": "92e8dc9c53eb593d649edb78a618c52103de8572",
"size": "4961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Model/HTTP/Request/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50088"
},
{
"name": "JavaScript",
"bytes": "116565"
},
{
"name": "PHP",
"bytes": "2314945"
}
],
"symlink_target": ""
} |
class ManageIQ::Providers::Amazon::Inventory::Collector::TargetCollection < ManageIQ::Providers::Amazon::Inventory::Collector
def initialize(_manager, _target)
super
parse_targets!
infer_related_ems_refs!
# Reset the target cache, so we can access new targets inside
target.manager_refs_by_association_reset
end
def references(collection)
target.manager_refs_by_association.try(:[], collection).try(:[], :ems_ref).try(:to_a) || []
end
def name_references(collection)
target.manager_refs_by_association.try(:[], collection).try(:[], :name).try(:to_a) || []
end
def instances
return [] if references(:vms).blank?
return @instances_hashes if @instances_hashes
@instances_hashes = hash_collection.new(
aws_ec2.instances(:filters => [{:name => 'instance-id', :values => references(:vms)}])
).all
end
def availability_zones
return [] if references(:availability_zones).blank?
hash_collection.new(
aws_ec2.client.describe_availability_zones(
:filters => [{:name => 'zone-name', :values => references(:availability_zones)}]
).availability_zones
)
end
def key_pairs
return [] if name_references(:key_pairs).blank?
hash_collection.new(
aws_ec2.client.describe_key_pairs(
:filters => [{:name => 'key-name', :values => name_references(:key_pairs)}]
).key_pairs
)
end
def referenced_images
return [] if references(:miq_templates).blank?
hash_collection.new(
aws_ec2.client.describe_images(:filters => [{:name => 'image-id', :values => references(:miq_templates)}]).images
)
end
def stacks
return [] if references(:orchestration_stacks).blank?
# TODO(lsmola) we can filter only one stack, so that means too many requests, lets try to figure out why
# CLoudFormations API doesn't support a standard filter
result = references(:orchestration_stacks).map do |stack_ref|
begin
aws_cloud_formation.client.describe_stacks(:stack_name => stack_ref)[:stacks]
rescue Aws::CloudFormation::Errors::ValidationError => _e
# A missing stack throws and exception like this, we want to ignore it and just don't list it
end
end.flatten.compact
hash_collection.new(result)
end
def cloud_networks
return [] if references(:cloud_networks).blank?
hash_collection.new(
aws_ec2.client.describe_vpcs(:filters => [{:name => 'vpc-id', :values => references(:cloud_networks)}]).vpcs
)
end
def cloud_subnets
return [] if references(:cloud_subnets).blank?
hash_collection.new(
aws_ec2.client.describe_subnets(:filters => [{:name => 'subnet-id', :values => references(:cloud_subnets)}]).subnets
)
end
def security_groups
return [] if references(:security_groups).blank?
hash_collection.new(
aws_ec2.security_groups(:filters => [{:name => 'group-id', :values => references(:security_groups)}])
)
end
def network_ports
return [] if references(:network_ports).blank?
return @network_ports_hashes if @network_ports_hashes
@network_ports_hashes = hash_collection.new(aws_ec2.client.describe_network_interfaces(
:filters => [{:name => 'network-interface-id', :values => references(:network_ports)}]
).network_interfaces).all
end
def load_balancers
return [] if references(:load_balancers).blank?
result = []
references(:load_balancers).each do |load_balancers_ref|
begin
result += aws_elb.client.describe_load_balancers(
:load_balancer_names => [load_balancers_ref]
).load_balancer_descriptions
rescue ::Aws::ElasticLoadBalancing::Errors::LoadBalancerNotFound => _e
# TODO(lsmola) maybe it will be faster to fetch all LBs and filter them?
# Ignore LB that was not found, it will be deleted from our DB
end
end
hash_collection.new(result)
end
def floating_ips
return [] if references(:floating_ips).blank?
hash_collection.new(
aws_ec2.client.describe_addresses(:filters => [{:name => 'allocation-id', :values => references(:floating_ips)}]).addresses
)
end
def cloud_volumes
return [] if references(:cloud_volumes).blank?
hash_collection.new(
aws_ec2.client.describe_volumes(:filters => [{:name => 'volume-id', :values => references(:cloud_volumes)}]).volumes
)
end
def cloud_volume_snapshots
return [] if references(:cloud_volume_snapshots).blank?
hash_collection.new(
aws_ec2.client.describe_snapshots(
:filters => [{:name => 'snapshot-id', :values => references(:cloud_volume_snapshots)}]
).snapshots
)
end
def cloud_object_store_containers
# hash_collection.new(aws_s3.client.list_buckets.buckets)
[]
end
def cloud_object_store_objects
# hash_collection.new([])
[]
end
# Nested API calls, we want all of them for our filtered list of LBs and Stacks
def stack_resources(stack_name)
begin
stack_resources = aws_cloud_formation.client.list_stack_resources(:stack_name => stack_name).try(:stack_resource_summaries)
rescue Aws::CloudFormation::Errors::ValidationError => _e
# When Stack was deleted we want to return empty list of resources
end
hash_collection.new(stack_resources || [])
end
def health_check_members(load_balancer_name)
hash_collection.new(aws_elb.client.describe_instance_health(
:load_balancer_name => load_balancer_name
).instance_states)
end
def stack_template(stack_name)
aws_cloud_formation.client.get_template(:stack_name => stack_name).template_body
rescue Aws::CloudFormation::Errors::ValidationError => _e
# When Stack was deleted we want to return empty string for template
""
end
private
def parse_targets!
target.targets.each do |t|
case t
when Vm
parse_vm_target!(t)
end
end
end
def parse_vm_target!(t)
add_simple_target!(:vms, t.ems_ref)
end
def infer_related_ems_refs!
# We have a list of instances_refs collected from events. Now we want to look into our DB and API, and collect
# ems_refs of every related object. Now this is not very nice fro ma design point of view, but we really want
# to see changes in VM's associated objects, so the VM view is always consistent and have fresh data. The partial
# reason for this is, that AWS doesn't send all the objects state change,
unless references(:vms).blank?
infer_related_vm_ems_refs_db!
infer_related_vm_ems_refs_api!
end
end
def infer_related_vm_ems_refs_db!
changed_vms = manager.vms.where(:ems_ref => references(:vms)).includes(:key_pairs, :network_ports, :floating_ips,
:orchestration_stack, :cloud_subnets)
changed_vms.each do |vm|
stack = vm.orchestration_stack
all_stacks = ([stack] + (stack.try(:ancestors) || [])).compact
all_stacks.collect(&:ems_ref).compact.each { |ems_ref| add_simple_target!(:orchestration_stacks, ems_ref) }
vm.cloud_subnets.collect(&:ems_ref).compact.each { |ems_ref| add_simple_target!(:cloud_subnets, ems_ref) }
vm.floating_ips.collect(&:ems_ref).compact.each { |ems_ref| add_simple_target!(:floating_ips, ems_ref) }
vm.network_ports.collect(&:ems_ref).compact.each do |ems_ref|
# Add only real network ports, starting with "eni-"
add_simple_target!(:network_ports, ems_ref) if ems_ref.start_with?("eni-")
end
vm.key_pairs.collect(&:name).compact.each do |name|
target.add_target(:association => :key_pairs, :manager_ref => {:name => name})
end
end
end
def infer_related_vm_ems_refs_api!
# TODO(lsmola) should we filter the VMs by only VMs we want to do full refresh for? Some of them, like FloatingIps
# need to be scanned for all, due to the fake FloatingIps we create.
instances.each do |vm|
add_simple_target!(:miq_templates, vm["image_id"])
add_simple_target!(:availability_zones, vm.fetch_path('placement', 'availability_zone'))
add_simple_target!(:orchestration_stacks, get_from_tags(vm, "aws:cloudformation:stack-id"))
target.add_target(:association => :key_pairs, :manager_ref => {:name => vm["key_name"]})
vm["network_interfaces"].each do |network_interface|
add_simple_target!(:network_ports, network_interface["network_interface_id"])
add_simple_target!(:cloud_subnets, network_interface["subnet_id"])
add_simple_target!(:cloud_networks, network_interface["vpc_id"])
end
vm["security_groups"].each do |security_group|
add_simple_target!(:security_groups, security_group["group_id"])
end
vm["block_device_mappings"].each do |cloud_volume|
add_simple_target!(:cloud_volumes, cloud_volume.fetch_path("ebs", "volume_id"))
end
# EC2 classic floating ips
if vm["network_interfaces"].blank? && vm['public_ip_address'].present?
add_simple_target!(:floating_ips, vm['public_ip_address'])
end
end
# TODO(lsmola) I don't like this anymore, the TargetCollection should just build structure with unique targets
# inside. The we don't need to do this cache invalidate, since add_target would be modifying it directly.
# Reset target cache, so we can get a fresh list of network_ports ids
target.manager_refs_by_association_reset
# We need to go through all network ports, to get a correct list of the floating IPs, for some reason, the list
# under a vm is missing allocation_ids.
network_ports.each do |network_port|
network_port['private_ip_addresses'].each do |private_ip_address|
floating_ip_id = (private_ip_address.fetch_path("association", "allocation_id") ||
private_ip_address.fetch_path("association", "public_ip"))
add_simple_target!(:floating_ips, floating_ip_id)
end
end
end
def add_simple_target!(association, ems_ref)
return if ems_ref.blank?
target.add_target(:association => association, :manager_ref => {:ems_ref => ems_ref})
end
def get_from_tags(resource, item)
(resource['tags'] || []).detect { |tag, _| tag['key'].downcase == item.to_s.downcase }.try(:[], 'value')
end
end
| {
"content_hash": "529cd309542d4e352337c07c6b46076d",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 129,
"avg_line_length": 36.3356890459364,
"alnum_prop": 0.6647865408927356,
"repo_name": "durandom/manageiq-providers-amazon",
"id": "804d4458d60fb95f00c55f4f5a7b06c9a05d879e",
"size": "10283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/manageiq/providers/amazon/inventory/collector/target_collection.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "616685"
}
],
"symlink_target": ""
} |
from ....utils import assert_cmd_success
from ....utils import catkin_success
from ....utils import in_temporary_directory
from ....utils import redirected_stdio
from ....workspace_assertions import assert_in_config
from ...workspace_factory import workspace_factory
BUILD = ['build', '--no-notify', '--no-status']
@in_temporary_directory
def test_profile_list():
assert_cmd_success(['mkdir', 'src'])
with redirected_stdio():
assert catkin_success(['init'])
assert catkin_success(BUILD)
assert catkin_success(['profile', 'list'])
@in_temporary_directory
def test_profile_set():
assert_cmd_success(['mkdir', 'src'])
with redirected_stdio():
assert catkin_success(['init'])
assert catkin_success(BUILD)
assert catkin_success(['profile', 'set', 'default'])
def test_profile_copy():
with workspace_factory() as wf:
wf.build()
with redirected_stdio():
assert catkin_success(['config', '--make-args', 'test'])
assert catkin_success(['profile', 'add', '--copy', 'default', 'mycopy'])
assert_in_config('.', 'mycopy', 'make_args', ['test'])
def test_profile_extend():
with workspace_factory() as wf:
wf.build()
with redirected_stdio():
assert catkin_success(['config', '--make-args', 'test'])
assert catkin_success(['profile', 'add', '--extend', 'default', 'myextend'])
assert catkin_success(['config', '--profile', 'myextend', '--skiplist', 'mypackage'])
assert_in_config('.', 'default', 'make_args', ['test'])
assert_in_config('.', 'myextend', 'blacklist', ['mypackage'])
| {
"content_hash": "dea7a6f634c2d12b8d998d07a7eb1536",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 97,
"avg_line_length": 36.130434782608695,
"alnum_prop": 0.6173285198555957,
"repo_name": "rhaschke/catkin_tools",
"id": "480b6a7a3e728be4a0cd8c05a503f0a03bc88c49",
"size": "1662",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "tests/system/verbs/catkin_profile/test_profile.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "860"
},
{
"name": "CMake",
"bytes": "5822"
},
{
"name": "Objective-C",
"bytes": "3354"
},
{
"name": "Python",
"bytes": "461125"
},
{
"name": "Rich Text Format",
"bytes": "872"
},
{
"name": "Shell",
"bytes": "8476"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.