text
stringlengths
2
1.04M
meta
dict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <title>Uses of Class org.apache.poi.ss.format.CellElapsedFormatter (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.ss.format.CellElapsedFormatter (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/ss/format/CellElapsedFormatter.html" title="class in org.apache.poi.ss.format">Class</a></li> <li class="navBarCell1Rev">Use</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>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/ss/format//class-useCellElapsedFormatter.html" target="_top">FRAMES</a></li> <li><a href="CellElapsedFormatter.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> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.poi.ss.format.CellElapsedFormatter" class="title">Uses of Class<br>org.apache.poi.ss.format.CellElapsedFormatter</h2> </div> <div class="classUseContainer">No usage of org.apache.poi.ss.format.CellElapsedFormatter</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/ss/format/CellElapsedFormatter.html" title="class in org.apache.poi.ss.format">Class</a></li> <li class="navBarCell1Rev">Use</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>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/ss/format//class-useCellElapsedFormatter.html" target="_top">FRAMES</a></li> <li><a href="CellElapsedFormatter.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> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2014 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
{ "content_hash": "1ff1a2d69aa6faa5a59e7f5774e2810a", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 153, "avg_line_length": 37.23076923076923, "alnum_prop": 0.6099632690541782, "repo_name": "tringuyen1401/Stock-analyzing", "id": "8bfe39655069302e5b2315705990fe2f86f8736c", "size": "4356", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "jdbc/lib/poi-3.11/docs/apidocs/org/apache/poi/ss/format/class-use/CellElapsedFormatter.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23219" }, { "name": "HTML", "bytes": "75486542" }, { "name": "Java", "bytes": "2810339" }, { "name": "Rust", "bytes": "92" } ], "symlink_target": "" }
<?php /* D:\phpstudy\WWW\pyrocms\core/anomaly/relationship-field_type/resources/views/filter.twig */ class __TwigTemplate_e206f02ef1389d1ecd1c557af0686c6259fd1d44bb4cf5617251ae3cb20e6aaf extends TwigBridge\Twig\Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<select class=\"custom-select form-control\" name=\""; // line 3 echo twig_escape_filter($this->env, $this->getAttribute(($context["field_type"] ?? null), "input_name", array()), "html", null, true); echo "\"> <option value=\"\" disabled "; // line 5 echo (( !$this->getAttribute(($context["field_type"] ?? null), "value", array())) ? ("selected") : ("")); echo ">"; echo twig_escape_filter($this->env, call_user_func_array($this->env->getFunction('trans')->getCallable(), array($this->getAttribute(($context["field_type"] ?? null), "placeholder", array()))), "html", null, true); echo "</option> "; // line 7 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute(($context["field_type"] ?? null), "options", array())); foreach ($context['_seq'] as $context["value"] => $context["title"]) { // line 8 echo " <option value=\""; echo twig_escape_filter($this->env, $context["value"], "html", null, true); echo "\" "; echo ((($this->getAttribute(($context["field_type"] ?? null), "value", array()) == $context["value"])) ? ("selected") : ("")); echo ">"; echo twig_escape_filter($this->env, call_user_func_array($this->env->getFunction('trans')->getCallable(), array($context["title"])), "html", null, true); echo "</option> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['value'], $context['title'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 10 echo "</select> "; } public function getTemplateName() { return "D:\\phpstudy\\WWW\\pyrocms\\core/anomaly/relationship-field_type/resources/views/filter.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 52 => 10, 39 => 8, 35 => 7, 28 => 5, 23 => 3, 19 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("<select class=\"custom-select form-control\" name=\"{{ field_type.input_name }}\"> <option value=\"\" disabled {{ not field_type.value ? 'selected' }}>{{ trans(field_type.placeholder) }}</option> {% for value, title in field_type.options %} <option value=\"{{ value }}\" {{ field_type.value == value ? 'selected' }}>{{ trans(title) }}</option> {% endfor %} </select> ", "D:\\phpstudy\\WWW\\pyrocms\\core/anomaly/relationship-field_type/resources/views/filter.twig", ""); } }
{ "content_hash": "b7ee66d2f91095be86f17a06182a0751", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 221, "avg_line_length": 39, "alnum_prop": 0.5726495726495726, "repo_name": "fannan1991/pyrocms", "id": "ef103cb83d30d2da7fb54c4314f4147096645ebd", "size": "3627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "storage/framework/views/twig/cf/cf8c54b9fb47e1f1f6ca75f6adc38cae1ae1dd1d3e52779cc063451744bcaad6.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "924" }, { "name": "Batchfile", "bytes": "851" }, { "name": "CSS", "bytes": "884694" }, { "name": "HTML", "bytes": "1990270" }, { "name": "JavaScript", "bytes": "337071" }, { "name": "PHP", "bytes": "4641867" }, { "name": "Shell", "bytes": "4281" }, { "name": "Vue", "bytes": "559" } ], "symlink_target": "" }
<?php namespace Dimimo\Forum\Controllers; use Illuminate\Routing\Controller; use Illuminate\Foundation\Bus\DispatchesJobs; use Dimimo\Forum\Jobs\Conversations\StartConversation; use Dimimo\Forum\Jobs\Conversations\UpdateConversation; use Dimimo\Forum\Jobs\StartConversationJob; use Dimimo\Forum\Requests\ConversationRequest; use Dimimo\Forum\Requests\UpdateReplyRequest; use Dimimo\Forum\Entities\Conversations\ConversationRepo; use Dimimo\Forum\Jobs\Conversations\CreateConversationThread; class ConversationController extends Controller { use DispatchesJobs; /** * @var ConversationRepo */ protected $conversationRepo; /** * @param ConversationRepo $conversationRepo */ function __construct(ConversationRepo $conversationRepo) { $this->middleware('auth', ['only' => ['store']]); $this->conversationRepo = $conversationRepo; } /** * Display a conversation and replies. * * @param string $slug * * @return \Illuminate\View\View */ public function show($slug) { $conversation = $this->conversationRepo->findBySlug($slug); $replies = $conversation->replies()->orderBy('created_at', 'asc')->paginate(4); return view('Forum::Conversations.show', compact('conversation', 'replies')); } /** * Store the new conversation. * * @param ConversationRequest $request * * @return \Illuminate\Http\RedirectResponse */ public function store(ConversationRequest $request) { $this->dispatch(new StartConversation($request)); return redirect()->route('forum'); } /** * Display the conversation edit form. * * @param string $slug * * @return \Illuminate\View\View */ public function edit($slug) { $conversation = $this->conversationRepo->findBySlug($slug); return view('Forum::Conversations.edit')->with(compact('conversation')); } /** * Update an existing conversation. * * @param UpdateReplyRequest $request * @param $slug * * @return \Illuminate\Http\RedirectResponse */ public function update(UpdateReplyRequest $request, $slug) { $this->dispatch(new UpdateConversation($request)); return redirect()->route('forum.conversation.show', $slug); } }
{ "content_hash": "aaeda4bbb07a25d0b351abaa98a99ecd", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 92, "avg_line_length": 26.58888888888889, "alnum_prop": 0.649811951525282, "repo_name": "Dimimo/Booklet", "id": "23755c14501281805d7101afa150825de07aa9b6", "size": "2560", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/dimimo/forum/src/Controllers/ConversationController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15281" }, { "name": "CoffeeScript", "bytes": "80553" }, { "name": "Dockerfile", "bytes": "996" }, { "name": "Go", "bytes": "15680" }, { "name": "HTML", "bytes": "6301872" }, { "name": "Hack", "bytes": "41" }, { "name": "JavaScript", "bytes": "3159767" }, { "name": "Makefile", "bytes": "163" }, { "name": "PHP", "bytes": "2015449" }, { "name": "Python", "bytes": "12750" }, { "name": "Vue", "bytes": "547" } ], "symlink_target": "" }
Owen::Owen() : pid((double*) &temperature, (double*) &pidValue, (double*) &targetTemperature, PID_P, PID_I, PID_D, DIRECT) { thermocouple = new MAX6675(THERMO_CLK, THERMO_CS, THERMO_DO); profile = ReflowProfile(); } void Owen::init() { pid.SetOutputLimits(0, 1); pid.SetMode(AUTOMATIC); pid.SetTunings(PID_P, PID_I, PID_D); } void Owen::tick() { temperature = getTemperature(); profile.setStartTemp(temperature); profile.tick(temperature); setTargetTemperature(profile.getTargetTemperature(profile.seconds + 10)); pid.Compute(); pidValue == 1 ? setHeaterOn() : setHeaterOff(); if (profile.state == REFLOW_STATE_COOL) { setHeaterOff(); } } ReflowProfile Owen::getProfile() { return profile; } void Owen::setTargetTemperature(float temperature) { targetTemperature = temperature; } float Owen::getTargetTemperature() { return targetTemperature; } float Owen::getTemperature() { return (float) thermocouple->readCelsius(); } void Owen::setHeaterOn() { heaterState = true; } void Owen::setHeaterOff() { heaterState = false; } boolean Owen::isHeaterOn() { return heaterState == true; } float Owen::getPidValue() { return pidValue; }
{ "content_hash": "ca37f186e2fd5481feb8344b6f3623a1", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 109, "avg_line_length": 19.467741935483872, "alnum_prop": 0.6859983429991715, "repo_name": "kallaspriit/OSRC", "id": "2c9b4bc142260a1322a8cd9fa0dba3420d8dee66", "size": "1267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "firmware/Reflow/Owen.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "1147" }, { "name": "C++", "bytes": "9724" }, { "name": "HTML", "bytes": "4369" } ], "symlink_target": "" }
bash /home/ubuntu/stopLoadBalancer cd
{ "content_hash": "55e1dabf298d92fdbcc854bf98d0a619", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 34, "avg_line_length": 13, "alnum_prop": 0.8205128205128205, "repo_name": "deib-polimi/modaclouds-tests", "id": "def4dc6128282598bf92af2cc1be6b2b67aba312", "size": "72", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "machines/LB/shutdown.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "246256" }, { "name": "Shell", "bytes": "71401" } ], "symlink_target": "" }
namespace EDSLot { using System; using System.Collections.Generic; using System.ServiceModel; using System.Runtime.Serialization; [DataContract] public partial class Record_MCCB:Record { } }
{ "content_hash": "9a619e4ed331201d520843f588a9be62", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 47, "avg_line_length": 21.333333333333332, "alnum_prop": 0.60546875, "repo_name": "hawesome512/edsmonitor", "id": "8ef08eb9b285b74b1c6bb89ebc85b416a1c9c16e", "size": "661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EDSLot/Record_MCCB.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "442605" } ], "symlink_target": "" }
require 'spec_helper' describe ActiveEncode::Input do subject { described_class.new } describe 'attributes' do it { is_expected.to respond_to(:id, :url) } it { is_expected.to respond_to(:state, :errors, :created_at, :updated_at) } it { is_expected.to respond_to(:width, :height, :frame_rate, :checksum, :audio_codec, :video_codec, :audio_bitrate, :video_bitrate) } end describe '#valid?' do let(:valid_input) do described_class.new.tap do |obj| obj.id = "1" obj.url = "file:///tmp/video.mp4" obj.created_at = Time.now.utc obj.updated_at = Time.now.utc end end it 'returns true when conditions met' do expect(valid_input).to be_valid end it 'returns false when conditions not met' do expect(valid_input.tap { |obj| obj.id = nil }).not_to be_valid expect(valid_input.tap { |obj| obj.url = nil }).not_to be_valid expect(valid_input.tap { |obj| obj.created_at = nil }).not_to be_valid expect(valid_input.tap { |obj| obj.created_at = "today" }).not_to be_valid expect(valid_input.tap { |obj| obj.updated_at = nil }).not_to be_valid expect(valid_input.tap { |obj| obj.updated_at = "today" }).not_to be_valid expect(valid_input.tap { |obj| obj.created_at = Time.now.utc }).not_to be_valid end end end
{ "content_hash": "21d7b77088b1239d4368e96887cab78f", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 91, "avg_line_length": 35.35897435897436, "alnum_prop": 0.612037708484409, "repo_name": "projecthydra-labs/active_encode", "id": "99e0ebf9491cbacebe4bfe7874329099b129a2ee", "size": "1409", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "spec/units/input_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "89765" } ], "symlink_target": "" }
<?php /** * Adminhtml Newsletter Template Grid Form Block */ class Contactlab_Template_Block_Adminhtml_Newsletter_Template_Grid extends Mage_Adminhtml_Block_Newsletter_Template_Grid { /** * Prepare columns * @return \Contactlab_Template_Block_Adminhtml_Newsletter_Template_Grid */ protected function _prepareColumns() { $this->addColumn('template_code', array('header'=>Mage::helper('newsletter')->__('ID'), 'align'=>'center', 'index'=>'template_id', 'width' => 1)); $this->addColumn('code', array( 'header'=>Mage::helper('newsletter')->__('Template Name'), 'index'=>'template_code', 'width' => 1 )); $this->addColumn('store_id', array( 'header'=>Mage::helper('newsletter')->__('Store View'), 'index'=>'store_id', 'width' => 1, 'type' => 'store', 'renderer' => 'contactlab_commons/adminhtml_tasks_renderer_store' )); $this->addColumn('template_type_name', array( 'header'=>Mage::helper('newsletter')->__('Template Type'), 'index'=>'template_type_name', 'width' => 1 )); $this->addColumn('added_at', array( 'header'=>Mage::helper('newsletter')->__('Date Added'), 'index'=>'added_at', 'gmtoffset' => true, 'type'=>'datetime' )); $this->addColumn('modified_at', array( 'header'=>Mage::helper('newsletter')->__('Date Updated'), 'index'=>'modified_at', 'gmtoffset' => true, 'type'=>'datetime' )); $this->addColumn('subject', array( 'header'=>Mage::helper('newsletter')->__('Subject'), 'index'=>'template_subject', 'width' => 1 )); $this->addColumn('sender', array( 'header'=>Mage::helper('newsletter')->__('Sender'), 'index'=>'template_sender_email', 'renderer' => 'adminhtml/newsletter_template_grid_renderer_sender', 'width' => 1 )); /* @var $formats Contactlab_Template_Model_System_Config_Source_Template_Format */ $formats = Mage::getModel('contactlab_template/system_config_source_template_format'); $this->addColumn('flg_html_txt', array( 'header'=>Mage::helper('newsletter')->__('Content Type'), 'index'=>'flg_html_txt', 'type' => 'options', 'options' => $formats->toArray(), 'width' => 1, )); $this->addColumn('priority', array( 'header'=>Mage::helper('newsletter')->__('Priority'), 'index'=>'priority', 'width' => 1 )); $this->addColumn('tasks', array( 'header' => Mage::helper('newsletter')->__('XML Delivery Status'), 'renderer' => 'contactlab_template/adminhtml_newsletter_template_grid_renderer_xmlDeliveryStatus' )); $this->addColumn('action', array( 'header' => Mage::helper('newsletter')->__('Action'), 'index' =>'template_id', 'sortable' =>false, 'filter' => false, 'no_link' => true, 'width' => '170px', 'renderer' => 'adminhtml/newsletter_template_grid_renderer_action' )); return $this; } /** * Prepare collection for the grid * @return \Contactlab_Template_Block_Adminhtml_Newsletter_Template_Grid */ protected function _prepareCollection() { /* @var $collection Mage_Newsletter_Model_Resource_Template_Collection */ $collection = Mage::getResourceSingleton('newsletter/template_collection') ->useOnlyActual(); $collection->getSelect() ->joinLeft(array('template_types' => $collection->getTable('contactlab_template/type')), "main_table.template_type_id = template_types.entity_id", array('template_type_name' => 'name')); $this->setCollection($collection); return parent::_prepareCollection(); } }
{ "content_hash": "5efc3c750a8e835fabe5476ef3d1eb19", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 122, "avg_line_length": 36.80165289256198, "alnum_prop": 0.4965192005389625, "repo_name": "contactlab/contactlab-magento-connect", "id": "b0ba97bce004525e8035780df50e09a94e473c11", "size": "4453", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/code/community/Contactlab/Template/Block/Adminhtml/Newsletter/Template/Grid.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "59754" }, { "name": "JavaScript", "bytes": "2278" }, { "name": "PHP", "bytes": "1907685" }, { "name": "Shell", "bytes": "1187" } ], "symlink_target": "" }
package kr.dogfoot.hwplib.writer; import kr.dogfoot.hwplib.object.fileheader.FileHeader; import kr.dogfoot.hwplib.object.fileheader.FileVersion; import kr.dogfoot.hwplib.util.binary.BitFlag; import kr.dogfoot.hwplib.util.compoundFile.writer.StreamWriter; import java.io.IOException; /** * 파일 헤더를 쓰기 위한 객체 * * @author neolord */ public class ForFileHeader { /** * 파일 헤더를 쓴다. * * @param fh 파일 헤더 * @param sw 스트림 라이터 * @throws IOException */ public static void write(FileHeader fh, StreamWriter sw) throws IOException { signature(sw); fileVersion(fh.getVersion(), sw); properties(fh, sw); zero216(sw); } /** * 파일 시그널을 쓴다. * * @param sw 스트림 라이터 * @throws IOException */ private static void signature(StreamWriter sw) throws IOException { byte[] signature = {0x48, 0x57, 0x50, 0x20, 0x44, 0x6F, 0x63, 0x75, 0x6D, 0x65, 0x6E, 0x74, 0x20, 0x46, 0x69, 0x6C, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; sw.writeBytes(signature); } /** * 파일 버전을 쓴다. * * @param version 파일 버전 * @param sw 스트림 라이터 * @throws IOException */ private static void fileVersion(FileVersion version, StreamWriter sw) throws IOException { sw.writeUInt4(version.getVersion()); } /** * 파일 속성을 쓴다. * * @param fh 파일 헤더 * @param sw 스트림 라이터 * @throws IOException */ private static void properties(FileHeader fh, StreamWriter sw) throws IOException { long properties = 0; properties = BitFlag.set(properties, 0, fh.isCompressed()); properties = BitFlag.set(properties, 1, fh.hasPassword()); properties = BitFlag.set(properties, 2, fh.isDeploymentDocument()); properties = BitFlag.set(properties, 3, fh.isSaveScript()); properties = BitFlag.set(properties, 4, fh.isDRMDocument()); properties = BitFlag.set(properties, 5, fh.hasXMLTemplate()); properties = BitFlag.set(properties, 6, fh.hasDocumentHistory()); properties = BitFlag.set(properties, 7, fh.hasSignature()); properties = BitFlag.set(properties, 8, fh.isEncryptPublicCertification()); properties = BitFlag.set(properties, 9, fh.isSavePrepareSignature()); properties = BitFlag.set(properties, 10, fh.isPublicCertificationDRMDocument()); properties = BitFlag.set(properties, 11, fh.isCCLDocument()); sw.writeUInt4(properties); } /** * 나머지 부분(216 bytes)을 0으로 쓴다. * * @param sw 스트림 라이터 * @throws IOException */ private static void zero216(StreamWriter sw) throws IOException { sw.writeZero(216); } }
{ "content_hash": "aee5fe4b16d3f14e8a89a42c63177be0", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 81, "avg_line_length": 31.065217391304348, "alnum_prop": 0.6130160951714486, "repo_name": "neolord0/hwplib", "id": "4550b0bf80f0bdfcf5d9a547a52121b74eb83292", "size": "3042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/kr/dogfoot/hwplib/writer/ForFileHeader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1206" }, { "name": "Java", "bytes": "2229316" } ], "symlink_target": "" }
Certificates ============ Certificates are used to manage authentications in LXD. Certificates are not editable. They may only be created or deleted. None of the certificate operations in LXD are asynchronous. Manager methods --------------- Certificates can be queried through the following client manager methods: - `all()` - Retrieve all certificates. - `get()` - Get a specifit certificate, by its fingerprint. - `create()` - Create a new certificate. This method requires a first argument that is the LXD trust password, and the cert data, in binary format. Certificate attributes ---------------------- Certificates have the following attributes: - `fingerprint` - The fingerprint of the certificate. Certificates are keyed off this attribute. - `certificate` - The certificate itself, in PEM format. - `type` - The certificate type (currently only "client")
{ "content_hash": "626c6a8b761246f0a40244dbc8ea539a", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 74, "avg_line_length": 30.93103448275862, "alnum_prop": 0.7134894091415831, "repo_name": "lxc/pylxd", "id": "0927617c1a9984cc9b7d2fc3ec95512723b63ca6", "size": "897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/source/certificates.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "444517" }, { "name": "Shell", "bytes": "6718" } ], "symlink_target": "" }
include_recipe 'composer'
{ "content_hash": "486e46e28ae7038a1d0cb0d1740a311c", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 25, "avg_line_length": 26, "alnum_prop": 0.8076923076923077, "repo_name": "ekreative/symfony-chef", "id": "17c8b7456de1e2f5c31f856d128db031c355cbba", "size": "26", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "go-composer/recipes/default.rb", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "9254" }, { "name": "HTML", "bytes": "11439" }, { "name": "Ruby", "bytes": "20109" } ], "symlink_target": "" }
import map = require("just-map-values"); const obj = {foo: {bar: []}}; map(obj, (value) => value); // $ExpectType {} map(obj, (value, key, object) => ''); // $ExpectType {} // Incorrect argument map(); // $ExpectError map(obj); // $ExpectError map(obj, ''); // $ExpectError
{ "content_hash": "577fd99f3bab95cddc02ccef9ca4a704", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 55, "avg_line_length": 25.181818181818183, "alnum_prop": 0.592057761732852, "repo_name": "dsebastien/DefinitelyTyped", "id": "85e8ce8d1302705bc076867683367a7347a2cff7", "size": "277", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "types/just-map-values/just-map-values-tests.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "HTML", "bytes": "308" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "20293816" } ], "symlink_target": "" }
/*global angular */ /* ========================================= NOTIFICATION Directive ========================================= */ (function() { var app = angular.module('notification-directives', []) .directive('notificationMsg', function () { return { restrict: 'E', template: '<section ng-show="dash.notification" ' + 'ng-click="dash.closeMsg()" ' + 'class="ng-notification"> ' + '<p class="notify-msg">{{dash.message}}</p> ' + '<div class="notify-bg {{dash.notification_type}}"></div> ' + '</section>' }; }); })();
{ "content_hash": "062e1328140fd1ff93cf22c5b98c8427", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 66, "avg_line_length": 26, "alnum_prop": 0.46488294314381273, "repo_name": "leongaban/bitage", "id": "e46cb1dc3619d444a48c17c3407f07696d43e85a", "size": "598", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/dashboard/app/shared/notificationDirectives.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "55708" }, { "name": "HTML", "bytes": "60217" }, { "name": "Handlebars", "bytes": "7179" }, { "name": "JavaScript", "bytes": "345016" }, { "name": "Shell", "bytes": "220" } ], "symlink_target": "" }
using InsideInning.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Xamarin.Forms; namespace InsideInning.ViewModels { public class HomeViewModel : BaseViewModel { public ObservableCollection<HomeMenuItem> MenuItems { get; set; } public HomeViewModel() { Title = "Hello"; MenuItems = new ObservableCollection<HomeMenuItem>(); MenuItems.Add(new HomeMenuItem { ID = 0, Title = "Dashboard", MenuType = MenuType.Dashboard }); MenuItems.Add(new HomeMenuItem { ID = 1, Title = "Create an Account", MenuType = MenuType.EmployeeAccount }); MenuItems.Add(new HomeMenuItem { ID = 2, Title = "Logout", MenuType = MenuType.Logout }); } public LoginViewModel LogViewModel { get; set; } } }
{ "content_hash": "29c5875ba485107aaa65f3fd093edd2c", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 73, "avg_line_length": 27.073170731707318, "alnum_prop": 0.5162162162162162, "repo_name": "rzeem7/InsideInning", "id": "6fc079e82b695c544fcbc42eaf40a93d6d9a0ba5", "size": "1112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "InsideInning/InsideInning/ViewModels/HomeViewModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "6070" }, { "name": "C#", "bytes": "662128" }, { "name": "CSS", "bytes": "30247" }, { "name": "JavaScript", "bytes": "1144" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.orc; import com.facebook.presto.common.Page; import com.facebook.presto.common.Subfield; import com.facebook.presto.common.block.Block; import com.facebook.presto.common.type.DecimalType; import com.facebook.presto.common.type.Decimals; import com.facebook.presto.common.type.SqlDate; import com.facebook.presto.common.type.SqlDecimal; import com.facebook.presto.common.type.SqlTimestamp; import com.facebook.presto.common.type.TimeZoneKey; import com.facebook.presto.common.type.Type; import com.facebook.presto.common.type.TypeSignature; import com.facebook.presto.common.type.VarcharType; import com.facebook.presto.orc.TupleDomainFilter.BigintRange; import com.facebook.presto.orc.TupleDomainFilter.BooleanValue; import com.facebook.presto.orc.TupleDomainFilter.BytesRange; import com.facebook.presto.orc.TupleDomainFilter.DoubleRange; import com.facebook.presto.orc.TupleDomainFilter.FloatRange; import com.facebook.presto.orc.cache.StorageOrcFileTailSource; import com.facebook.presto.type.TypeRegistry; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.Longs; import io.airlift.units.DataSize; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.VerboseMode; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.BooleanType.BOOLEAN; import static com.facebook.presto.common.type.DateType.DATE; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.common.type.IntegerType.INTEGER; import static com.facebook.presto.common.type.RealType.REAL; import static com.facebook.presto.common.type.SmallintType.SMALLINT; import static com.facebook.presto.common.type.TimestampType.TIMESTAMP; import static com.facebook.presto.common.type.TinyintType.TINYINT; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.facebook.presto.orc.DwrfEncryptionProvider.NO_ENCRYPTION; import static com.facebook.presto.orc.NoopOrcAggregatedMemoryContext.NOOP_ORC_AGGREGATED_MEMORY_CONTEXT; import static com.facebook.presto.orc.OrcEncoding.ORC; import static com.facebook.presto.orc.OrcReader.INITIAL_BATCH_SIZE; import static com.facebook.presto.orc.OrcTester.Format.ORC_12; import static com.facebook.presto.orc.OrcTester.writeOrcColumnHive; import static com.facebook.presto.orc.TupleDomainFilter.LongDecimalRange; import static com.facebook.presto.orc.metadata.CompressionKind.NONE; import static com.google.common.io.Files.createTempDir; import static com.google.common.io.MoreFiles.deleteRecursively; import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.util.UUID.randomUUID; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.stream.Collectors.toList; import static org.joda.time.DateTimeZone.UTC; @SuppressWarnings("MethodMayBeStatic") @State(Scope.Thread) @OutputTimeUnit(TimeUnit.SECONDS) @Fork(2) @Warmup(iterations = 10, time = 1000, timeUnit = MILLISECONDS) @Measurement(iterations = 10, time = 1000, timeUnit = MILLISECONDS) @BenchmarkMode(Mode.AverageTime) public class BenchmarkSelectiveStreamReaders { private static final int ROWS = 10_000_000; private static final List<?> NULL_VALUES = Collections.nCopies(ROWS, null); private static final DecimalType SHORT_DECIMAL_TYPE = DecimalType.createDecimalType(10, 5); private static final DecimalType LONG_DECIMAL_TYPE = DecimalType.createDecimalType(30, 10); private static final int MAX_STRING_LENGTH = 10; @Benchmark public Object readAllNull(AllNullBenchmarkData data) throws Throwable { return readAllBlocks(data.createRecordReader(Optional.empty())); } @Benchmark public Object read(BenchmarkData data) throws IOException { return readAllBlocks(data.createRecordReader(Optional.empty())); } @Benchmark public Object readWithFilter(BenchmarkData data) throws IOException { return readAllBlocks(data.createRecordReader(data.getFilter())); } private static List<Block> readAllBlocks(OrcSelectiveRecordReader recordReader) throws IOException { List<Block> blocks = new ArrayList<>(); while (true) { Page page = recordReader.getNextPage(); if (page == null) { break; } if (page.getPositionCount() > 0) { blocks.add(page.getBlock(0).getLoadedBlock()); } } return blocks; } private abstract static class AbstractBenchmarkData { protected final Random random = new Random(0); private Type type; private File temporaryDirectory; private File orcFile; private String typeSignature; public void setup(String typeSignature) throws Exception { if (typeSignature.startsWith("varchar")) { type = new TypeRegistry().getType(TypeSignature.parseTypeSignature("varchar")); } else { type = new TypeRegistry().getType(TypeSignature.parseTypeSignature(typeSignature)); } this.typeSignature = typeSignature; temporaryDirectory = createTempDir(); orcFile = new File(temporaryDirectory, randomUUID().toString()); writeOrcColumnHive(orcFile, ORC_12, NONE, type, createValues()); } @TearDown public void tearDown() throws IOException { deleteRecursively(temporaryDirectory.toPath(), ALLOW_INSECURE); } public Type getType() { return type; } public String getTypeSignature() { return typeSignature; } protected abstract List<?> createValues(); public OrcSelectiveRecordReader createRecordReader(Optional<TupleDomainFilter> filter) throws IOException { OrcDataSource dataSource = new FileOrcDataSource(orcFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( dataSource, ORC, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), NOOP_ORC_AGGREGATED_MEMORY_CONTEXT, OrcReaderTestingUtils.createDefaultTestConfig(), false, NO_ENCRYPTION); return orcReader.createSelectiveRecordReader( ImmutableMap.of(0, type), ImmutableList.of(0), filter.isPresent() ? ImmutableMap.of(0, ImmutableMap.of(new Subfield("c"), filter.get())) : ImmutableMap.of(), ImmutableList.of(), ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), OrcPredicate.TRUE, 0, dataSource.getSize(), UTC, // arbitrary true, new TestingHiveOrcAggregatedMemoryContext(), Optional.empty(), INITIAL_BATCH_SIZE, ImmutableMap.of()); } } @State(Scope.Thread) public static class AllNullBenchmarkData extends AbstractBenchmarkData { @SuppressWarnings("unused") @Param({ "boolean", "integer", "bigint", "smallint", "tinyint", "date", "timestamp", "real", "double", "decimal(10,5)", "decimal(30,10)", "varchar_direct", "varchar_dictionary" }) private String typeSignature; @Setup public void setup() throws Exception { setup(typeSignature); } @Override protected final List<?> createValues() { return NULL_VALUES; } } @State(Scope.Thread) public static class BenchmarkData extends AbstractBenchmarkData { @SuppressWarnings("unused") @Param({ "boolean", "integer", "bigint", "smallint", "tinyint", "date", "timestamp", "real", "double", "decimal(10,5)", "decimal(30,10)", "varchar_direct", "varchar_dictionary" }) private String typeSignature; @SuppressWarnings("unused") @Param({"true", "false"}) private boolean withNulls; private Optional<TupleDomainFilter> filter; @Setup public void setup() throws Exception { setup(typeSignature); this.filter = getFilter(getType()); } public Optional<TupleDomainFilter> getFilter() { return filter; } private static Optional<TupleDomainFilter> getFilter(Type type) { if (type == BOOLEAN) { return Optional.of(BooleanValue.of(true, true)); } if (type == TINYINT || type == BIGINT || type == INTEGER || type == SMALLINT || type == DATE || type == TIMESTAMP) { return Optional.of(BigintRange.of(0, Long.MAX_VALUE, true)); } if (type == REAL) { return Optional.of(FloatRange.of(0, true, true, Integer.MAX_VALUE, true, true, true)); } if (type == DOUBLE) { return Optional.of(DoubleRange.of(.5, false, false, 2, false, false, false)); } if (type instanceof DecimalType) { if (((DecimalType) type).isShort()) { return Optional.of(BigintRange.of(0, Long.MAX_VALUE, true)); } return Optional.of(LongDecimalRange.of(0, 0, false, true, Long.MAX_VALUE, Long.MAX_VALUE, false, true, true)); } if (type instanceof VarcharType) { return Optional.of(BytesRange.of("0".getBytes(), false, Longs.toByteArray(Long.MAX_VALUE), false, true)); } throw new UnsupportedOperationException("Unsupported type: " + type); } @Override protected final List<?> createValues() { if (withNulls) { return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); } return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } private final Object createValue() { if (getType() == BOOLEAN) { return random.nextBoolean(); } if (getType() == BIGINT) { return random.nextLong(); } if (getType() == INTEGER) { return random.nextInt(); } if (getType() == SMALLINT) { return (short) random.nextInt(); } if (getType() == TINYINT) { return (byte) random.nextInt(); } if (getType() == DATE) { return new SqlDate(random.nextInt()); } if (getType() == TIMESTAMP) { return new SqlTimestamp(random.nextLong(), TimeZoneKey.UTC_KEY); } if (getType() == REAL) { return random.nextFloat(); } if (getType() == DOUBLE) { return random.nextDouble(); } if (getType() instanceof DecimalType) { if (Decimals.isShortDecimal(getType())) { return new SqlDecimal(BigInteger.valueOf(random.nextLong() % 10_000_000_000L), SHORT_DECIMAL_TYPE.getPrecision(), SHORT_DECIMAL_TYPE.getScale()); } else { return new SqlDecimal(BigInteger.valueOf(random.nextLong() % 10_000_000_000L), LONG_DECIMAL_TYPE.getPrecision(), LONG_DECIMAL_TYPE.getScale()); } } if (getType() == VARCHAR) { if (typeSignature.equals("varchar_dictionary")) { return Strings.repeat("0", MAX_STRING_LENGTH); } return randomAsciiString(random, MAX_STRING_LENGTH); } throw new UnsupportedOperationException("Unsupported type: " + getType()); } } private static String randomAsciiString(Random random, int maxLength) { char[] value = new char[random.nextInt(maxLength)]; for (int i = 0; i < value.length; i++) { value[i] = (char) random.nextInt(Byte.MAX_VALUE); } return new String(value); } public static void main(String[] args) throws Throwable { Options options = new OptionsBuilder() .verbosity(VerboseMode.NORMAL) .include(".*" + BenchmarkSelectiveStreamReaders.class.getSimpleName() + ".*") .build(); new Runner(options).run(); } }
{ "content_hash": "5bb1aec0a6f627b5db1313771e4ff591", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 165, "avg_line_length": 35.30769230769231, "alnum_prop": 0.6155674390968509, "repo_name": "twitter-forks/presto", "id": "9c04654e4c9e8ef8bb8b6b9e9e38ca829e19e68f", "size": "15147", "binary": false, "copies": "1", "ref": "refs/heads/twitter-master", "path": "presto-orc/src/test/java/com/facebook/presto/orc/BenchmarkSelectiveStreamReaders.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "26944" }, { "name": "CSS", "bytes": "12676" }, { "name": "HTML", "bytes": "50340" }, { "name": "Java", "bytes": "30663750" }, { "name": "JavaScript", "bytes": "203196" }, { "name": "Makefile", "bytes": "6822" }, { "name": "PLSQL", "bytes": "3891" }, { "name": "Python", "bytes": "7552" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "28316" }, { "name": "TSQL", "bytes": "161763" }, { "name": "Thrift", "bytes": "16916" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Shlinkio\Shlink\CLI\Util; use Cake\Chronos\Chronos; use GeoIp2\Database\Reader; use Shlinkio\Shlink\CLI\Exception\GeolocationDbUpdateFailedException; use Shlinkio\Shlink\IpGeolocation\Exception\RuntimeException; use Shlinkio\Shlink\IpGeolocation\GeoLite2\DbUpdaterInterface; use Symfony\Component\Lock\LockFactory; class GeolocationDbUpdater implements GeolocationDbUpdaterInterface { private const LOCK_NAME = 'geolocation-db-update'; private DbUpdaterInterface $dbUpdater; private Reader $geoLiteDbReader; private LockFactory $locker; public function __construct(DbUpdaterInterface $dbUpdater, Reader $geoLiteDbReader, LockFactory $locker) { $this->dbUpdater = $dbUpdater; $this->geoLiteDbReader = $geoLiteDbReader; $this->locker = $locker; } /** * @throws GeolocationDbUpdateFailedException */ public function checkDbUpdate(?callable $mustBeUpdated = null, ?callable $handleProgress = null): void { $lock = $this->locker->createLock(self::LOCK_NAME); $lock->acquire(true); // Block until lock is released try { $this->downloadIfNeeded($mustBeUpdated, $handleProgress); } finally { $lock->release(); } } /** * @throws GeolocationDbUpdateFailedException */ private function downloadIfNeeded(?callable $mustBeUpdated, ?callable $handleProgress): void { if (! $this->dbUpdater->databaseFileExists()) { $this->downloadNewDb(false, $mustBeUpdated, $handleProgress); return; } $meta = $this->geoLiteDbReader->metadata(); if ($this->buildIsTooOld($meta->buildEpoch)) { $this->downloadNewDb(true, $mustBeUpdated, $handleProgress); } } /** * @throws GeolocationDbUpdateFailedException */ private function downloadNewDb(bool $olderDbExists, ?callable $mustBeUpdated, ?callable $handleProgress): void { if ($mustBeUpdated !== null) { $mustBeUpdated($olderDbExists); } try { $this->dbUpdater->downloadFreshCopy($handleProgress); } catch (RuntimeException $e) { throw GeolocationDbUpdateFailedException::create($olderDbExists, $e); } } private function buildIsTooOld(int $buildTimestamp): bool { $buildDate = Chronos::createFromTimestamp($buildTimestamp); $now = Chronos::now(); return $now->gt($buildDate->addDays(35)); } }
{ "content_hash": "b0f037d8d0bfa9998966578b731d52bc", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 114, "avg_line_length": 31.097560975609756, "alnum_prop": 0.6592156862745098, "repo_name": "acelaya/shlink", "id": "fd40fc15a60e6ab21c07ef4c1c242b1130728f69", "size": "2550", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "module/CLI/src/Util/GeolocationDbUpdater.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "5199" }, { "name": "HTML", "bytes": "2659" }, { "name": "PHP", "bytes": "550608" }, { "name": "Shell", "bytes": "4645" } ], "symlink_target": "" }
<?php namespace Adteam\Core\Checkout\Entity; use Doctrine\ORM\Mapping as ORM; /** * OauthUsers * * @ORM\Table(name="oauth_users", uniqueConstraints={@ORM\UniqueConstraint(name="AK_username", columns={"username"}), @ORM\UniqueConstraint(name="AK_email", columns={"email"})}, indexes={@ORM\Index(name="role_id", columns={"role_id"}), @ORM\Index(name="oauth_users_ibfk_2", columns={"created_by_id"})}) * @ORM\Entity */ class OauthUsers { /** * @var integer * * @ORM\Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="username", type="string", length=255, precision=0, scale=0, nullable=false, unique=false) */ private $username; /** * @var string * * @ORM\Column(name="password", type="string", length=2000, precision=0, scale=0, nullable=true, unique=false) */ private $password; /** * @var string * * @ORM\Column(name="first_name", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $firstName; /** * @var string * * @ORM\Column(name="last_name", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $lastName; /** * @var string * * @ORM\Column(name="surname", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $surname; /** * @var string * * @ORM\Column(name="email", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $email; /** * @var string * * @ORM\Column(name="display_name", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $displayName; /** * @var boolean * * @ORM\Column(name="enabled", type="boolean", precision=0, scale=0, nullable=false, unique=false) */ private $enabled; /** * @var boolean * * @ORM\Column(name="profile_fulfilled", type="boolean", precision=0, scale=0, nullable=false, unique=false) */ private $profileFulfilled; /** * @var string * * @ORM\Column(name="telephone1", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $telephone1; /** * @var string * * @ORM\Column(name="telephone2", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $telephone2; /** * @var string * * @ORM\Column(name="mobile", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $mobile; /** * @var \DateTime * * @ORM\Column(name="birthday", type="date", precision=0, scale=0, nullable=true, unique=false) */ private $birthday; /** * @var string * * @ORM\Column(name="gender", type="string", precision=0, scale=0, nullable=true, unique=false) */ private $gender; /** * @var string * * @ORM\Column(name="job_title", type="string", length=255, precision=0, scale=0, nullable=true, unique=false) */ private $jobTitle; /** * @var \DateTime * * @ORM\Column(name="created_at", type="datetime", precision=0, scale=0, nullable=false, unique=false) */ private $createdAt; /** * @var \DateTime * * @ORM\Column(name="modified_at", type="datetime", precision=0, scale=0, nullable=true, unique=false) */ private $modifiedAt; /** * @var \Application\Entity\CoreRoles * * @ORM\ManyToOne(targetEntity="Adteam\Core\Checkout\Entity\CoreRoles") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="role_id", referencedColumnName="id", nullable=true) * }) */ private $role; /** * @var \Adteam\Core\Checkout\Entity\OauthUsers * * @ORM\ManyToOne(targetEntity="Adteam\Core\Checkout\Entity\OauthUsers") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="created_by_id", referencedColumnName="id", nullable=true) * }) */ private $createdBy; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set username * * @param string $username * * @return OauthUsers */ public function setUsername($username) { $this->username = $username; return $this; } /** * Get username * * @return string */ public function getUsername() { return $this->username; } /** * Set password * * @param string $password * * @return OauthUsers */ public function setPassword($password) { $this->password = $password; return $this; } /** * Get password * * @return string */ public function getPassword() { return $this->password; } /** * Set firstName * * @param string $firstName * * @return OauthUsers */ public function setFirstName($firstName) { $this->firstName = $firstName; return $this; } /** * Get firstName * * @return string */ public function getFirstName() { return $this->firstName; } /** * Set lastName * * @param string $lastName * * @return OauthUsers */ public function setLastName($lastName) { $this->lastName = $lastName; return $this; } /** * Get lastName * * @return string */ public function getLastName() { return $this->lastName; } /** * Set surname * * @param string $surname * * @return OauthUsers */ public function setSurname($surname) { $this->surname = $surname; return $this; } /** * Get surname * * @return string */ public function getSurname() { return $this->surname; } /** * Set email * * @param string $email * * @return OauthUsers */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set displayName * * @param string $displayName * * @return OauthUsers */ public function setDisplayName($displayName) { $this->displayName = $displayName; return $this; } /** * Get displayName * * @return string */ public function getDisplayName() { return $this->displayName; } /** * Set enabled * * @param boolean $enabled * * @return OauthUsers */ public function setEnabled($enabled) { $this->enabled = $enabled; return $this; } /** * Get enabled * * @return boolean */ public function getEnabled() { return $this->enabled; } /** * Set profileFulfilled * * @param boolean $profileFulfilled * * @return OauthUsers */ public function setProfileFulfilled($profileFulfilled) { $this->profileFulfilled = $profileFulfilled; return $this; } /** * Get profileFulfilled * * @return boolean */ public function getProfileFulfilled() { return $this->profileFulfilled; } /** * Set telephone1 * * @param string $telephone1 * * @return OauthUsers */ public function setTelephone1($telephone1) { $this->telephone1 = $telephone1; return $this; } /** * Get telephone1 * * @return string */ public function getTelephone1() { return $this->telephone1; } /** * Set telephone2 * * @param string $telephone2 * * @return OauthUsers */ public function setTelephone2($telephone2) { $this->telephone2 = $telephone2; return $this; } /** * Get telephone2 * * @return string */ public function getTelephone2() { return $this->telephone2; } /** * Set mobile * * @param string $mobile * * @return OauthUsers */ public function setMobile($mobile) { $this->mobile = $mobile; return $this; } /** * Get mobile * * @return string */ public function getMobile() { return $this->mobile; } /** * Set birthday * * @param \DateTime $birthday * * @return OauthUsers */ public function setBirthday($birthday) { $this->birthday = $birthday; return $this; } /** * Get birthday * * @return \DateTime */ public function getBirthday() { return $this->birthday; } /** * Set gender * * @param string $gender * * @return OauthUsers */ public function setGender($gender) { $this->gender = $gender; return $this; } /** * Get gender * * @return string */ public function getGender() { return $this->gender; } /** * Set jobTitle * * @param string $jobTitle * * @return OauthUsers */ public function setJobTitle($jobTitle) { $this->jobTitle = $jobTitle; return $this; } /** * Get jobTitle * * @return string */ public function getJobTitle() { return $this->jobTitle; } /** * Set createdAt * * @param \DateTime $createdAt * * @return OauthUsers */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * Set modifiedAt * * @param \DateTime $modifiedAt * * @return OauthUsers */ public function setModifiedAt($modifiedAt) { $this->modifiedAt = $modifiedAt; return $this; } /** * Get modifiedAt * * @return \DateTime */ public function getModifiedAt() { return $this->modifiedAt; } /** * Set role * * @param \Application\Entity\CoreRoles $role * * @return OauthUsers */ public function setRole(\Adteam\Core\Checkout\Entity\CoreRoles $role = null) { $this->role = $role; return $this; } /** * Get role * * @return \Application\Entity\CoreRoles */ public function getRole() { return $this->role; } /** * Set createdBy * * @param \Application\Entity\OauthUsers $createdBy * * @return OauthUsers */ public function setCreatedBy(\Adteam\Core\Checkout\Entity\OauthUsers $createdBy = null) { $this->createdBy = $createdBy; return $this; } /** * Get createdBy * * @return \Application\Entity\OauthUsers */ public function getCreatedBy() { return $this->createdBy; } }
{ "content_hash": "e11e3f9fe7300d9f4a0ce3ee217bdbcb", "timestamp": "", "source": "github", "line_count": 630, "max_line_length": 302, "avg_line_length": 18.503174603174603, "alnum_prop": 0.5258642875525436, "repo_name": "CookieShop/core-checkout", "id": "8a3bcbb77a35e03981de0dc698dd5ebf2ee96676", "size": "11657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Entity/OauthUsers.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "143310" } ], "symlink_target": "" }
<?php /** string hint */ "Package %s's source key should be specified as {\"type\": ..., \"url\": ..., \"reference\": ...},\n%s given."; ?> <<<TEST>>> "GlobalCode":{"NamingContext":{}, "PHPDocStmt":{"PHPDoc":{"Comment":"stringhint"}}, "StringLiteral":{"Value":"Package %s's source key should be specified as {"type": ..., "url": ..., "reference": ...},%s given."}, "EchoStmt":{"StringLiteral":{"Value":""}} }
{ "content_hash": "75d3a02f6ed7d9d11aa1b284f9d04e27", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 131, "avg_line_length": 30.357142857142858, "alnum_prop": 0.5552941176470588, "repo_name": "DEVSENSE/Parsers", "id": "91b2dbe361bb35be820416a9aca9f753e95608f6", "size": "425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/UnitTests/TestData/parser/ArrayLoader.phpt", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "784" }, { "name": "C#", "bytes": "2922707" }, { "name": "Lex", "bytes": "21560" }, { "name": "PHP", "bytes": "578766" }, { "name": "Yacc", "bytes": "69592" } ], "symlink_target": "" }
<?php namespace yariksav\actives\view\plugins; use yii; class InfinityScroll extends Plugin { public $pageSize = 20; public $page = 0; function init() { $this->registerEvents(); parent::init(); } protected function registerEvents() { $this->owner->on('beforeData', function ($event) { $owner = $event->sender; $provider = $owner->provider; $provider->pagination->pageSize = $this->pageSize; $provider->pagination->page = $this->page; }, [$this]); } public function build() { return array_merge(parent::build(), [ 'pageSize' => $this->pageSize, ]); } /* public function getPageSize() { if ($this->owner->method === 'init') { $this->_pageSize = $this->owner->getState($this->name.'size', $this->_pageSize); } return $this->_pageSize; } public function setPageSize($value) { $this->_pageSize = $value; if ($this->owner->method === 'load') { $this->owner->setState($this->name.'size', $value); } }*/ }
{ "content_hash": "856564c8ddf20e2d6863269a27dfc488", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 92, "avg_line_length": 25.818181818181817, "alnum_prop": 0.5299295774647887, "repo_name": "yariksav/yii2-actives", "id": "e13073895b931ceedd17cf9f2baf0f5f94045540", "size": "1136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "view/plugins/InfinityScroll.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "193827" } ], "symlink_target": "" }
<?php session_start(); require_once("../../vars.php"); $res = array(); if (isset($_SESSION['admin_user_id']) && $_SESSION['admin_user_id']){ header('Content-type: text/html; charset=utf-8'); $uploaddir = "$basepath/thumbs/"; $basename = $_FILES['userfile']['name']; $cleanname = "ethumb_".md5(basename($_FILES['userfile']['name'])).".jpg"; $uploadfile = $uploaddir . $cleanname; if ((substr_count($basename,".jpg")) || (substr_count($basename,".jpeg")) || (substr_count($basename,".gif")) || (substr_count($basename,".png"))){ if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { $res['status'] = 1; $res['message'] = $cleanname; } else { $res['status'] = 0; $res['message'] = "Unexpected error occured. Please try again"; } } else { $res['status'] = 0; $res['message'] = "Invalid file type"; } } else { $res['status'] = 0; $res['message'] = "Session timeout error. Please login again"; } print(json_encode($res)); ?>
{ "content_hash": "3185bb1ee9a12cd18e967e4f9714014f", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 148, "avg_line_length": 27.333333333333332, "alnum_prop": 0.5955284552845529, "repo_name": "DeeJaVu/tvstreamscript", "id": "973f78c5fc555ebbc0b79a1226911d0f887bd368", "size": "984", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "control/ajax/episode_thumbnail_upload.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "15950" }, { "name": "CSS", "bytes": "785408" }, { "name": "JavaScript", "bytes": "2082010" }, { "name": "PHP", "bytes": "3119608" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ ~ WSO2 Inc. licenses this file to you 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <groupId>org.wso2.carbon.devicemgt-plugins</groupId> <artifactId>virtual-fire-alarm-plugin-feature</artifactId> <version>4.0.35-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics.feature</artifactId> <packaging>pom</packaging> <name>WSO2 Carbon - IoT Server VirtualFireAlarm Analytics Feature</name> <url>http://wso2.org</url> <description>This feature contains the VirtualFireAlarm Device type specific analytics implementations for the IoT Server </description> <build> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-resources</id> <phase>generate-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>src/main/resources</outputDirectory> <resources> <resource> <directory>resources</directory> <includes> <include>build.properties</include> <include>p2.inf</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>unpack</id> <phase>package</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>org.wso2.carbon.devicemgt-plugins</groupId> <artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics </artifactId> <version>${project.version}</version> <type>zip</type> <overWrite>true</overWrite> <outputDirectory> ${project.build.directory}/maven-shared-archive-resources/carbonapps </outputDirectory> <includes>**/*</includes> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.wso2.maven</groupId> <artifactId>carbon-p2-plugin</artifactId> <version>${carbon.p2.plugin.version}</version> <executions> <execution> <id>p2-feature-generation</id> <phase>package</phase> <goals> <goal>p2-feature-gen</goal> </goals> <configuration> <id>org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics</id> <propertiesFile>../../../features/etc/feature.properties</propertiesFile> <adviceFile> <properties> <propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef> <propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef> </properties> </adviceFile> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "d88e1d5aa4da8bc174dc5118ad37c7e2", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 201, "avg_line_length": 31.84552845528455, "alnum_prop": 0.6540719938728619, "repo_name": "warunalakshitha/carbon-device-mgt-plugins", "id": "7d6c2daf31b73b23757c9c038ddbad273e0ae968", "size": "3917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "features/device-types-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics.feature/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "14451" }, { "name": "Batchfile", "bytes": "912" }, { "name": "C", "bytes": "2475" }, { "name": "CSS", "bytes": "977941" }, { "name": "HTML", "bytes": "738697" }, { "name": "Java", "bytes": "2952742" }, { "name": "JavaScript", "bytes": "13542353" }, { "name": "PLSQL", "bytes": "3627" }, { "name": "Python", "bytes": "36810" }, { "name": "Shell", "bytes": "16631" } ], "symlink_target": "" }
package com.suscipio_solutions.consecro_mud.Items.Weapons; import com.suscipio_solutions.consecro_mud.Common.interfaces.PhyStats; import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial; import com.suscipio_solutions.consecro_mud.core.CMLib; public class DrowSword extends Longsword { @Override public String ID(){ return "DrowSword";} public DrowSword() { super(); setName("a longsword"); setDisplayText("a fancy longsword has been dropped on the ground."); setDescription("A one-handed sword with a very dark blade."); secretIdentity="A Drow Sword"; basePhyStats().setAbility(CMLib.dice().roll(1,6,0)); basePhyStats().setLevel(1); basePhyStats().setWeight(4); basePhyStats().setAttackAdjustment(0); basePhyStats().setDamage(8); basePhyStats().setDisposition(basePhyStats().disposition()|PhyStats.IS_BONUS); baseGoldValue=2500; recoverPhyStats(); material=RawMaterial.RESOURCE_STEEL; weaponType=TYPE_SLASHING; } }
{ "content_hash": "73fcde13c660a4fe08a6935f169b9785", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 80, "avg_line_length": 29.454545454545453, "alnum_prop": 0.7613168724279835, "repo_name": "ConsecroMUD/ConsecroMUD", "id": "be34bd1e742c1e209715c1e8e7a6c36b40ea1c86", "size": "972", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com/suscipio_solutions/consecro_mud/Items/Weapons/DrowSword.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1413" }, { "name": "Java", "bytes": "21670655" }, { "name": "JavaScript", "bytes": "23366" }, { "name": "Perl", "bytes": "732" }, { "name": "Shell", "bytes": "6214" } ], "symlink_target": "" }
<br/> <div style="text-align:center;"> <button class="button large hollow warning" (click)="getOldData()">Get Normal Data</button> <button class="button large hollow warning" (click)="getArrayedData()">Get Arrayed Data</button> <button class="button large hollow warning" (click)="printData()">Print JSON to Console</button> <button *ngIf="polling == true" class="button large hollow warning" (click)="toggleTick()">Speed Up Time</button> <button *ngIf="polling == false" class="button large hollow warning" (click)="toggleTick()">Reset Time</button> </div> <!-- The question mark indicated in Angular API as an Elvis operator will wait for schedules to be non-null before rendering the values below it --> <div *ngIf="visible"> <div *ngIf="arrayed" class="centerText"> <br/> <h2 class="gold">Today is: {{date}} {{convertToReadableTime(hour)}}</h2> <div class="small-12" *ngFor="#building of schedules?.schedules;"> <div class="row openHeader" *ngIf="isOpen(building)"> <div class="small-3 columns"> <h1><a href="{{building.map_url}}" target="_blank">{{building.name}}</a></h1> </div> <div class="small-3 columns"> <div><h2 class="gold">{{generateHours(building, true)}}</h2></div> </div> <div class="small-3 columns"> <div> <h2 class="gold">{{generateHours(building, false)}}</h2> </div> </div> <div class="small-3 columns"> <div><h2 class="gold">Open</h2></div> </div> </div> <div class="row closedHeader" *ngIf="!isOpen(building)"> <div class="small-3 columns"> <h1><a href="{{building.map_url}}" target="_blank">{{building.name}}</a></h1> </div> <div class="small-6 columns"> <div><h2 class="gold">Card Accesible</h2></div> </div> <div class="small-3 columns"> <div> <h2 class="gold">Closed</h2> </div> </div> </div> <div class="row"> <table class="mainTable"> <tr> <th>Name</th> <th>Service</th> <th>Open</th> <th>Close</th> </tr> <tr *ngFor="#place of building.places;"> <td [ngClass]="{'closed': !isOpen(place)}">{{place.name}}</td> <td *ngIf="isOpen(place)">{{place.times[getCurrentDay(place)].hours[getCurrentHours(place, getCurrentDay(place))].name}}</td> <td *ngIf="isOpen(place)">{{generateHours(place, true)}}</td> <td *ngIf="isOpen(place)">{{generateHours(place, false)}}</td> <td *ngIf="!isOpen(place)" class="closed">Closed</td> <td *ngIf="!isOpen(place)" class="closed">---</td> <td *ngIf="!isOpen(place)" class="closed">---</td> </tr> </table> </div> </div> </div> <div *ngIf="!arrayed" class="centerText"> <h2 class="gold">Raw Data</h2> <h5 class="gold">{{schedules?.schedules | json}}</h5> </div> </div>
{ "content_hash": "77c58ff37d679439989902b9afc8f67b", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 148, "avg_line_length": 36.68421052631579, "alnum_prop": 0.6079626972740315, "repo_name": "kylewistrand/IsUWOpen", "id": "c3ae1e598f3f736cb87bd32028714d0c52abaf6b", "size": "2788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "partials/main.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "409" }, { "name": "HTML", "bytes": "5475" }, { "name": "JavaScript", "bytes": "11099" }, { "name": "TypeScript", "bytes": "4266" } ], "symlink_target": "" }
#ifndef _DRIVER_NL80211_H_ #define _DRIVER_NL80211_H_ #include "includes.h" #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <net/if.h> #include <netlink/genl/genl.h> #include <netlink/genl/family.h> #include <netlink/genl/ctrl.h> #include <linux/rtnetlink.h> #include <netpacket/packet.h> #include <linux/filter.h> #include "nl80211_copy.h" #include "common.h" #include "eloop.h" #include "utils/list.h" #include "common/ieee802_11_defs.h" #include "netlink.h" #include "linux_ioctl.h" #include "radiotap.h" #include "radiotap_iter.h" #include "rfkill.h" #include "driver.h" #ifdef CONFIG_LIBNL20 /* libnl 2.0 compatibility code */ #define nl_handle nl_sock #define nl80211_handle_alloc nl_socket_alloc_cb #define nl80211_handle_destroy nl_socket_free #endif /* CONFIG_LIBNL20 */ #ifndef IFF_LOWER_UP #define IFF_LOWER_UP 0x10000 /* driver signals L1 up */ #endif #ifndef IFF_DORMANT #define IFF_DORMANT 0x20000 /* driver signals dormant */ #endif #ifndef IF_OPER_DORMANT #define IF_OPER_DORMANT 5 #endif #ifndef IF_OPER_UP #define IF_OPER_UP 6 #endif struct nl80211_global { struct dl_list interfaces; }; struct i802_bss { struct wpa_driver_nl80211_data *drv; struct i802_bss *next; int ifindex; char ifname[IFNAMSIZ + 1]; char brname[IFNAMSIZ]; unsigned int beacon_set:1; unsigned int added_if_into_bridge:1; unsigned int added_bridge:1; }; struct wpa_driver_nl80211_data { struct nl80211_global *global; struct dl_list list; u8 addr[ETH_ALEN]; char phyname[32]; void *ctx; struct netlink_data *netlink; int ioctl_sock; /* socket for ioctl() use */ int ifindex; int if_removed; int if_disabled; struct rfkill_data *rfkill; struct wpa_driver_capa capa; int has_capability; int operstate; int scan_complete_events; struct nl_handle *nl_handle; struct nl_handle *nl_handle_event; struct nl_handle *nl_handle_preq; struct nl_cache *nl_cache; struct nl_cache *nl_cache_event; struct nl_cache *nl_cache_preq; struct nl_cb *nl_cb; struct genl_family *nl80211; u8 auth_bssid[ETH_ALEN]; u8 bssid[ETH_ALEN]; int associated; u8 ssid[32]; size_t ssid_len; int nlmode; int ap_scan_as_station; unsigned int assoc_freq; int monitor_sock; int monitor_ifidx; int no_monitor_iface_capab; int disable_11b_rates; unsigned int pending_remain_on_chan:1; u64 remain_on_chan_cookie; u64 send_action_cookie; unsigned int last_mgmt_freq; unsigned int ap_oper_freq; struct wpa_driver_scan_filter *filter_ssids; size_t num_filter_ssids; struct i802_bss first_bss; #ifdef HOSTAPD int eapol_sock; /* socket for EAPOL frames */ int default_if_indices[16]; int *if_indices; int num_if_indices; int last_freq; int last_freq_ht; #endif /* HOSTAPD */ }; #endif
{ "content_hash": "78a376abd08b24882bf5be9efa056864", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 73, "avg_line_length": 20.84328358208955, "alnum_prop": 0.7157178660938059, "repo_name": "Str1ker17/android_device_samsung_delos3geur", "id": "7d19995b7f83d701b8d9c537c4ce6348fdec3edb", "size": "3452", "binary": false, "copies": "3", "ref": "refs/heads/cm-10.1", "path": "wifi/wpa_supplicant_8_lib/driver_nl80211.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "491881" }, { "name": "C++", "bytes": "574693" }, { "name": "Java", "bytes": "61050" }, { "name": "Makefile", "bytes": "24290" }, { "name": "Objective-C", "bytes": "3739" }, { "name": "PHP", "bytes": "3995" }, { "name": "Shell", "bytes": "98257" } ], "symlink_target": "" }
layout: post title: "My view on Deep Work" description: "" headline: modified: 2019-05-21 category: Productivity tags: [productivity] imagefeature: mathjax: chart: comments: true featured: false --- Naveen asked me to write [for him](https://docs.google.com/document/d/1EbSu5K4tDEaMAnJFL35qwUgh_uw8S2HZQhH7ekJiDrM/). Reposting my response here. Below is his note to me. `Surya, I understand you like the work of Cal Newport on Deep Work which you have been for quite some time. I was wondering if you can share your experience with us which I think can be quite beneficial for anyone reading it. To start off, I've listed three simple questions, you can add more details if you'd like to.`** My response to it is below. **In short, how do you define Deep Work?** * Planned 0-distraction pomodoro sessions on a single task. Many tricks on how to do it effectively are shared in the book which are quite helpful. (ex. making grand gestures, having a shutdown routine, tracking progress during session, maintaining a scorecard, pomodoros, etc.) **What are the preparations you do before hand for this?** * I plan (but not as much as I should yet). I minimize distractions-- turn off internet block software, keep water next to me, eat sometime if I'm hungry, turn off my phone. If I'm feeling lazy/tired, I follow Spencer Greenberg's Cool Reboot strategy to feel more active. **Can you please your experience so far and how helpful it has been? (If you can add one or two specific experiences that'd be great)** * It's been a wonderful experience, I'm happy that I'm experimenting with these ideas. I have good and bad sessions. In good sessions, I go into the experience of flow (which is the most pleasurable experience in life). In bad sessions, I kinda push myself to make it through. Still figuring out and experimenting to understand what leads to good and bad sessions. * Somedays, due to external factors, a complete 0-distraction is not possible. It's okay, just try to minimize them as much as you can and keep going. Doesn't always have to be deep work.
{ "content_hash": "a89d7c4dbf6b79817d4dd0048a5ca08f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 365, "avg_line_length": 71.55172413793103, "alnum_prop": 0.7701204819277109, "repo_name": "psurya1994/psurya1994.github.io", "id": "01f039d053ec278aafaa5109d7f7c41ba21f26f0", "size": "2079", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2019-05-21-my-view-on-deep-work.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "74516" }, { "name": "CSS", "bytes": "52263" }, { "name": "HTML", "bytes": "30767" }, { "name": "JavaScript", "bytes": "2198" }, { "name": "Smalltalk", "bytes": "3" } ], "symlink_target": "" }
package com.amazonaws.services.appstream.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.appstream.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Fleet JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class FleetJsonUnmarshaller implements Unmarshaller<Fleet, JsonUnmarshallerContext> { public Fleet unmarshall(JsonUnmarshallerContext context) throws Exception { Fleet fleet = new Fleet(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Arn", targetDepth)) { context.nextToken(); fleet.setArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Name", targetDepth)) { context.nextToken(); fleet.setName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("DisplayName", targetDepth)) { context.nextToken(); fleet.setDisplayName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Description", targetDepth)) { context.nextToken(); fleet.setDescription(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ImageName", targetDepth)) { context.nextToken(); fleet.setImageName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ImageArn", targetDepth)) { context.nextToken(); fleet.setImageArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("InstanceType", targetDepth)) { context.nextToken(); fleet.setInstanceType(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("FleetType", targetDepth)) { context.nextToken(); fleet.setFleetType(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ComputeCapacityStatus", targetDepth)) { context.nextToken(); fleet.setComputeCapacityStatus(ComputeCapacityStatusJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("MaxUserDurationInSeconds", targetDepth)) { context.nextToken(); fleet.setMaxUserDurationInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("DisconnectTimeoutInSeconds", targetDepth)) { context.nextToken(); fleet.setDisconnectTimeoutInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("State", targetDepth)) { context.nextToken(); fleet.setState(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("VpcConfig", targetDepth)) { context.nextToken(); fleet.setVpcConfig(VpcConfigJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("CreatedTime", targetDepth)) { context.nextToken(); fleet.setCreatedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("FleetErrors", targetDepth)) { context.nextToken(); fleet.setFleetErrors(new ListUnmarshaller<FleetError>(FleetErrorJsonUnmarshaller.getInstance()).unmarshall(context)); } if (context.testExpression("EnableDefaultInternetAccess", targetDepth)) { context.nextToken(); fleet.setEnableDefaultInternetAccess(context.getUnmarshaller(Boolean.class).unmarshall(context)); } if (context.testExpression("DomainJoinInfo", targetDepth)) { context.nextToken(); fleet.setDomainJoinInfo(DomainJoinInfoJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("IdleDisconnectTimeoutInSeconds", targetDepth)) { context.nextToken(); fleet.setIdleDisconnectTimeoutInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return fleet; } private static FleetJsonUnmarshaller instance; public static FleetJsonUnmarshaller getInstance() { if (instance == null) instance = new FleetJsonUnmarshaller(); return instance; } }
{ "content_hash": "4d0718bc9a18aa2c747f10e128241786", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 137, "avg_line_length": 47.33587786259542, "alnum_prop": 0.5913562328656669, "repo_name": "jentfoo/aws-sdk-java", "id": "e70084ded9b137e4b35363a245cab7079e2e41ce", "size": "6781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-appstream/src/main/java/com/amazonaws/services/appstream/model/transform/FleetJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: ./analysis/common/src/java/org/apache/lucene/analysis/hu/package-info.java // /*! @brief Analyzer for Hungarian. */ #include "J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_OrgApacheLuceneAnalysisHuPackage_info") #ifdef RESTRICT_OrgApacheLuceneAnalysisHuPackage_info #define INCLUDE_ALL_OrgApacheLuceneAnalysisHuPackage_info 0 #else #define INCLUDE_ALL_OrgApacheLuceneAnalysisHuPackage_info 1 #endif #undef RESTRICT_OrgApacheLuceneAnalysisHuPackage_info #if __has_feature(nullability) #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wnullability" #pragma GCC diagnostic ignored "-Wnullability-completeness" #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneAnalysisHuPackage_info")
{ "content_hash": "4f429a770ba759ad091957804080cf55", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 86, "avg_line_length": 29.137931034482758, "alnum_prop": 0.8023668639053254, "repo_name": "lukhnos/objclucene", "id": "586a444951905adaa6009942b1efed81ae2884d9", "size": "845", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/org/apache/lucene/analysis/hu/package-info.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "72674" }, { "name": "Objective-C", "bytes": "31684259" }, { "name": "Shell", "bytes": "491" } ], "symlink_target": "" }
#ifndef CBITS_ALLOC_H #define CBITS_ALLOC_H #include <stddef.h> /* Hopefully this won't collide with cstddef. */ struct BlockChain; /* For C++ linkage */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* TODO: comments. */ struct BlockChain *BlockChain_new(size_t blockSize); void BlockChain_retain(struct BlockChain *bc); void BlockChain_release(struct BlockChain *bc); void BlockChain_reset(struct BlockChain *bc, size_t blockSize); void *BlockChain_alloc(struct BlockChain *bc, size_t bytes, size_t align); size_t BlockChain_getBlockSize(struct BlockChain *bc); void BlockChain_setBlockSize(struct BlockChain *bc, size_t blockSize); size_t BlockChain_freeBytes(struct BlockChain *bc, size_t align); size_t BlockChain_canAlloc(struct BlockChain *bc, size_t nelem, size_t align); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !CBITS_ALLOC_H */
{ "content_hash": "25ad8ffa567b4443b9f072628ca75640", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 78, "avg_line_length": 28.193548387096776, "alnum_prop": 0.7379862700228833, "repo_name": "bassettmb/simple-block-alloc", "id": "704bef377c9c8bf40849e30bff52f6f4712a1a1d", "size": "874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cbits/BlockChain.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5773" }, { "name": "C++", "bytes": "3494" } ], "symlink_target": "" }
<?php namespace Native5\Identity; /** * SimpleAuthInfo * * @category Identity * @package Native5\<package> * @author Barada Sahu <barry@native5.com> * @copyright 2012 Native5. All Rights Reserved * @license See attached NOTICE.md for details * @version Release: 1.0 * @link http://www.docs.native5.com * Created : 27-11-2012 * Last Modified : Fri Dec 21 09:11:53 2012 */ class SimpleAuthInfo implements AuthInfo { private $_principals; private $_credentials; /** * Default Constructor * * @access public * @return void */ public function __construct() { $this->_principals = array(); $this->_credentials = array(); }//end __construct() /** * addPrincipal * * @param mixed $principal The Principal to add * * @access public * @return void */ public function addPrincipal($principal) { $this->_principals[] = $principal; }//end addPrincipal() /** * setPrincipals * * @param mixed $principals The principals to set * * @access public * @return void */ public function setPrincipals($principals) { $this->_principals = $principals; }//end setPrincipals() /** * setCredentials * * @param mixed $credentials The credentials to set. * * @access public * @return void */ public function setCredentials($credentials) { $this->_credentials = $credentials; }//end setCredentials() /** * getPrincipals * * @access public * @return void */ public function getPrincipals() { return $this->_principals; }//end getPrincipals() /** * getCredentials * * @access public * @return void */ public function getCredentials() { return $this->_credentials; }//end getCredentials() }//end class ?>
{ "content_hash": "0f4340af9822485e4f9b8ccb628c244c", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 56, "avg_line_length": 17.394736842105264, "alnum_prop": 0.5612708018154312, "repo_name": "native5/native5-sdk-client-php", "id": "2ff8e50c5a2525537162e990ad62757d7e4bcb11", "size": "2800", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "src/Native5/Identity/SimpleAuthInfo.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7870" }, { "name": "JavaScript", "bytes": "132848" }, { "name": "PHP", "bytes": "356980" } ], "symlink_target": "" }
def remove_letters(letters, word): for ch in word: del letters[letters.index(ch)] t = int(raw_input()) for case in xrange(1,t+1): numbers = [] letters = [x for x in raw_input()] #ZERO while 'Z' in letters: numbers.append(0) remove_letters(letters, 'ZERO') #TWO while 'W' in letters: numbers.append(2) remove_letters(letters, 'TWO') #FOUR while 'U' in letters: numbers.append(4) remove_letters(letters,'FOUR') #SIX while 'X' in letters: numbers.append(6) remove_letters(letters,'SIX') #EIGHT while 'G' in letters: numbers.append(8) remove_letters(letters,'EIGHT') #ONE while 'O' in letters: numbers.append(1) remove_letters(letters,'ONE') #THREE while 'T' in letters: numbers.append(3) remove_letters(letters,'THREE') #FIVE while 'F' in letters: numbers.append(5) remove_letters(letters,'FIVE') #SEVEN while 'S' in letters: numbers.append(7) remove_letters(letters,'SEVEN') #NINE while 'I' in letters: numbers.append(9) remove_letters(letters,'NINE') numbers.sort() print "Case #{}: {}".format(case, ''.join([str(x) for x in numbers]))
{ "content_hash": "c27c0df8df756afe141f7509ea375a00", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 73, "avg_line_length": 25.58823529411765, "alnum_prop": 0.5685823754789272, "repo_name": "clemus90/competitive-programming", "id": "2185630a80713a376d1426ddab1e42a7f4e61f19", "size": "1305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GoogleCodeJam/2016/round1B/a_getting_the_digits.py", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1067" }, { "name": "Java", "bytes": "30862" }, { "name": "JavaScript", "bytes": "4311" }, { "name": "Python", "bytes": "49167" }, { "name": "Scala", "bytes": "38749" } ], "symlink_target": "" }
import React from 'react'; import Dragger from './Dragger'; import { UploadProps } from './interface'; export interface UploadContext { antLocale?: { Upload?: any; }; } export { UploadProps }; export default class Upload extends React.Component<UploadProps, any> { static Dragger: typeof Dragger; static defaultProps: { prefixCls: string; type: string; multiple: boolean; action: string; data: {}; accept: string; beforeUpload: () => boolean; showUploadList: boolean; listType: string; className: string; disabled: boolean; supportServerRender: boolean; }; static contextTypes: { antLocale: any; }; context: UploadContext; recentUploadStatus: boolean | PromiseLike<any>; progressTimer: any; refs: { [key: string]: any; upload: any; }; constructor(props: any); componentWillUnmount(): void; getLocale(): { uploading?: string | undefined; removeFile?: string | undefined; uploadError?: string | undefined; previewFile?: string | undefined; } | { uploading?: string | undefined; removeFile?: string | undefined; uploadError?: string | undefined; previewFile?: string | undefined; }; onStart: (file: any) => void; autoUpdateProgress(_: any, file: any): void; onSuccess: (response: any, file: any) => void; onProgress: (e: any, file: any) => void; onError: (error: any, response: any, file: any) => void; handleRemove(file: any): void; handleManualRemove: (file: any) => void; onChange: (info: any) => void; componentWillReceiveProps(nextProps: any): void; onFileDrop: (e: any) => void; beforeUpload: (file: any, fileList: any) => boolean; clearProgressTimer(): void; render(): JSX.Element; }
{ "content_hash": "78b5c3a3773b72a0e8e042c1c4b17ecb", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 71, "avg_line_length": 30.64516129032258, "alnum_prop": 0.6052631578947368, "repo_name": "ligangwolai/blog", "id": "4e0339d35100bdfb532f4ab6e1c4fe26a8e1c314", "size": "1932", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/_antd@2.13.4@antd/es/upload/Upload.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "832" }, { "name": "HTML", "bytes": "282" }, { "name": "JavaScript", "bytes": "42612" } ], "symlink_target": "" }
MIT License Copyright (c) 2017 shubham2604 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{ "content_hash": "0b87e0b5feb66bdf21f8f9155e150355", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 78, "avg_line_length": 50.857142857142854, "alnum_prop": 0.8061797752808989, "repo_name": "shubham2604/nRf24-based-quadcopter", "id": "323593742cb73053346425d49cfe79db5303fb6c", "size": "1068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "license.md", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "16540" } ], "symlink_target": "" }
class TimeAttribute < Cms::ContentAttribute content_type :datetime def value=(time) if time.present? && value = Time.zone.parse(time) assign_value(value) else if content_value.present? content_value.destroy end end end end
{ "content_hash": "9737e18d12e772a57e0e277ead1fd2bf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 53, "avg_line_length": 20.615384615384617, "alnum_prop": 0.6529850746268657, "repo_name": "Promptus/cms", "id": "ec6e39de74dcadee9dbb06cd5f8d22b588ee4bfb", "size": "287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/cms/content_attributes/time_attribute.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59679" }, { "name": "HTML", "bytes": "42308" }, { "name": "JavaScript", "bytes": "15717" }, { "name": "Ruby", "bytes": "136861" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../../../test_helper' module SourceControl class Subversion::UpdateParserTest < Test::Unit::TestCase UPDATE_OUTPUT = <<EOF A failing_project D failing_project\\Rakefile U* failing_project\\failing_test.rb G failing_project\\revision_label.txt C B passing_project\\revision_label.txt ? foo.txt Fetching external item into 'vendor\rails' Updated external to revision 5875. Updated to revision 46. EOF def test_can_parse_UPDATE_OUTPUT expected_result = [ ChangesetEntry.new('A ', 'failing_project'), ChangesetEntry.new('D ', 'failing_project\Rakefile'), ChangesetEntry.new('U* ', 'failing_project\\failing_test.rb'), ChangesetEntry.new('G ', 'failing_project\\revision_label.txt'), ChangesetEntry.new('C B', 'passing_project\\revision_label.txt'), ChangesetEntry.new('? ', 'foo.txt')] assert_equal expected_result, parse_update(UPDATE_OUTPUT) end def parse_update(log_entry) Subversion::UpdateParser.new.parse(log_entry.split("\n")) end end end
{ "content_hash": "20e68827635e5a3b498936331a358bce", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 73, "avg_line_length": 29.486486486486488, "alnum_prop": 0.6764436296975253, "repo_name": "craigw/cruisecontrol.rb", "id": "268fde53e254b85b1c87113dcb90955439ec4559", "size": "1091", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "test/unit/source_control/subversion/update_parser_test.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "802" }, { "name": "Ruby", "bytes": "382367" } ], "symlink_target": "" }
<?php namespace Google\Service\DriveActivity; class Rename extends \Google\Model { /** * @var string */ public $newTitle; /** * @var string */ public $oldTitle; /** * @param string */ public function setNewTitle($newTitle) { $this->newTitle = $newTitle; } /** * @return string */ public function getNewTitle() { return $this->newTitle; } /** * @param string */ public function setOldTitle($oldTitle) { $this->oldTitle = $oldTitle; } /** * @return string */ public function getOldTitle() { return $this->oldTitle; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(Rename::class, 'Google_Service_DriveActivity_Rename');
{ "content_hash": "0dcb0844e13a53716c7816eefec4d8d1", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 81, "avg_line_length": 15.895833333333334, "alnum_prop": 0.6159895150720839, "repo_name": "googleapis/google-api-php-client-services", "id": "87a8819605a1697a7d6182aab23f2535a127a40c", "size": "1353", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "src/DriveActivity/Rename.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "55414116" }, { "name": "Python", "bytes": "427325" }, { "name": "Shell", "bytes": "787" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Linq; namespace WSMailSupport { [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { public ProjectInstaller() { InitializeComponent(); } } }
{ "content_hash": "d912fe1b62a945387e95d61e322ab4c4", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 82, "avg_line_length": 20.94736842105263, "alnum_prop": 0.7060301507537688, "repo_name": "protechdm/CompareCloudware", "id": "230d44d1491fe65d78c4310885cae4fe3103de8c", "size": "400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WSMailSupport/ProjectInstaller.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "224" }, { "name": "C#", "bytes": "17009063" }, { "name": "CSS", "bytes": "444980" }, { "name": "JavaScript", "bytes": "655133" }, { "name": "Makefile", "bytes": "1852" }, { "name": "PHP", "bytes": "25856" }, { "name": "PowerShell", "bytes": "107710" }, { "name": "Ruby", "bytes": "4362" }, { "name": "XSLT", "bytes": "10095" } ], "symlink_target": "" }
JSON command line processing toolkit. no more writing code to inspect or transform JSON objects. this npm module includes a json shell command. the json command processes standard input and parses json objects. json currently handles a few different standard input formats and provides a number of options tailored toward inspecting and transforming the parsed json objects. ## IMPORTANT json-command has been renamed to json in npm. all updates will be made to the json npm package. you need node v0.4.0 or higher and npm to run this program. ## Installation npm install json installs json shell command. ## Examples the following examples parse json output from twitter http requests and output the requested json fields. please note that the last two examples require you to enter your username and password. curl http://search.twitter.com/search.json?q=node.js curl -s http://search.twitter.com/search.json?q=node.js | json curl -s http://search.twitter.com/search.json?q=node.js | json -o results curl -s http://search.twitter.com/search.json?q=node.js | json -o results from_user metadata curl -s http://search.twitter.com/search.json?q=node.js | json -o results new_id=id curl -s http://search.twitter.com/search.json?q=node.js | json -o results -C from_user from_user_id curl -s http://stream.twitter.com/1/statuses/sample.json -uAnyTwitterUser:Password | json user.name user.id curl -s http://stream.twitter.com/1/statuses/sample.json -uAnyTwitterUser:Password | json user.name user.id -c "entities.user_mentions.length > 0" ## Synopsis json [options] [fields] ## Options -h print help info and exit -v (-V | --version) print version number and exit -u print ugly json output, each object on a single line -d print debugging output including exception messages -o object.path specify the path to an array to be iterated on new.key=old_key move old_key to new.key in output object -a input object is an array, process each element separately -c "js conditional" js conditional to be run in the context of each object that determines whether an object is printed -C print the output fields as tab delimited columns in the order specified by fields -e "js expression" execute arbitrary js in the context of each object. -i use node's util.inspect instead of JSON.stringify. -H print headers, if they are supplied. Useful for output from curl -i. ## Fields any number of fields can be specified to be printed from each json object. by default the structure of the original json object is maintained, however options like -e and foo=bar allow for transforming object structure. to remove a particular key, assign it to undefined using the -e flag. ## Standard Input Formats * line delimited json objects * back to back json objects. e.g. { obj1 : body }{ obj2 : body } * file separated json objects. e.g. cat files/* | json * when using -a, a single JSON array ## Order of operations 1. objects are parsed from stdin 2. any non-existing requested keys are instantiated 3. key transforms are applied to the object 4. expressions are run against the object 5. conditionals are checked against the object. the object is discarded if conditionals do not pass 6. the requested keys are pulled from the object and output ## Limitations * all input is handled through standard in * the current version is not particularly slow, but is NOT optimized for speed in any way ## Documentation the npm package includes a man page that can be accessed using: man json ## Known Issues this is alpha quality code, so use at your own risk. ## Thanks this project respectfully uses code from and thanks the authors of: * [node](http://github.com/ry/node) * [npm](http://npmjs.org/)
{ "content_hash": "31fd09bc95d917c401f26dd2e52e50da", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 150, "avg_line_length": 30.458015267175572, "alnum_prop": 0.7135338345864661, "repo_name": "roselleebarle04/eac", "id": "caf865f16ff1049e68138e3a4968e3785d22d66c", "size": "4006", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/json/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "454246" }, { "name": "HTML", "bytes": "6820" }, { "name": "Handlebars", "bytes": "58384" }, { "name": "JavaScript", "bytes": "383346" }, { "name": "PHP", "bytes": "690" } ], "symlink_target": "" }
FROM ngduc/deb-dev ADD ./package.json /tmp RUN cd /tmp \ && npm set progress=false \ && npm install RUN mkdir -p /src \ && ln -s /tmp/node_modules /src/node_modules COPY . /src WORKDIR /src EXPOSE 8100 CMD npm run build && npm start
{ "content_hash": "4d83ae97e04441bfae08d78f7f196739", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 46, "avg_line_length": 15.25, "alnum_prop": 0.6598360655737705, "repo_name": "ngduc/react-setup", "id": "ebc8cf29f1438841948a3060bf77b7e270618c27", "size": "278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "750" }, { "name": "HTML", "bytes": "947" }, { "name": "JavaScript", "bytes": "36800" } ], "symlink_target": "" }
enum ClassType { CLASS_NULL = 0, CLASS_GC, CLASS_GLM, CLASS_POINT, CLASS_MATRIX2, CLASS_MATRIX3, CLASS_MATRIX4, CLASS_VEC2, CLASS_VEC3, CLASS_VEC4, CLASS_FILE, CLASS_IMAGE, CLASS_EVENT, CLASS_ArrayBuffer,// byte CLASS_Int8Array, CLASS_Uint8Array, CLASS_Int16Array, CLASS_Uint16Array, CLASS_Int32Array, CLASS_Uint32Array, CLASS_Float32Array, CLASS_Float64Array, CLASS_Font, CLASS_Atlas, CLASS_AutoRelease// auto release }; #endif
{ "content_hash": "8fb9adb2b65474efee544d4391203dad", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 36, "avg_line_length": 16.78125, "alnum_prop": 0.6256983240223464, "repo_name": "hurry07/opengl_android", "id": "984bf45dcd20ad6ed9d2745bc4bc45bec19cfefc", "size": "700", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jni/classes/classenum.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "36952" }, { "name": "C", "bytes": "7224888" }, { "name": "C++", "bytes": "1814788" }, { "name": "CSS", "bytes": "3640" }, { "name": "Java", "bytes": "14934" }, { "name": "JavaScript", "bytes": "254869" }, { "name": "Objective-C", "bytes": "700" }, { "name": "Shell", "bytes": "322882" }, { "name": "Smalltalk", "bytes": "10530" } ], "symlink_target": "" }
package com.zaniacvids.firstmod.items; import com.zaniacvids.firstmod.FirstMod; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.common.IPlantable; public class SkyBerrySeed extends Item implements IPlantable { private Block plant; private String name = "SkyBerrySeed"; public SkyBerrySeed(Block plant) { this.plant = plant; setUnlocalizedName(FirstMod.MODID + "_" + name); setTextureName(FirstMod.MODID + ":" + name); setCreativeTab(CreativeTabs.tabMaterials); } @Override public EnumPlantType getPlantType(IBlockAccess world, int x, int y, int z) { return EnumPlantType.Crop; } @Override public Block getPlant(IBlockAccess world, int x, int y, int z) { return plant; } @Override public int getPlantMetadata(IBlockAccess world, int x, int y, int z) { return 0; } public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10) { if (par7 != 1) { return false; } else if (par2EntityPlayer.canPlayerEdit(par4, par5, par6, par7, par1ItemStack) && par2EntityPlayer.canPlayerEdit(par4, par5 + 1, par6, par7, par1ItemStack)) { if (par3World.getBlock(par4, par5, par6) == Blocks.grass || par3World.getBlock(par4, par5, par6) == Blocks.dirt) { if (par3World.isAirBlock(par4, par5 + 1, par6)) { par3World.setBlock(par4, par5+1, par6, this.plant); --par1ItemStack.stackSize; return true; } else { return false; } } else { return false; } } else { return false; } } }
{ "content_hash": "633ba82f52cb4998ccf70328b5d015e2", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 175, "avg_line_length": 25.8, "alnum_prop": 0.7209302325581395, "repo_name": "zaniacvids/SkyBerryMod", "id": "96a26d50f5c71f7e8af6fab3848c811c6f8f20b5", "size": "1935", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/com/zaniacvids/firstmod/items/SkyBerrySeed.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "44816" } ], "symlink_target": "" }
package brut.androlib; import java.io.File; import java.util.Collection; import org.jf.util.Log; public class ApkOptions { public boolean forceBuildAll = false; public boolean forceDeleteFramework = false; public boolean debugMode = false; public boolean verbose = false; public boolean copyOriginalFiles = false; public boolean updateFiles = false; public boolean isFramework = false; public boolean resourcesAreCompressed = false; public Collection<String> doNotCompress; public int api; public File in,out,tmp; public String frameworkFolderLocation = null; public String frameworkTag = null; public String aaptPath = ""; public SignTool signTool; public void sign () throws Exception { if(signTool==null){ tmp.renameTo(out); return; } Log.info("正在签名"); signTool.sign(tmp,out); tmp.delete(); } }
{ "content_hash": "dee7464859ed8e7e68319568d7334166", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 50, "avg_line_length": 23.64864864864865, "alnum_prop": 0.7165714285714285, "repo_name": "4455jkjh/apktool", "id": "ab215f799ba033b3e3f9c0f6009984d294f9dc7c", "size": "1592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apktool-lib/src/main/java/brut/androlib/ApkOptions.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2159467" }, { "name": "Lex", "bytes": "8300" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ISO-8859-1"?> <project> <skin> <groupId>it.unisa.dia.gas</groupId> <artifactId>jpbc-site-skin</artifactId> <version>2.0.0</version> </skin> <body> <links> <item name="PBC" href="http://crypto.stanford.edu/pbc/"/> <item name="Sourceforge" href="http://sourceforge.net/projects/jpbc/"/> <item name="Piwik" href="http://sourceforge.net/apps/piwik/jpbc/index.php?module=CoreHome&amp;action=index&amp;idSite=2&amp;period=week&amp;date=today"/> </links> <menu name="JPBC Library"> <item name="Introduction" href="index.html"/> <item name="Download" href="download.html"/> <item name="Build HowTo" href="buildHowto.html"/> <item name="Contact" href="contact.html"/> <item name="Benchmark" href="benchmark.html"/> <item name="Android" href="/docs/android.html"/> <item name="Who Uses JPBC?" href="who.html"/> <item name="FAQ" href="faq.html"/> </menu> <menu name="Documentation"> <item name="Java Docs" href="/java-docs/api/index.html"/> <item name="Pairing" href="/docs/pairing.html"> <item name="Initializing" href="/docs/pairing.html#initializing"/> <item name="Applying" href="/docs/pairing.html#applying"/> <item name="Preprocessing" href="/docs/pairing.html#preprocessing"/> </item> <item name="Field" href="/docs/field.html"/> <item name="Element" href="/docs/element.html"> <item name="Initializing" href="/docs/element.html#initializing"/> <item name="Assigning" href="/docs/element.html#assigning"/> <item name="Arithmetic" href="/docs/element.html#arithmetic"/> <item name="Exponentiation" href="/docs/element.html#exponentiation"/> <item name="Comparing" href="/docs/element.html#comparing"/> <item name="Import/Export" href="/docs/element.html#io"/> <item name="Immutable" href="/docs/element.html#immutable"/> <item name="Preprocessing" href="/docs/element.html#preprocessing"/> </item> <item name="Parameter Generators" href="/docs/pg.html"> <item name="Bilinear Maps" href="/docs/ecpg.html"> <item name="Type A" href="/docs/ecpg.html#TypeA"/> <item name="Type A1" href="/docs/ecpg.html#TypeA1"/> <item name="Type D" href="/docs/ecpg.html#TypeD"/> <item name="Type E" href="/docs/ecpg.html#TypeE"/> <item name="Type F" href="/docs/ecpg.html#TypeF"/> <item name="Type G" href="/docs/ecpg.html#TypeG"/> </item> <item name="Multilinear Maps" href="/docs/mmpg.html"> <item name="Over the Integers [CTL'13]" href="/docs/mmpg.html#ctl13"/> </item> </item> <item name="PBC Wrapper" href="/docs/pbcwrapper.html"/> </menu> <menu name="Crypto"> <item name="Schemes" href="/schemes/schemes.html"> <item name="Functional Encryption" href="/schemes/schemes.html#fe"> <item name="ABE for Circuits [GGHSW'13]" href="/schemes/abe_gghsw13.html"/> <item name="ABE for Circuits [GGHVV'13]" href="/schemes/abe_gghvv13.html"/> <item name="Regular Languages [W'12]" href="/schemes/rl_w12.html"/> <item name="Unbounded HIBE [LW'11]" href="/schemes/uhibe_lw11.html"/> <item name="Inner Product [LOSTW'10]" href="/schemes/ip_lostw10.html"/> <item name="Anonymous HIBE [DIP'10]" href="/schemes/ahibe_dip10.html"/> <item name="HVE [IP'08]" href="/schemes/hve_ip08.html"/> </item> <item name="Signature" href="/schemes/schemes.html#ss"> <item name="SS [BLS'01]" href="/schemes/ss_bls01.html"/> <item name="IBS [PS'06]" href="/schemes/ibs_ps06.html"/> </item> <item name="KEM" href="/schemes/kem.html"/> </item> </menu> ${reports} </body> </project>
{ "content_hash": "f40026bd1ca447dce2480397d47009ca", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 165, "avg_line_length": 48.30769230769231, "alnum_prop": 0.5379890809827116, "repo_name": "woojung3/RewardScheme", "id": "90a7fca9f37690ba6d61de6cd37ccdc76e8d3dab", "size": "4396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RewardScheme/lib/jpbc-2.0.0/src/site/site.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "14472" }, { "name": "CSS", "bytes": "23781" }, { "name": "HTML", "bytes": "584119" }, { "name": "Java", "bytes": "1172571" }, { "name": "JavaScript", "bytes": "857" }, { "name": "Protocol Buffer", "bytes": "315" }, { "name": "TeX", "bytes": "3437" } ], "symlink_target": "" }
require 'spec_helper' require 'nfg-client/utils' describe NFGClient::Utils do class TestClass include ::NFGClient::Utils end let(:test_class) { TestClass.new } describe "#build_nfg_soap_request" do subject { test_class.build_nfg_soap_request('CreateCOF', new_cof_params) } context "when a text field contains a non-standard character" do let(:new_cof_params) { create_cof_params.merge({first_name: 'Janet & Peter'}) } it "should encode them" do expect(subject).to match(/Janet &amp; Peter/) end end end end
{ "content_hash": "33290627139ea6ba97cae694c4d96a50", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 85, "avg_line_length": 23.583333333333332, "alnum_prop": 0.6713780918727915, "repo_name": "GiveCorps/nfg-client", "id": "8973d70a622347a5b7bf7711701dc95e0af5f46c", "size": "566", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/unit/utils_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "62817" } ], "symlink_target": "" }
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/av/music-video": require('material-ui/svg-icons/av/music-video') } }, name: "AvMusicVideo", ports: { input: {}, output: { component: { title: "AvMusicVideo", type: "Component" } } } }
{ "content_hash": "d7fdeee4ff703fb98f8fc09493f65045", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 93, "avg_line_length": 18.95, "alnum_prop": 0.5461741424802111, "repo_name": "nodule/react-material-ui", "id": "3a92a355b04cafd10428e283106116ca7f6a6537", "size": "379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AvMusicVideo.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1678" }, { "name": "JavaScript", "bytes": "614152" } ], "symlink_target": "" }
#include "system_control.h" /* * Gets the Mac OS X's version * * @return * The version of Mac OS X that is decimal number. * @example * version = System::OS::version * sprintf("%x", version) # => "1071" if Mac OS X 10.7.1 */ static VALUE rb_sys_version(VALUE obj) { SInt32 version = 0; Gestalt(gestaltSystemVersion, &version); return INT2NUM(version); } void Init_OS(void) { VALUE mOS = rb_define_module_under(mSystem, "OS"); rb_define_module_function(mOS, "version", rb_sys_version, 0); }
{ "content_hash": "4db1662b233789ecb82a0388fe08ad84", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 65, "avg_line_length": 21.08, "alnum_prop": 0.6432637571157496, "repo_name": "Watson1978/system_control", "id": "c96e766c54075d440330e6543f1b6e623c1ad55f", "size": "527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ext/system_control/os.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "14381" }, { "name": "Ruby", "bytes": "16074" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <entity-engine-xml> <Uom abbreviation="CRC" description="Costa Rica Colon" uomId="CRC" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="COP" description="Colombian Peso" uomId="COP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="CNY" description="China" uomId="CNY" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="CLP" description="Chilean Peso" uomId="CLP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="CHF" description="Swiss Franc" uomId="CHF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="CAD" description="Canadian Dollar" uomId="CAD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BZD" description="Belize Dollar" uomId="BZD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BYN" description="Belorussian Ruble" uomId="BYN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BWP" description="Botswana Pula" uomId="BWP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BSD" description="Bahaman Dollar" uomId="BSD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BRL" description="Brazilian Real" uomId="BRL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BOB" description="Bolivian Boliviano" uomId="BOB" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BND" description="Brunei Dollar" uomId="BND" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BMD" description="Bermudan Dollar" uomId="BMD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BIF" description="Burundi Franc" uomId="BIF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BHD" description="Bahrain Dinar" uomId="BHD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BGN" description="Bulgarian Lev" uomId="BGN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BDT" description="Bangladesh Taka" uomId="BDT" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="BBD" description="Barbados Dollar" uomId="BBD" uomTypeId="CURRENCY_MEASURE"/> <!--https://www.currency-iso.org/dam/isocy/downloads/dl_currency_iso_amendment_96.pdf This amendment changes the currency for BOSNIA AND HERZEGOVINA from the Dinar to the Convertible Marks--> <Uom abbreviation="BAM" description="Convertible Marks" uomId="BAM" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="AZN" description="Azerbaijan Manat" uomId="AZN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="AWG" description="Aruban Guilder" uomId="AWG" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="AUD" description="Australian Dollar" uomId="AUD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ARS" description="Argentina Peso" uomId="ARS" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="AOA" description="Angolan Kwanza" uomId="AOA" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ANG" description="West Indian Guilder" uomId="ANG" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="AMD" description="Armenian Dram" uomId="AMD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ALL" description="Albanian Lek" uomId="ALL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="AFN" description="Afghani" uomId="AFN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="AED" description="United Arab Emirates Dirham" uomId="AED" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="CUP" description="Cuban Peso" uomId="CUP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="CVE" description="Cape Verde Escudo" uomId="CVE" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="CZK" description="Czech Koruna" uomId="CZK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="DJF" description="Djibouti Franc" uomId="DJF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="DKK" description="Danish Krone" uomId="DKK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="DOP" description="Dominican Peso" uomId="DOP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="DZD" description="Algerian Dinar" uomId="DZD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="EGP" description="Egyptian Pound" uomId="EGP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ETB" description="Ethiopian Birr" uomId="ETB" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="EUR" description="Euro" uomId="EUR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="FJD" description="Fiji Dollar" uomId="FJD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="FKP" description="Falkland Pound" uomId="FKP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GBP" description="British Pound" uomId="GBP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GEL" description="Lari" uomId="GEL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GHS" description="Ghanian Cedi" uomId="GHS" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GIP" description="Gibraltar Pound" uomId="GIP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GMD" description="Gambian Dalasi" uomId="GMD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GNF" description="Guinea Franc" uomId="GNF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GTQ" description="Guatemalan Quedzal" uomId="GTQ" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="GYD" description="Guyanese Dollar" uomId="GYD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="HKD" description="Hong Kong Dollar" uomId="HKD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="HNL" description="Honduran Lempira" uomId="HNL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="HRK" description="Croatian Kuna" uomId="HRK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="HTG" description="Haitian Gourde" uomId="HTG" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="HUF" description="Hungarian forint" uomId="HUF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="IDR" description="Indeonesian Rupiah" uomId="IDR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="INR" description="Indian Rupee" uomId="INR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="IQD" description="Iraqui Dinar" uomId="IQD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="IRR" description="Iranian Rial" uomId="IRR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ISK" description="Iceland Krona" uomId="ISK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="JMD" description="Jamaican Dollar" uomId="JMD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="JOD" description="Jordanian Dinar" uomId="JOD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="JPY" description="Japanese Yen" uomId="JPY" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KES" description="Kenyan Shilling" uomId="KES" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KHR" description="Cambodian Riel" uomId="KHR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KGS" description="Kyrgyzstan Som" uomId="KGS" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KMF" description="Comoros Franc" uomId="KMF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KPW" description="North Korean Won" uomId="KPW" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KRW" description="South Korean Won" uomId="KRW" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KWD" description="Kuwaiti Dinar" uomId="KWD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KYD" description="Cayman Dollar" uomId="KYD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="KZT" description="Kazakhstani Tenge" uomId="KZT" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="LAK" description="Laotian Kip" uomId="LAK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="LBP" description="Lebanese Pound" uomId="LBP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="LKR" description="Sri Lankan Rupee" uomId="LKR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="LRD" description="Liberian Dollar" uomId="LRD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="LSL" description="Lesotho Loti" uomId="LSL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="LYD" description="Libyan Dinar" uomId="LYD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MAD" description="Moroccan Dirham" uomId="MAD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MDL" description="Moldavian Lei" uomId="MDL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MGA" description="Malagascy Ariary" uomId="MGA" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MNT" description="Mongolian Tugrik" uomId="MNT" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MOP" description="Macao Pataca" uomId="MOP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MRO" description="Mauritanian Ouguiya" uomId="MRO" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MUR" description="Mauritius Rupee" uomId="MUR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MVR" description="Maldive Rufiyaa" uomId="MVR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MWK" description="Malawi Kwacha" uomId="MWK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MXN" description="Mexican Peso" uomId="MXN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MYR" description="Malaysian Ringgit" uomId="MYR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="MZN" description="Mozambique Metical" uomId="MZN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="NGN" description="Nigerian Naira" uomId="NGN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="NIO" description="Nicaraguan Cordoba Oro" uomId="NIO" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ILS" description="New Israeli Shekel" uomId="ILS" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="NOK" description="Norwegian Krone" uomId="NOK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="NPR" description="Nepalese Rupee" uomId="NPR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="NZD" description="New Zealand Dollar" uomId="NZD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="OMR" description="Omani Rial" uomId="OMR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="PAB" description="Panamanian Balboa" uomId="PAB" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="PEN" description="Peruvian Sol" uomId="PEN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="PGK" description="Papua New Guinea Kina" uomId="PGK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="PHP" description="Philippino Peso" uomId="PHP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="PKR" description="Pakistan Rupee" uomId="PKR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="PLN" description="Poland Zloty" uomId="PLN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="PYG" description="Paraguayan Guarani" uomId="PYG" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="QAR" description="Qatar Riyal" uomId="QAR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="RON" description="Romanian Leu" uomId="RON" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="RUB" description="Russian Rouble" uomId="RUB" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="RWF" description="Rwanda Franc" uomId="RWF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SAR" description="Saudi Riyal" uomId="SAR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SBD" description="Solomon Islands Dollar" uomId="SBD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SCR" description="Seychelles Rupee" uomId="SCR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SDG" description="Sudanese Pound" uomId="SDG" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SSP" description="South Sudanese Pound" uomId="SSP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SEK" description="Swedish Krona" uomId="SEK" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SGD" description="Singapore Dollar" uomId="SGD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SHP" description="St.Helena Pound" uomId="SHP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SLL" description="Leone" uomId="SLL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SOS" description="Somalian Shilling" uomId="SOS" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SRD" description="Surinam Dollar" uomId="SRD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="STD" description="Sao Tome / Principe Dobra" uomId="STD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SVC" description="El Salvador Colon" uomId="SVC" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SYP" description="Syrian Pound" uomId="SYP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="SZL" description="Swaziland Lilangeni" uomId="SZL" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="THB" description="Thailand Baht" uomId="THB" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TJS" description="Tadzhikistani Somoni" uomId="TJS" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TMT" description="Turkmenistani Manat" uomId="TMT" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TND" description="Tunisian Dinar" uomId="TND" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TOP" description="Tongan Pa&apos;anga" uomId="TOP" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TRY" description="Turkish Lira" uomId="TRY" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TTD" description="Trinidad and Tobago Dollar" uomId="TTD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TWD" description="New Taiwan Dollar" uomId="TWD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="TZS" description="Tanzanian Shilling" uomId="TZS" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="UAH" description="Ukrainian Hryvnia" uomId="UAH" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="UGX" description="Ugandan Shilling" uomId="UGX" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="USD" description="United States Dollar" uomId="USD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="UYU" description="Uruguay Peso" uomId="UYU" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="UYI" description="Uruguay Peso en Unidades Indexadas (UI)" uomId="UYI" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="VEF" description="Venezuelan Bolívar" uomId="VEF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="VND" description="Vietnamese Dong" uomId="VND" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="VUV" description="Vanuatu Vatu" uomId="VUV" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="WST" description="Samoan Tala" uomId="WST" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="XAF" description="Gabon C.f.A Franc" uomId="XAF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="XCD" description="East Carribean Dollar" uomId="XCD" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="XOF" description="Benin C.f.A. Franc" uomId="XOF" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="YER" description="Yemeni Ryal" uomId="YER" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ZAR" description="South African Rand" uomId="ZAR" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ZMW" description="Zambian Kwacha" uomId="ZMW" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ZRN" description="New Zaire" uomId="ZRN" uomTypeId="CURRENCY_MEASURE"/> <Uom abbreviation="ZWL" description="Zimbabwe Dollar" uomId="ZWL" uomTypeId="CURRENCY_MEASURE"/> </entity-engine-xml>
{ "content_hash": "c54ca2bd7fc43890c9ea6060189920b0", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 124, "avg_line_length": 92.83236994219654, "alnum_prop": 0.7422166874221668, "repo_name": "yuri0x7c1/ofbiz-explorer", "id": "bf80a6bd56ec781be6d4475749d63331d9801b9b", "size": "16061", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources/apache-ofbiz-16.11.03/framework/common/data/CurrencyData.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "17446" }, { "name": "CSS", "bytes": "1890137" }, { "name": "FreeMarker", "bytes": "4633734" }, { "name": "Groovy", "bytes": "1724859" }, { "name": "HTML", "bytes": "12835438" }, { "name": "Java", "bytes": "16138651" }, { "name": "JavaScript", "bytes": "4284839" }, { "name": "Makefile", "bytes": "25802" }, { "name": "PHP", "bytes": "150" }, { "name": "Perl", "bytes": "2756" }, { "name": "Python", "bytes": "19974" }, { "name": "Roff", "bytes": "4118" }, { "name": "Ruby", "bytes": "2533" }, { "name": "Shell", "bytes": "44075" }, { "name": "XSLT", "bytes": "8467700" } ], "symlink_target": "" }
package swarm import ( "context" "runtime" "testing" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" swarmtypes "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/client" "github.com/docker/docker/testutil/daemon" "github.com/docker/docker/testutil/environment" "gotest.tools/v3/assert" "gotest.tools/v3/poll" "gotest.tools/v3/skip" ) // ServicePoll tweaks the pollSettings for `service` func ServicePoll(config *poll.Settings) { // Override the default pollSettings for `service` resource here ... config.Timeout = 15 * time.Second config.Delay = 100 * time.Millisecond if runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" { config.Timeout = 90 * time.Second } } // NetworkPoll tweaks the pollSettings for `network` func NetworkPoll(config *poll.Settings) { // Override the default pollSettings for `network` resource here ... config.Timeout = 30 * time.Second config.Delay = 100 * time.Millisecond if runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" { config.Timeout = 50 * time.Second } } // ContainerPoll tweaks the pollSettings for `container` func ContainerPoll(config *poll.Settings) { // Override the default pollSettings for `container` resource here ... if runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" { config.Timeout = 30 * time.Second config.Delay = 100 * time.Millisecond } } // NewSwarm creates a swarm daemon for testing func NewSwarm(t *testing.T, testEnv *environment.Execution, ops ...daemon.Option) *daemon.Daemon { t.Helper() skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, testEnv.DaemonInfo.OSType == "windows") if testEnv.DaemonInfo.ExperimentalBuild { ops = append(ops, daemon.WithExperimental()) } d := daemon.New(t, ops...) d.StartAndSwarmInit(t) return d } // ServiceSpecOpt is used with `CreateService` to pass in service spec modifiers type ServiceSpecOpt func(*swarmtypes.ServiceSpec) // CreateService creates a service on the passed in swarm daemon. func CreateService(t *testing.T, d *daemon.Daemon, opts ...ServiceSpecOpt) string { t.Helper() client := d.NewClientT(t) defer client.Close() spec := CreateServiceSpec(t, opts...) resp, err := client.ServiceCreate(context.Background(), spec, types.ServiceCreateOptions{}) assert.NilError(t, err, "error creating service") return resp.ID } // CreateServiceSpec creates a default service-spec, and applies the provided options func CreateServiceSpec(t *testing.T, opts ...ServiceSpecOpt) swarmtypes.ServiceSpec { t.Helper() var spec swarmtypes.ServiceSpec ServiceWithImage("busybox:latest")(&spec) ServiceWithCommand([]string{"/bin/top"})(&spec) ServiceWithReplicas(1)(&spec) for _, o := range opts { o(&spec) } return spec } // ServiceWithMode sets the mode of the service to the provided mode. func ServiceWithMode(mode swarmtypes.ServiceMode) func(*swarmtypes.ServiceSpec) { return func(spec *swarmtypes.ServiceSpec) { spec.Mode = mode } } // ServiceWithInit sets whether the service should use init or not func ServiceWithInit(b *bool) func(*swarmtypes.ServiceSpec) { return func(spec *swarmtypes.ServiceSpec) { ensureContainerSpec(spec) spec.TaskTemplate.ContainerSpec.Init = b } } // ServiceWithImage sets the image to use for the service func ServiceWithImage(image string) func(*swarmtypes.ServiceSpec) { return func(spec *swarmtypes.ServiceSpec) { ensureContainerSpec(spec) spec.TaskTemplate.ContainerSpec.Image = image } } // ServiceWithCommand sets the command to use for the service func ServiceWithCommand(cmd []string) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { ensureContainerSpec(spec) spec.TaskTemplate.ContainerSpec.Command = cmd } } // ServiceWithConfig adds the config reference to the service func ServiceWithConfig(configRef *swarmtypes.ConfigReference) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { ensureContainerSpec(spec) spec.TaskTemplate.ContainerSpec.Configs = append(spec.TaskTemplate.ContainerSpec.Configs, configRef) } } // ServiceWithSecret adds the secret reference to the service func ServiceWithSecret(secretRef *swarmtypes.SecretReference) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { ensureContainerSpec(spec) spec.TaskTemplate.ContainerSpec.Secrets = append(spec.TaskTemplate.ContainerSpec.Secrets, secretRef) } } // ServiceWithReplicas sets the replicas for the service func ServiceWithReplicas(n uint64) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { spec.Mode = swarmtypes.ServiceMode{ Replicated: &swarmtypes.ReplicatedService{ Replicas: &n, }, } } } // ServiceWithMaxReplicas sets the max replicas for the service func ServiceWithMaxReplicas(n uint64) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { ensurePlacement(spec) spec.TaskTemplate.Placement.MaxReplicas = n } } // ServiceWithName sets the name of the service func ServiceWithName(name string) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { spec.Annotations.Name = name } } // ServiceWithNetwork sets the network of the service func ServiceWithNetwork(network string) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { spec.TaskTemplate.Networks = append(spec.TaskTemplate.Networks, swarmtypes.NetworkAttachmentConfig{Target: network}) } } // ServiceWithEndpoint sets the Endpoint of the service func ServiceWithEndpoint(endpoint *swarmtypes.EndpointSpec) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { spec.EndpointSpec = endpoint } } // ServiceWithSysctls sets the Sysctls option of the service's ContainerSpec. func ServiceWithSysctls(sysctls map[string]string) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { ensureContainerSpec(spec) spec.TaskTemplate.ContainerSpec.Sysctls = sysctls } } // ServiceWithCapabilities sets the Capabilities option of the service's ContainerSpec. func ServiceWithCapabilities(Capabilities []string) ServiceSpecOpt { return func(spec *swarmtypes.ServiceSpec) { ensureContainerSpec(spec) spec.TaskTemplate.ContainerSpec.Capabilities = Capabilities } } // GetRunningTasks gets the list of running tasks for a service func GetRunningTasks(t *testing.T, c client.ServiceAPIClient, serviceID string) []swarmtypes.Task { t.Helper() tasks, err := c.TaskList(context.Background(), types.TaskListOptions{ Filters: filters.NewArgs( filters.Arg("service", serviceID), filters.Arg("desired-state", "running"), ), }) assert.NilError(t, err) return tasks } // ExecTask runs the passed in exec config on the given task func ExecTask(t *testing.T, d *daemon.Daemon, task swarmtypes.Task, config types.ExecConfig) types.HijackedResponse { t.Helper() client := d.NewClientT(t) defer client.Close() ctx := context.Background() resp, err := client.ContainerExecCreate(ctx, task.Status.ContainerStatus.ContainerID, config) assert.NilError(t, err, "error creating exec") startCheck := types.ExecStartCheck{} attach, err := client.ContainerExecAttach(ctx, resp.ID, startCheck) assert.NilError(t, err, "error attaching to exec") return attach } func ensureContainerSpec(spec *swarmtypes.ServiceSpec) { if spec.TaskTemplate.ContainerSpec == nil { spec.TaskTemplate.ContainerSpec = &swarmtypes.ContainerSpec{} } } func ensurePlacement(spec *swarmtypes.ServiceSpec) { if spec.TaskTemplate.Placement == nil { spec.TaskTemplate.Placement = &swarmtypes.Placement{} } }
{ "content_hash": "a23799a9151bd4ada3e95acddf3d7c51", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 117, "avg_line_length": 31.234309623430963, "alnum_prop": 0.763027461486939, "repo_name": "SvenDowideit/docker", "id": "ed30045c2d5877a30e7e7958df5248bb20f543b0", "size": "7465", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integration/internal/swarm/service.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "81" }, { "name": "C", "bytes": "4815" }, { "name": "Dockerfile", "bytes": "18628" }, { "name": "Go", "bytes": "7487741" }, { "name": "Makefile", "bytes": "11274" }, { "name": "PowerShell", "bytes": "85657" }, { "name": "Shell", "bytes": "137119" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.sbbs</groupId> <artifactId>framework</artifactId> <version>1.0-SNAPSHOT</version> </parent> <artifactId>web</artifactId> <version>${project.parent.version}</version> <name>sbbs-web</name> <properties> </properties> <dependencies> <!-- <dependency> <groupId>${jdbc.groupId}</groupId> <artifactId>${jdbc.artifactId}</artifactId> </dependency>--> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> </dependency> <dependency> <groupId>org.sbbs</groupId> <artifactId>service</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <exclusions> <exclusion> <artifactId>tools</artifactId> <groupId>com.sun</groupId> </exclusion> <exclusion> <artifactId>javassist</artifactId> <groupId>javassist</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-config-browser-plugin</artifactId> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <!-- <scope>test</scope> --> <!-- <exclusions> <exclusion> <artifactId>spring-beans</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-context</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> --> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <!-- <version>2.4</version> --> <classifier>jdk15</classifier> <exclusions> <exclusion> <artifactId>commons-lang</artifactId> <groupId>commons-lang</groupId> </exclusion> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-junit-plugin</artifactId> <scope>test</scope> <exclusions> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <forkCount>0</forkCount> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>hibernate3-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>dbunit-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <excludes> <!-- <exclude>**/*.xml</exclude> --> <exclude>**/demo/**</exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "2ef560356812a2b49517d0647962dfd9", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 104, "avg_line_length": 26.95906432748538, "alnum_prop": 0.6726681127982647, "repo_name": "fdcmessenger/framework", "id": "f70be63659471b6d0ece4b5e3f74e71caa4ea93b", "size": "4610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "234552" }, { "name": "HTML", "bytes": "902343" }, { "name": "Java", "bytes": "360396" }, { "name": "JavaScript", "bytes": "1944782" }, { "name": "PHP", "bytes": "27273" }, { "name": "SQLPL", "bytes": "1449" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <LinearLayout android:layout_width="wrap_content" android:layout_height = "wrap_content" android:id = "@+id/innerList" android:orientation="horizontal" android:layout_alignParentTop="true"></LinearLayout> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id = "@+id/scrollOverlay" android:layout_alignParentTop = "true" /> </RelativeLayout>
{ "content_hash": "1feb439da665e1fb9ecc01b4348e7dd1", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 87, "avg_line_length": 45.5, "alnum_prop": 0.6938775510204082, "repo_name": "hexagonc/Android-Lisp", "id": "d10aca9e6da41a1ef57d29d92ac5a8ba865121e9", "size": "637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/eclipse/AndroidTools/res/layout/horizontal_wrapping_listview_layout.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Common Lisp", "bytes": "77736" }, { "name": "Java", "bytes": "1558288" } ], "symlink_target": "" }
<?php namespace T3chnik\FlysystemCloudinaryAdapter; use Exception; use Cloudinary; use Cloudinary\Api; use Cloudinary\Uploader; use League\Flysystem\Config; use League\Flysystem\AdapterInterface; use League\Flysystem\Adapter\Polyfill\NotSupportingVisibilityTrait; /** * */ class CloudinaryAdapter implements AdapterInterface { /** * @var Cloudinary\Api */ protected $api; /** * Cloudinary does not suppory visibility - all is public */ use NotSupportingVisibilityTrait; /** * Constructor * Sets configuration, and dependency Cloudinary Api. * @param array $config Cloudinary configuration * @param Api $api Cloudinary Api instance */ public function __construct(array $config, Api $api) { Cloudinary::config($config); $this->api = $api; } /** * Write a new file. * Create temporary stream with content. * Pass to writeStream. * * @param string $path * @param string $contents * @param Config $config Config object * * @return array|false false on failure file meta data on success */ public function write($path, $contents, Config $config) { // 1. Save to temporary local file -- it will be destroyed automatically $tempfile = tmpfile(); fwrite($tempfile, $contents); // 2. Use Cloudinary to send $uploaded_metadata = $this->writeStream($path, $tempfile, $config); return $uploaded_metadata; } /** * Write a new file using a stream. * * @param string $path * @param resource $resource * @param Config $config Config object * * @return array|false false on failure file meta data on success */ public function writeStream($path, $resource, Config $config) { $resource_metadata = stream_get_meta_data($resource); $uploaded_metadata = Uploader::upload($resource_metadata['uri'], ['public_id' => $path]); return $uploaded_metadata; } /** * Update a file. * Cloudinary has no specific update method. Overwrite instead. * * @param string $path * @param string $contents * @param Config $config Config object * * @return array|false false on failure file meta data on success */ public function update($path, $contents, Config $config) { return $this->write($path, $contents, $config); } /** * Update a file using a stream. * Cloudinary has no specific update method. Overwrite instead. * * @param string $path * @param resource $resource * @param Config $config Config object * * @return array|false false on failure file meta data on success */ public function updateStream($path, $resource, Config $config) { return $this->writeStream($path, $resource, $config); } /** * Rename a file. * Paths without extensions. * * @param string $path * @param string $newpath * * @return bool */ public function rename($path, $newpath) { $pathinfo = pathinfo($path); if ($pathinfo['dirname'] != '.') { $path_remote = $pathinfo['dirname'] . '/' . $pathinfo['filename']; } else { $path_remote = $pathinfo['filename']; } $newpathinfo = pathinfo($newpath); if ($newpathinfo['dirname'] != '.') { $newpath_remote = $newpathinfo['dirname'] . '/' . $newpathinfo['filename']; } else { $newpath_remote = $newpathinfo['filename']; } $result = Uploader::rename($path_remote, $newpath_remote); return $result['public_id'] == $newpathinfo['filename']; } /** * Copy a file. * Copy content from existing url. * * @param string $path * @param string $newpath * * @return bool */ public function copy($path, $newpath) { $url = cloudinary_url_internal($path); $result = Uploader::upload($url, ['public_id' => $newpath]); return is_array($result) ? $result['public_id'] == $newpath : false; } /** * Delete a file. * * @param string $path * * @return bool */ public function delete($path) { $result = Uploader::destroy($path, ['invalidate' => true]); return is_array($result) ? $result['result'] == 'ok' : false; } /** * Delete a directory. * Delete Files using directory as a prefix. * * @param string $dirname * * @return bool */ public function deleteDir($dirname) { $response = $this->api->delete_resources_by_prefix($dirname); return true; } /** * Create a directory. * Cloudinary does not realy embrace the concept of "directories". * Those are more like a part of a name / public_id. * Just keep swimming. * * @param string $dirname directory name * @param Config $config * * @return array|false */ public function createDir($dirname, Config $config) { return ['path' => $dirname]; } /** * Check whether a file exists. * Using url to check response headers. * Maybe I should use api resource? * * substr(get_headers(cloudinary_url_internal($path))[0], -6 ) == '200 OK'; * need to test that for spead * * @param string $path * * @return array|bool|null */ public function has($path) { try { $this->api->resource($path); } catch (Exception $e) { return false; } return true; } /** * Read a file. * * @param string $path * * @return array|false */ public function read($path) { $contents = file_get_contents(cloudinary_url($path)); return compact('contents', 'path'); } /** * Read a file as a stream. * * @param string $path * * @return array|false */ public function readStream($path) { try { $stream = fopen(cloudinary_url($path), 'r'); } catch (Exception $e) { return false; } return compact('stream', 'path'); } /** * List contents of a directory. * * @param string $directory * @param bool $recursive * * @return array */ public function listContents($directory = '', $recursive = false) { // get resources array $resources = ((array) $this->api->resources([ 'type' => 'upload', 'prefix' => $directory ])['resources']); // parse resourses foreach ($resources as $i => $resource) { $resources[$i] = $this->prepareResourceMetadata($resource); } return $resources; } /** * Get all the meta data of a file or directory. * * @param string $path * * @return array|false */ public function getMetadata($path) { return $this->prepareResourceMetadata($this->getResource($path)); } /** * Get Resource data * @param string $path * @return array */ public function getResource($path) { return (array) $this->api->resource($path); } /** * Get all the meta data of a file or directory. * * @param string $path * * @return array|false */ public function getSize($path) { return $this->prepareSize($this->getResource($path)); } /** * Get the mimetype of a file. * Actually I don't think cloudinary supports mimetypes. * Or I am just stupid and cannot find it. * This is an ugly hack. * * @param string $path * * @return array|false */ public function getMimetype($path) { return $this->prepareMimetype($this->getResource($path)); } /** * Get the timestamp of a file. * * @param string $path * * @return array|false */ public function getTimestamp($path) { return $this->prepareTimestamp($this->getResource($path)); } /** * Prepare apropriate metadata for resource metadata given from cloudinary. * @param array $resource * @return array */ protected function prepareResourceMetadata($resource) { $resource['type'] = 'file'; $resource['path'] = $resource['public_id']; $resource = array_merge($resource, $this->prepareSize($resource)); $resource = array_merge($resource, $this->prepareTimestamp($resource)); $resource = array_merge($resource, $this->prepareMimetype($resource)); return $resource; } /** * prepare timestpamp response * @param array $resource * @return array */ protected function prepareMimetype($resource) { // hack $mimetype = $resource['resource_type'] . '/' . $resource['format']; $mimetype = str_replace('jpg', 'jpeg', $mimetype); // hack to a hack return compact('mimetype'); } /** * prepare timestpamp response * @param array $resource * @return array */ protected function prepareTimestamp($resource) { $timestamp = strtotime($resource['created_at']); return compact('timestamp'); } /** * prepare size response * @param array $resource * @return array */ protected function prepareSize($resource) { $size = $resource['bytes']; return compact('size'); } }
{ "content_hash": "692f891a745d191ba1162acb6347884e", "timestamp": "", "source": "github", "line_count": 396, "max_line_length": 97, "avg_line_length": 24.406565656565657, "alnum_prop": 0.5602690118986032, "repo_name": "t3chnik/flysystem-cloudinary-adapter", "id": "b6efba715de65426534e77715aff0e60189be532", "size": "9665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/CloudinaryAdapter.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "9665" } ], "symlink_target": "" }
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { PokerCommandHeaderSerializer } from "../../core/serializers/PokerCommandHeaderSerializer"; import { PokerCommandHeader } from "../../core/data/PokerCommandHeader"; import { SrvSSLDataCommand } from "../commands/SrvSSLDataCommand"; import { SrvSSLDataData } from "../data/SrvSSLDataData"; import { SrvSSLDataDataSerializer } from "./SrvSSLDataDataSerializer"; export class SrvSSLDataCommandSerializer { public static serialize(buffer: ArrayBufferBuilder, command: SrvSSLDataCommand ): void { buffer.pointer += PokerCommandHeader.HEADER_SIZE_BYTES; SrvSSLDataDataSerializer.serialize(buffer, command.data); PokerCommandHeaderSerializer.serialize(buffer, command.header); } public static deserialize(buffer: ArrayBufferBuilder, command: SrvSSLDataCommand ): void { PokerCommandHeaderSerializer.deserialize(buffer, command.header); command.data = new SrvSSLDataData(); SrvSSLDataDataSerializer.deserialize(buffer, command.data); } }
{ "content_hash": "9c049f1087373e0451abaefbf808ece3", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 99, "avg_line_length": 45.65217391304348, "alnum_prop": 0.7752380952380953, "repo_name": "gesh123/MyLibrary", "id": "1c2015d590d756ac297ad9c1880632c7f096252d", "size": "1051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/app/poker/connection/protocol/generated/serializers/SrvSSLDataCommandSerializer.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1191" }, { "name": "HTML", "bytes": "595" }, { "name": "JavaScript", "bytes": "7934" }, { "name": "TypeScript", "bytes": "1251145" } ], "symlink_target": "" }
package com.thoughtworks.go.domain; import com.thoughtworks.go.server.service.AgentRuntimeInfo; import com.thoughtworks.go.work.DefaultGoPublisher; import java.io.File; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; public class StubGoPublisher extends DefaultGoPublisher { private String message = ""; private Map<File, String> uploadedFiles = new HashMap<>(); private boolean shouldFail; public StubGoPublisher() { this(false); } public StubGoPublisher(boolean shouldFail) { super(null, null, null, AgentRuntimeInfo.initialState(NullAgent.createNullAgent()), "utf-8"); this.shouldFail = shouldFail; } @Override protected void init() { } @Override public void taggedConsumeLineWithPrefix(String tag, String message) { this.message += message; } @Override public void taggedConsumeLine(String tag, String message) { this.message += message; } @Override public void consumeLineWithPrefix(String message) { this.message += message; } @Override public void consumeLine(String message) { this.message += message; } public String getMessage() { return message; } @Override public void upload(File fileToUpload, String destPath) { if (shouldFail) { throw new RuntimeException("failed on purpose"); } uploadedFiles.put(fileToUpload, destPath); } public Map<File, String> publishedFiles() { return uploadedFiles; } public void assertPublished(String endOfFileName, String destination) { for (File file : uploadedFiles.keySet()) { if (file.getAbsolutePath().endsWith(endOfFileName)) { org.junit.Assert.assertThat(uploadedFiles.get(file), is(destination)); return; } } fail(endOfFileName + " was not published to " + destination + ".\n" + uploadedFiles); } public void setShouldFail(boolean shouldFail) { this.shouldFail = shouldFail; } }
{ "content_hash": "2d8ce53366a955d7215c96628fc7c2a7", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 101, "avg_line_length": 26.25609756097561, "alnum_prop": 0.6544356711565258, "repo_name": "ibnc/gocd", "id": "93b4aaafd352bd99c461ad3f3cb86955b8ff5a30", "size": "2754", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "common/src/test/java/com/thoughtworks/go/domain/StubGoPublisher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "466" }, { "name": "CSS", "bytes": "833927" }, { "name": "FreeMarker", "bytes": "9764" }, { "name": "Groovy", "bytes": "2043806" }, { "name": "HTML", "bytes": "644360" }, { "name": "Java", "bytes": "20536854" }, { "name": "JavaScript", "bytes": "2679628" }, { "name": "NSIS", "bytes": "23526" }, { "name": "PowerShell", "bytes": "691" }, { "name": "Ruby", "bytes": "1952239" }, { "name": "Shell", "bytes": "169149" }, { "name": "TSQL", "bytes": "200114" }, { "name": "TypeScript", "bytes": "2964749" }, { "name": "XSLT", "bytes": "200357" } ], "symlink_target": "" }
This reporter pushes data to [InfluxDB](https://influxdb.com/index.html). [![Build Status](https://travis-ci.org/travelping/exometer_influxdb.svg)](https://travis-ci.org/travelping/exometer_influxdb) [![Hex pm](http://img.shields.io/hexpm/v/exometer_influxdb.svg?style=flat)](https://hex.pm/packages/exometer_influxdb) ## Usage 1. Add exometer_influxdb to your list of dependencies in rebar.config: ```erlang {deps, [ {exometer_influxdb, "0.6.0"} ]}. ``` 2. Ensure exometer_influxdb is started before your application: ```erlang {applications, [exometer_influxdb]}. ``` 3. Configure it: ```erlang {exometer_core, [ {report, [ {reporters, [ {exometer_report_influxdb, [{protocol, http}, {host, <<"localhost">>}, {port, 8086}, {db, <<"exometer">>}, {tags, [{region, ru}]}]} ]} ]} ]}. ``` Available options: * __protocol__ - `http`, `https` or `udp` for operating with InfluxDB. `http` by default. If you use `udp`, check __udp_mtu__ below to avoid `{error,emsgsize}`. * __host__ - InfluxDB host. `127.0.0.1` by default. * __port__ - InfluxDB port. `8086` by default. * __db__ - Database on InfluxDB for writing data. `exometer` by default. * __username__ - Username for authorization on InfluxDB. * __password__ - Password for authorization on InfluxDB. * __timestamping__ - Enable timestamping, `false` by default. To enable `timestamping` with the reporter you can use `true` or `{true, Precision}` where `Precision` is a unit taken from `[n,u,ms,s,m,h]`. The default unit is `u`. * __batch_window_size__ - Set window size in ms for batch sending. This means the reporter will collect measurements within this interval and send all measurements in one packet. `0` by default. * __udp_mtu__ - (Used only with __protocol__ == `udp`.) MTU of the network interface through which UDP packets flow to the __host__. `65536` by default (Linux loopback interface MTU). Run `ifconfig` on the machine where this app will run to find it out. Metrics will be sent out if their size (in the Line Protocol format) exceeds this value, even if the current __batch_window_size__ is not over yet. (They will also be sent out at the end of __batch_window_size__ as usual, regardless of their size.) The following options can be set globally in the reporter config or locally in a specific subscription. The latter case overwrites the first. * __tags__ - List of tags for each time series. The `host` is automatically included here. * __series_name__ - The name of a time series visible within the `FROM` field. By default this is set to the concatenated elements of the exometer id. Caution: If set in the global reporter config then every time series will have this name. * __formatting__ - Formatting options to alter the appearance of a series name or tags. ### Subscription examples: ```erlang {exometer_core, [ {report, [ {subscribers, [ {exometer_report_influxdb, [erlang, memory], total, 5000, [{tags, {tag, value}}]} ]} ]} ]}. ``` By default the in InfluxDB visible name of the metric is derived from the exometer id: Here `[erlang, memory]` is translated to `erlang_memory`. It is possible to remove an item from this list by naming itself or its position with the `from_name` keyword. A removed element is then used as tag value: ```erlang exometer_report:subscribe(exometer_report_influxdb, [erlang, memory], total, 5000, [{tags, [{tag, {from_name, 2}}]}]). ``` This will result in a name `erlang` with the tag pair `{tag, memory}` (plus the default pair `{host, Host}`). To disable the removal of elements in the series name you can set: ```erlang {formatting, [{purge, [{all_from_name, false}]}]} ``` Further it might be handy to remove e.g. `undefined` tag keys or values. This can be done via: ```erlang {formatting, [{purge, [{tag_keys, undefined}, {tag_values, undefined}]}]} ``` ### Auto subscriptions: There is capability for making a subscription automatically for each new entry. By default it is off. If you need to enable it in the reporter options and also provide a callback module which handles newly created entries. ```erlang {exometer_core, [ {report, [ {reporters, [ {exometer_report_influxdb, [{autosubscribe, true}, {subscriptions_module, exometer_influxdb_subscribe_mod}, {protocol, http}, {host, <<"localhost">>}, {port, 8086}, {db, <<"exometer">>}, {tags, [{region, ru}]}]} ]} ]} ]}. ``` The callback module may look like: ```erlang -module(exometer_influxdb_subscribe_mod). -export([subscribe/2]). subscribe([metric, test], histogram) -> Tags = [{tags, [{type, {from_name, 2}}]}], [{[metric, test], min, 1000, Tags}, {[metric, test], max, 1000, Tags}, {[metric, test], median, 1000, Tags}]; subscribe([metric, test1], histogram) -> Tags = [{tags, [{type, {from_name, 2}}]}], [{[metric, test1], max, 1000, Tags}, {[metric, test1], median, 1000, Tags}]; subscribe(_, _) -> []. ``` `subscribe/2` calls for each new entry and it should return a list or just one subscription. Here a single subscription has the following layout: ```erlang {exometer_report:metric(), exometer_report:datapoint(), exometer_report:interval(), exometer_report:extra()} ``` # TODO * Reconfiguration on runtime * Enhance the formatting options (e.g. concatenation chars, format strings, etc.)
{ "content_hash": "32c27eb51c5d99125d05c075e39f3f07", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 502, "avg_line_length": 43.58955223880597, "alnum_prop": 0.6288306796781373, "repo_name": "CloudI/CloudI", "id": "5f75e1c419c36653a2f3f53bb6f34de60f814177", "size": "5872", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/external/cloudi_x_exometer_influxdb/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "ATS", "bytes": "123970" }, { "name": "C", "bytes": "86415" }, { "name": "C++", "bytes": "534886" }, { "name": "CSS", "bytes": "47622" }, { "name": "Elixir", "bytes": "15280" }, { "name": "Erlang", "bytes": "25037953" }, { "name": "Go", "bytes": "138051" }, { "name": "HTML", "bytes": "2685054" }, { "name": "Haskell", "bytes": "138722" }, { "name": "Java", "bytes": "599881" }, { "name": "JavaScript", "bytes": "178935" }, { "name": "Lua", "bytes": "522" }, { "name": "M4", "bytes": "99018" }, { "name": "Makefile", "bytes": "97661" }, { "name": "OCaml", "bytes": "149872" }, { "name": "PHP", "bytes": "140502" }, { "name": "Perl", "bytes": "129952" }, { "name": "Python", "bytes": "335976" }, { "name": "Ruby", "bytes": "125197" }, { "name": "SWIG", "bytes": "89" }, { "name": "Shell", "bytes": "17258" } ], "symlink_target": "" }
require 'test_helper' module ActionController module Serialization class JsonApiLinkedTest < ActionController::TestCase class MyController < ActionController::Base def setup_post ActionController::Base.cache_store.clear @role1 = Role.new(id: 1, name: 'admin') @role2 = Role.new(id: 2, name: 'colab') @author = Author.new(id: 1, name: 'Steve K.') @author.posts = [] @author.bio = nil @author.roles = [@role1, @role2] @role1.author = @author @role2.author = @author @author2 = Author.new(id: 2, name: 'Anonymous') @author2.posts = [] @author2.bio = nil @author2.roles = [] @post = Post.new(id: 1, title: 'New Post', body: 'Body') @first_comment = Comment.new(id: 1, body: 'ZOMG A COMMENT') @second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT') @post.comments = [@first_comment, @second_comment] @post.author = @author @first_comment.post = @post @first_comment.author = @author2 @second_comment.post = @post @second_comment.author = nil @post2 = Post.new(id: 2, title: "Another Post", body: "Body") @post2.author = @author @post2.comments = [] @blog = Blog.new(id: 1, name: "My Blog!!") @post.blog = @blog @post2.blog = @blog end def render_resource_without_include setup_post render json: @post, adapter: :json_api end def render_resource_with_include setup_post render json: @post, include: 'author', adapter: :json_api end def render_resource_with_nested_include setup_post render json: @post, include: 'comments.author', adapter: :json_api end def render_resource_with_nested_has_many_include setup_post render json: @post, include: ['author', 'author.roles'], adapter: :json_api end def render_resource_with_missing_nested_has_many_include setup_post @post.author = @author2 # author2 has no roles. render json: @post, include: 'author,author.roles', adapter: :json_api end def render_collection_with_missing_nested_has_many_include setup_post @post.author = @author2 render json: [@post, @post2], include: 'author,author.roles', adapter: :json_api end def render_collection_without_include setup_post render json: [@post], adapter: :json_api end def render_collection_with_include setup_post render json: [@post], include: ['author', 'comments'], adapter: :json_api end end tests MyController def test_render_resource_without_include get :render_resource_without_include response = JSON.parse(@response.body) refute response.key? 'included' end def test_render_resource_with_include get :render_resource_with_include response = JSON.parse(@response.body) assert response.key? 'included' assert_equal 1, response['included'].size assert_equal 'Steve K.', response['included'].first['name'] end def test_render_resource_with_nested_has_many_include get :render_resource_with_nested_has_many_include response = JSON.parse(@response.body) expected_linked = [ { "id" => "1", "type" => "authors", "name" => "Steve K.", "links" => { "posts" => { "linkage" => [] }, "roles" => { "linkage" => [{ "type" =>"roles", "id" => "1" }, { "type" =>"roles", "id" => "2" }] }, "bio" => { "linkage" => nil } } }, { "id" => "1", "type" => "roles", "name" => "admin", "links" => { "author" => { "linkage" => { "type" =>"authors", "id" => "1" } } } }, { "id" => "2", "type" => "roles", "name" => "colab", "links" => { "author" => { "linkage" => { "type" =>"authors", "id" => "1" } } } } ] assert_equal expected_linked, response['included'] end def test_render_resource_with_nested_include get :render_resource_with_nested_include response = JSON.parse(@response.body) assert response.key? 'included' assert_equal 1, response['included'].size assert_equal 'Anonymous', response['included'].first['name'] end def test_render_collection_without_include get :render_collection_without_include response = JSON.parse(@response.body) refute response.key? 'included' end def test_render_collection_with_include get :render_collection_with_include response = JSON.parse(@response.body) assert response.key? 'included' end def test_render_resource_with_nested_attributes_even_when_missing_associations get :render_resource_with_missing_nested_has_many_include response = JSON.parse(@response.body) assert response.key? 'included' refute has_type?(response['included'], 'roles') end def test_render_collection_with_missing_nested_has_many_include get :render_collection_with_missing_nested_has_many_include response = JSON.parse(@response.body) assert response.key? 'included' assert has_type?(response['included'], 'roles') end def has_type?(collection, value) collection.detect { |i| i['type'] == value} end end end end
{ "content_hash": "a997f857f67016c7ad3622cdc7aa17b2", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 113, "avg_line_length": 34.44378698224852, "alnum_prop": 0.5526541831300464, "repo_name": "estum/active_model_serializers", "id": "321974e39244597a08c0efe86a2646980e58c996", "size": "5821", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/action_controller/json_api_linked_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "95055" } ], "symlink_target": "" }
<?php /** * Logout as the current user, back to the original user. */ $session = elgg_get_session(); $user_guid = $session->get('login_as_original_user_guid'); $user = get_entity($user_guid); $persistent = $session->get('login_as_original_persistent'); if (!$user instanceof ElggUser || !$user->isadmin()) { register_error(elgg_echo('login_as:unknown_user')); } else { if (login($user, $persistent)) { $session->remove('login_as_original_user_guid'); $session->remove('login_as_original_persistent'); system_message(elgg_echo('login_as:logged_in_as_user', array($user->username))); } else { register_error(elgg_echo('login_as:could_not_login_as_user', array($user->username))); } } forward(REFERER);
{ "content_hash": "0c3f64433b8d4d67ad2d58d6806f5fee", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 88, "avg_line_length": 27.692307692307693, "alnum_prop": 0.6777777777777778, "repo_name": "miniguez/novadores", "id": "f4bc75981dcf3d0d72046b3b402228f11c4a6c17", "size": "720", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "elgg/mod/login_as/actions/logout_as.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "5021" }, { "name": "Batchfile", "bytes": "6697" }, { "name": "CSS", "bytes": "9308" }, { "name": "HTML", "bytes": "29934" }, { "name": "JavaScript", "bytes": "123742" }, { "name": "Makefile", "bytes": "6738" }, { "name": "PHP", "bytes": "5638516" }, { "name": "Python", "bytes": "8408" }, { "name": "Shell", "bytes": "1127" } ], "symlink_target": "" }
import jwt from flask import Blueprint, abort, request from flask.ext.jsonpify import jsonpify from conductor.blueprints.user.controllers import PRIVATE_KEY from . import controllers def create(): """Create blueprint. """ # Create instance blueprint = Blueprint('search', 'search') # Controller Proxies search_controller = controllers.search def search(kind): token = request.values.get('jwt') userid = None try: if token is not None: token = jwt.decode(token, PRIVATE_KEY) userid = token.get('userid') except jwt.InvalidTokenError: pass ret = search_controller(kind, userid, request.args) if ret is None: abort(400) return jsonpify(ret) # Register routes blueprint.add_url_rule( '<kind>', 'search', search, methods=['GET']) # Return blueprint return blueprint
{ "content_hash": "8c37a915b21be10da95d20602c2266da", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 61, "avg_line_length": 24.86842105263158, "alnum_prop": 0.6158730158730159, "repo_name": "openspending/os-authz-service", "id": "a6480c71839d89be9d24b096c7b7b443b84c69d8", "size": "945", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "conductor/blueprints/search/blueprint.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1415" }, { "name": "Python", "bytes": "43730" }, { "name": "Shell", "bytes": "344" } ], "symlink_target": "" }
<?php // Version: 2.1 Beta 2; ManageBoards $txt['boards_and_cats'] = 'Manage Boards and Categories'; $txt['order'] = 'Order'; $txt['full_name'] = 'Full name'; $txt['name_on_display'] = 'This is the name that will be displayed.'; $txt['boards_and_cats_desc'] = 'Edit your categories and boards here. List multiple moderators as <em>&quot;username&quot;, &quot;username&quot;</em>. (these must be usernames and *not* display names)<br>To create a new board, click the Add Board button. To make the new board a sub-board of a current board, select "Sub-board of..." from the Order drop down menu when creating the board.'; $txt['parent_members_only'] = 'Regular Members'; $txt['parent_guests_only'] = 'Guests'; $txt['catConfirm'] = 'Do you really want to delete this category?'; $txt['boardConfirm'] = 'Do you really want to delete this board?'; $txt['catEdit'] = 'Edit Category'; $txt['collapse_enable'] = 'Collapsible'; $txt['collapse_desc'] = 'Allow users to collapse this category'; $txt['catModify'] = '(modify)'; $txt['mboards_order_after'] = 'After '; $txt['mboards_order_inside'] = 'Inside '; $txt['mboards_order_first'] = 'In first place'; $txt['mboards_new_board'] = 'Add Board'; $txt['mboards_new_cat_name'] = 'New Category'; $txt['mboards_add_cat_button'] = 'Add Category'; $txt['mboards_new_board_name'] = 'New Board'; $txt['mboards_name'] = 'Name'; $txt['mboards_modify'] = 'modify'; $txt['mboards_permissions'] = 'permissions'; // Don't use entities in the below string. $txt['mboards_permissions_confirm'] = 'Are you sure you want to switch this board to use local permissions?'; $txt['mboards_delete_cat'] = 'Delete Category'; $txt['mboards_delete_board'] = 'Delete Board'; $txt['mboards_delete_cat_contains'] = 'Deleting this category will also delete the below boards, including all topics, posts and attachments within each board'; $txt['mboards_delete_option1'] = 'Delete category and all boards contained within.'; $txt['mboards_delete_option2'] = 'Delete category and move all boards contained within to'; $txt['mboards_delete_board_contains'] = 'Deleting this board will also move the sub-boards below, including all topics, posts and attachments within each board'; $txt['mboards_delete_board_option1'] = 'Delete board and move sub-boards contained within to category level.'; $txt['mboards_delete_board_option2'] = 'Delete board and move all sub-boards contained within to'; $txt['mboards_delete_what_do'] = 'Please select what you would like to do with these boards'; $txt['mboards_delete_confirm'] = 'Confirm'; $txt['mboards_delete_cancel'] = 'Cancel'; $txt['mboards_category'] = 'Category'; $txt['mboards_description'] = 'Description'; $txt['mboards_description_desc'] = 'A short description of your board. HTML is not allowed, you can use the following BBC tags: {allowed_tags}'; $txt['mboards_cat_description_desc'] = 'A short description of your category. HTML is not allowed, you can use the following BBC tags: {allowed_tags}'; $txt['mboards_groups'] = 'Allowed Groups'; $txt['mboards_groups_desc'] = 'Groups allowed to access this board.<br><em>Note: if the member is in any group or post group checked, they will have access to this board.</em>'; $txt['mboards_groups_regular_members'] = 'This group contains all members that have no primary group set.'; $txt['mboards_groups_post_group'] = 'This group is a post count based group.'; $txt['mboards_moderators'] = 'Moderators'; $txt['mboards_moderators_desc'] = 'Additional members to have moderation privileges on this board. Note that administrators don\'t have to be listed here.'; $txt['mboards_moderator_groups'] = 'Moderator Groups'; $txt['mboards_moderator_groups_desc'] = 'Groups whose members have moderation privileges on this board. Note that this is limited to groups which are not post-based and not "hidden".'; $txt['mboards_count_posts'] = 'Count Posts'; $txt['mboards_count_posts_desc'] = 'Makes new replies and topics raise members\' post counts.'; $txt['mboards_unchanged'] = 'Unchanged'; $txt['mboards_theme'] = 'Board Theme'; $txt['mboards_theme_desc'] = 'This allows you to change the look of your forum inside only this board.'; $txt['mboards_theme_default'] = '(overall forum default.)'; $txt['mboards_override_theme'] = 'Override Member\'s Theme'; $txt['mboards_override_theme_desc'] = 'Use this board\'s theme even if the member didn\'t choose to use the defaults.'; $txt['mboards_redirect'] = 'Redirect to a web address'; $txt['mboards_redirect_desc'] = 'Enable this option to redirect anyone who clicks on this board to another web address.'; $txt['mboards_redirect_url'] = 'Address to redirect users to'; $txt['mboards_redirect_url_desc'] = 'For example: &quot;http://www.simplemachines.org&quot;.'; $txt['mboards_redirect_reset'] = 'Reset redirect count'; $txt['mboards_redirect_reset_desc'] = 'Selecting this will reset the redirection count for this board to zero.'; $txt['mboards_current_redirects'] = 'Currently: %1$s'; $txt['mboards_order_before'] = 'Before'; $txt['mboards_order_child_of'] = 'Sub-board of'; $txt['mboards_order_in_category'] = 'In category'; $txt['mboards_current_position'] = 'Current Position'; $txt['no_valid_parent'] = 'Board %1$s does not have a valid parent. Use the \'find and repair errors\' function to fix this.'; $txt['mboards_recycle_disabled_delete'] = 'Note: You must select an alternative recycle bin board or disable recycling before you can delete this board.'; $txt['mboards_settings_desc'] = 'Edit general board and category settings.'; $txt['groups_manage_boards'] = 'Membergroups allowed to manage boards and categories'; $txt['mboards_settings_submit'] = 'Save'; $txt['recycle_enable'] = 'Enable recycling of deleted topics'; $txt['recycle_board'] = 'Board for recycled topics'; $txt['redirect_board_desc'] = 'A board that redirects users if they visit it'; $txt['recycle_board_unselected_notice'] = 'You have enabled the recycling of topics without specifying a board to place them in. This feature will not be enabled until you specify a board to place recycled topics into.'; $txt['countChildPosts'] = 'Count sub-board\'s posts in parent\'s totals'; $txt['allow_ignore_boards'] = 'Allow boards to be ignored'; $txt['deny_boards_access'] = 'Enable the option to deny board access based on membergroup'; $txt['boardsaccess_option_desc'] = 'For each permission you can choose \'Allow\' (A), \'Disallow\' (X), or <span class="alert">\'Deny\' (D)</span>.<br><br>If you deny access, any member - (including moderators) - in that group will be denied access.<br>For this reason, you should set deny carefully, only when <strong>necessary</strong>. Disallow, on the other hand, denies unless otherwise granted.'; $txt['mboards_select_destination'] = 'Select destination for board \'<strong>%1$s</strong>\''; $txt['mboards_cancel_moving'] = 'Cancel moving'; $txt['mboards_move'] = 'move'; $txt['mboards_no_cats'] = 'There are currently no categories or boards configured.'; ?>
{ "content_hash": "bbf1c600079c50d54230486049bb7b11", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 402, "avg_line_length": 68.04901960784314, "alnum_prop": 0.7207895115977525, "repo_name": "margarett/SMF2.1", "id": "1c1025692c5a5493b680ab1b31b333157d51fd0e", "size": "6941", "binary": false, "copies": "1", "ref": "refs/heads/release-2.1", "path": "Themes/default/languages/ManageBoards.english.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "279" }, { "name": "CSS", "bytes": "136074" }, { "name": "JavaScript", "bytes": "263202" }, { "name": "PHP", "bytes": "6437149" }, { "name": "PLpgSQL", "bytes": "139665" } ], "symlink_target": "" }
// // Quantum Script // // Copyright (c) 2020-2022 Grigore Stefan <g_stefan@yahoo.com> // Created by Grigore Stefan <g_stefan@yahoo.com> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #include <stdio.h> #include <stdlib.h> #include <string.h> #include "quantum-script-variableobject.hpp" #include "quantum-script-context.hpp" #include "quantum-script-objectiteratorkey.hpp" #include "quantum-script-objectiteratorvalue.hpp" #include "quantum-script-variablesymbol.hpp" #include "quantum-script-variablefunction.hpp" #include "quantum-script-variablefunctionwithyield.hpp" #include "quantum-script-variablevmfunction.hpp" #include "quantum-script-variablenativevmfunction.hpp" namespace Quantum { namespace Script { using namespace XYO; XYO_DYNAMIC_TYPE_IMPLEMENT(VariableObject, "{1F81286F-F646-4DCD-B5B5-EEB61C2BFDC0}"); const char *VariableObject::strTypeObject = "Object"; VariableObject::VariableObject() { XYO_DYNAMIC_TYPE_PUSH(VariableObject); value.pointerLink(this); prototype.pointerLink(this); value.newMemory(); prototype.newMemory(); }; String VariableObject::getVariableType() { return strTypeObject; }; Variable *VariableObject::newVariable() { return (Variable *)TMemory<VariableObject>::newMemory(); }; TPointer<Variable> VariableObject::getPropertyBySymbol(Symbol symbolId) { PropertyNode *outX; outX = value->find(symbolId); if (outX) { return outX->value; }; Variable *prototype_ = instancePrototype(); if (prototype_) { return prototype_->getPropertyBySymbol(symbolId); }; return Context::getValueUndefined(); }; TPointer<Variable> VariableObject::getPropertyByIndex(size_t index) { char buffer[22]; sprintf(buffer, "%zu", index); return getPropertyBySymbol(Context::getSymbol(buffer)); }; TPointer<Variable> VariableObject::getPropertyByVariable(Variable *index) { if (TIsType<VariableSymbol>(index)) { return getPropertyBySymbol(((VariableSymbol *)index)->value); }; return getPropertyBySymbol(Context::getSymbol(index->toString())); }; void VariableObject::setPropertyBySymbol(Symbol symbolId, Variable *valueToSet) { PropertyNode *node; node = value->find(symbolId); if (node) { node->value = valueToSet; return; }; node = Property::newNode(); node->key = symbolId; node->value.pointerLink(this); node->value = valueToSet; value->insertNode(node); }; void VariableObject::setPropertyByIndex(size_t index, Variable *valueToSet) { char buffer[22]; sprintf(buffer, "%zu", index); setPropertyBySymbol(Context::getSymbol(buffer), valueToSet); }; void VariableObject::setPropertyByVariable(Variable *index, Variable *valueToSet) { if (TIsType<VariableSymbol>(index)) { return setPropertyBySymbol(((VariableSymbol *)index)->value, valueToSet); }; return setPropertyBySymbol(Context::getSymbol(index->toString()), valueToSet); }; bool VariableObject::deletePropertyBySymbol(Symbol symbolId) { value->remove(symbolId); return true; }; bool VariableObject::deletePropertyByIndex(size_t index) { char buffer[22]; sprintf(buffer, "%zu", index); return deletePropertyBySymbol(Context::getSymbol(buffer)); }; bool VariableObject::deletePropertyByVariable(Variable *index) { if (TIsType<VariableSymbol>(index)) { return deletePropertyBySymbol(((VariableSymbol *)index)->value); }; return deletePropertyBySymbol(Context::getSymbol(index->toString())); }; Variable *VariableObject::instancePrototype() { if (prototype->prototype) { return prototype->prototype; }; if (((Variable *)this) == (Context::getPrototypeObject())->prototype) { return nullptr; }; return (Context::getPrototypeObject())->prototype; }; TPointer<Iterator> VariableObject::getIteratorKey() { ObjectIteratorKey *iterator_ = TMemory<ObjectIteratorKey>::newMemory(); iterator_->value_ = this; iterator_->value = value->begin(); return iterator_; }; TPointer<Iterator> VariableObject::getIteratorValue() { ObjectIteratorValue *iterator_ = TMemory<ObjectIteratorValue>::newMemory(); iterator_->value_ = this; iterator_->value = value->begin(); return iterator_; }; void VariableObject::initMemory() { Variable::initMemory(); TMemory<Prototype>::initMemory(); TMemory<Property>::initMemory(); TMemory<Variable>::initMemory(); }; Variable *VariableObject::clone(SymbolList &inSymbolList) { VariableObject *out = (VariableObject *)newVariable(); PropertyNode *scan; Symbol symbolId; String symbolString; for (scan = value->begin(); scan; scan = scan->successor()) { if (inSymbolList.symbolListMirror.get(scan->key, symbolString)) { symbolId = Context::getSymbol(symbolString.value()); out->value->set(symbolId, scan->value->clone(inSymbolList)); }; }; // don't copy prototype ... return out; }; bool VariableObject::hasPropertyByVariable(Variable *variable) { PropertyNode *outX; Symbol symbolId = Context::getSymbol(variable->toString()); outX = value->find(symbolId); if (outX) { return true; }; Variable *prototype_ = instancePrototype(); if (prototype_) { return prototype_->hasPropertyByVariable(variable); }; return false; }; bool VariableObject::toBoolean() { return true; }; String VariableObject::toString() { TPointer<Variable> variable = getPropertyBySymbol(Context::getSymbolToString()); if ( TIsType<VariableFunction>(variable) || TIsType<VariableFunctionWithYield>(variable) || TIsType<VariableVmFunction>(variable) || TIsType<VariableNativeVmFunction>(variable)) { TPointer<VariableArray> arguments(VariableArray::newArray()); return (variable->functionApply(this, arguments))->toString(); }; return strTypeObject; }; }; };
{ "content_hash": "fe2ef5cf1716118ecace6d66fb958807", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 87, "avg_line_length": 30.597989949748744, "alnum_prop": 0.6825422893742815, "repo_name": "g-stefan/quantum-script", "id": "b85e4ce5b2917e5ad6d2f39955b276774d6826b2", "size": "6091", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "source/quantum-script.lib/quantum-script-variableobject.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "20382" }, { "name": "C++", "bytes": "649446" }, { "name": "JavaScript", "bytes": "20798" }, { "name": "Shell", "bytes": "10921" } ], "symlink_target": "" }
class LogoUploader < CarrierWave::Uploader::Base #Include MiniMagick support: include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # def cache_dir # '/tmp/dmptool2-cache' # end # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: process :scale => [200, 90] # def scale(width, height) resize_to_fit(width, height) end # Create different versions of your uploaded files: # version :thumb do # process :scale => [50, 50] # end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg gif png) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end end
{ "content_hash": "dbf51e2c2b862f9512a0657fdf355396", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 112, "avg_line_length": 28.692307692307693, "alnum_prop": 0.6849865951742627, "repo_name": "2015SebINF1340/dmptool", "id": "1a49b2bcffbced53b9bfe8b5799ca466ba55d935", "size": "1511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/uploaders/logo_uploader.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23475" }, { "name": "HTML", "bytes": "444409" }, { "name": "JavaScript", "bytes": "264451" }, { "name": "Ruby", "bytes": "490623" } ], "symlink_target": "" }
package org.apache.shindig.gadgets.rewrite; import org.apache.shindig.common.uri.Uri; import org.apache.shindig.common.xml.DomUtil; import org.apache.shindig.gadgets.Gadget; import org.apache.shindig.gadgets.http.HttpRequest; import org.apache.shindig.gadgets.http.HttpResponse; import org.apache.shindig.gadgets.spec.View; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Inject; /** * Perform rewriting of HTML content including * - Concatenating & proxying of referred script content * - Concatenating & proxying of stylesheet links * - Moving all style into head and converting @imports into links * - Proxying referred content of images and embeds */ public class HTMLContentRewriter implements GadgetRewriter, RequestRewriter { private final static String JS_MIME_TYPE = "text/javascript"; public final static Set<String> TAGS = ImmutableSet.of("img", "embed", "link", "script", "style"); private final static ImmutableMap<String, ImmutableSet<String>> LINKING_TAG_ATTRS = ImmutableMap.of( "img", ImmutableSet.of("src"), "embed", ImmutableSet.of("src") ); private final ContentRewriterFeatureFactory rewriterFeatureFactory; private final CssRequestRewriter cssRewriter; private final ConcatLinkRewriterFactory concatLinkRewriterFactory; private final ProxyingLinkRewriterFactory proxyingLinkRewriterFactory; @Inject public HTMLContentRewriter(ContentRewriterFeatureFactory rewriterFeatureFactory, CssRequestRewriter cssRewriter, ConcatLinkRewriterFactory concatLinkRewriterFactory, ProxyingLinkRewriterFactory proxyingLinkRewriterFactory) { this.rewriterFeatureFactory = rewriterFeatureFactory; this.cssRewriter = cssRewriter; this.concatLinkRewriterFactory = concatLinkRewriterFactory; this.proxyingLinkRewriterFactory = proxyingLinkRewriterFactory; } public boolean rewrite(HttpRequest request, HttpResponse original, MutableContent content) { if (RewriterUtils.isHtml(request, original)) { ContentRewriterFeature feature = rewriterFeatureFactory.get(request); return rewriteImpl(feature, request.getGadget(), request.getUri(), content, request.getContainer(), false, request.getIgnoreCache()); } return false; } public void rewrite(Gadget gadget, MutableContent content) { // Don't rewrite urls if caja is enabled since caja will inline them anyway if (gadget.getSpec().getModulePrefs().getFeatures().containsKey("caja") || "1".equals(gadget.getContext().getParameter("caja"))) { return; } ContentRewriterFeature feature = rewriterFeatureFactory.get(gadget.getSpec()); Uri contentBase = gadget.getSpec().getUrl(); View view = gadget.getCurrentView(); if (view != null && view.getHref() != null) { contentBase = view.getHref(); } rewriteImpl(feature, gadget.getSpec().getUrl(), contentBase, content, gadget.getContext().getContainer(), gadget.getContext().getDebug(), gadget.getContext().getIgnoreCache()); } boolean rewriteImpl(ContentRewriterFeature feature, Uri gadgetUri, Uri contentBase, MutableContent content, String container, boolean debug, boolean ignoreCache) { if (!feature.isRewriteEnabled() || content.getDocument() == null) { return false; } // Get ALL interesting tags List<Element> tagList = DomUtil.getElementsByTagNameCaseInsensitive(content.getDocument(), TAGS); Element head = (Element)DomUtil.getFirstNamedChildNode( content.getDocument().getDocumentElement(), "head"); boolean mutated = false; // 1st step. Rewrite links in all embedded style tags. Convert @import statements into // links and add them to the tag list. // Move all style and link tags into head and concat the link tags mutated = rewriteStyleTags(head, tagList, feature, gadgetUri, contentBase, container, debug, ignoreCache); // Concat script links mutated |= rewriteJsTags(tagList, feature, gadgetUri, contentBase, container, debug, ignoreCache); // Rewrite links in images, embeds etc mutated |= rewriteContentReferences(tagList, feature, gadgetUri, contentBase, container, debug, ignoreCache); if (mutated) { MutableContent.notifyEdit(content.getDocument()); } return mutated; } protected boolean rewriteStyleTags(Element head, List<Element> elementList, ContentRewriterFeature feature, Uri gadgetUri, Uri contentBase, String container, boolean debug, boolean ignoreCache) { if (!feature.getIncludedTags().contains("style")) { return false; } boolean mutated = false; // Filter to just style tags Iterable<Element> styleTags = Lists.newArrayList(Iterables.filter(elementList, new Predicate<Element>() { public boolean apply(Element element) { return element.getNodeName().equalsIgnoreCase("style"); } })); LinkRewriter linkRewriter = proxyingLinkRewriterFactory.create(gadgetUri, feature, container, debug, ignoreCache); for (Element styleTag : styleTags) { mutated |= true; if (styleTag.getParentNode() != head) { styleTag.getParentNode().removeChild(styleTag); head.appendChild(styleTag); } List<String> extractedUrls = cssRewriter.rewrite( styleTag, contentBase, linkRewriter, true); for (String extractedUrl : extractedUrls) { // Add extracted urls as link elements to head Element newLink = head.getOwnerDocument().createElement("link"); newLink.setAttribute("rel", "stylesheet"); newLink.setAttribute("type", "text/css"); newLink.setAttribute("href", extractedUrl); head.appendChild(newLink); elementList.add(newLink); } } // Filter to just stylesheet link tags List<Element> linkTags = Lists.newArrayList(Iterables.filter(elementList, new Predicate<Element>() { public boolean apply(Element element) { return element.getNodeName().equalsIgnoreCase("link") && ("stylesheet".equalsIgnoreCase(element.getAttribute("rel")) || element.getAttribute("type").toLowerCase().contains("css")); } })); concatenateTags(feature, linkTags, gadgetUri, contentBase, "text/css", "href", container, debug, ignoreCache); return mutated; } protected boolean rewriteJsTags(List<Element> elementList, ContentRewriterFeature feature, Uri gadgetUri, Uri contentBase, String container, boolean debug, boolean ignoreCache) { if (!feature.getIncludedTags().contains("script")) { return false; } boolean mutated = false; // Filter to just script tags List<Element> scriptTags = Lists.newArrayList(Iterables.filter(elementList, new Predicate<Element>() { public boolean apply(Element node) { if (node.getNodeName().equalsIgnoreCase("script")) { String type = node.getAttribute("type"); return type == null || type.length() == 0 || type.equalsIgnoreCase(JS_MIME_TYPE); } return false; } })); List<Element> concatenateable = Lists.newArrayList(); for (int i = 0; i < scriptTags.size(); i++) { Element scriptTag = scriptTags.get(i); Element nextSciptTag = null; if (i + 1 < scriptTags.size()) { nextSciptTag = scriptTags.get(i+1); } if (scriptTag.hasAttribute("src") && feature.shouldRewriteURL(scriptTag.getAttribute("src"))) { mutated = true; concatenateable.add(scriptTag); if (nextSciptTag == null || !nextSciptTag.equals(getNextSiblingElement(scriptTag))) { // Next tag is not concatenateable concatenateTags(feature, concatenateable, gadgetUri, contentBase, JS_MIME_TYPE, "src", container, debug, ignoreCache); concatenateable.clear(); } } else { concatenateTags(feature, concatenateable, gadgetUri, contentBase, JS_MIME_TYPE, "src", container, debug, ignoreCache); concatenateable.clear(); } } concatenateTags(feature, concatenateable, gadgetUri, contentBase, JS_MIME_TYPE, "src", container, debug, ignoreCache); return mutated; } protected boolean rewriteContentReferences(List<Element> elementList, ContentRewriterFeature feature, Uri gadgetUri, Uri contentBase, String container, boolean debug, boolean ignoreCache) { boolean mutated = false; LinkRewriter rewriter = proxyingLinkRewriterFactory.create(gadgetUri, feature, container, debug, ignoreCache); final Set<String> tagNames = Sets.intersection(LINKING_TAG_ATTRS.keySet(), feature.getIncludedTags()); // Filter to just style tags Iterable<Element> tags = Iterables.filter(elementList, new Predicate<Element>() { public boolean apply(Element node) { return tagNames.contains(node.getNodeName().toLowerCase()); } }); for (Element node : tags) { NamedNodeMap attributes = node.getAttributes(); Set<String> rewriteable = LINKING_TAG_ATTRS.get(node.getNodeName().toLowerCase()); for (int i = 0; i < attributes.getLength(); i++) { Node attr = attributes.item(i); if (rewriteable.contains(attr.getNodeName().toLowerCase())) { mutated = true; attr.setNodeValue(rewriter.rewrite(attr.getNodeValue(), contentBase)); } } } return mutated; } private void concatenateTags(final ContentRewriterFeature feature, List<Element> tags, Uri gadgetUri, Uri contentBase, String mimeType, final String attr, String container, boolean debug, boolean ignoreCache) { // Filter out excluded URLs tags = Lists.newArrayList(Iterables.filter(tags, new Predicate<Element>() { public boolean apply(Element element) { return (element.hasAttribute(attr) && feature.shouldRewriteURL(element.getAttribute(attr))); } })); // Eliminate duplicates while maintaining order LinkedHashSet<Uri> nodeRefList = Sets.newLinkedHashSet(); for (Element tag : tags) { try { nodeRefList.add(contentBase.resolve(Uri.parse(tag.getAttribute(attr)))); } catch (IllegalArgumentException e) { // Same behavior as JavascriptTagMerger // Perhaps switch to ignoring script src instead? throw new RuntimeException(e); } } List<Uri> concatented = concatLinkRewriterFactory.create(gadgetUri, feature, container, debug, ignoreCache).rewrite(mimeType, nodeRefList); for (int i = 0; i < tags.size(); i++) { if (i < concatented.size()) { // Set new URLs into existing tags tags.get(i).setAttribute(attr, concatented.get(i).toString()); } else { // Remove remainder tags.get(i).getParentNode().removeChild(tags.get(i)); } } } private Element getNextSiblingElement(Element elem) { Node n = elem; n = n.getNextSibling(); while (n != null && n.getNodeType() != Node.ELEMENT_NODE) { n = n.getNextSibling(); } return (Element)n; } }
{ "content_hash": "ce030d4f9b55e92775defcc05a5b3ec5", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 128, "avg_line_length": 38.77104377104377, "alnum_prop": 0.6930091185410334, "repo_name": "inevo/shindig-1.1-BETA5-incubating", "id": "ca600ee5e879950106a43782b10691f924359962", "size": "12314", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "java/gadgets/src/main/java/org/apache/shindig/gadgets/rewrite/HTMLContentRewriter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "2353" }, { "name": "Java", "bytes": "3596488" }, { "name": "JavaScript", "bytes": "3153239" }, { "name": "PHP", "bytes": "2969921" }, { "name": "Shell", "bytes": "13712" } ], "symlink_target": "" }
#Supported architectures class Architecture: #Plain C++ code generic = {'level': 100, 'name': 'Generic', 'size': 1, 'flag': '' } #C++ with ARM NEON intrinsics neon = {'level': 200, 'name': 'NEON' , 'size': 4, 'flag': '' } #Utility functions def is_generic(arch): return (arch['level'] // 100) == 1 def is_arm(arch): return (arch['level'] // 100) == 2 #Supported data types class DataType: float = 'float' uint32 = 'unsigned int' #Utility functions def is_floating(type): return type in (DataType.float,) def is_integral(type): return type in (DataType.uint32,) #Available language bindings class Binding: all = 'java' #'*all*' java = 'java' #Compile time options class Options: def __init__(self, arch, type, bindings=(Binding.java,), threads=None, java_package='com_vecandroid'): if arch is None or type is None or bindings is None or len(bindings) == 0: raise Exception('Invalid options') #Target architecture self.arch = arch #Kernel data type self.type = type #Language API bindings self.bindings = bindings #Number of threads to spawn self.threads = threads #Java package name self.java_package = java_package def show(self, path=0): print('=' * 40) print('VecAndroid options') print('-' * 40) print('Data Type: ' + self.type) print('Threads: ' + str(self.threads)) print('Architecture: ' + self.arch['name']) #print('Language Bindings: ' + ','.join(self.bindings)) if Binding.all in self.bindings or Binding.java in self.bindings: print('Java Package: ' + str(self.java_package)) if path == 0: print('Save path: ' + '(Not specified.)') else: print('Save path: ' + path) print('=' * 40) #Indent amount def get_indent(level): return ' ' * (4 * level) #Source code formatter class Formatter: def __init__(self): self.level = 0 self.code = '' def section(self, title): width = 78 left = (width - len(title)) // 2 right = width - len(title) - left self.append('/' + ('*' * width) + '*') self.append('*' + (' ' * left) + title + (' ' * right) + '*') self.append('*' + ('*' * width) + '/') def __iadd__(self, other): self.append(other) return self def append(self, code, end='\n'): self.code += get_indent(self.level) + code + end def indent(self): self.level += 1 def unindent(self): self.level -= 1 if self.level < 0: raise Exception('Negative indent') def get_code(self): if self.level != 0: raise Exception('Still indented') return self.code
{ "content_hash": "9ce6c687c796fdec6d631a588c584690", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 104, "avg_line_length": 29.92391304347826, "alnum_prop": 0.5728296403922993, "repo_name": "yongshanding/vecAndroid", "id": "b70b0cae09be1a8d3c6bfdd09fd14852928fd0b8", "size": "2896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils/neoncompile/compiler_constants.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "93198" }, { "name": "Java", "bytes": "4878" }, { "name": "Makefile", "bytes": "3542" } ], "symlink_target": "" }
@interface CAHTableViewController () @property (nonatomic, retain) NSArray* results; @end @implementation CAHTableViewController - (void)viewDidLoad { [super viewDidLoad]; NSURL* url = [NSURL URLWithString:QUERY_URL]; NSData* data = [NSData dataWithContentsOfURL:url]; NSError* error = nil; self.results = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error][@"responseData"][@"results"]; self.title = @"National Parks"; } #pragma mark - #pragma mark UITableViewController - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.results.count; } - (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ImageCell"]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ImageCell"]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } __weak UIImageView* imageView = (UIImageView*)[cell.contentView viewWithTag:100]; __weak UILabel* detailLabel = (UILabel*)[cell.contentView viewWithTag:101]; NSDictionary* response = self.results[indexPath.row]; detailLabel.text = @"Loading"; // load image into image view from web [CAHImageCacher asyncLoadImageIntoImageView:imageView imageURLString:response[@"unescapedUrl"] altImage:[UIImage imageNamed:@"TestImage"] viewToRefresh:imageView completion:^{ detailLabel.text = response[@"titleNoFormatting"]; }]; return cell; } @end
{ "content_hash": "645b8a2408c3fdcd6825f33a96c846af", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 176, "avg_line_length": 30.163636363636364, "alnum_prop": 0.7667269439421338, "repo_name": "chaseholland/CAHImageCacher", "id": "13ad385d91a2637aa049c25ab508f7830c082a0e", "size": "1897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/CAHImageCacher/CAHTableViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "21380" }, { "name": "Ruby", "bytes": "2071" }, { "name": "Shell", "bytes": "16392" } ], "symlink_target": "" }
#include <crypto/crypto_encryption.h> #include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #include <io/net/tcp_server.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_producer.h> #include <io/pipe/splice.h> #include <io/socket/simple_server.h> #include <ssh/ssh_algorithm_negotiation.h> #include <ssh/ssh_protocol.h> #include <ssh/ssh_server_host_key.h> #include <ssh/ssh_session.h> #include <ssh/ssh_transport_pipe.h> /* * XXX Create an SSH chat program. Let only one of each user be connected at a time. Send lines of data to all others. */ class SSHConnection { struct SSHChannel { enum Mode { SetupMode, ShellMode, ExecMode, SubsystemMode }; Mode mode_; uint32_t local_channel_; uint32_t local_window_size_; uint32_t local_packet_size_; uint32_t remote_channel_; uint32_t remote_window_size_; uint32_t remote_packet_size_; std::map<std::string, Buffer> environment_; SSHChannel(uint32_t local_channel, uint32_t remote_channel, uint32_t local_window_size, uint32_t local_packet_size, uint32_t remote_window_size, uint32_t remote_packet_size) : mode_(SetupMode), local_channel_(local_channel), local_window_size_(local_window_size), local_packet_size_(local_packet_size), remote_channel_(remote_channel), remote_window_size_(remote_window_size), remote_packet_size_(remote_packet_size), environment_() { } }; LogHandle log_; Socket *peer_; SSH::Session session_; SSH::TransportPipe *pipe_; Action *receive_action_; Splice *splice_; Action *splice_action_; Action *close_action_; uint32_t channel_next_; std::map<uint32_t, SSHChannel *> channel_map_; public: SSHConnection(Socket *peer) : log_("/ssh/connection"), peer_(peer), session_(SSH::ServerRole), pipe_(NULL), splice_(NULL), splice_action_(NULL), close_action_(NULL), channel_next_(0), channel_map_() { session_.algorithm_negotiation_ = new SSH::AlgorithmNegotiation(&session_); if (session_.role_ == SSH::ServerRole) { SSH::ServerHostKey *server_host_key = SSH::ServerHostKey::server(&session_, "ssh-server1.pem"); session_.algorithm_negotiation_->add_algorithm(server_host_key); } session_.algorithm_negotiation_->add_algorithms(); pipe_ = new SSH::TransportPipe(&session_); EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); splice_ = new Splice(log_ + "/splice", peer_, pipe_, peer_); EventCallback *cb = callback(this, &SSHConnection::splice_complete); splice_action_ = splice_->start(cb); } ~SSHConnection() { ASSERT(log_, close_action_ == NULL); ASSERT(log_, splice_action_ == NULL); ASSERT(log_, splice_ == NULL); ASSERT(log_, receive_action_ == NULL); ASSERT(log_, pipe_ == NULL); ASSERT(log_, peer_ == NULL); } private: void receive_complete(Event e) { receive_action_->cancel(); receive_action_ = NULL; switch (e.type_) { case Event::Done: break; default: ERROR(log_) << "Unexpected event while waiting for a packet: " << e; return; } ASSERT(log_, !e.buffer_.empty()); Buffer service; Buffer type; Buffer msg; SSHChannel *channel; uint32_t recipient_channel, sender_channel, window_size, packet_size; bool want_reply; std::map<uint32_t, SSHChannel *>::const_iterator chit; switch (e.buffer_.peek()) { case SSH::Message::TransportDisconnectMessage: break; case SSH::Message::TransportServiceRequestMessage: /* Claim to support any kind of service the client requests. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No service name after transport request."; return; } if (!SSH::String::decode(&service, &e.buffer_)) { ERROR(log_) << "Could not decode service name."; return; } if (!e.buffer_.empty()) { ERROR(log_) << "Extraneous data after service name."; return; } msg.append(SSH::Message::TransportServiceAcceptMessage); SSH::String::encode(&msg, service); pipe_->send(&msg); if (service.equal("ssh-userauth")) { msg.append(SSH::Message::UserAuthenticationBannerMessage); SSH::String::encode(&msg, std::string(" *\r\n\007 * This is a test server. Sessions, including authentication, may be logged.\r\n *\r\n")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); } break; case SSH::Message::UserAuthenticationRequestMessage: /* Any authentication request succeeds. */ e.buffer_.skip(1); msg.append(SSH::Message::UserAuthenticationSuccessMessage); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelOpen: /* Opening a channel. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel type after channel open."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel type."; return; } if (!SSH::UInt32::decode(&sender_channel, &e.buffer_)) { ERROR(log_) << "Could not decode sender channel."; return; } if (!SSH::UInt32::decode(&window_size, &e.buffer_)) { ERROR(log_) << "Could not decode window size."; return; } if (!SSH::UInt32::decode(&packet_size, &e.buffer_)) { ERROR(log_) << "Could not decode packet size."; return; } /* Only support session channels. */ if (!type.equal("session")) { msg.append(SSH::Message::ConnectionChannelOpenFailure); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, 3); SSH::String::encode(&msg, std::string("Unsupported session type.")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); return; } recipient_channel = sender_channel; sender_channel = channel_setup(recipient_channel, window_size, packet_size); /* Set up session. */ msg.append(SSH::Message::ConnectionChannelOpenConfirmation); SSH::UInt32::encode(&msg, recipient_channel); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, window_size); SSH::UInt32::encode(&msg, packet_size); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelRequest: /* For now just fail any channel request. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel after channel request."; return; } if (!SSH::UInt32::decode(&recipient_channel, &e.buffer_)) { ERROR(log_) << "Could not decode recipient channel."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel request type."; return; } if (e.buffer_.empty()) { ERROR(log_) << "Missing want_reply field."; return; } want_reply = e.buffer_.pop(); chit = channel_map_.find(recipient_channel); if (chit == channel_map_.end()) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, 0); /* XXX What to do for a request that fails due to unknown channel? */ pipe_->send(&msg); } break; } channel = chit->second; if (type.equal("pty-req")) { /* Fail for now. */ } else if (type.equal("env")) { Buffer keybuf; if (!SSH::String::decode(&keybuf, &e.buffer_)) { ERROR(log_) << "Could not decode environment key."; return; } Buffer value; if (!SSH::String::decode(&value, &e.buffer_)) { ERROR(log_) << "Could not decode environment value."; return; } std::string key; keybuf.extract(key); if (channel->environment_.find(key) == channel->environment_.end()) { channel->environment_[key] = value; DEBUG(log_) << "Client set environment variable."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } INFO(log_) << "Client attempted to set environment variable twice."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } else if (type.equal("shell")) { if (channel->mode_ == SSHChannel::SetupMode) { channel->mode_ = SSHChannel::ShellMode; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } msg.append(SSH::Message::ConnectionChannelData); SSH::UInt32::encode(&msg, channel->remote_channel_); SSH::String::encode(&msg, std::string(">>> Connected to shell.\r\n")); pipe_->send(&msg); break; } ERROR(log_) << "Client requested a shell session, but session is not in setup mode."; } else { DEBUG(log_) << "Unhandled channel request type:" << std::endl << type.hexdump(); } if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; case SSH::Message::ConnectionChannelWindowAdjust: /* Follow our peer's lead on window adjustments. */ case SSH::Message::ConnectionChannelData: /* For now, just ignore data. Will pass to something shell-like eventually. */ break; default: DEBUG(log_) << "Unhandled message:" << std::endl << e.buffer_.hexdump(); break; } EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); } void close_complete(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(log_, peer_ != NULL); delete peer_; peer_ = NULL; delete this; } void splice_complete(Event e) { splice_action_->cancel(); splice_action_ = NULL; switch (e.type_) { case Event::EOS: DEBUG(log_) << "Peer exiting normally."; break; case Event::Error: ERROR(log_) << "Peer exiting with error: " << e; break; default: ERROR(log_) << "Peer exiting with unknown event: " << e; break; } ASSERT(log_, splice_ != NULL); delete splice_; splice_ = NULL; if (receive_action_ != NULL) { INFO(log_) << "Peer exiting while waiting for a packet."; receive_action_->cancel(); receive_action_ = NULL; } ASSERT(log_, pipe_ != NULL); delete pipe_; pipe_ = NULL; ASSERT(log_, close_action_ == NULL); SimpleCallback *cb = callback(this, &SSHConnection::close_complete); close_action_ = peer_->close(cb); } uint32_t channel_setup(const uint32_t& remote_channel, const uint32_t& window_size, const uint32_t& packet_size) { std::map<uint32_t, SSHChannel *>::const_iterator it; uint32_t local_channel; uint32_t next = channel_next_; for (;;) { it = channel_map_.find(next); if (it == channel_map_.end()) break; next++; } channel_next_ = next + 1; local_channel = next; channel_map_[local_channel] = new SSHChannel(local_channel, remote_channel, 65536, 65536, window_size, packet_size); return (local_channel); } }; class SSHServer : public SimpleServer<TCPServer> { public: SSHServer(SocketAddressFamily family, const std::string& interface) : SimpleServer<TCPServer>("/ssh/server", family, interface) { } ~SSHServer() { } void client_connected(Socket *client) { new SSHConnection(client); } }; int main(void) { new SSHServer(SocketAddressFamilyIP, "[::]:2299"); event_main(); }
{ "content_hash": "61e4164746c8a13195074ba2b28ba02a", "timestamp": "", "source": "github", "line_count": 410, "max_line_length": 175, "avg_line_length": 27.826829268292684, "alnum_prop": 0.6435270400560961, "repo_name": "diegows/wanproxy", "id": "7ca09915c2e706f0598efcb1a93e0de9c1beaeee", "size": "12756", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ssh/example/ssh-server1/ssh-server1.cc", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "935775" }, { "name": "Awk", "bytes": "120493" }, { "name": "C", "bytes": "54615824" }, { "name": "C++", "bytes": "1777707" }, { "name": "Objective-C", "bytes": "75702" }, { "name": "Shell", "bytes": "29861" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Mycol. Res. 113(3): 287 (2008) #### Original name Calonectria pruinosa Petch ### Remarks null
{ "content_hash": "076091073bc005ff69767e047edd28a7", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 30, "avg_line_length": 12.076923076923077, "alnum_prop": 0.6942675159235668, "repo_name": "mdoering/backbone", "id": "70b47299507cfd067f385b37d7a9f486c25ba983", "size": "259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Ophiocordycipitaceae/Ophiocordyceps/Ophiocordyceps pruinosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// --------------------------------------------------------------------------------- // <copyright file="LoadPostItMessageComposer.cs" company="https://github.com/sant0ro/Yupi"> // Copyright (c) 2016 Claudio Santoro, TheDoctor // </copyright> // <license> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // </license> // --------------------------------------------------------------------------------- namespace Yupi.Messages.Items { using System; using Yupi.Model.Domain; using Yupi.Protocol.Buffers; public class LoadPostItMessageComposer : Yupi.Messages.Contracts.LoadPostItMessageComposer { #region Methods public override void Compose(Yupi.Protocol.ISender session, PostItItem item) { using (ServerMessage message = Pool.GetMessageBuffer(Id)) { message.AppendString(item.Id.ToString()); message.AppendString(item.Text); session.Send(message); } } #endregion Methods } }
{ "content_hash": "af7b093fabc004f58d2e67f58161c3fd", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 94, "avg_line_length": 43.416666666666664, "alnum_prop": 0.6429942418426103, "repo_name": "TheDoct0r11/Yupi", "id": "7646a3a2856bc32e9903cf529c4d934be02d50ef", "size": "2086", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "Yupi.Messages/Composer/Items/LoadPostItMessageComposer.cs", "mode": "33261", "license": "mit", "language": [ { "name": "ASP", "bytes": "49" }, { "name": "Batchfile", "bytes": "48" }, { "name": "C#", "bytes": "3235386" }, { "name": "CSS", "bytes": "1232" }, { "name": "HTML", "bytes": "1769025" }, { "name": "Python", "bytes": "1894" }, { "name": "Shell", "bytes": "1150" } ], "symlink_target": "" }
from dwarfsquad.lib.compat import join_dicts from dwarfsquad.model.BaseWebModel import BaseWebModel class Smoothing(BaseWebModel): required_fields = { "optimal_enabled": True, "fixed": "", "min": "4", "max": "22", "start": "8" } @classmethod def __str__(cls): return "smoothing" def __init__(self, *args): base = {} for arg in reversed(args): if isinstance(arg, dict): base = join_dicts(arg, base) BaseWebModel.__init__(self, self.build_required_entities_only(base)) def set_max(self, max): try: int(max) self.max = str(int(max)) except ValueError: self.max = str(33) def set_optimal_enabled(self, optimal_enabled): self.optimal_enabled = str(optimal_enabled).lower() == 'true' def set_min(self, min): try: self.min = str(int(min)) except ValueError: self.min = str(3) def set_start(self, start): try: self.start = str(int(start)) except ValueError: self.start = str(12) def set_fixed(self, fixed): try: self.fixed = str(int(fixed)) except ValueError: self.fixed = str(12)
{ "content_hash": "0bca5a3e43f46d6dc4e86c0c705039ff", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 76, "avg_line_length": 25.153846153846153, "alnum_prop": 0.5275229357798165, "repo_name": "whereskenneth/Dwarfsquad", "id": "9469549b4a8c23e45604359769117791ffdbca7f", "size": "1308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dwarfsquad/model/Smoothing.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "107917" } ], "symlink_target": "" }
<?php /** * Needed for error handling */ require_once 'PEAR.php'; require_once 'PEAR/Frontend.php'; require_once 'PEAR/XMLParser.php'; /** * List of commands and what classes they are implemented in. * @var array command => implementing class */ $GLOBALS['_PEAR_Command_commandlist'] = array(); /** * List of commands and their descriptions * @var array command => description */ $GLOBALS['_PEAR_Command_commanddesc'] = array(); /** * List of shortcuts to common commands. * @var array shortcut => command */ $GLOBALS['_PEAR_Command_shortcuts'] = array(); /** * Array of command objects * @var array class => object */ $GLOBALS['_PEAR_Command_objects'] = array(); /** * PEAR command class, a simple factory class for administrative * commands. * * How to implement command classes: * * - The class must be called PEAR_Command_Nnn, installed in the * "PEAR/Common" subdir, with a method called getCommands() that * returns an array of the commands implemented by the class (see * PEAR/Command/Install.php for an example). * * - The class must implement a run() function that is called with three * params: * * (string) command name * (array) assoc array with options, freely defined by each * command, for example: * array('force' => true) * (array) list of the other parameters * * The run() function returns a PEAR_CommandResponse object. Use * these methods to get information: * * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL) * *_PARTIAL means that you need to issue at least * one more command to complete the operation * (used for example for validation steps). * * string getMessage() Returns a message for the user. Remember, * no HTML or other interface-specific markup. * * If something unexpected happens, run() returns a PEAR error. * * - DON'T OUTPUT ANYTHING! Return text for output instead. * * - DON'T USE HTML! The text you return will be used from both Gtk, * web and command-line interfaces, so for now, keep everything to * plain text. * * - DON'T USE EXIT OR DIE! Always use pear errors. From static * classes do PEAR::raiseError(), from other classes do * $this->raiseError(). * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version Release: @package_version@ * @link http://pear.php.net/package/PEAR * @since Class available since Release 0.1 */ class PEAR_Command { // {{{ factory() /** * Get the right object for executing a command. * * @param string $command The name of the command * @param object $config Instance of PEAR_Config object * * @return object the command object or a PEAR error * * @access public * @static */ function &factory($command, &$config) { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { $a = PEAR::raiseError("unknown command `$command'"); return $a; } $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; if (!class_exists($class)) { require_once $GLOBALS['_PEAR_Command_objects'][$class]; } if (!class_exists($class)) { $a = PEAR::raiseError("unknown command `$command'"); return $a; } $ui =& PEAR_Command::getFrontendObject(); $obj = &new $class($ui, $config); return $obj; } // }}} // {{{ & getObject() function &getObject($command) { $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; if (!class_exists($class)) { require_once $GLOBALS['_PEAR_Command_objects'][$class]; } if (!class_exists($class)) { return PEAR::raiseError("unknown command `$command'"); } $ui =& PEAR_Command::getFrontendObject(); $config = &PEAR_Config::singleton(); $obj = &new $class($ui, $config); return $obj; } // }}} // {{{ & getFrontendObject() /** * Get instance of frontend object. * * @return object|PEAR_Error * @static */ function &getFrontendObject() { $a = &PEAR_Frontend::singleton(); return $a; } // }}} // {{{ & setFrontendClass() /** * Load current frontend class. * * @param string $uiclass Name of class implementing the frontend * * @return object the frontend object, or a PEAR error * @static */ function &setFrontendClass($uiclass) { $a = &PEAR_Frontend::setFrontendClass($uiclass); return $a; } // }}} // {{{ setFrontendType() /** * Set current frontend. * * @param string $uitype Name of the frontend type (for example "CLI") * * @return object the frontend object, or a PEAR error * @static */ function setFrontendType($uitype) { $uiclass = 'PEAR_Frontend_' . $uitype; return PEAR_Command::setFrontendClass($uiclass); } // }}} // {{{ registerCommands() /** * Scan through the Command directory looking for classes * and see what commands they implement. * * @param bool (optional) if FALSE (default), the new list of * commands should replace the current one. If TRUE, * new entries will be merged with old. * * @param string (optional) where (what directory) to look for * classes, defaults to the Command subdirectory of * the directory from where this file (__FILE__) is * included. * * @return bool TRUE on success, a PEAR error on failure * * @access public * @static */ function registerCommands($merge = false, $dir = null) { $parser = new PEAR_XMLParser; if ($dir === null) { $dir = dirname(__FILE__) . '/Command'; } if (!is_dir($dir)) { return PEAR::raiseError("registerCommands: opendir($dir) '$dir' does not exist or is not a directory"); } $dp = @opendir($dir); if (empty($dp)) { return PEAR::raiseError("registerCommands: opendir($dir) failed"); } if (!$merge) { $GLOBALS['_PEAR_Command_commandlist'] = array(); } while ($file = readdir($dp)) { if ($file{0} == '.' || substr($file, -4) != '.xml') { continue; } $f = substr($file, 0, -4); $class = "PEAR_Command_" . $f; // List of commands if (empty($GLOBALS['_PEAR_Command_objects'][$class])) { $GLOBALS['_PEAR_Command_objects'][$class] = "$dir/" . $f . '.php'; } $parser->parse(file_get_contents("$dir/$file")); $implements = $parser->getData(); foreach ($implements as $command => $desc) { if ($command == 'attribs') { continue; } if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { return PEAR::raiseError('Command "' . $command . '" already registered in ' . 'class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"'); } $GLOBALS['_PEAR_Command_commandlist'][$command] = $class; $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary']; if (isset($desc['shortcut'])) { $shortcut = $desc['shortcut']; if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) { return PEAR::raiseError('Command shortcut "' . $shortcut . '" already ' . 'registered to command "' . $command . '" in class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"'); } $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command; } if (isset($desc['options']) && $desc['options']) { foreach ($desc['options'] as $oname => $option) { if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) { return PEAR::raiseError('Option "' . $oname . '" short option "' . $option['shortopt'] . '" must be ' . 'only 1 character in Command "' . $command . '" in class "' . $class . '"'); } } } } } ksort($GLOBALS['_PEAR_Command_shortcuts']); ksort($GLOBALS['_PEAR_Command_commandlist']); @closedir($dp); return true; } // }}} // {{{ getCommands() /** * Get the list of currently supported commands, and what * classes implement them. * * @return array command => implementing class * * @access public * @static */ function getCommands() { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } return $GLOBALS['_PEAR_Command_commandlist']; } // }}} // {{{ getShortcuts() /** * Get the list of command shortcuts. * * @return array shortcut => command * * @access public * @static */ function getShortcuts() { if (empty($GLOBALS['_PEAR_Command_shortcuts'])) { PEAR_Command::registerCommands(); } return $GLOBALS['_PEAR_Command_shortcuts']; } // }}} // {{{ getGetoptArgs() /** * Compiles arguments for getopt. * * @param string $command command to get optstring for * @param string $short_args (reference) short getopt format * @param array $long_args (reference) long getopt format * * @return void * * @access public * @static */ function getGetoptArgs($command, &$short_args, &$long_args) { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { return null; } $obj = &PEAR_Command::getObject($command); return $obj->getGetoptArgs($command, $short_args, $long_args); } // }}} // {{{ getDescription() /** * Get description for a command. * * @param string $command Name of the command * * @return string command description * * @access public * @static */ function getDescription($command) { if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) { return null; } return $GLOBALS['_PEAR_Command_commanddesc'][$command]; } // }}} // {{{ getHelp() /** * Get help for command. * * @param string $command Name of the command to return help for * * @access public * @static */ function getHelp($command) { $cmds = PEAR_Command::getCommands(); if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (isset($cmds[$command])) { $obj = &PEAR_Command::getObject($command); return $obj->getHelp($command); } return false; } // }}} }
{ "content_hash": "f936be9b0b38e21794bc57ca48b3b127", "timestamp": "", "source": "github", "line_count": 400, "max_line_length": 115, "avg_line_length": 30.565, "alnum_prop": 0.5339440536561426, "repo_name": "glensc/php-pear-core", "id": "5dd3cc5943e8e7965ffffb2317ebddec1c0e94a1", "size": "12663", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "PEAR/Command.php", "mode": "33188", "license": "bsd-2-clause", "language": [], "symlink_target": "" }
<?php use yii\db\Schema; use yii\db\Migration; class m150724_101714_words extends Migration { public function up() { $this->createTable('words', [ 'id' => Schema::TYPE_PK, 'name' => Schema::TYPE_STRING . '(60) NOT NULL', ]); } public function down() { $this->dropTable('words'); /*echo "m150724_101714_word cannot be reverted.\n"; return false;*/ } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ }
{ "content_hash": "cf072089d44ef6d42cd713d312e00f8b", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 69, "avg_line_length": 18, "alnum_prop": 0.526984126984127, "repo_name": "dmitry-zinchenko/Connected", "id": "3f73a6ccac81babdb553deeee7ade60ea735f062", "size": "630", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "migrations/m150724_101714_words.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "113" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "371549" }, { "name": "JavaScript", "bytes": "175017" }, { "name": "PHP", "bytes": "175756" } ], "symlink_target": "" }
package com.pheide.trainose; import android.database.Cursor; /** * Helper functions when using cursors. * * @author Christine Gerpheide */ public class CursorHelper { /** * Convenience method to return the specified column * in a Cursor as a long. * * @param Cursor the managed cursor * @param columnName the column to retrieve * * @return the column as a long */ public static long getLong(Cursor cursor, String columnName) { return cursor.getLong(cursor.getColumnIndex(columnName)); } /** * Convenience method to return the specified column * in a Cursor as a String. * * @param Cursor the managed cursor * @param columnName the column to retrieve * * @return the column as a String */ public static String getString(Cursor cursor, String columnName) { return cursor.getString(cursor.getColumnIndex(columnName)); } /** * Convenience method to return the specified column * in a Cursor as an int. * * @param Cursor the managed cursor * @param columnName the column to retrieve * * @return the column as an int */ public static int getInt(Cursor cursor, String columnName) { return cursor.getInt(cursor.getColumnIndex(columnName)); } }
{ "content_hash": "cc9bdc3869ae7165cc735c2d322f97c7", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 67, "avg_line_length": 23.53846153846154, "alnum_prop": 0.704248366013072, "repo_name": "phoxicle/TrainOse", "id": "6a2c72a044cc9f5c969404ae97efd788c5dcea95", "size": "1224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/pheide/trainose/CursorHelper.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "65313" }, { "name": "PHP", "bytes": "32853" } ], "symlink_target": "" }
title "Generating Projects..." mvn archetype:generate -B -DarchetypeCatalog=local -DarchetypeRepository=local -DarchetypeGroupId=com.shijie99 -DarchetypeArtifactId=quick-start-archetype -DarchetypeVersion=0.0.1-SNAPSHOT -DgroupId=com.shijie99 -DartifactId=testArcheType -Dpackage=com.shijie99.basic
{ "content_hash": "d652c3c7688954b04442875c1174da29", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 267, "avg_line_length": 100, "alnum_prop": 0.8433333333333334, "repo_name": "zhoucl/quick-start", "id": "d29b58aa28ce6534d7990f1753c979dcb69a0edb", "size": "300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quickstart.bat", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "300" }, { "name": "CSS", "bytes": "12978" }, { "name": "Java", "bytes": "392632" }, { "name": "JavaScript", "bytes": "414402" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.elfwerks</groupId> <artifactId>spring-dynamic-languages</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>spring-dynamic-languages</name> <organization> <name>Elfwerks</name> <url>http://spot.elfwerks.org</url> </organization> <properties> <spring.version>3.0.5.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <artifactId>mail</artifactId> <groupId>javax.mail</groupId> </exclusion> <exclusion> <artifactId>jms</artifactId> <groupId>javax.jms</groupId> </exclusion> <exclusion> <artifactId>jmxtools</artifactId> <groupId>com.sun.jdmk</groupId> </exclusion> <exclusion> <artifactId>jmxri</artifactId> <groupId>com.sun.jmx</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <inherited>true</inherited> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <artifactId>maven-source-plugin</artifactId> <executions> <execution> </execution> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-javadoc-plugin</artifactId> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "f8b0fd3273ae052831fd8e8e1c9c135c", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 104, "avg_line_length": 28.37864077669903, "alnum_prop": 0.5843311666096476, "repo_name": "egustafson/sandbox", "id": "7f1984b346a9de436d8e1046ba49f1c0b4a42ee3", "size": "2923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Java/mvn/spring-dynamic-languages/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "65426" }, { "name": "Assembly", "bytes": "2103" }, { "name": "C", "bytes": "94748" }, { "name": "C++", "bytes": "52883" }, { "name": "Dockerfile", "bytes": "873" }, { "name": "FreeMarker", "bytes": "195" }, { "name": "Game Maker Language", "bytes": "24204" }, { "name": "Go", "bytes": "128092" }, { "name": "Groovy", "bytes": "584" }, { "name": "HTML", "bytes": "2491" }, { "name": "Java", "bytes": "232698" }, { "name": "JavaScript", "bytes": "278" }, { "name": "Lex", "bytes": "2806" }, { "name": "Lua", "bytes": "809" }, { "name": "M4", "bytes": "1718" }, { "name": "Makefile", "bytes": "22166" }, { "name": "Perl", "bytes": "25945" }, { "name": "Python", "bytes": "131732" }, { "name": "Roff", "bytes": "1455" }, { "name": "Ruby", "bytes": "5870" }, { "name": "Scala", "bytes": "2130" }, { "name": "Shell", "bytes": "7117" }, { "name": "Tcl", "bytes": "4561" }, { "name": "TeX", "bytes": "63201" }, { "name": "Yacc", "bytes": "924" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.kc.using_notification.app.NotificationActivity"> <item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderInCategory="100" app:showAsAction="never"/> </menu>
{ "content_hash": "0b110994e8449bbdb0e82ef804e17c24", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 73, "avg_line_length": 47.666666666666664, "alnum_prop": 0.6806526806526807, "repo_name": "kingsamchen/Eureka", "id": "53cade69e51d005f5cb20d0281a1c5c15ad6c4ae", "size": "429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LearnAndroid/Using-Notification/app/src/main/res/menu/menu_notification.xml", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "320" }, { "name": "Assembly", "bytes": "1523" }, { "name": "C", "bytes": "115900" }, { "name": "C#", "bytes": "21241" }, { "name": "C++", "bytes": "1125565" }, { "name": "CMake", "bytes": "645800" }, { "name": "Dockerfile", "bytes": "717" }, { "name": "Go", "bytes": "111089" }, { "name": "HTML", "bytes": "3869" }, { "name": "Java", "bytes": "101720" }, { "name": "Makefile", "bytes": "110" }, { "name": "PowerShell", "bytes": "9136" }, { "name": "Python", "bytes": "210011" }, { "name": "Shell", "bytes": "9338" } ], "symlink_target": "" }
Scrape [HKExnews](http://www.hkexnews.hk/sdw/search/search_sdw_c.asp) share holdings page and output JSON data. HKExnews will return data for the previous day if the day requested is a public holiday. If the period is greater than `30` calender days, weekly data for each Friday within the period will be used. > Note: `Date` object prototype will be extended by this package ## Installation ```bash npm install hkstock-holdings ``` ## Usage See [bin/hkstock-holdings](bin/hkstock-holdings). ```sh bin/hkstock-holdings -t 1w 5 -j ``` ## Data Returned ```javascript var _result = { code, // code of the stock name, // name of the stock // period specified by user startDate, endDate, // actual dates where data is retrieved // this is a subset of the input period (minus public holidays) period, series // array with each element corresponding to data of one // parti over the period, filling missing records and have // some statistics computed, suitable for plotting }; ``` ## Debug Following `needle`, `hkstock-holdings` uses [visionmedia/debug](https://github.com/visionmedia/debug) to enable debug message at runtime. It defines two scopes: `stockholding:main` and `stockholding:scraper`. Also check the comments in [lib/scraper.js](lib/scraper.js) for the expected content of DOM elements. ```sh DEBUG=stockholding:main,stockholding:scraper bin/hkstock-holdings -vB 5 -j # adding scrapebp to the mix DEBUG=stockholding:main,stockholding:scraper,scrapebp bin/hkstock-holdings -vB 5 -j ``` ## Performance > `user` field can be taken as the time spent by this (and under-lying) modules ### 20140211 ```sh time ./bin/hkstock-holdings 1 -t 1m -e 2014-01-31 -j real 0m8.275s user 0m2.512s sys 0m0.288s ``` ```sh time ./bin/hkstock-holdings 700 -t 1m -e 2014-01-31 -j real 0m8.108s user 0m2.360s sys 0m0.196s ``` ### 20140223 ```sh time ./bin/hkstock-holdings 1 -t 1m -e 2014-01-31 -j real 0m7.342s user 0m2.188s sys 0m0.164s ``` ```sh time ./bin/hkstock-holdings 700 -t 1m -e 2014-01-31 -j real 0m5.460s user 0m2.124s sys 0m0.184s ```
{ "content_hash": "e16e6963fd107f78271416e813342f4c", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 137, "avg_line_length": 23.747252747252748, "alnum_prop": 0.6973623322535863, "repo_name": "leesei/node-hkstock-holdings", "id": "ab0b89c5ecf4d8e1106aacbce6aa9490cad19c1d", "size": "2186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "17483" } ], "symlink_target": "" }
#include "slib/ui/image_view.h" #include "slib/core/timer.h" namespace slib { SLIB_DEFINE_OBJECT(ImageView, View) ImageView::ImageView() { setSavingCanvasState(sl_false); m_scaleMode = ScaleMode::Stretch; m_gravity = Alignment::MiddleCenter; m_flagAutoAspectRatio = sl_false; m_aspectRatioMin = -1; m_aspectRatioMax = -1; } ImageView::~ImageView() { } Ref<ImageView> ImageView::create(sl_ui_len width, sl_ui_len height, const Ref<slib::Drawable> &drawable) { Ref<ImageView> ret = new ImageView; if (ret.isNotNull()) { ret->setSource(drawable, UIUpdateMode::Init); ret->setWidth(width, UIUpdateMode::Init); ret->setHeight(height, UIUpdateMode::Init); return ret; } return sl_null; } Ref<Drawable> ImageView::getSource() { return m_source; } void ImageView::setSource(const Ref<Drawable>& source, UIUpdateMode mode) { if (m_source == source) { return; } m_source = source; m_timerAnimation.setNull(); if (source.isNotNull()) { if (m_flagAutoAspectRatio) { sl_real h = source->getDrawableHeight(); if (h > 0.0000001) { sl_real ratio = source->getDrawableWidth() / h; sl_real min = m_aspectRatioMin; if (min > 0.0000001) { if (ratio < min) { ratio = min; } } sl_real max = m_aspectRatioMax; if (max > 0) { if (ratio > max) { ratio = max; } } setAspectRatio(ratio, mode); } } DrawableAnimationInfo animation; if (source->getAnimationInfo(&animation)) { float fps = animation.framesPerSecond; if (fps < 1) { fps = 1; } sl_uint32 interval = (sl_int32)(1000 / fps); if (interval > 60) { interval = 60; } m_timeStartAnimation = Time::now(); m_timerAnimation = startTimer(SLIB_FUNCTION_WEAKREF(ImageView, onAnimationFrame, this), interval); } } invalidateLayoutOfWrappingControl(mode); } ScaleMode ImageView::getScaleMode() { return m_scaleMode; } void ImageView::setScaleMode(ScaleMode scaleMode, UIUpdateMode updateMode) { m_scaleMode = scaleMode; invalidate(updateMode); } Alignment ImageView::getGravity() { return m_gravity; } void ImageView::setGravity(const Alignment& align, UIUpdateMode mode) { m_gravity = align; invalidate(mode); } sl_bool ImageView::isAutoAspectRatio() { return m_flagAutoAspectRatio; } void ImageView::setAutoAspectRatio(sl_bool flag) { m_flagAutoAspectRatio = flag; } sl_real ImageView::getMinimumAutoAspectRatio() { return m_aspectRatioMin; } void ImageView::setMinimumAutoAspectRatio(sl_real ratio) { m_aspectRatioMin = ratio; } sl_real ImageView::getMaximumAutoAspectRatio() { return m_aspectRatioMax; } void ImageView::setMaximumAutoAspectRatio(sl_real ratio) { m_aspectRatioMax = ratio; } void ImageView::onDraw(Canvas* canvas) { if (m_timerAnimation.isNotNull()) { double time = (Time::now() - m_timeStartAnimation).getSecondsCountf(); DrawParam param; param.time = (float)time; canvas->draw(getBoundsInnerPadding(), m_source, m_scaleMode, m_gravity, param); } else { canvas->draw(getBoundsInnerPadding(), m_source, m_scaleMode, m_gravity); } } void ImageView::onUpdateLayout() { sl_bool flagHorizontal = isWidthWrapping(); sl_bool flagVertical = isHeightWrapping(); if (!flagVertical && !flagHorizontal) { return; } Ref<Drawable> source = m_source; if (source.isNotNull()) { if (flagHorizontal) { setLayoutWidth((sl_ui_len)(source->getDrawableWidth())); } if (flagVertical) { setLayoutHeight((sl_ui_len)(source->getDrawableHeight())); } } } void ImageView::onAnimationFrame(Timer* timer) { invalidate(); } }
{ "content_hash": "0d7606e41ee437c307db611ca33684ff", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 105, "avg_line_length": 21.056497175141242, "alnum_prop": 0.661658170110008, "repo_name": "SLIBIO/SLib", "id": "dab1f44d91eee44af2d54e318626e1252ff8b649", "size": "4902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/slib/ui/image_view.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "12324" }, { "name": "C", "bytes": "172728" }, { "name": "C++", "bytes": "8974152" }, { "name": "CMake", "bytes": "25579" }, { "name": "Java", "bytes": "412451" }, { "name": "Objective-C", "bytes": "13961" }, { "name": "Objective-C++", "bytes": "641784" }, { "name": "PHP", "bytes": "306070" }, { "name": "Shell", "bytes": "4835" }, { "name": "SourcePawn", "bytes": "19475" } ], "symlink_target": "" }
Contributing ============ Get Source Code --------------- Clone the repo from github:: $ git clone git@github.com:tomcatmanager/tomcatmanager.git Create Python Environments -------------------------- tomcatamanger uses `tox <https://tox.readthedocs.io/en/latest/>`_ to run the test suite against multiple python versions. I recommend using `pyenv <https://github.com/pyenv/pyenv>`_ with the `pyenv-virtualenv <https://github.com/pyenv/pyenv-virtualenv>`_ plugin to manage these various versions. If you are a Windows user, ``pyenv`` won't work for you, you'll probably have to use `conda <https://conda.io/>`_. This distribution includes a shell script ``build-pyenvs.sh`` which automates the creation of these environments. If you prefer to create these virtual envs by hand, do the following:: $ cd tomcatmanager $ pyenv install 3.8.0 $ pyenv virtualenv -p python3.8 3.8.0 tomcatmanager-3.8 $ pyenv install 3.7.5 $ pyenv virtualenv -p python3.7 3.7.5 tomcatmanager-3.7 $ pyenv install 3.6.9 $ pyenv virtualenv -p python3.6 3.6.9 tomcatmanager-3.6 $ pyenv install 3.5.8 $ pyenv virtualenv -p python3.5 3.5.8 tomcatmanager-3.5 Now set pyenv to make all four of those available at the same time:: $ pyenv local tomcatmanager-3.8 tomcatmanager-3.7 tomcatmanager-3.6 tomcatmanager-3.5 Whether you ran the script, or did it by hand, you now have isolated virtualenvs for each of the minor python versions. This table shows various python commands, the version of python which will be executed, and the virtualenv it will utilize. ============= ====== ================= Command python virtualenv ============= ====== ================= ``python`` 3.8.0 tomcatmanager-3.8 ``python3`` 3.8.0 tomcatmanager-3.8 ``python3.8`` 3.8.0 tomcatmanager-3.8 ``python3.7`` 3.7.5 tomcatmanager-3.7 ``python3.6`` 3.6.9 tomcatmanager-3.6 ``python3.5`` 3.5.8 tomcatmanager-3.5 ``pip`` 3.8.0 tomcatmanager-3.8 ``pip3`` 3.8.0 tomcatmanager-3.8 ``pip3.8`` 3.8.0 tomcatmanager-3.8 ``pip3.7`` 3.7.5 tomcatmanager-3.7 ``pip3.6`` 3.6.9 tomcatmanager-3.6 ``pip3.5`` 3.5.8 tomcatmanager-3.5 ============= ====== ================= Install Dependencies -------------------- Now install all the development dependencies:: $ pip install -e .[dev] This installs the tomcatmanager package "in-place", so the package points to the source code instead of copying files to the python ``site-packages`` folder. All the dependencies now have been installed in the ``tomcatmanager-3.8`` virtualenv. If you want to work in other virtualenvs, you'll need to manually select it, and install again:: $ pyenv shell tomcatmanager-3.6 $ pip install -e .[dev] Branches, Tags, and Versions ---------------------------- This project uses a simplified version of the `git flow branching strategy <http://nvie.com/posts/a-successful-git-branching-model/>`_. We don't use release branches, and we generally don't do hotfixes, so we don't have any of those branches either. The master branch always contains the latest release of the code uploaded to PyPI, with a tag for the version number of that release. The develop branch is where all the action occurs. Feature branches are welcome. When it's time for a release, we merge develop into master. This project uses `semantic versioning <https://semver.org/>`_. Invoking Common Development Tasks --------------------------------- This project uses many other python modules for various development tasks, including testing, rendering documentation, and building and distributing releases. These modules can be configured many different ways, which can make it difficult to learn the specific incantations required for each project you are familiar with. This project uses `invoke <http://www.pyinvoke.org>`_ to provide a clean, high level interface for these development tasks. To see the full list of functions available:: $ invoke -l You can run multiple tasks in a single invocation, for example:: $ invoke clean docs sdist wheel That one command will remove all superflous cache, testing, and build files, render the documentation, and build a source distribution and a wheel distribution. You probably won't need to read further in this document unless you want more information about the specific tools used. Testing ------- To ensure the tests can run without an external dependencies, ``tests/mock_server80.py`` contains a HTTP server which emulates the behavior of Tomcat Manager 8.0. There is a test fixture to start this server, and all the tests run against this fixture. I created this fixture to speed up testing time. It doesn't do everything a real Tomcat server does, but it's close enough for the tests to run, and it allows you to parallelize the test suite using ``python-xdist``. You can run the tests against all the supported versions of python using tox:: $ tox tox expects that when it runs ``python3.4`` it will actually get a python from the 3.4.x series. That's why we set up the various python environments earlier. If you just want to run the tests in your current python environment, use pytest:: $ pytest This runs all the test in ``tests/`` and also runs doctests in ``tomcatmanager/`` and ``docs/``. You can speed up the test suite by using ``pytest-xdist`` to parallelize the tests across the number of cores you have:: $ pip install pytest-xdist $ pytest -n8 In many of the doctests you'll see something like: >>> tomcat = getfixture('tomcat') This ``getfixture()`` helper imports fixtures defined in ``conftest.py``, which has several benefits: - reduces the amount of redundant code in doctests which shows connecting to a tomcat server and handling exceptions - allows doctests to execute against a mock tomcat server Testing Against A Real Server ----------------------------- If you wish, you can run the test suite against a real Tomcat Server instead of against the mock server included in this distribution. Running the test suite will deploy and undeploy an app hundreds of times, and will definitely trigger garbage collection, so you might not want to run it against a production server. It's also slow (which is why the tests normally run against a mock server). When I run the test suite against a stock Tomcat on a Linode with 2 cores and 4GB of memory it takes approximately 3 minutes to complete. I don't think throwing more CPU at this would make it any faster: during the run of the test suite the Tomcat Server never consumes more than a few percent of the CPU capacity. You must prepare some files on the server in order for the test suite to run successfully. Some of the tests instruct the Tomcat Server to deploy an application from a warfile stored on the server. I suggest you use the minimal application included in this distribution at ``tomcatmanager/tests/war/sample.war``, but you can use any valid war file. Put this file in some directory on the server; I typically put it in ``/tmp/sample.war``. You must also construct a minimal context file on the server. You can see an example of such a context file in ``tomcatmanager/tests/war/context.xml``: .. code-block:: xml <?xml version="1.0" encoding="UTF-8"?> <!-- Context configuration file for my web application --> <Context path='/ignored' docBase='/tmp/sample.war'> </Context> The ``docBase`` attribute must point to a valid war file or the tests will fail. It can be the same minimal war file you already put on the server. The ``path`` attribute is ignored for context files that are not visible to Tomcat when it starts up, so it doesn't matter what you have there. I typically put this context file at ``/tmp/context.xml``. You will also need: - the url where the manager app of your Tomcat Server is available - a user with the ``manager-script`` role - the password for the aforementioned user With all these prerequisites ready, you can feed them to ``pytest`` as shown: .. code-block:: shell $ pytest --url=http://localhost:8080/manager --user=ace \ --password=newenglandclamchowder --warfile=/tmp/sample.war \ --contextfile=/tmp/context.xml .. warning:: If you test against a real Tomcat server, you should not use the ``pytest-xdist`` plugin to parallelize testing across multiple CPUs or many platforms. Many of the tests depend on deploying and undeploying an app at a specific path, and that path is shared across the entire test suite. It wouldn't help much anyway because the testing is constrained by the speed of the Tomcat server. If you kill the test suite in the middle of a run, you may leave the test application deployed in your tomcat server. If this happens, you must undeploy it before rerunning the test suite or you will get lots of errors. When the test suite deploys applications, it will be at the path returned by the ``safe_path`` fixture in ``conftest.py``. You can modify that fixture if for some reason you need to deploy at a different path. Code Quality ------------ Use ``pylint`` to check code quality. There is a pylint config file for the tests and for the main module:: $ pylint --rcfile=tests/pylintrc tests $ pylint --rcfile=tomcatmanager/pylintrc tomcatmanager You are welcome to use the pylint comment directives to disable certain messages in the code, but pull requests containing these directives will be carefully scrutinized. As allowed by `PEP 8 <https://www.python.org/dev/peps/pep-0008/#maximum-line-length>`_ this project uses a nominal line length of 100 characters. Documentation ------------- The documentation is written in reStructured Test, and turned into HTML using `Sphinx <http://www.sphinx-doc.org>`_:: $ cd docs $ make html The output will be in ``docs/build/html``. If you are doing a lot of documentation work, the `sphinx-autobuild <https://github.com/GaretJax/sphinx-autobuild>`_ module has been integrated. Type:: $ cd docs $ make livehtml Then point your browser at `<http://localhost:8000>`_ to see the documentation automatically rebuilt as you save your changes. .. note:: The ``sphinx-autobuild`` module has some limitations. Much of the documentation produced in this project is contained in the source code, and is incorporated via the Sphinx ``autodoc`` module. In order for ``autodoc`` to work, it must import the source code, and it's not very good about noticing and reloading source code modules as they change. If you change the source code and want to make sure you are seeing the current changes in your browser, best to kill the webserver and start it back up again. Use ``doc8`` to check documentation quality:: $ invoke doc8 Make a Release -------------- To make a release and deploy it to `PyPI <https://pypi.python.org/pypi>`_, do the following: 1. Merge everything to be included in the release into the **develop** branch. 2. Run ``tox`` to make sure the tests pass in all the supported python versions. 3. Review and update ``CHANGELOG.rst``. 4. Update the milestone corresponding to the release at `https://github.com/tomcatmanager/tomcatmanager/milestones <https://github.com/tomcatmanager/tomcatmanager/milestones>`_ 5. Push the **develop** branch to github. 6. Create a pull request on github to merge the **develop** branch into **master**. Wait for the checks to pass. 7. Merge the **develop** branch into the **master** branch and close the pull request. 8. Tag the **master** branch with the new version number, and push the tag. 9. Build source distribution, wheel distribution, and upload them to pypi staging:: $ invoke pypi-test 10. Build source distribution, wheel distribution, and upload them to pypi:: $ invoke pypi 11. Docs are automatically deployed to http://tomcatmanager.readthedocs.io/en/latest/. Make sure they look good. Add a "Version" in readthedocs which points to the tag you just created. Prune old versions as necessary. 12. Switch back to the **develop** branch. Merge changes in from **master**. 13. Add an **Unreleased** section to the top of ``CHANGELOG.rst``. Push the change to github.
{ "content_hash": "26c85632265c0206b4c472421c80147e", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 176, "avg_line_length": 36.34431137724551, "alnum_prop": 0.7314441057747755, "repo_name": "kotfu/tomcat-manager", "id": "6819883271c2dcacb9cdec4800c9e833aab96398", "size": "12139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONTRIBUTING.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "33840" } ], "symlink_target": "" }
import matplotlib; matplotlib.use('Agg') from netpyne import sim # read cfg and netParams from command line arguments if available; otherwise use default simConfig, netParams = sim.readCmdLineArgs(simConfigDefault='cfg.py', netParamsDefault='netParams.py') # Create network and run simulation sim.createSimulateAnalyze(netParams=netParams, simConfig=simConfig)
{ "content_hash": "365291187fbbfa5be70e32a80f6dd0b1", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 102, "avg_line_length": 45.375, "alnum_prop": 0.8209366391184573, "repo_name": "Neurosim-lab/netpyne", "id": "d579d7b39f52648e3783f11c3b01d0721aef34e3", "size": "363", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "examples/optunaOptim/init.py", "mode": "33188", "license": "mit", "language": [ { "name": "AMPL", "bytes": "25324" }, { "name": "Jupyter Notebook", "bytes": "2588467" }, { "name": "Python", "bytes": "1802020" }, { "name": "Shell", "bytes": "915" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="FOL_Theme_SnackbarWrapper" parent="@style/Theme.AppCompat"> <!--Insert customization here--> </style> </resources>
{ "content_hash": "b865fbdec6d2e2a69f0091243ed249d7", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 76, "avg_line_length": 32.333333333333336, "alnum_prop": 0.654639175257732, "repo_name": "leocarona/MyHitchhikingSpots-for-Android", "id": "6a920bb94a886f8b38d2f8849d0d25a7724780a2", "size": "194", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/res/values/FOL_Theme_SnackbarWrapper.xml", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "996905" } ], "symlink_target": "" }
package androidx.car.app.sample.places.common; import android.location.Location; import androidx.car.app.sample.places.common.places.PlaceCategory; /** App-wide constants */ class Constants { /** The initial location to use as an anchor for searches. */ static final Location INITIAL_SEARCH_LOCATION; /** The radius around the current anchor location to to search for POIs. */ static final int POI_SEARCH_RADIUS_METERS = 2000; // 2 km ~ 1.2 miles. /** The maximum number of location search results when searching for POIs. */ static final int POI_SEARCH_MAX_RESULTS = 12; /** The radius around the current anchor location to search for other anchor locations. */ static final int LOCATION_SEARCH_RADIUS_METERS = 100000; // 100 km ~ 62 miles. /** The maximum number of location search results when searching for anchors. */ static final int LOCATION_SEARCH_MAX_RESULTS = 5; static final PlaceCategory[] CATEGORIES = { PlaceCategory.create("Banks", "bank"), PlaceCategory.create("Bars", "bar"), PlaceCategory.create("Parking", "parking"), PlaceCategory.create("Restaurants", "restaurant"), PlaceCategory.create("Gas stations", "gas_station"), PlaceCategory.create("Transit stations", "transit_station") }; static { INITIAL_SEARCH_LOCATION = new Location("PlacesDemo"); // Googleplex INITIAL_SEARCH_LOCATION.setLatitude(37.422255); INITIAL_SEARCH_LOCATION.setLongitude(-122.084047); } private Constants() { } }
{ "content_hash": "9e6df84be5f386f9a65e1ced77300f93", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 94, "avg_line_length": 35.31111111111111, "alnum_prop": 0.6746381371932033, "repo_name": "android/car-samples", "id": "349721c7485db36bff1774afb3aa6ee53a779c06", "size": "2208", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "car_app_library/places/common/src/main/java/androidx/car/app/sample/places/common/Constants.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "550937" }, { "name": "Kotlin", "bytes": "3814" } ], "symlink_target": "" }
require 'minitest/autorun' require 'stringio' require 'cgi' require 'rack/request' require 'rack/mock' require 'rack/multipart' require 'securerandom' class RackRequestTest < Minitest::Spec it "copies the env when duping" do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) refute_same req.env, req.dup.env end it 'can check if something has been set' do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) refute req.has_header?("FOO") end it "can get a key from the env" do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) assert_equal "example.com", req.get_header("SERVER_NAME") end it 'can calculate the authority' do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) assert_equal "example.com:8080", req.authority end it 'can calculate the authority without a port' do req = make_request(Rack::MockRequest.env_for("http://example.com/")) assert_equal "example.com:80", req.authority end it 'can calculate the authority without a port on ssl' do req = make_request(Rack::MockRequest.env_for("https://example.com/")) assert_equal "example.com:443", req.authority end it 'yields to the block if no value has been set' do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) yielded = false req.fetch_header("FOO") do yielded = true req.set_header "FOO", 'bar' end assert yielded assert_equal "bar", req.get_header("FOO") end it 'can iterate over values' do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) req.set_header 'foo', 'bar' hash = {} req.each_header do |k,v| hash[k] = v end assert_equal 'bar', hash['foo'] end it 'can set values in the env' do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) req.set_header("FOO", "BAR") assert_equal "BAR", req.get_header("FOO") end it 'can add to multivalued headers in the env' do req = make_request(Rack::MockRequest.env_for('http://example.com:8080/')) assert_equal '1', req.add_header('FOO', '1') assert_equal '1', req.get_header('FOO') assert_equal '1,2', req.add_header('FOO', '2') assert_equal '1,2', req.get_header('FOO') assert_equal '1,2', req.add_header('FOO', nil) assert_equal '1,2', req.get_header('FOO') end it 'can delete env values' do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) req.set_header 'foo', 'bar' assert req.has_header? 'foo' req.delete_header 'foo' refute req.has_header? 'foo' end it "wrap the rack variables" do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) req.body.must_respond_to :gets req.scheme.must_equal "http" req.request_method.must_equal "GET" req.must_be :get? req.wont_be :post? req.wont_be :put? req.wont_be :delete? req.wont_be :head? req.wont_be :patch? req.script_name.must_equal "" req.path_info.must_equal "/" req.query_string.must_equal "" req.host.must_equal "example.com" req.port.must_equal 8080 req.content_length.must_equal "0" req.content_type.must_be_nil end it "figure out the correct host" do req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org") req.host.must_equal "www2.example.org" req = make_request \ Rack::MockRequest.env_for("/", "SERVER_NAME" => "example.org", "SERVER_PORT" => "9292") req.host.must_equal "example.org" req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9292") req.host.must_equal "example.org" env = Rack::MockRequest.env_for("/", "SERVER_ADDR" => "192.168.1.1", "SERVER_PORT" => "9292") env.delete("SERVER_NAME") req = make_request(env) req.host.must_equal "192.168.1.1" env = Rack::MockRequest.env_for("/") env.delete("SERVER_NAME") req = make_request(env) req.host.must_equal "" end it "figure out the correct port" do req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org") req.port.must_equal 80 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org:81") req.port.must_equal 81 req = make_request \ Rack::MockRequest.env_for("/", "SERVER_NAME" => "example.org", "SERVER_PORT" => "9292") req.port.must_equal 9292 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9292") req.port.must_equal 9292 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org") req.port.must_equal 80 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "HTTP_X_FORWARDED_SSL" => "on") req.port.must_equal 443 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "HTTP_X_FORWARDED_PROTO" => "https") req.port.must_equal 443 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "HTTP_X_FORWARDED_PORT" => "9393") req.port.must_equal 9393 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9393", "SERVER_PORT" => "80") req.port.must_equal 9393 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "SERVER_PORT" => "9393") req.port.must_equal 80 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost", "HTTP_X_FORWARDED_PROTO" => "https", "SERVER_PORT" => "80") req.port.must_equal 443 req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost", "HTTP_X_FORWARDED_PROTO" => "https,https", "SERVER_PORT" => "80") req.port.must_equal 443 end it "figure out the correct host with port" do req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org") req.host_with_port.must_equal "www2.example.org" req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81") req.host_with_port.must_equal "localhost:81" req = make_request \ Rack::MockRequest.env_for("/", "SERVER_NAME" => "example.org", "SERVER_PORT" => "9292") req.host_with_port.must_equal "example.org:9292" req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9292") req.host_with_port.must_equal "example.org:9292" req = make_request \ Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "SERVER_PORT" => "9393") req.host_with_port.must_equal "example.org" end it "parse the query string" do req = make_request(Rack::MockRequest.env_for("/?foo=bar&quux=bla")) req.query_string.must_equal "foo=bar&quux=bla" req.GET.must_equal "foo" => "bar", "quux" => "bla" req.POST.must_be :empty? req.params.must_equal "foo" => "bar", "quux" => "bla" end it "not truncate query strings containing semi-colons #543 only in POST" do mr = Rack::MockRequest.env_for("/", "REQUEST_METHOD" => 'POST', :input => "foo=bar&quux=b;la") req = make_request mr req.query_string.must_equal "" req.GET.must_be :empty? req.POST.must_equal "foo" => "bar", "quux" => "b;la" req.params.must_equal req.GET.merge(req.POST) end it "should use the query_parser for query parsing" do c = Class.new(Rack::QueryParser::Params) do def initialize(*) super @params = Hash.new{|h,k| h[k.to_s] if k.is_a?(Symbol)} end end parser = Rack::QueryParser.new(c, 65536, 100) c = Class.new(Rack::Request) do define_method(:query_parser) do parser end end req = c.new(Rack::MockRequest.env_for("/?foo=bar&quux=bla")) req.GET[:foo].must_equal "bar" req.GET[:quux].must_equal "bla" req.params[:foo].must_equal "bar" req.params[:quux].must_equal "bla" end it "use semi-colons as separators for query strings in GET" do req = make_request(Rack::MockRequest.env_for("/?foo=bar&quux=b;la;wun=duh")) req.query_string.must_equal "foo=bar&quux=b;la;wun=duh" req.GET.must_equal "foo" => "bar", "quux" => "b", "la" => nil, "wun" => "duh" req.POST.must_be :empty? req.params.must_equal "foo" => "bar", "quux" => "b", "la" => nil, "wun" => "duh" end it "limit the keys from the GET query string" do env = Rack::MockRequest.env_for("/?foo=bar") old, Rack::Utils.key_space_limit = Rack::Utils.key_space_limit, 1 begin req = make_request(env) lambda { req.GET }.must_raise RangeError ensure Rack::Utils.key_space_limit = old end end it "limit the key size per nested params hash" do nested_query = Rack::MockRequest.env_for("/?foo%5Bbar%5D%5Bbaz%5D%5Bqux%5D=1") plain_query = Rack::MockRequest.env_for("/?foo_bar__baz__qux_=1") old, Rack::Utils.key_space_limit = Rack::Utils.key_space_limit, 3 begin exp = {"foo"=>{"bar"=>{"baz"=>{"qux"=>"1"}}}} make_request(nested_query).GET.must_equal exp lambda { make_request(plain_query).GET }.must_raise RangeError ensure Rack::Utils.key_space_limit = old end end it "not unify GET and POST when calling params" do mr = Rack::MockRequest.env_for("/?foo=quux", "REQUEST_METHOD" => 'POST', :input => "foo=bar&quux=bla" ) req = make_request mr req.params req.GET.must_equal "foo" => "quux" req.POST.must_equal "foo" => "bar", "quux" => "bla" req.params.must_equal req.GET.merge(req.POST) end it "use the query_parser's params_class for multipart params" do c = Class.new(Rack::QueryParser::Params) do def initialize(*) super @params = Hash.new{|h,k| h[k.to_s] if k.is_a?(Symbol)} end end parser = Rack::QueryParser.new(c, 65536, 100) c = Class.new(Rack::Request) do define_method(:query_parser) do parser end end mr = Rack::MockRequest.env_for("/?foo=quux", "REQUEST_METHOD" => 'POST', :input => "foo=bar&quux=bla" ) req = c.new mr req.params req.GET[:foo].must_equal "quux" req.POST[:foo].must_equal "bar" req.POST[:quux].must_equal "bla" req.params[:foo].must_equal "bar" req.params[:quux].must_equal "bla" end it "raise if input params has invalid %-encoding" do mr = Rack::MockRequest.env_for("/?foo=quux", "REQUEST_METHOD" => 'POST', :input => "a%=1" ) req = make_request mr lambda { req.POST }.must_raise(Rack::Utils::InvalidParameterError). message.must_equal "invalid %-encoding (a%)" end it "raise if rack.input is missing" do req = make_request({}) lambda { req.POST }.must_raise RuntimeError end it "parse POST data when method is POST and no Content-Type given" do req = make_request \ Rack::MockRequest.env_for("/?foo=quux", "REQUEST_METHOD" => 'POST', :input => "foo=bar&quux=bla") req.content_type.must_be_nil req.media_type.must_be_nil req.query_string.must_equal "foo=quux" req.GET.must_equal "foo" => "quux" req.POST.must_equal "foo" => "bar", "quux" => "bla" req.params.must_equal "foo" => "bar", "quux" => "bla" end it "limit the keys from the POST form data" do env = Rack::MockRequest.env_for("", "REQUEST_METHOD" => 'POST', :input => "foo=bar&quux=bla") old, Rack::Utils.key_space_limit = Rack::Utils.key_space_limit, 1 begin req = make_request(env) lambda { req.POST }.must_raise RangeError ensure Rack::Utils.key_space_limit = old end end it "parse POST data with explicit content type regardless of method" do req = make_request \ Rack::MockRequest.env_for("/", "CONTENT_TYPE" => 'application/x-www-form-urlencoded;foo=bar', :input => "foo=bar&quux=bla") req.content_type.must_equal 'application/x-www-form-urlencoded;foo=bar' req.media_type.must_equal 'application/x-www-form-urlencoded' req.media_type_params['foo'].must_equal 'bar' req.POST.must_equal "foo" => "bar", "quux" => "bla" req.params.must_equal "foo" => "bar", "quux" => "bla" end it "not parse POST data when media type is not form-data" do req = make_request \ Rack::MockRequest.env_for("/?foo=quux", "REQUEST_METHOD" => 'POST', "CONTENT_TYPE" => 'text/plain;charset=utf-8', :input => "foo=bar&quux=bla") req.content_type.must_equal 'text/plain;charset=utf-8' req.media_type.must_equal 'text/plain' req.media_type_params['charset'].must_equal 'utf-8' req.POST.must_be :empty? req.params.must_equal "foo" => "quux" req.body.read.must_equal "foo=bar&quux=bla" end it "parse POST data on PUT when media type is form-data" do req = make_request \ Rack::MockRequest.env_for("/?foo=quux", "REQUEST_METHOD" => 'PUT', "CONTENT_TYPE" => 'application/x-www-form-urlencoded', :input => "foo=bar&quux=bla") req.POST.must_equal "foo" => "bar", "quux" => "bla" req.body.read.must_equal "foo=bar&quux=bla" end it "rewind input after parsing POST data" do input = StringIO.new("foo=bar&quux=bla") req = make_request \ Rack::MockRequest.env_for("/", "CONTENT_TYPE" => 'application/x-www-form-urlencoded;foo=bar', :input => input) req.params.must_equal "foo" => "bar", "quux" => "bla" input.read.must_equal "foo=bar&quux=bla" end it "safely accepts POST requests with empty body" do mr = Rack::MockRequest.env_for("/", "REQUEST_METHOD" => "POST", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => '0', :input => nil) req = make_request mr req.query_string.must_equal "" req.GET.must_be :empty? req.POST.must_be :empty? req.params.must_equal({}) end it "clean up Safari's ajax POST body" do req = make_request \ Rack::MockRequest.env_for("/", 'REQUEST_METHOD' => 'POST', :input => "foo=bar&quux=bla\0") req.POST.must_equal "foo" => "bar", "quux" => "bla" end it "get value by key from params with #[]" do req = make_request \ Rack::MockRequest.env_for("?foo=quux") req['foo'].must_equal 'quux' req[:foo].must_equal 'quux' end it "set value to key on params with #[]=" do req = make_request \ Rack::MockRequest.env_for("?foo=duh") req['foo'].must_equal 'duh' req[:foo].must_equal 'duh' req.params.must_equal 'foo' => 'duh' if req.delegate? skip "delegate requests don't cache params, so mutations have no impact" end req['foo'] = 'bar' req.params.must_equal 'foo' => 'bar' req['foo'].must_equal 'bar' req[:foo].must_equal 'bar' req[:foo] = 'jaz' req.params.must_equal 'foo' => 'jaz' req['foo'].must_equal 'jaz' req[:foo].must_equal 'jaz' end it "return values for the keys in the order given from values_at" do req = make_request \ Rack::MockRequest.env_for("?foo=baz&wun=der&bar=ful") req.values_at('foo').must_equal ['baz'] req.values_at('foo', 'wun').must_equal ['baz', 'der'] req.values_at('bar', 'foo', 'wun').must_equal ['ful', 'baz', 'der'] end it "extract referrer correctly" do req = make_request \ Rack::MockRequest.env_for("/", "HTTP_REFERER" => "/some/path") req.referer.must_equal "/some/path" req = make_request \ Rack::MockRequest.env_for("/") req.referer.must_be_nil end it "extract user agent correctly" do req = make_request \ Rack::MockRequest.env_for("/", "HTTP_USER_AGENT" => "Mozilla/4.0 (compatible)") req.user_agent.must_equal "Mozilla/4.0 (compatible)" req = make_request \ Rack::MockRequest.env_for("/") req.user_agent.must_be_nil end it "treat missing content type as nil" do req = make_request \ Rack::MockRequest.env_for("/") req.content_type.must_be_nil end it "treat empty content type as nil" do req = make_request \ Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "") req.content_type.must_be_nil end it "return nil media type for empty content type" do req = make_request \ Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "") req.media_type.must_be_nil end it "cache, but invalidates the cache" do req = make_request \ Rack::MockRequest.env_for("/?foo=quux", "CONTENT_TYPE" => "application/x-www-form-urlencoded", :input => "foo=bar&quux=bla") req.GET.must_equal "foo" => "quux" req.GET.must_equal "foo" => "quux" req.set_header("QUERY_STRING", "bla=foo") req.GET.must_equal "bla" => "foo" req.GET.must_equal "bla" => "foo" req.POST.must_equal "foo" => "bar", "quux" => "bla" req.POST.must_equal "foo" => "bar", "quux" => "bla" req.set_header("rack.input", StringIO.new("foo=bla&quux=bar")) req.POST.must_equal "foo" => "bla", "quux" => "bar" req.POST.must_equal "foo" => "bla", "quux" => "bar" end it "figure out if called via XHR" do req = make_request(Rack::MockRequest.env_for("")) req.wont_be :xhr? req = make_request \ Rack::MockRequest.env_for("", "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest") req.must_be :xhr? end it "ssl detection" do request = make_request(Rack::MockRequest.env_for("/")) request.scheme.must_equal "http" request.wont_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'HTTPS' => 'on')) request.scheme.must_equal "https" request.must_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'rack.url_scheme' => 'https')) request.scheme.must_equal "https" request.must_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'HTTP_HOST' => 'www.example.org:8080')) request.scheme.must_equal "http" request.wont_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'HTTP_HOST' => 'www.example.org:8443', 'HTTPS' => 'on')) request.scheme.must_equal "https" request.must_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'HTTP_HOST' => 'www.example.org:8443', 'HTTP_X_FORWARDED_SSL' => 'on')) request.scheme.must_equal "https" request.must_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'HTTP_X_FORWARDED_SCHEME' => 'https')) request.scheme.must_equal "https" request.must_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'HTTP_X_FORWARDED_PROTO' => 'https')) request.scheme.must_equal "https" request.must_be :ssl? request = make_request(Rack::MockRequest.env_for("/", 'HTTP_X_FORWARDED_PROTO' => 'https, http, http')) request.scheme.must_equal "https" request.must_be :ssl? end it "prevents scheme abuse" do request = make_request(Rack::MockRequest.env_for("/", 'HTTP_X_FORWARDED_SCHEME' => 'a."><script>alert(1)</script>')) request.scheme.must_equal 'http' end it "parse cookies" do req = make_request \ Rack::MockRequest.env_for("", "HTTP_COOKIE" => "foo=bar;quux=h&m") req.cookies.must_equal "foo" => "bar", "quux" => "h&m" req.cookies.must_equal "foo" => "bar", "quux" => "h&m" req.delete_header("HTTP_COOKIE") req.cookies.must_equal({}) end it "always return the same hash object" do req = make_request \ Rack::MockRequest.env_for("", "HTTP_COOKIE" => "foo=bar;quux=h&m") hash = req.cookies req.env.delete("HTTP_COOKIE") req.cookies.must_equal hash req.env["HTTP_COOKIE"] = "zoo=m" req.cookies.must_equal hash end it "modify the cookies hash in place" do req = make_request(Rack::MockRequest.env_for("")) req.cookies.must_equal({}) req.cookies['foo'] = 'bar' req.cookies.must_equal 'foo' => 'bar' end it "not modify the params hash in place" do e = Rack::MockRequest.env_for("") req1 = make_request(e) if req1.delegate? skip "delegate requests don't cache params, so mutations have no impact" end req1.params.must_equal({}) req1.params['foo'] = 'bar' req1.params.must_equal 'foo' => 'bar' req2 = make_request(e) req2.params.must_equal({}) end it "modify params hash if param is in GET" do e = Rack::MockRequest.env_for("?foo=duh") req1 = make_request(e) req1.params.must_equal 'foo' => 'duh' req1.update_param 'foo', 'bar' req1.params.must_equal 'foo' => 'bar' req2 = make_request(e) req2.params.must_equal 'foo' => 'bar' end it "modify params hash if param is in POST" do e = Rack::MockRequest.env_for("", "REQUEST_METHOD" => 'POST', :input => 'foo=duh') req1 = make_request(e) req1.params.must_equal 'foo' => 'duh' req1.update_param 'foo', 'bar' req1.params.must_equal 'foo' => 'bar' req2 = make_request(e) req2.params.must_equal 'foo' => 'bar' end it "modify params hash, even if param didn't exist before" do e = Rack::MockRequest.env_for("") req1 = make_request(e) req1.params.must_equal({}) req1.update_param 'foo', 'bar' req1.params.must_equal 'foo' => 'bar' req2 = make_request(e) req2.params.must_equal 'foo' => 'bar' end it "modify params hash by changing only GET" do e = Rack::MockRequest.env_for("?foo=duhget") req = make_request(e) req.GET.must_equal 'foo' => 'duhget' req.POST.must_equal({}) req.update_param 'foo', 'bar' req.GET.must_equal 'foo' => 'bar' req.POST.must_equal({}) end it "modify params hash by changing only POST" do e = Rack::MockRequest.env_for("", "REQUEST_METHOD" => 'POST', :input => "foo=duhpost") req = make_request(e) req.GET.must_equal({}) req.POST.must_equal 'foo' => 'duhpost' req.update_param 'foo', 'bar' req.GET.must_equal({}) req.POST.must_equal 'foo' => 'bar' end it "modify params hash, even if param is defined in both POST and GET" do e = Rack::MockRequest.env_for("?foo=duhget", "REQUEST_METHOD" => 'POST', :input => "foo=duhpost") req1 = make_request(e) req1.GET.must_equal 'foo' => 'duhget' req1.POST.must_equal 'foo' => 'duhpost' req1.params.must_equal 'foo' => 'duhpost' req1.update_param 'foo', 'bar' req1.GET.must_equal 'foo' => 'bar' req1.POST.must_equal 'foo' => 'bar' req1.params.must_equal 'foo' => 'bar' req2 = make_request(e) req2.GET.must_equal 'foo' => 'bar' req2.POST.must_equal 'foo' => 'bar' req2.params.must_equal 'foo' => 'bar' req2.params.must_equal 'foo' => 'bar' end it "allow deleting from params hash if param is in GET" do e = Rack::MockRequest.env_for("?foo=bar") req1 = make_request(e) req1.params.must_equal 'foo' => 'bar' req1.delete_param('foo').must_equal 'bar' req1.params.must_equal({}) req2 = make_request(e) req2.params.must_equal({}) end it "allow deleting from params hash if param is in POST" do e = Rack::MockRequest.env_for("", "REQUEST_METHOD" => 'POST', :input => 'foo=bar') req1 = make_request(e) req1.params.must_equal 'foo' => 'bar' req1.delete_param('foo').must_equal 'bar' req1.params.must_equal({}) req2 = make_request(e) req2.params.must_equal({}) end it "pass through non-uri escaped cookies as-is" do req = make_request Rack::MockRequest.env_for("", "HTTP_COOKIE" => "foo=%") req.cookies["foo"].must_equal "%" end it "parse cookies according to RFC 2109" do req = make_request \ Rack::MockRequest.env_for('', 'HTTP_COOKIE' => 'foo=bar;foo=car') req.cookies.must_equal 'foo' => 'bar' end it 'parse cookies with quotes' do req = make_request Rack::MockRequest.env_for('', { 'HTTP_COOKIE' => '$Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"' }) req.cookies.must_equal({ '$Version' => '"1"', 'Customer' => '"WILE_E_COYOTE"', '$Path' => '"/acme"', 'Part_Number' => '"Rocket_Launcher_0001"', }) end it "provide setters" do req = make_request(e=Rack::MockRequest.env_for("")) req.script_name.must_equal "" req.script_name = "/foo" req.script_name.must_equal "/foo" e["SCRIPT_NAME"].must_equal "/foo" req.path_info.must_equal "/" req.path_info = "/foo" req.path_info.must_equal "/foo" e["PATH_INFO"].must_equal "/foo" end it "provide the original env" do req = make_request(e = Rack::MockRequest.env_for("")) req.env.must_equal e end it "restore the base URL" do make_request(Rack::MockRequest.env_for("")).base_url. must_equal "http://example.org" make_request(Rack::MockRequest.env_for("", "SCRIPT_NAME" => "/foo")).base_url. must_equal "http://example.org" end it "restore the URL" do make_request(Rack::MockRequest.env_for("")).url. must_equal "http://example.org/" make_request(Rack::MockRequest.env_for("", "SCRIPT_NAME" => "/foo")).url. must_equal "http://example.org/foo/" make_request(Rack::MockRequest.env_for("/foo")).url. must_equal "http://example.org/foo" make_request(Rack::MockRequest.env_for("?foo")).url. must_equal "http://example.org/?foo" make_request(Rack::MockRequest.env_for("http://example.org:8080/")).url. must_equal "http://example.org:8080/" make_request(Rack::MockRequest.env_for("https://example.org/")).url. must_equal "https://example.org/" make_request(Rack::MockRequest.env_for("coffee://example.org/")).url. must_equal "coffee://example.org/" make_request(Rack::MockRequest.env_for("coffee://example.org:443/")).url. must_equal "coffee://example.org:443/" make_request(Rack::MockRequest.env_for("https://example.com:8080/foo?foo")).url. must_equal "https://example.com:8080/foo?foo" end it "restore the full path" do make_request(Rack::MockRequest.env_for("")).fullpath. must_equal "/" make_request(Rack::MockRequest.env_for("", "SCRIPT_NAME" => "/foo")).fullpath. must_equal "/foo/" make_request(Rack::MockRequest.env_for("/foo")).fullpath. must_equal "/foo" make_request(Rack::MockRequest.env_for("?foo")).fullpath. must_equal "/?foo" make_request(Rack::MockRequest.env_for("http://example.org:8080/")).fullpath. must_equal "/" make_request(Rack::MockRequest.env_for("https://example.org/")).fullpath. must_equal "/" make_request(Rack::MockRequest.env_for("https://example.com:8080/foo?foo")).fullpath. must_equal "/foo?foo" end it "handle multiple media type parameters" do req = make_request \ Rack::MockRequest.env_for("/", "CONTENT_TYPE" => 'text/plain; foo=BAR,baz=bizzle dizzle;BLING=bam;blong="boo";zump="zoo\"o";weird=lol"') req.wont_be :form_data? req.media_type_params.must_include 'foo' req.media_type_params['foo'].must_equal 'BAR' req.media_type_params.must_include 'baz' req.media_type_params['baz'].must_equal 'bizzle dizzle' req.media_type_params.wont_include 'BLING' req.media_type_params.must_include 'bling' req.media_type_params['bling'].must_equal 'bam' req.media_type_params['blong'].must_equal 'boo' req.media_type_params['zump'].must_equal 'zoo\"o' req.media_type_params['weird'].must_equal 'lol"' end it "parse with junk before boundary" do # Adapted from RFC 1867. input = <<EOF blah blah\r \r --AaB03x\r content-disposition: form-data; name="reply"\r \r yes\r --AaB03x\r content-disposition: form-data; name="fileupload"; filename="dj.jpg"\r Content-Type: image/jpeg\r Content-Transfer-Encoding: base64\r \r /9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcg\r --AaB03x--\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) req.POST.must_include "fileupload" req.POST.must_include "reply" req.must_be :form_data? req.content_length.must_equal input.size req.media_type.must_equal 'multipart/form-data' req.media_type_params.must_include 'boundary' req.media_type_params['boundary'].must_equal 'AaB03x' req.POST["reply"].must_equal "yes" f = req.POST["fileupload"] f.must_be_kind_of Hash f[:type].must_equal "image/jpeg" f[:filename].must_equal "dj.jpg" f.must_include :tempfile f[:tempfile].size.must_equal 76 end it "not infinite loop with a malformed HTTP request" do # Adapted from RFC 1867. input = <<EOF --AaB03x content-disposition: form-data; name="reply" yes --AaB03x content-disposition: form-data; name="fileupload"; filename="dj.jpg" Content-Type: image/jpeg Content-Transfer-Encoding: base64 /9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcg --AaB03x-- EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) lambda{req.POST}.must_raise EOFError end it "parse multipart form data" do # Adapted from RFC 1867. input = <<EOF --AaB03x\r content-disposition: form-data; name="reply"\r \r yes\r --AaB03x\r content-disposition: form-data; name="fileupload"; filename="dj.jpg"\r Content-Type: image/jpeg\r Content-Transfer-Encoding: base64\r \r /9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcg\r --AaB03x--\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) req.POST.must_include "fileupload" req.POST.must_include "reply" req.must_be :form_data? req.content_length.must_equal input.size req.media_type.must_equal 'multipart/form-data' req.media_type_params.must_include 'boundary' req.media_type_params['boundary'].must_equal 'AaB03x' req.POST["reply"].must_equal "yes" f = req.POST["fileupload"] f.must_be_kind_of Hash f[:type].must_equal "image/jpeg" f[:filename].must_equal "dj.jpg" f.must_include :tempfile f[:tempfile].size.must_equal 76 end it "MultipartPartLimitError when request has too many multipart parts if limit set" do begin data = 10000.times.map { "--AaB03x\r\nContent-Type: text/plain\r\nContent-Disposition: attachment; name=#{SecureRandom.hex(10)}; filename=#{SecureRandom.hex(10)}\r\n\r\ncontents\r\n" }.join("\r\n") data += "--AaB03x--\r" options = { "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x", "CONTENT_LENGTH" => data.length.to_s, :input => StringIO.new(data) } request = make_request Rack::MockRequest.env_for("/", options) lambda { request.POST }.must_raise Rack::Multipart::MultipartPartLimitError end end it 'closes tempfiles it created in the case of too many created' do begin data = 10000.times.map { "--AaB03x\r\nContent-Type: text/plain\r\nContent-Disposition: attachment; name=#{SecureRandom.hex(10)}; filename=#{SecureRandom.hex(10)}\r\n\r\ncontents\r\n" }.join("\r\n") data += "--AaB03x--\r" files = [] options = { "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x", "CONTENT_LENGTH" => data.length.to_s, Rack::RACK_MULTIPART_TEMPFILE_FACTORY => lambda { |filename, content_type| file = Tempfile.new(["RackMultipart", ::File.extname(filename)]) files << file file }, :input => StringIO.new(data) } request = make_request Rack::MockRequest.env_for("/", options) assert_raises(Rack::Multipart::MultipartPartLimitError) do request.POST end refute_predicate files, :empty? files.each { |f| assert_predicate f, :closed? } end end it "parse big multipart form data" do input = <<EOF --AaB03x\r content-disposition: form-data; name="huge"; filename="huge"\r \r #{"x"*32768}\r --AaB03x\r content-disposition: form-data; name="mean"; filename="mean"\r \r --AaB03xha\r --AaB03x--\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) req.POST["huge"][:tempfile].size.must_equal 32768 req.POST["mean"][:tempfile].size.must_equal 10 req.POST["mean"][:tempfile].read.must_equal "--AaB03xha" end it "record tempfiles from multipart form data in env[rack.tempfiles]" do input = <<EOF --AaB03x\r content-disposition: form-data; name="fileupload"; filename="foo.jpg"\r Content-Type: image/jpeg\r Content-Transfer-Encoding: base64\r \r /9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcg\r --AaB03x\r content-disposition: form-data; name="fileupload"; filename="bar.jpg"\r Content-Type: image/jpeg\r Content-Transfer-Encoding: base64\r \r /9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcg\r --AaB03x--\r EOF env = Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) req = make_request(env) req.params env['rack.tempfiles'].size.must_equal 2 end it "detect invalid multipart form data" do input = <<EOF --AaB03x\r content-disposition: form-data; name="huge"; filename="huge"\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) lambda { req.POST }.must_raise EOFError input = <<EOF --AaB03x\r content-disposition: form-data; name="huge"; filename="huge"\r \r foo\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) lambda { req.POST }.must_raise EOFError input = <<EOF --AaB03x\r content-disposition: form-data; name="huge"; filename="huge"\r \r foo\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) lambda { req.POST }.must_raise EOFError end it "consistently raise EOFError on bad multipart form data" do input = <<EOF --AaB03x\r content-disposition: form-data; name="huge"; filename="huge"\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) lambda { req.POST }.must_raise EOFError lambda { req.POST }.must_raise EOFError end it "correctly parse the part name from Content-Id header" do input = <<EOF --AaB03x\r Content-Type: text/xml; charset=utf-8\r Content-Id: <soap-start>\r Content-Transfer-Encoding: 7bit\r \r foo\r --AaB03x--\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/related, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) req.params.keys.must_equal ["<soap-start>"] end it "not try to interpret binary as utf8" do input = <<EOF --AaB03x\r content-disposition: form-data; name="fileupload"; filename="junk.a"\r content-type: application/octet-stream\r \r #{[0x36,0xCF,0x0A,0xF8].pack('c*')}\r --AaB03x--\r EOF req = make_request Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size, :input => input) req.POST["fileupload"][:tempfile].size.must_equal 4 end it "use form_hash when form_input is a Tempfile" do input = "{foo: 'bar'}" rack_input = Tempfile.new("rackspec") rack_input.write(input) rack_input.rewind req = make_request Rack::MockRequest.env_for("/", "rack.request.form_hash" => {'foo' => 'bar'}, "rack.request.form_input" => rack_input, :input => rack_input) req.POST.must_equal req.env['rack.request.form_hash'] end it "conform to the Rack spec" do app = lambda { |env| content = make_request(env).POST["file"].inspect size = content.bytesize [200, {"Content-Type" => "text/html", "Content-Length" => size.to_s}, [content]] } input = <<EOF --AaB03x\r content-disposition: form-data; name="reply"\r \r yes\r --AaB03x\r content-disposition: form-data; name="fileupload"; filename="dj.jpg"\r Content-Type: image/jpeg\r Content-Transfer-Encoding: base64\r \r /9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcg\r --AaB03x--\r EOF input.force_encoding(Encoding::ASCII_8BIT) res = Rack::MockRequest.new(Rack::Lint.new(app)).get "/", "CONTENT_TYPE" => "multipart/form-data, boundary=AaB03x", "CONTENT_LENGTH" => input.size.to_s, "rack.input" => StringIO.new(input) res.must_be :ok? end it "parse Accept-Encoding correctly" do parser = lambda do |x| make_request(Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => x)).accept_encoding end parser.call(nil).must_equal [] parser.call("compress, gzip").must_equal [["compress", 1.0], ["gzip", 1.0]] parser.call("").must_equal [] parser.call("*").must_equal [["*", 1.0]] parser.call("compress;q=0.5, gzip;q=1.0").must_equal [["compress", 0.5], ["gzip", 1.0]] parser.call("gzip;q=1.0, identity; q=0.5, *;q=0").must_equal [["gzip", 1.0], ["identity", 0.5], ["*", 0] ] parser.call("gzip ; q=0.9").must_equal [["gzip", 0.9]] parser.call("gzip ; deflate").must_equal [["gzip", 1.0]] end it "parse Accept-Language correctly" do parser = lambda do |x| make_request(Rack::MockRequest.env_for("", "HTTP_ACCEPT_LANGUAGE" => x)).accept_language end parser.call(nil).must_equal [] parser.call("fr, en").must_equal [["fr", 1.0], ["en", 1.0]] parser.call("").must_equal [] parser.call("*").must_equal [["*", 1.0]] parser.call("fr;q=0.5, en;q=1.0").must_equal [["fr", 0.5], ["en", 1.0]] parser.call("fr;q=1.0, en; q=0.5, *;q=0").must_equal [["fr", 1.0], ["en", 0.5], ["*", 0] ] parser.call("fr ; q=0.9").must_equal [["fr", 0.9]] parser.call("fr").must_equal [["fr", 1.0]] end def ip_app lambda { |env| request = make_request(env) response = Rack::Response.new response.write request.ip response.finish } end it 'provide ip information' do mock = Rack::MockRequest.new(Rack::Lint.new(ip_app)) res = mock.get '/', 'REMOTE_ADDR' => '1.2.3.4' res.body.must_equal '1.2.3.4' res = mock.get '/', 'REMOTE_ADDR' => 'fe80::202:b3ff:fe1e:8329' res.body.must_equal 'fe80::202:b3ff:fe1e:8329' res = mock.get '/', 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6' res.body.must_equal '1.2.3.4' end it 'deals with proxies' do mock = Rack::MockRequest.new(Rack::Lint.new(ip_app)) res = mock.get '/', 'REMOTE_ADDR' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' res.body.must_equal '1.2.3.4' res = mock.get '/', 'REMOTE_ADDR' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => 'unknown' res.body.must_equal '1.2.3.4' res = mock.get '/', 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' res.body.must_equal '3.4.5.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'unknown,3.4.5.6' res.body.must_equal '3.4.5.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6' res.body.must_equal '3.4.5.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6' res.body.must_equal '3.4.5.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6' res.body.must_equal '3.4.5.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '127.0.0.1, 3.4.5.6' res.body.must_equal '3.4.5.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1' res.body.must_equal 'unknown' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'other,unknown,192.168.0.1' res.body.must_equal 'unknown' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'unknown,localhost,192.168.0.1' res.body.must_equal 'unknown' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4' res.body.must_equal '3.4.5.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '::1,2620:0:1c00:0:812c:9583:754b:ca11' res.body.must_equal '2620:0:1c00:0:812c:9583:754b:ca11' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,::1' res.body.must_equal '2620:0:1c00:0:812c:9583:754b:ca11' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'fd5b:982e:9130:247f:0000:0000:0000:0000,2620:0:1c00:0:812c:9583:754b:ca11' res.body.must_equal '2620:0:1c00:0:812c:9583:754b:ca11' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,fd5b:982e:9130:247f:0000:0000:0000:0000' res.body.must_equal '2620:0:1c00:0:812c:9583:754b:ca11' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '1.1.1.1, 127.0.0.1', 'HTTP_CLIENT_IP' => '1.1.1.1' res.body.must_equal '1.1.1.1' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, 9.9.9.9' res.body.must_equal '9.9.9.9' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, fe80::202:b3ff:fe1e:8329' res.body.must_equal 'fe80::202:b3ff:fe1e:8329' # Unix Sockets res = mock.get '/', 'REMOTE_ADDR' => 'unix', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' res.body.must_equal '3.4.5.6' res = mock.get '/', 'REMOTE_ADDR' => 'unix:/tmp/foo', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' res.body.must_equal '3.4.5.6' end it "not allow IP spoofing via Client-IP and X-Forwarded-For headers" do mock = Rack::MockRequest.new(Rack::Lint.new(ip_app)) # IP Spoofing attempt: # Client sends X-Forwarded-For: 6.6.6.6 # Client-IP: 6.6.6.6 # Load balancer adds X-Forwarded-For: 2.2.2.3, 192.168.0.7 # App receives: X-Forwarded-For: 6.6.6.6 # X-Forwarded-For: 2.2.2.3, 192.168.0.7 # Client-IP: 6.6.6.6 # Rack env: HTTP_X_FORWARDED_FOR: '6.6.6.6, 2.2.2.3, 192.168.0.7' # HTTP_CLIENT_IP: '6.6.6.6' res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '6.6.6.6, 2.2.2.3, 192.168.0.7', 'HTTP_CLIENT_IP' => '6.6.6.6' res.body.must_equal '2.2.2.3' end it "regard local addresses as proxies" do req = make_request(Rack::MockRequest.env_for("/")) req.trusted_proxy?('127.0.0.1').must_equal 0 req.trusted_proxy?('10.0.0.1').must_equal 0 req.trusted_proxy?('172.16.0.1').must_equal 0 req.trusted_proxy?('172.20.0.1').must_equal 0 req.trusted_proxy?('172.30.0.1').must_equal 0 req.trusted_proxy?('172.31.0.1').must_equal 0 req.trusted_proxy?('192.168.0.1').must_equal 0 req.trusted_proxy?('::1').must_equal 0 req.trusted_proxy?('fd00::').must_equal 0 req.trusted_proxy?('localhost').must_equal 0 req.trusted_proxy?('unix').must_equal 0 req.trusted_proxy?('unix:/tmp/sock').must_equal 0 req.trusted_proxy?("unix.example.org").must_be_nil req.trusted_proxy?("example.org\n127.0.0.1").must_be_nil req.trusted_proxy?("127.0.0.1\nexample.org").must_be_nil req.trusted_proxy?("11.0.0.1").must_be_nil req.trusted_proxy?("172.15.0.1").must_be_nil req.trusted_proxy?("172.32.0.1").must_be_nil req.trusted_proxy?("2001:470:1f0b:18f8::1").must_be_nil end it "sets the default session to an empty hash" do req = make_request(Rack::MockRequest.env_for("http://example.com:8080/")) assert_equal Hash.new, req.session end class MyRequest < Rack::Request def params {:foo => "bar"} end end it "allow subclass request to be instantiated after parent request" do env = Rack::MockRequest.env_for("/?foo=bar") req1 = make_request(env) req1.GET.must_equal "foo" => "bar" req1.params.must_equal "foo" => "bar" req2 = MyRequest.new(env) req2.GET.must_equal "foo" => "bar" req2.params.must_equal :foo => "bar" end it "allow parent request to be instantiated after subclass request" do env = Rack::MockRequest.env_for("/?foo=bar") req1 = MyRequest.new(env) req1.GET.must_equal "foo" => "bar" req1.params.must_equal :foo => "bar" req2 = make_request(env) req2.GET.must_equal "foo" => "bar" req2.params.must_equal "foo" => "bar" end it "raise TypeError every time if request parameters are broken" do broken_query = Rack::MockRequest.env_for("/?foo%5B%5D=0&foo%5Bbar%5D=1") req = make_request(broken_query) lambda{req.GET}.must_raise TypeError lambda{req.params}.must_raise TypeError end (0x20...0x7E).collect { |a| b = a.chr c = CGI.escape(b) it "not strip '#{a}' => '#{c}' => '#{b}' escaped character from parameters when accessed as string" do url = "/?foo=#{c}bar#{c}" env = Rack::MockRequest.env_for(url) req2 = make_request(env) req2.GET.must_equal "foo" => "#{b}bar#{b}" req2.params.must_equal "foo" => "#{b}bar#{b}" end } class NonDelegate < Rack::Request def delegate?; false; end end def make_request(env) NonDelegate.new env end class TestProxyRequest < RackRequestTest class DelegateRequest include Rack::Request::Helpers extend Forwardable def_delegators :@req, :has_header?, :get_header, :fetch_header, :each_header, :set_header, :add_header, :delete_header def_delegators :@req, :[], :[]=, :values_at def initialize(req) @req = req end def delegate?; true; end def env; @req.env.dup; end end def make_request(env) DelegateRequest.new super(env) end end end
{ "content_hash": "fa10628861b0557edf8d8e707f15663e", "timestamp": "", "source": "github", "line_count": 1398, "max_line_length": 203, "avg_line_length": 33.628755364806864, "alnum_prop": 0.6152766256141918, "repo_name": "hafeild/alice", "id": "cfaedbcfe6cdc9aff9377dca2248c62fc826b2ae", "size": "47013", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "vendor/bundle/ruby/2.3.0/gems/rack-2.0.6/test/spec_request.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CoffeeScript", "bytes": "211" }, { "name": "HTML", "bytes": "226549" }, { "name": "JavaScript", "bytes": "22184" }, { "name": "Ruby", "bytes": "426829" }, { "name": "SCSS", "bytes": "12517" }, { "name": "Shell", "bytes": "16921" } ], "symlink_target": "" }
#include "base/third_party/xdg_user_dirs/xdg_user_dir_lookup.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "starboard/memory.h" #include "starboard/types.h" /** * xdg_user_dir_lookup_with_fallback: * @type: a string specifying the type of directory * @fallback: value to use if the directory isn't specified by the user * @returns: a newly allocated absolute pathname * * Looks up a XDG user directory of the specified type. * Example of types are "DESKTOP" and "DOWNLOAD". * * In case the user hasn't specified any directory for the specified * type the value returned is @fallback. * * The return value is newly allocated and must be freed with * SbMemoryDeallocate(). The return value is never NULL if @fallback != NULL, unless * out of memory. **/ static char * xdg_user_dir_lookup_with_fallback (const char *type, const char *fallback) { FILE *file; char *home_dir, *config_home, *config_file; char buffer[512]; char *user_dir; char *p, *d; int len; int relative; home_dir = getenv ("HOME"); if (home_dir == NULL) goto error; config_home = getenv ("XDG_CONFIG_HOME"); if (config_home == NULL || config_home[0] == 0) { config_file = (char*) malloc (strlen (home_dir) + strlen ("/.config/user-dirs.dirs") + 1); if (config_file == NULL) goto error; strcpy (config_file, home_dir); strcat (config_file, "/.config/user-dirs.dirs"); } else { config_file = (char*) malloc (strlen (config_home) + strlen ("/user-dirs.dirs") + 1); if (config_file == NULL) goto error; strcpy (config_file, config_home); strcat (config_file, "/user-dirs.dirs"); } file = fopen (config_file, "r"); free (config_file); if (file == NULL) goto error; user_dir = NULL; while (fgets (buffer, sizeof (buffer), file)) { /* Remove newline at end */ len = strlen (buffer); if (len > 0 && buffer[len-1] == '\n') buffer[len-1] = 0; p = buffer; while (*p == ' ' || *p == '\t') p++; if (strncmp (p, "XDG_", 4) != 0) continue; p += 4; if (strncmp (p, type, strlen (type)) != 0) continue; p += strlen (type); if (strncmp (p, "_DIR", 4) != 0) continue; p += 4; while (*p == ' ' || *p == '\t') p++; if (*p != '=') continue; p++; while (*p == ' ' || *p == '\t') p++; if (*p != '"') continue; p++; relative = 0; if (strncmp (p, "$HOME/", 6) == 0) { p += 6; relative = 1; } else if (*p != '/') continue; if (relative) { user_dir = (char*) malloc (strlen (home_dir) + 1 + strlen (p) + 1); if (user_dir == NULL) goto error2; strcpy (user_dir, home_dir); strcat (user_dir, "/"); } else { user_dir = (char*) malloc (strlen (p) + 1); if (user_dir == NULL) goto error2; *user_dir = 0; } d = user_dir + strlen (user_dir); while (*p && *p != '"') { if ((*p == '\\') && (*(p+1) != 0)) p++; *d++ = *p++; } *d = 0; } error2: fclose (file); if (user_dir) return user_dir; error: if (fallback) return strdup (fallback); return NULL; } /** * xdg_user_dir_lookup: * @type: a string specifying the type of directory * @returns: a newly allocated absolute pathname * * Looks up a XDG user directory of the specified type. * Example of types are "DESKTOP" and "DOWNLOAD". * * The return value is always != NULL (unless out of memory), * and if a directory * for the type is not specified by the user the default * is the home directory. Except for DESKTOP which defaults * to ~/Desktop. * * The return value is newly allocated and must be freed with * SbMemoryDeallocate(). **/ char * xdg_user_dir_lookup (const char *type) { char *dir, *home_dir, *user_dir; dir = xdg_user_dir_lookup_with_fallback (type, NULL); if (dir != NULL) return dir; home_dir = getenv ("HOME"); if (home_dir == NULL) return strdup ("/tmp"); /* Special case desktop for historical compatibility */ if (strcmp (type, "DESKTOP") == 0) { user_dir = (char*) malloc (strlen (home_dir) + strlen ("/Desktop") + 1); if (user_dir == NULL) return NULL; strcpy (user_dir, home_dir); strcat (user_dir, "/Desktop"); return user_dir; } return strdup (home_dir); } #ifdef STANDALONE_XDG_USER_DIR_LOOKUP int main (int argc, char *argv[]) { if (argc != 2) { fprintf (stderr, "Usage %s <dir-type>\n", argv[0]); exit (1); } printf ("%s\n", xdg_user_dir_lookup (argv[1])); return 0; } #endif
{ "content_hash": "f5bf5ddf43d1f96a623cbc674827036a", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 96, "avg_line_length": 22.2311320754717, "alnum_prop": 0.5605771270952684, "repo_name": "youtube/cobalt_sandbox", "id": "598659cddb9135dbe02906285f450f436bae5696", "size": "5951", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "base/third_party/xdg_user_dirs/xdg_user_dir_lookup.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
"Dexter" is a script that can help in applying workaround for dex count issues during android build for a Unity Android project. The script parses the Unity project for Android libraries that can be refactored to reduce the overall method count via the process mentioned in our documentation linked below: https://developers.helpshift.com/unity/troubleshooting-android/#dex-64k-issue ## NOTE: * This script refactors the folder structure and the AndroidManifest.xml files of the Android libraries in your project. The app needs to be thoroughly tested after executing the script. * Updating the refactored plugins can have issues. A Unity plugin/android library upgrade generally looks for updating a predefined folder/file path. Since this script can potentially change the folder/file structure, upgrading plugins can have issues. Update of any plugin/library needs to be thoroughly tested for integration and functionality. * Although the script itself checks for updates, you should always check that you're using the latest version of the script. ## Setup/Installation * Make sure you are running Python version `2.7.x`. * Make sure pip is installed. If not, follow instructions here - https://packaging.python.org/installing/ * `dexter` depends on a few external Python libs, which can be installed by running the following command, ```bash pip install requests==2.7.0 PyYAML==3.10 ``` * Make the script executable ```bash chmod u+x dexter ``` ## Script arguments | Argument | Description | | ------------- | ------------- | | '-v', '--verbose' | Enables logging. | | '-p', '--project-dir' | Path to the project directory. Default is the present working directory. | | '-b', '--backup-suffix' | Suffix to add to dir where backup is taken. Default is '.bkp'. | | '-a', '--android-target' | Android target version to be added in the project.properties file of refactored android libraries. |
{ "content_hash": "0241f5a13a0eeb346dd3189d755b97ed", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 346, "avg_line_length": 49.8, "alnum_prop": 0.7233935742971888, "repo_name": "helpshift/dexter", "id": "202015bac4a12b313f9ffaa83266cd3186dae81a", "size": "2002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "17153" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4c04f188764b54d27f2f577c0c1d3cb3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "efa22350394b2b7fcc34ccee38bfd6dbced03aef", "size": "202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Lachenalia/Lachenalia maximiliani/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_SVGTextPositioningElement_h #define mozilla_dom_SVGTextPositioningElement_h #include "mozilla/dom/SVGTextContentElement.h" #include "SVGAnimatedLengthList.h" #include "SVGAnimatedNumberList.h" namespace mozilla { class SVGAnimatedLengthList; class DOMSVGAnimatedLengthList; class DOMSVGAnimatedNumberList; namespace dom { typedef SVGTextContentElement SVGTextPositioningElementBase; class SVGTextPositioningElement : public SVGTextPositioningElementBase { public: // WebIDL already_AddRefed<DOMSVGAnimatedLengthList> X(); already_AddRefed<DOMSVGAnimatedLengthList> Y(); already_AddRefed<DOMSVGAnimatedLengthList> Dx(); already_AddRefed<DOMSVGAnimatedLengthList> Dy(); already_AddRefed<DOMSVGAnimatedNumberList> Rotate(); protected: explicit SVGTextPositioningElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo) : SVGTextPositioningElementBase(aNodeInfo) {} virtual LengthListAttributesInfo GetLengthListInfo() override; virtual NumberListAttributesInfo GetNumberListInfo() override; enum { ATTR_X, ATTR_Y, ATTR_DX, ATTR_DY }; SVGAnimatedLengthList mLengthListAttributes[4]; static LengthListInfo sLengthListInfo[4]; enum { ROTATE }; SVGAnimatedNumberList mNumberListAttributes[1]; static NumberListInfo sNumberListInfo[1]; }; } // namespace dom } // namespace mozilla #endif // mozilla_dom_SVGTextPositioningElement_h
{ "content_hash": "dc8004a32afe7d6b23c484640d88d824", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 89, "avg_line_length": 32.471698113207545, "alnum_prop": 0.7797791981406159, "repo_name": "andrasigneczi/TravelOptimizer", "id": "b58bba84a6fe436e9f7acc19e30c0ffb4754a05a", "size": "1721", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/SVGTextPositioningElement.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3443874" }, { "name": "C++", "bytes": "33624518" }, { "name": "CSS", "bytes": "1225" }, { "name": "HTML", "bytes": "13117" }, { "name": "IDL", "bytes": "1110940" }, { "name": "Java", "bytes": "562163" }, { "name": "JavaScript", "bytes": "1480" }, { "name": "Makefile", "bytes": "360" }, { "name": "Objective-C", "bytes": "3166" }, { "name": "Python", "bytes": "322743" }, { "name": "Shell", "bytes": "2539" } ], "symlink_target": "" }
- [Introduction](#introduction) - [After Installation](#after-installation) - [Accessing Configuration Values](#accessing-configuration-values) - [Environment Configuration](#environment-configuration) - [Configuration Caching](#configuration-caching) - [Maintenance Mode](#maintenance-mode) - [Pretty URLs](#pretty-urls) <a name="introduction"></a> ## Introduction All of the configuration files for the Laravel framework are stored in the `config` directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you. <a name="after-installation"></a> ## After Installation ### Naming Your Application After installing Laravel, you may wish to "name" your application. By default, the `app` directory is namespaced under `App`, and autoloaded by Composer using the [PSR-4 autoloading standard](http://www.php-fig.org/psr/psr-4/). However, you may change the namespace to match the name of your application, which you can easily do via the `app:name` Artisan command. For example, if your application is named "Horsefly", you could run the following command from the root of your installation: php artisan app:name Horsefly Renaming your application is entirely optional, and you are free to keep the `App` namespace if you wish. ### Other Configuration Laravel needs very little configuration out of the box. You are free to get started developing! However, you may wish to review the `config/app.php` file and its documentation. It contains several options such as `timezone` and `locale` that you may wish to change according to your location. Once Laravel is installed, you should also [configure your local environment](/docs/5.0/configuration#environment-configuration). > **Note:** You should never have the `app.debug` configuration option set to `true` for a production application. <a name="permissions"></a> ### Permissions Laravel may require one set of permissions to be configured: folders within `storage` require write access by the web server. <a name="accessing-configuration-values"></a> ## Accessing Configuration Values You may easily access your configuration values using the `Config` facade: $value = Config::get('app.timezone'); Config::set('app.timezone', 'America/Chicago'); You may also use the `config` helper function: $value = config('app.timezone'); <a name="environment-configuration"></a> ## Environment Configuration It is often helpful to have different configuration values based on the environment the application is running in. For example, you may wish to use a different cache driver locally than you do on your production server. It's easy using environment based configuration. To make this a cinch, Laravel utilizes the [DotEnv](https://github.com/vlucas/phpdotenv) PHP library by Vance Lucas. In a fresh Laravel installation, the root directory of your application will contain a `.env.example` file. If you install Laravel via Composer, this file will automatically be renamed to `.env`. Otherwise, you should rename the file manually. All of the variables listed in this file will be loaded into the `$_ENV` PHP super-global when your application receives a request. You may use the `env` helper to retrieve values from these variables. In fact, if you review the Laravel configuration files, you will notice several of the options already using this helper! Feel free to modify your environment variables as needed for your own local server, as well as your production environment. However, your `.env` file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. If you are developing with a team, you may wish to continue including a `.env.example` file with your application. By putting place-holder values in the example configuration file, other developers on your team can clearly see which environment variables are needed to run your application. #### Accessing The Current Application Environment You may access the current application environment via the `environment` method on the `Application` instance: $environment = $app->environment(); You may also pass arguments to the `environment` method to check if the environment matches a given value: if ($app->environment('local')) { // The environment is local } if ($app->environment('local', 'staging')) { // The environment is either local OR staging... } To obtain an instance of the application, resolve the `Illuminate\Contracts\Foundation\Application` contract via the [service container](/docs/5.0/container). Of course, if you are within a [service provider](/docs/5.0/providers), the application instance is available via the `$this->app` instance variable. An application instance may also be accessed via the `app` helper or the `App` facade: $environment = app()->environment(); $environment = App::environment(); <a name="configuration-caching"></a> ## Configuration Caching To give your application a little speed boost, you may cache all of your configuration files into a single file using the `config:cache` Artisan command. This will combine all of the configuration options for your application into a single file which can be loaded quickly by the framework. You should typically run the `config:cache` command as part of your deployment routine. <a name="maintenance-mode"></a> ## Maintenance Mode When your application is in maintenance mode, a custom view will be displayed for all requests into your application. This makes it easy to "disable" your application while it is updating or when you are performing maintenance. A maintenance mode check is included in the default middleware stack for your application. If the application is in maintenance mode, an `HttpException` will be thrown with a status code of 503. To enable maintenance mode, simply execute the `down` Artisan command: php artisan down To disable maintenance mode, use the `up` command: php artisan up ### Maintenance Mode Response Template The default template for maintenance mode responses is located in `resources/views/errors/503.blade.php`. ### Maintenance Mode & Queues While your application is in maintenance mode, no [queued jobs](/docs/5.0/queues) will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode. <a name="pretty-urls"></a> ## Pretty URLs ### Apache The framework ships with a `public/.htaccess` file that is used to allow URLs without `index.php`. If you use Apache to serve your Laravel application, be sure to enable the `mod_rewrite` module. If the `.htaccess` file that ships with Laravel does not work with your Apache installation, try this one: Options +FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] ### Nginx On Nginx, the following directive in your site configuration will allow "pretty" URLs: location / { try_files $uri $uri/ /index.php?$query_string; } Of course, when using [Homestead](/docs/5.0/homestead), pretty URLs will be configured automatically.
{ "content_hash": "43e1a92867b9276005771f98705aa9c9", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 422, "avg_line_length": 50.03472222222222, "alnum_prop": 0.7730742539902845, "repo_name": "adamgoose/docs", "id": "717bef0c641d3e9c818423d66988e5341effff81", "size": "7222", "binary": false, "copies": "5", "ref": "refs/heads/5.0", "path": "configuration.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
@implementation CHTextShow { UIView *view_; } +(id)sharedManager { static CHTextShow *sharedManager; static dispatch_once_t oneceToken; dispatch_once(&oneceToken, ^{ sharedManager = [[CHTextShow alloc] init]; }); return sharedManager; } - (void)showBtnText:(NSString *)content withImage:(UIImage *)image inView:(UIView *)view delay:(NSInteger)sec { UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)]; //图片 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 80, ScreenWidth-20, (ScreenWidth-20))]; imageView.image = image; //imageView.backgroundColor = [UIColor yellowColor]; [backView addSubview:imageView]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, imageView.frame.size.height+imageView.frame.origin.y, view.frame.size.width-20, 100)]; label.font = [UIFont boldSystemFontOfSize:24]; label.backgroundColor = [UIColor whiteColor]; label.text = content; label.textAlignment = NSTextAlignmentCenter; label.textColor = [UIColor redColor]; [backView addSubview:label]; [[CHLayout sharedManager] fitsize:label]; [view addSubview:backView]; UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)]; [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; button.backgroundColor = [UIColor clearColor]; [backView addSubview:button]; backView.backgroundColor = [UIColor whiteColor]; [self performSelector:@selector(deleteView:) withObject:backView afterDelay:sec]; view_ = backView; } - (void)deleteView:(UIView *)view { [view removeFromSuperview]; if (self.didClick!=nil) { self.didClick(); } } - (void)btnClick:(id)sender { if (self.didClick!=nil) { self.didClick(); } [view_ removeFromSuperview]; } @end
{ "content_hash": "e2f709aca0c5457bbce5c47779770202", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 153, "avg_line_length": 30.424242424242426, "alnum_prop": 0.6917330677290837, "repo_name": "ZICUNREN/MicroShopProject", "id": "93b73f461cb8247090578af9ec319911124527da", "size": "2183", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MicroShop/MicroShop/Extend/CHTextShow/CHTextShow.m", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "18978" }, { "name": "HTML", "bytes": "4555" }, { "name": "Objective-C", "bytes": "2708496" }, { "name": "Swift", "bytes": "52719" } ], "symlink_target": "" }
package org.apache.flink.yarn; import org.apache.flink.client.deployment.ClusterSpecification; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.HighAvailabilityOptions; import org.apache.flink.configuration.JobManagerOptions; import org.apache.flink.configuration.TaskManagerOptions; import org.apache.flink.util.FlinkException; import org.apache.flink.util.TestLogger; import org.apache.flink.yarn.cli.FlinkYarnSessionCli; import org.apache.flink.yarn.configuration.YarnConfigOptions; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.Map; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * Tests for the {@link FlinkYarnSessionCli}. */ public class FlinkYarnSessionCliTest extends TestLogger { private static final ApplicationId TEST_YARN_APPLICATION_ID = ApplicationId.newInstance(System.currentTimeMillis(), 42); private static final ApplicationId TEST_YARN_APPLICATION_ID_2 = ApplicationId.newInstance(System.currentTimeMillis(), 43); private static final String TEST_YARN_JOB_MANAGER_ADDRESS = "22.33.44.55"; private static final int TEST_YARN_JOB_MANAGER_PORT = 6655; private static final String validPropertiesFile = "applicationID=" + TEST_YARN_APPLICATION_ID; private static final String invalidPropertiesFile = "jasfobManager=" + TEST_YARN_JOB_MANAGER_ADDRESS + ":asf" + TEST_YARN_JOB_MANAGER_PORT; @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Test public void testDynamicProperties() throws Exception { FlinkYarnSessionCli cli = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "", "", false); Options options = new Options(); cli.addGeneralOptions(options); cli.addRunOptions(options); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, new String[]{"run", "-j", "fake.jar", "-D", "akka.ask.timeout=5 min", "-D", "env.java.opts=-DappName=foobar", "-D", "security.ssl.internal.key-password=changeit"}); YarnClusterDescriptor flinkYarnDescriptor = cli.createClusterDescriptor(cmd); Assert.assertNotNull(flinkYarnDescriptor); Map<String, String> dynProperties = FlinkYarnSessionCli.getDynamicProperties(flinkYarnDescriptor.getDynamicPropertiesEncoded()); assertEquals(3, dynProperties.size()); assertEquals("5 min", dynProperties.get("akka.ask.timeout")); assertEquals("-DappName=foobar", dynProperties.get("env.java.opts")); assertEquals("changeit", dynProperties.get("security.ssl.internal.key-password")); } @Test public void testCorrectSettingOfMaxSlots() throws Exception { String[] params = new String[] {"-ys", "3"}; FlinkYarnSessionCli yarnCLI = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true); YarnClusterDescriptor descriptor = yarnCLI.createClusterDescriptor(commandLine); final ClusterSpecification clusterSpecification = yarnCLI.getClusterSpecification(commandLine); // each task manager has 3 slots but the parallelism is 7. Thus the slots should be increased. assertEquals(3, clusterSpecification.getSlotsPerTaskManager()); assertEquals(1, clusterSpecification.getNumberTaskManagers()); } @Test public void testCorrectSettingOfDetachedMode() throws Exception { String[] params = new String[] {"-yd"}; FlinkYarnSessionCli yarnCLI = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true); YarnClusterDescriptor descriptor = yarnCLI.createClusterDescriptor(commandLine); // each task manager has 3 slots but the parallelism is 7. Thus the slots should be increased. assertTrue(descriptor.isDetachedMode()); } @Test public void testZookeeperNamespaceProperty() throws Exception { String zkNamespaceCliInput = "flink_test_namespace"; String[] params = new String[] {"-yz", zkNamespaceCliInput}; FlinkYarnSessionCli yarnCLI = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true); YarnClusterDescriptor descriptor = yarnCLI.createClusterDescriptor(commandLine); assertEquals(zkNamespaceCliInput, descriptor.getZookeeperNamespace()); } @Test public void testNodeLabelProperty() throws Exception { String nodeLabelCliInput = "flink_test_nodelabel"; String[] params = new String[] {"-ynl", nodeLabelCliInput }; FlinkYarnSessionCli yarnCLI = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true); YarnClusterDescriptor descriptor = yarnCLI.createClusterDescriptor(commandLine); assertEquals(nodeLabelCliInput, descriptor.getNodeLabel()); } /** * Test that the CliFrontend is able to pick up the .yarn-properties file from a specified location. */ @Test public void testResumeFromYarnPropertiesFile() throws Exception { File directoryPath = writeYarnPropertiesFile(validPropertiesFile); final Configuration configuration = new Configuration(); configuration.setString(YarnConfigOptions.PROPERTIES_FILE_LOCATION, directoryPath.getAbsolutePath()); final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {}, true); final ApplicationId clusterId = flinkYarnSessionCli.getClusterId(commandLine); assertEquals(TEST_YARN_APPLICATION_ID, clusterId); } /** * Tests that we fail when reading an invalid yarn properties file when retrieving * the cluster id. */ @Test(expected = FlinkException.class) public void testInvalidYarnPropertiesFile() throws Exception { File directoryPath = writeYarnPropertiesFile(invalidPropertiesFile); final Configuration configuration = new Configuration(); configuration.setString(YarnConfigOptions.PROPERTIES_FILE_LOCATION, directoryPath.getAbsolutePath()); new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); } @Test public void testResumeFromYarnID() throws Exception { final Configuration configuration = new Configuration(); final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID.toString()}, true); final ApplicationId clusterId = flinkYarnSessionCli.getClusterId(commandLine); assertEquals(TEST_YARN_APPLICATION_ID, clusterId); } @Test public void testResumeFromYarnIDZookeeperNamespace() throws Exception { final Configuration configuration = new Configuration(); final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID.toString()}, true); final YarnClusterDescriptor clusterDescriptor = flinkYarnSessionCli.createClusterDescriptor(commandLine); final Configuration clusterDescriptorConfiguration = clusterDescriptor.getFlinkConfiguration(); String zkNs = clusterDescriptorConfiguration.getValue(HighAvailabilityOptions.HA_CLUSTER_ID); assertTrue(zkNs.matches("application_\\d+_0042")); } @Test public void testResumeFromYarnIDZookeeperNamespaceOverride() throws Exception { final Configuration configuration = new Configuration(); final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); final String overrideZkNamespace = "my_cluster"; final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID.toString(), "-yz", overrideZkNamespace}, true); final YarnClusterDescriptor clusterDescriptor = flinkYarnSessionCli.createClusterDescriptor(commandLine); final Configuration clusterDescriptorConfiguration = clusterDescriptor.getFlinkConfiguration(); final String clusterId = clusterDescriptorConfiguration.getValue(HighAvailabilityOptions.HA_CLUSTER_ID); assertEquals(overrideZkNamespace, clusterId); } @Test public void testYarnIDOverridesPropertiesFile() throws Exception { File directoryPath = writeYarnPropertiesFile(validPropertiesFile); final Configuration configuration = new Configuration(); configuration.setString(YarnConfigOptions.PROPERTIES_FILE_LOCATION, directoryPath.getAbsolutePath()); final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID_2.toString() }, true); final ApplicationId clusterId = flinkYarnSessionCli.getClusterId(commandLine); assertEquals(TEST_YARN_APPLICATION_ID_2, clusterId); } /** * Tests that the command line arguments override the configuration settings * when the {@link ClusterSpecification} is created. */ @Test public void testCommandLineClusterSpecification() throws Exception { final Configuration configuration = new Configuration(); final int jobManagerMemory = 1337; final int taskManagerMemory = 7331; final int slotsPerTaskManager = 30; configuration.setString(JobManagerOptions.JOB_MANAGER_HEAP_MEMORY, jobManagerMemory + "m"); configuration.setString(TaskManagerOptions.TASK_MANAGER_HEAP_MEMORY, taskManagerMemory + "m"); configuration.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, slotsPerTaskManager); final String[] args = {"-yjm", String.valueOf(jobManagerMemory) + "m", "-ytm", String.valueOf(taskManagerMemory) + "m", "-ys", String.valueOf(slotsPerTaskManager)}; final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false); final ClusterSpecification clusterSpecification = flinkYarnSessionCli.getClusterSpecification(commandLine); assertThat(clusterSpecification.getMasterMemoryMB(), is(jobManagerMemory)); assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(taskManagerMemory)); assertThat(clusterSpecification.getSlotsPerTaskManager(), is(slotsPerTaskManager)); } /** * Tests that the configuration settings are used to create the * {@link ClusterSpecification}. */ @Test public void testConfigurationClusterSpecification() throws Exception { final Configuration configuration = new Configuration(); final int jobManagerMemory = 1337; configuration.setString(JobManagerOptions.JOB_MANAGER_HEAP_MEMORY, jobManagerMemory + "m"); final int taskManagerMemory = 7331; configuration.setString(TaskManagerOptions.TASK_MANAGER_HEAP_MEMORY, taskManagerMemory + "m"); final int slotsPerTaskManager = 42; configuration.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, slotsPerTaskManager); final String[] args = {}; final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false); final ClusterSpecification clusterSpecification = flinkYarnSessionCli.getClusterSpecification(commandLine); assertThat(clusterSpecification.getMasterMemoryMB(), is(jobManagerMemory)); assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(taskManagerMemory)); assertThat(clusterSpecification.getSlotsPerTaskManager(), is(slotsPerTaskManager)); } /** * Tests the specifying heap memory without unit for job manager and task manager. */ @Test public void testHeapMemoryPropertyWithoutUnit() throws Exception { final String[] args = new String[] { "-yjm", "1024", "-ytm", "2048" }; final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false); final ClusterSpecification clusterSpecification = flinkYarnSessionCli.getClusterSpecification(commandLine); assertThat(clusterSpecification.getMasterMemoryMB(), is(1024)); assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(2048)); } /** * Tests the specifying heap memory with unit (MB) for job manager and task manager. */ @Test public void testHeapMemoryPropertyWithUnitMB() throws Exception { final String[] args = new String[] { "-yjm", "1024m", "-ytm", "2048m" }; final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false); final ClusterSpecification clusterSpecification = flinkYarnSessionCli.getClusterSpecification(commandLine); assertThat(clusterSpecification.getMasterMemoryMB(), is(1024)); assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(2048)); } /** * Tests the specifying heap memory with arbitrary unit for job manager and task manager. */ @Test public void testHeapMemoryPropertyWithArbitraryUnit() throws Exception { final String[] args = new String[] { "-yjm", "1g", "-ytm", "2g" }; final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false); final ClusterSpecification clusterSpecification = flinkYarnSessionCli.getClusterSpecification(commandLine); assertThat(clusterSpecification.getMasterMemoryMB(), is(1024)); assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(2048)); } /** * Tests the specifying heap memory with old config key for job manager and task manager. */ @Test public void testHeapMemoryPropertyWithOldConfigKey() throws Exception { Configuration configuration = new Configuration(); configuration.setInteger(JobManagerOptions.JOB_MANAGER_HEAP_MEMORY_MB, 2048); configuration.setInteger(TaskManagerOptions.TASK_MANAGER_HEAP_MEMORY_MB, 4096); final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( configuration, tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[0], false); final ClusterSpecification clusterSpecification = flinkYarnSessionCli.getClusterSpecification(commandLine); assertThat(clusterSpecification.getMasterMemoryMB(), is(2048)); assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(4096)); } /** * Tests the specifying heap memory with config default value for job manager and task manager. */ @Test public void testHeapMemoryPropertyWithConfigDefaultValue() throws Exception { final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[0], false); final ClusterSpecification clusterSpecification = flinkYarnSessionCli.getClusterSpecification(commandLine); assertThat(clusterSpecification.getMasterMemoryMB(), is(1024)); assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(1024)); } @Test public void testMultipleYarnShipOptions() throws Exception { final String[] args = new String[]{"run", "--yarnship", tmp.newFolder().getAbsolutePath(), "--yarnship", tmp.newFolder().getAbsolutePath()}; final FlinkYarnSessionCli flinkYarnSessionCli = new FlinkYarnSessionCli( new Configuration(), tmp.getRoot().getAbsolutePath(), "y", "yarn"); final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false); YarnClusterDescriptor flinkYarnDescriptor = flinkYarnSessionCli.createClusterDescriptor(commandLine); assertEquals(2, flinkYarnDescriptor.getShipFiles().size()); } /////////// // Utils // /////////// private File writeYarnPropertiesFile(String contents) throws IOException { File tmpFolder = tmp.newFolder(); String currentUser = System.getProperty("user.name"); // copy .yarn-properties-<username> File testPropertiesFile = new File(tmpFolder, ".yarn-properties-" + currentUser); Files.write(testPropertiesFile.toPath(), contents.getBytes(), StandardOpenOption.CREATE); return tmpFolder.getAbsoluteFile(); } }
{ "content_hash": "d6775a98274f8baa194438770c4129b1", "timestamp": "", "source": "github", "line_count": 470, "max_line_length": 172, "avg_line_length": 37.272340425531915, "alnum_prop": 0.7781710240895079, "repo_name": "mbode/flink", "id": "23388751133aca5ecf2937d9d78be025b42009aa", "size": "18323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-yarn/src/test/java/org/apache/flink/yarn/FlinkYarnSessionCliTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5666" }, { "name": "CSS", "bytes": "18100" }, { "name": "Clojure", "bytes": "80170" }, { "name": "CoffeeScript", "bytes": "91220" }, { "name": "Dockerfile", "bytes": "9756" }, { "name": "HTML", "bytes": "86821" }, { "name": "Java", "bytes": "40396270" }, { "name": "JavaScript", "bytes": "8267" }, { "name": "Python", "bytes": "249644" }, { "name": "Scala", "bytes": "7495458" }, { "name": "Shell", "bytes": "388738" } ], "symlink_target": "" }
import inspect import logging from functools import wraps import pp __author__ = 'andrew.shvv@gmail.com' def get_prev_method_name(): return inspect.stack()[2][3] def pretty_wrapper(func): @wraps(func) def decorator(msg, *args, **kwargs): pretty_msg = "Func: %s\n" % get_prev_method_name() if type(msg) == str: pretty_msg += msg else: pretty_msg += pp.fmt(msg) pretty_msg += "\n+ " + "- " * 30 + "+\n" func(pretty_msg, *args, **kwargs) return decorator def wrap_logger(logger): logger.info = pretty_wrapper(logger.info) logger.debug = pretty_wrapper(logger.debug) logger.warning = pretty_wrapper(logger.warning) logger.exception = pretty_wrapper(logger.exception) return logger def getLogger(name, level=logging.DEBUG): # create logger logger = logging.getLogger(name) logger = wrap_logger(logger) # create console handler and set level to debug ch = logging.StreamHandler() # create formatter formatter = logging.Formatter('\nLevel: %(levelname)s - %(name)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) logger.setLevel(level) return logger
{ "content_hash": "762994abe91d140d84f108e51acaa97a", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 84, "avg_line_length": 22.333333333333332, "alnum_prop": 0.6347211311861743, "repo_name": "absortium/poloniex-api", "id": "d4d0f0e9d5aa72ff43545d70fd87b16508855ef5", "size": "1273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "poloniex/logger.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "35921" } ], "symlink_target": "" }
module Grooveshark # Client class class Client attr_accessor :session, :comm_token attr_reader :user, :comm_token_ttl, :country def initialize(params = {}) @ttl = params[:ttl] || 120 # 2 minutes @uuid = UUID.new.generate.upcase token_data end # Authenticate user def login(user, password) data = request('authenticateUser', { username: user, password: password }, true) @user = User.new(self, data) fail InvalidAuthentication, 'Wrong username or password!' if @user.id == 0 @user end # Find user by ID def get_user_by_id(id) resp = request('getUserByID', userID: id)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end # Find user by username def get_user_by_username(name) resp = request('getUserByUsername', username: name)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end # Get recently active users def recent_users request('getRecentlyActiveUsers', {})['users'] .map do |u| User.new(self, u) end end # Get popular songs # type => daily, monthly def popular_songs(type = 'daily') fail ArgumentError, 'Invalid type' unless %w(daily monthly).include?(type) request('popularGetSongs', type: type)['songs'].map { |s| Song.new(s) } end # Get top broadcasts # count => specifies how many broadcasts to get def top_broadcasts(count = 10) top_broadcasts = [] request('getTopBroadcastsCombined').each do |key, _val| broadcast_id = key.split(':')[1] top_broadcasts.push(Broadcast.new(self, broadcast_id)) count -= 1 break if count == 0 end top_broadcasts end # Perform search request for query def search(type, query) results = [] search = request('getResultsFromSearch', type: type, query: query) results = search['result'].map do |data| next Song.new data if type == 'Songs' next Playlist.new(self, data) if type == 'Playlists' data end if search.key?('result') results end # Perform songs search request for query def search_songs(query) search('Songs', query) end # Return raw response for songs search request def search_songs_pure(query) request('getSearchResultsEx', type: 'Songs', query: query) end # Get stream authentication by song ID def get_stream_auth_by_songid(song_id) result = request('getStreamKeyFromSongIDEx', 'type' => 0, 'prefetch' => false, 'songID' => song_id, 'country' => @country, 'mobile' => false) if result == [] fail GeneralError, 'No data for this song. ' \ 'Maybe Grooveshark banned your IP.' end result end # Get stream authentication for song object def get_stream_auth(song) get_stream_auth_by_songid(song.id) end # Get song stream url by ID def get_song_url_by_id(id) resp = get_stream_auth_by_songid(id) "http://#{resp['ip']}/stream.php?streamKey=#{resp['stream_key']}" end # Get song stream def get_song_url(song) get_song_url_by_id(song.id) end def token_data response = RestClient.get('http://grooveshark.com') preload_regex = /gsPreloadAjax\(\{url: '\/preload.php\?(.*)&hash=' \+ clientPage\}\)/ # rubocop:disable Metrics/LineLength preload_id = response.to_s.scan(preload_regex).flatten.first preload_url = "http://grooveshark.com/preload.php?#{preload_id}" \ '&getCommunicationToken=1&hash=%2F' preload_response = RestClient.get(preload_url) token_data_json = preload_response.to_s .scan(/window.tokenData = (.*);/).flatten.first fail GeneralError, 'token data not found' unless token_data_json token_data = JSON.parse(token_data_json) @comm_token = token_data['getCommunicationToken'] @comm_token_ttl = Time.now.to_i config = token_data['getGSConfig'] @country = config['country'] @session = config['sessionID'] end # Sign method def create_token(method) rnd = get_random_hex_chars(6) salt = 'gooeyFlubber' plain = [method, @comm_token, salt, rnd].join(':') hash = Digest::SHA1.hexdigest(plain) "#{rnd}#{hash}" end def get_random_hex_chars(length) chars = ('a'..'f').to_a | (0..9).to_a (0...length).map { chars[rand(chars.length)] }.join end def body(method, params) body = { 'header' => { 'client' => 'mobileshark', 'clientRevision' => '20120830', 'country' => @country, 'privacy' => 0, 'session' => @session, 'uuid' => @uuid }, 'method' => method, 'parameters' => params } body['header']['token'] = create_token(method) if @comm_token body end # Perform API request def request(method, params = {}, secure = false) refresh_token if @comm_token url = "#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}" begin data = RestClient.post(url, body(method, params).to_json, 'Content-Type' => 'application/json') rescue StandardError => ex raise GeneralError, ex.message end data = JSON.parse(data) data = data.normalize if data.is_a?(Hash) if data.key?('fault') fail ApiError, data['fault'] else data['result'] end end # Refresh communications token on ttl def refresh_token token_data if Time.now.to_i - @comm_token_ttl > @ttl end end end
{ "content_hash": "cc95e58668b0b0744c1ea37d3a4201ca", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 128, "avg_line_length": 29.84263959390863, "alnum_prop": 0.5725463514203096, "repo_name": "sosedoff/grooveshark", "id": "7cb3b76081147a611e2e2fa30a8f6c18913fbde4", "size": "5900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/grooveshark/client.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "32956" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Backend servers &mdash; Varnish version 4.0.0 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '4.0.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="top" title="Varnish version 4.0.0 documentation" href="../index.html" /> <link rel="up" title="The Varnish Tutorial" href="index.html" /> <link rel="next" title="Peculiarities" href="peculiarities.html" /> <link rel="prev" title="Put Varnish on port 80" href="putting_varnish_on_port_80.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="peculiarities.html" title="Peculiarities" accesskey="N">next</a> |</li> <li class="right" > <a href="putting_varnish_on_port_80.html" title="Put Varnish on port 80" accesskey="P">previous</a> |</li> <li><a href="../index.html">Varnish version 4.0.0 documentation</a> &raquo;</li> <li><a href="index.html" accesskey="U">The Varnish Tutorial</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="backend-servers"> <span id="tutorial-backend-servers"></span><h1>Backend servers<a class="headerlink" href="#backend-servers" title="Permalink to this headline">¶</a></h1> <p>Varnish has a concept of <cite>backend</cite> or origin servers. A backend server is the server providing the content Varnish will accelerate via the cache.</p> <p>Our first task is to tell Varnish where it can find its content. Start your favorite text editor and open the Varnish default configuration file. If you installed from source this is <cite>/usr/local/etc/varnish/default.vcl</cite>, if you installed from a package it is probably <cite>/etc/varnish/default.vcl</cite>.</p> <p>If you've been following the tutorial there is probably a section of the configuration that looks like this::</p> <div class="highlight-python"><pre>vcl 4.0; backend default { .host = "www.varnish-cache.org"; .port = "80"; }</pre> </div> <p>This means we set up a backend in Varnish that fetches content from the host www.varnish-cache.org on port 80.</p> <p>Since you probably don't want to be mirroring varnish-cache.org we need to get Varnish to fetch content from your own origin server. We've already bound Varnish to the public port 80 on the server so now we need to tie it to the origin.</p> <p>For this example, let's pretend the origin server is running on localhost, port 8080.:</p> <div class="highlight-python"><pre>vcl 4.0; backend default { .host = "127.0.0.1"; .port = "8080"; }</pre> </div> <p>Varnish can have several backends defined and can even join several backends together into clusters of backends for load balancing purposes, having Varnish pick one backend based on different algorithms.</p> <p>Next, let's have a look at some of what makes Varnish unique and what you can do with it.</p> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="putting_varnish_on_port_80.html" title="previous chapter">Put Varnish on port 80</a></p> <h4>Next topic</h4> <p class="topless"><a href="peculiarities.html" title="next chapter">Peculiarities</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/tutorial/backend_servers.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="peculiarities.html" title="Peculiarities" >next</a> |</li> <li class="right" > <a href="putting_varnish_on_port_80.html" title="Put Varnish on port 80" >previous</a> |</li> <li><a href="../index.html">Varnish version 4.0.0 documentation</a> &raquo;</li> <li><a href="index.html" >The Varnish Tutorial</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2010-2014, Varnish Software AS. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
{ "content_hash": "4f69e72e8eb569aa0235b7de690073ac", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 153, "avg_line_length": 40.7027027027027, "alnum_prop": 0.6248339973439575, "repo_name": "reesun/varnish-cache-4.0.0", "id": "a4e6e63326dd26ca8d65506489b3f5279eb5e49a", "size": "6027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/sphinx/build/html/tutorial/backend_servers.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "1743848" }, { "name": "C++", "bytes": "46440" }, { "name": "CSS", "bytes": "16431" }, { "name": "JavaScript", "bytes": "80947" }, { "name": "Objective-C", "bytes": "33093" }, { "name": "Python", "bytes": "55936" }, { "name": "Shell", "bytes": "332400" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Editor; using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System.Linq; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality.Editor { [CustomEditor(typeof(WindowsMixedRealityCameraSettingsProfile))] public class WindowsMixedRealityCameraSettingsProfileInspector : BaseMixedRealityToolkitConfigurationProfileInspector { private const string ProfileTitle = "Windows Mixed Reality Camera Settings"; private const string ProfileDescription = ""; private SerializedProperty renderFromPVCameraForMixedRealityCapture; private SerializedProperty reprojectionMethod; private SerializedProperty readingModeEnabled; private static readonly GUIContent PVCameraRenderingTitle = new GUIContent("Render from PV Camera (Align holograms)"); private static readonly GUIContent ReprojectionMethodTitle = new GUIContent("HoloLens 2 Reprojection Method"); private const string MRCDocURL = "https://docs.microsoft.com/windows/mixed-reality/mixed-reality-capture-for-developers#render-from-the-pv-camera-opt-in"; private const string DepthReprojectionDocURL = "https://docs.microsoft.com/windows/mixed-reality/hologram-stability#reprojection"; private const string ReadingModeDocURL = "https://docs.microsoft.com/en-us/hololens/hololens2-display#what-improvements-are-coming-that-will-improve-hololens-2-image-quality"; protected override void OnEnable() { base.OnEnable(); renderFromPVCameraForMixedRealityCapture = serializedObject.FindProperty("renderFromPVCameraForMixedRealityCapture"); reprojectionMethod = serializedObject.FindProperty("reprojectionMethod"); readingModeEnabled = serializedObject.FindProperty("readingModeEnabled"); } public override void OnInspectorGUI() { RenderProfileHeader(ProfileTitle, ProfileDescription, target); using (new EditorGUI.DisabledGroupScope(IsProfileLock((BaseMixedRealityProfile)target))) { serializedObject.Update(); EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("Mixed Reality Capture Settings", EditorStyles.boldLabel); InspectorUIUtility.RenderDocumentationButton(MRCDocURL); } EditorGUILayout.HelpBox("On legacy XR, render from PV camera is supported in Unity 2018.4.35f1 and newer if using Unity 2018 and Unity 2019.4.26f1 and newer if using Unity 2019.", MessageType.Info); EditorGUILayout.HelpBox("On Windows XR Plugin, render from PV camera is supported in versions 2.8.0, 4.5.0, and 5.3.0 (and newer in each respective major version).", MessageType.Info); EditorGUILayout.PropertyField(renderFromPVCameraForMixedRealityCapture, PVCameraRenderingTitle); EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("Depth Reprojection Settings", EditorStyles.boldLabel); InspectorUIUtility.RenderDocumentationButton(DepthReprojectionDocURL); } EditorGUILayout.PropertyField(reprojectionMethod, ReprojectionMethodTitle); EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("Reading Mode Settings", EditorStyles.boldLabel); InspectorUIUtility.RenderDocumentationButton(ReadingModeDocURL); } EditorGUILayout.PropertyField(readingModeEnabled); serializedObject.ApplyModifiedProperties(); } } protected override bool IsProfileInActiveInstance() { var profile = target as BaseMixedRealityProfile; return MixedRealityToolkit.IsInitialized && profile != null && MixedRealityToolkit.Instance.HasActiveProfile && MixedRealityToolkit.Instance.ActiveProfile.CameraProfile != null && MixedRealityToolkit.Instance.ActiveProfile.CameraProfile.SettingsConfigurations != null && MixedRealityToolkit.Instance.ActiveProfile.CameraProfile.SettingsConfigurations.Any(s => s.SettingsProfile == profile); } } }
{ "content_hash": "2d0962f7263761d21b5ef953c3f2efca", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 214, "avg_line_length": 52.64772727272727, "alnum_prop": 0.6965249298510684, "repo_name": "killerantz/HoloToolkit-Unity", "id": "f37ecc09a4af0b585c05fa7463f7b541a49dd925", "size": "4635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/MRTK/Providers/WindowsMixedReality/Shared/Editor/WindowsMixedRealityCameraSettingsProfileInspector.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "10228041" }, { "name": "CSS", "bytes": "771" }, { "name": "GLSL", "bytes": "44693" }, { "name": "HLSL", "bytes": "856" }, { "name": "HTML", "bytes": "203" }, { "name": "JavaScript", "bytes": "2818" }, { "name": "PowerShell", "bytes": "123810" }, { "name": "Python", "bytes": "9153" }, { "name": "ShaderLab", "bytes": "130983" } ], "symlink_target": "" }
define([], function() { var spec = { id: "ApplicationHeader", name: "basics.ApplicationHeader", requireName: "basicsapplicationheader", fullComponentName: "org.scn.community.basics.ApplicationHeader", fullComponentPackage: "org.scn.community.basics/res/ApplicationHeader", script: "org.scn.community.basics/res/ApplicationHeader/ApplicationHeader", scriptSpec: "org.scn.community.basics/res/ApplicationHeader/ApplicationHeaderSpec", min: false }; spec.spec = { "displayLogoff": { "opts": { "apsControl": "checkbox", "cat": "Display-Texts", "desc": "Display Logoff", "noAps": false, "noZtl": false, "tooltip": "If Set To True, The Logoff Area Will Be Displayed At The Right Hand Side Of The Application Header.", "ztlFunction": "", "ztlType": "boolean" }, "template": "boolean", "type": "boolean", "value": "", "visible": true }, "displayWelcome": { "opts": { "apsControl": "checkbox", "cat": "Display-Texts", "desc": "Display Welcome", "noAps": false, "noZtl": false, "tooltip": "By Default, Set To True And Dislpays The Welcome Text.", "ztlFunction": "", "ztlType": "boolean" }, "template": "boolean", "type": "boolean", "value": "true", "visible": true }, "logoSrc": { "opts": { "apsControl": "text", "cat": "Display-Logo", "desc": "Logo Source", "noAps": false, "noZtl": false, "tooltip": "Path (src) To The Logo Icon To Be Displayed In The Application Header.", "ztlFunction": "", "ztlType": "String" }, "template": "default", "type": "String", "value": "", "visible": true }, "logoText": { "opts": { "apsControl": "text", "cat": "Display-Logo", "desc": "Logo Text", "noAps": false, "noZtl": false, "tooltip": "The Text That Will Be Displayed Beside The Logo In The Application Header. This Property Is Optional.", "ztlFunction": "", "ztlType": "String" }, "template": "String", "type": "String", "value": "", "visible": true }, "onLogoff": { "opts": { "apsControl": "text", "cat": "Events", "desc": "On Logoff", "noAps": true, "noZtl": true, "tooltip": "Fires An Event To Log Off The User From The Application." }, "template": "Event", "type": "ScriptText", "value": "", "visible": true }, "userName": { "opts": { "apsControl": "text", "cat": "Display-Texts", "desc": "User Name", "noAps": false, "noZtl": false, "tooltip": "User Name That Will Be Displayed Beside The Welcome Text.", "ztlFunction": "", "ztlType": "String" }, "template": "String", "type": "String", "value": "", "visible": true } }; spec.specInclude = {}; spec.specAbout = { "description": "Application Header", "icon": "ApplicationHeader.png", "title": "Application Header 2.0", "topics": [ { "content": "Application Header", "title": "Application Header" }, { "content": "This component is a visualization component. It requires specific space in the application canvas.", "title": "Visualization" } ] }; spec.specComp = { "databound": false, "extension": "Component", "group": "ScnCommunityBasics", "handlerType": "sapui5", "height": "38", "id": "ApplicationHeader", "package": "basics", "parentControl": "sap.ui.commons.ApplicationHeader", "require": [{ "id": "common_basics", "space": "known" }], "title": "Application Header 2.0", "tooltip": "Application Header", "width": "auto" }; return spec; });// End of closure
{ "content_hash": "51f7cf2af76a641f7bbcc546b006d183", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 121, "avg_line_length": 25.4025974025974, "alnum_prop": 0.5460122699386503, "repo_name": "org-scn-design-studio-community/lumiradesignercommunityext_src", "id": "2ff734b2c571bdc838d072789ef73ad3263a8e1b", "size": "4654", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "legacy_src/org.scn.community.basics/res/ApplicationHeader/ApplicationHeaderSpec.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "27333" }, { "name": "CSS", "bytes": "2639483" }, { "name": "HTML", "bytes": "162729" }, { "name": "Java", "bytes": "197833" }, { "name": "JavaScript", "bytes": "13143865" }, { "name": "Shell", "bytes": "443" }, { "name": "XSLT", "bytes": "552" } ], "symlink_target": "" }
<HEAD> <SCRIPT> function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function load_all_subscriptions_cb(xhr) { if (xhr.readyState == 4) { if (xhr.status == 200) { var result = JSON.parse(xhr.responseText); sort_subscriptions(result); populate_table(result); } else { alert("Error, status = " + xhr.status + ", " + xhr.responseText); } } } function load_all_subscriptions() { var xhr = new window.XMLHttpRequest; xhr.open("GET", "/v1/subscriptions", true); xhr.onreadystatechange = function() { load_all_subscriptions_cb(xhr); }; xhr.send(); } function filter_by_principal(principal, subscriptions) { var index; var output = new Array(); for (index in subscriptions) { var sub = subscriptions[index]; if (sub.principal_id == principal) { output.push(sub); } } return output; } function populate_table(subscriptions) { var principal = getParameterByName("PRINCIPAL"); if (principal != "") { subscriptions = filter_by_principal(principal, subscriptions); } var table = document.getElementById("subscriptions"); for (sub in subscriptions) { create_row(table, subscriptions[sub]); } } function get_message_type(subscription) { for (index in subscription.tags) { var tag = subscription.tags[index]; if (tag.type == "MessageType") { return tag.value } } return "unknown"; } function create_button(text) { var button = document.createElement("button"); var textNode = document.createTextNode(text); button.appendChild(textNode); return button; } function do_delete_subscription_cb(xhr) { if (xhr.readyState == 4) { window.location = "subscriptions.html"; } } function do_delete_subscription(id) { var xhr = new window.XMLHttpRequest; xhr.open("DELETE", "/v1/subscription/" + id, true); xhr.onreadystatechange = function() { do_delete_subscription_cb(xhr); }; xhr.send(); } function delete_subscription(id) { if (confirm("Delete " + id)) { do_delete_subscription(id) } } function view_subscription(id) { window.location = "/file/view_subscription.html?id=" + id; } function create_row(table, subscription) { var messageType = get_message_type(subscription); var row = table.insertRow(-1); var cell = row.insertCell(-1); var button = create_button("Delete"); button.onclick = function () { delete_subscription(subscription.id); }; cell.appendChild(button); var button = create_button("View"); button.onclick = function () { view_subscription(subscription.id); } cell.appendChild(button); cell = row.insertCell(-1); cell.innerHTML = subscription.id; cell = row.insertCell(-1); cell.innerHTML = get_message_type(subscription); cell = row.insertCell(-1); cell.innerHTML = subscription.callback_url; } function goback() { window.history.back(); } function sort_subscriptions(subscriptions) { var compare = function (a,b) { if (get_message_type(a) > get_message_type(b)) { return 1; } else if (get_message_type(a) < get_message_type(b)) { return -1; } else { return 0; } } subscriptions.sort(compare); } function create_subscription() { window.location = "create_subscription.html"; } load_all_subscriptions(); </SCRIPT> </HEAD> <BODY> <H3>Subscriptions</H3> <BUTTON onclick="goback()">Back</BUTTON> <BUTTON onclick="create_subscription()">Create</BUTTON> <P> <TABLE id="subscriptions" border="1"> <TR id="first_row"> <TH>Action</TH> <TH>ID</TH> <TH>Message Type</TH> <TH>Callback</TH> </TR> </TABLE> </P> </BODY>
{ "content_hash": "468fb26fbc2a5648b7ac99d1e4c66a23", "timestamp": "", "source": "github", "line_count": 206, "max_line_length": 94, "avg_line_length": 18.067961165048544, "alnum_prop": 0.6673831273508867, "repo_name": "PearsonEducation/subpub", "id": "b39019d2b45176899f4f53a8b10d91dde658d746", "size": "3722", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "www/subscriptions.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Erlang", "bytes": "335454" }, { "name": "Java", "bytes": "68812" }, { "name": "JavaScript", "bytes": "7763" }, { "name": "Python", "bytes": "8500" }, { "name": "Ruby", "bytes": "94" }, { "name": "Shell", "bytes": "28475" } ], "symlink_target": "" }
// Originally based on: //----------------------------------------------------------------------------- // Community detection // Based on the article "Fast unfolding of community hierarchies in large networks" // Copyright (C) 2008 V. Blondel, J.-L. Guillaume, R. Lambiotte, E. Lefebvre // // This program must not be distributed without agreement of the above mentionned authors. //----------------------------------------------------------------------------- // Author : E. Lefebvre, adapted by J.-L. Guillaume // Email : jean-loup.guillaume@lip6.fr // Location : Paris, France // Time : February 2008 //----------------------------------------------------------------------------- #ifndef SLICER_H #define SLICER_H #include <stdlib.h> #include <stdio.h> #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <map> #include <set> #include <algorithm> #include "../Base/graph.h" #define WEIGHTED 0 #define UNWEIGHTED 1 // The file format for the slice is the following: // First a list of node names. // Node Name // 1 Node A // 2 Node B // ... // // Then a list of slices: // Slice Name // 1 Slice A // 2 Slice B // // Then a list of links in the format: // From To Weight Slice // 1 2 2 1 // 3 1 1 2 // ... // Each section is started with a line containing only a '>'. The complete // file would thus look something like this: // > // 1 Node A // 2 Node B // > // 1 Slice A // 2 Slice B // > // 1 2 2 1 // 3 1 1 2 // // The same node can appear in various slices, connected by an interslice link. // This means the nodes are renumbered (that is done anyhow), taking into account // the actual slice. For example, Node 1 in Slice 1 will be renumbered to 0, and // Node 1 in Slice 2 to 1, etc... // // It is assumed that if the graph is undirected, that each link is two times in the // file. In other words, we assume it is directed. #define NO_NULL 1 #define ER_NULL 2 //currently not implemented #define CONF_NULL 3 #define POSITIVE 1 #define NEGATIVE -1 using namespace std; class Slicer { public: struct LinkInfo { LinkInfo (int n, double w) { node = n; weight = w; }; int node; double weight; }; map<int, char*> node_names; map<int, char*> slice_names; //in_links[from_node][slice][neighbour_1] //in_links[from_node][slice][neighbour_2] //etc... map< int, map< int, vector< Slicer::LinkInfo > > > in_links; map< int, map< int, vector< Slicer::LinkInfo > > > out_links; map< int, map< int, vector< Slicer::LinkInfo > > > neg_in_links; map< int, map< int, vector< Slicer::LinkInfo > > > neg_out_links; map< int, vector< Slicer::LinkInfo > > interslice_in_links; map< int, vector< Slicer::LinkInfo > > interslice_out_links; /*vector< vector< vector< Slicer::LinkInfo > > > in_links; vector< vector< vector< Slicer::LinkInfo > > > out_links; vector< vector< vector< Slicer::LinkInfo > > > neg_in_links; vector< vector< vector< Slicer::LinkInfo > > > neg_out_links; vector< vector< Slicer::LinkInfo > > interslice_in_links; vector< vector< Slicer::LinkInfo > > interslice_out_links; */ map<long,int> node_map; map<int,int> slice_map; map<int,int> slice_rmap; int nb_links; int nb_slices; int nb_nodes; int is_directed; int is_weighted; int is_single_slice; int* nb_links_per_slice; Slicer (char *filename, double weight, int is_directed, int is_weighted, int is_single_slice); Slicer (Slicer& s); ~Slicer(); int max_node_id; int max_slice_id; void readNodes(ifstream& finput); void readSlices(ifstream& finput); void readLinks(ifstream& finput); void init_slice_links(); long getNodeSliceId(int node, int slice); void setId(long nodeSliceId, int &node, int &slice); void add_interslice_links(double w); void clean(); void renumber(); Graph* get_graph(); void display(char *filename); void display_node_mapping(char *filename); void display_binary(char *filename); void display_conf(char* filename, int modelType); }; #endif // SLICER_H
{ "content_hash": "ada5147facbd3a9a90267d9f972bdc29", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 96, "avg_line_length": 25.726708074534162, "alnum_prop": 0.6141960405601159, "repo_name": "artemyk/graphy", "id": "dd50973628c63e3445e97637605c177a6c4dc8d2", "size": "5165", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "graphy/external/SurpriseMeCPM/src/Slicer/slicer.h", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "48515" } ], "symlink_target": "" }
<?php // Don't load directly if ( !defined( 'ABSPATH' ) ) { die( '-1' ); } if ( !class_exists( 'Muut_Escaped_Fragments' ) ) { /** * Muut Escaped Fragments class. * * @package Muut * @author Paul Hughes * @since 3.0.1 */ class Muut_Escaped_Fragments { /** * @static * @property Muut_Escaped_Fragments The instance of the class. */ protected static $instance; /** * @property bool Whether we need to do any further escaped fragment work. */ protected $maybeDoEscapedFragments; /** * @property string The context of the embed for which we are getting the index: * channel, forum, or commenting representing the page embed. */ protected $context; /** * The singleton method. * * @return Muut_Escaped_Fragments The instance. * @author Paul Hughes * @since 3.0.1 */ public static function instance() { if ( !is_a( self::$instance, __CLASS__ ) ) { self::$instance = new self(); } return self::$instance; } /** * The class constructor. * * @return Muut_Escaped_Fragments * @author Paul Hughes * @since 3.0.1 */ protected function __construct() { $this->addActions(); $this->addFilters(); } /** * Adds the actions used by this class. * * @return void * @author Paul Hughes * @since 3.0.1 */ protected function addActions() { add_action( 'wp_head', array( $this, 'printEscapedFragmentMetaRequire' ) ); add_action( 'wp', array( $this, 'registerCanonicalTagAction' ) ); } /** * Adds the filters used by this class. * * @return void * @author Paul Hughes * @since 3.0.1 */ protected function addFilters() { add_filter( 'muut_channel_embed_content', array( $this, 'filterChannelIndexContent' ), 10, 2 ); add_filter( 'muut_forum_page_embed_content', array( $this, 'filterForumIndexContent' ), 10, 2 ); add_filter( 'muut_comment_overrides_embed_content', array( $this, 'filterCommentsOverrideIndexContent' ), 10, 3 ); } /** * Prints the proper meta tag to make sure that googlebots run this page with the _escaped_fragment_ parameter. * * @return void * @author Paul Hughes * @since 3.0.1 */ public function printEscapedFragmentMetaRequire() { global $post; if ( isset( $post ) && is_singular() && ( Muut_Post_Utility::isMuutPost( $post->ID ) || Muut_Post_Utility::isMuutCommentingPost( $post->ID ) ) ) { echo '<meta name="fragment" content="!">'; } } /** * Checks whether we are/should be using escaped fragments on this page load. * * @return bool Whether we are using escaped fragments support on this page load. * @author Paul Hughes * @since 3.0.1 */ public function isUsingEscapedFragments() { if ( !isset( $this->maybeDoEscapedFragments ) ) { global $post; if ( isset( $_GET['_escaped_fragment_'] ) && isset ( $post ) && is_a( $post, 'WP_Post' ) && ( Muut_Post_Utility::isMuutPost( $post->ID ) || Muut_Post_Utility::isMuutCommentingPost( $post->ID ) ) ) { $this->maybeDoEscapedFragments = true; } else { $this->maybeDoEscapedFragments = false; } } return apply_filters( 'muut_is_using_escaped_fragments', $this->maybeDoEscapedFragments ); } /** * Filters the Channel embed content to render the index content rather than the JS anchor. * * @param string $content The current embed content (anchor). * @param int $page_id The page for which we are filtering the embed. * @return string The filtered content. * @author Paul Hughes * @since 3.0.1 */ public function filterChannelIndexContent( $content, $page_id ) { if ( $this->isUsingEscapedFragments() && apply_filters( 'muut_index_channels_on_channel_pages', true ) ) { $this->context = 'channel'; if ( $_GET['_escaped_fragment_'] ) { $remote_path = $_GET['_escaped_fragment_'][0] == '/' ? substr( $_GET['_escaped_fragment_'], 1 ) : $_GET['_escaped_fragment_']; } else { $remote_path = Muut_Post_Utility::getChannelRemotePathForPage( $page_id ); } $content = $this->getIndexContentForPath( $remote_path ); } return $content; } /** * Filters the Forum embed content to render the index content rather than the full Forum embed code. * * @param string $content The current embed content. * @param int $page_id The page for which we are filtering the embed. * @return string The filtered content. * @author Paul Hughes * @since 3.0.1 */ public function filterForumIndexContent( $content, $page_id ) { if ( $this->isUsingEscapedFragments() ) { $this->context = 'forum'; if ( $_GET['_escaped_fragment_'] ) { $remote_path = $_GET['_escaped_fragment_'][0] == '/' ? substr( $_GET['_escaped_fragment_'], 1 ) : $_GET['_escaped_fragment_']; } else { $remote_path = ''; } $content = $this->getIndexContentForPath( $remote_path ); } return $content; } /** * Filters the commenting embed anchor to render the index content rather than the commenting anchor. * * @param string $content The current embed content (anchor). * @param int $post_id The post for which we are filtering the embed. * @return string The filtered content. * @author Paul Hughes * @since 3.0.1 */ public function filterCommentsOverrideIndexContent( $content, $post_id, $type ) { if ( $this->isUsingEscapedFragments() ) { $post_commenting_options = Muut_Post_Utility::getPostOption( $post_id, 'commenting_settings' ); if ( isset( $post_commenting_options['type'] ) && $post_commenting_options['type'] == 'threaded' ) { $this->context = 'threaded-commenting'; } else { $this->context = 'flat-commenting'; } if ( $_GET['_escaped_fragment_'] ) { $remote_path = $_GET['_escaped_fragment_']; } else { $remote_path = Muut_Comment_Overrides::instance()->getCommentsPath( $post_id ); } $content = $this->getIndexContentForPath( $remote_path ); } return $content; } /** * Gets the body content of an index request for a given Muut path (relative path). * * @param string $path The path (relative to the registered forum name). * @param bool $force_muut_server Will bypass any S3 bucket or other setup and go directly to the muut.com index. * @return string The content. * @author Paul Hughes * @since 3.0.1 */ public function getIndexContentForPath( $path, $force_muut_server = false ) { global $wp_version; $request_args = apply_filters( 'muut_request_path_index_content_args', array( 'timeout' => 6, 'user-agent' => 'WordPress/' . $wp_version . '; Muut Plugin/' . Muut::MUUTVERSION .'; ' . home_url(), ) ); $base_uri = muut()->getForumIndexUri( $force_muut_server ); if ( $path == '' ) { $base_uri = untrailingslashit( $base_uri ); } $uri = $base_uri . $path; $request_for_index = wp_remote_get( $uri, $request_args ); $content = ''; if ( wp_remote_retrieve_response_code( $request_for_index ) == 200 ) { $response_content = wp_remote_retrieve_body( $request_for_index ); if ( $path == '' ) { $content = $this->getForumIndexContent( $response_content ); } else { $colon_pos = strrpos( $path, ':' ); $last_slash_pos = strrpos( $path, '/' ); if ( $colon_pos && ( $colon_pos > $last_slash_pos || !$last_slash_pos ) ) { $content = $this->getFlatIndexContent( $response_content ); } else { $content = $this->getThreadedIndexContent( $response_content, $path ); } } } return $content; } /** * Grabs the proper markup from the return body for Forum root that should be rendered. * * @param string $content The markup we will be filtering. * @return string The content we actually want to display. * @author Paul Hughes * @since 3.0.1 */ protected function getForumIndexContent( $content ) { // Make sure to only get the content we want. $new_content = $content; $new_content = strstr( $new_content, '<ul id="forums">' ); $new_content = substr( $new_content, 0, strpos( $new_content, '</body>' ) ); // Replace links within the threaded response with new hasbang urls (to lead to the "share" location. $new_content = str_replace( '<a href="/i/' . muut()->getForumName() . '/', '<a href="' . get_permalink() . '#!/', $new_content ); if ( $new_content ) { $content = $new_content; } return $content; } /** * Grabs the proper markup from the return body (just the muuts) that should be rendered. * * @param string $content The markup we will be filtering. * @return string The content we actually want to display. * @author Paul Hughes * @since 3.0.1 */ protected function getFlatIndexContent( $content ) { // Make sure to only get the content we want. $new_content = $content; if ( $this->context == 'channel' || $this->context == 'threaded-commenting' || $this->context == 'forum' ) { $new_content = strstr( $new_content, '<div id="title">' ); } else { $new_content = strstr( $new_content, '<article class="seed">' ); } $new_content = substr( $new_content, 0, strpos( $new_content, '<body>' ) ); if ( $new_content ) { $content = $new_content; } return $content; } /** * Grabs the proper markup from the return body of the Muut indexes for Non-flat channels. * * @param string $content The markup we will be filtering. * @return string The content we actually want to display. * @author Paul Hughes * @since 3.0.1 */ protected function getThreadedIndexContent( $content, $remote_path = '' ) { // Make sure to only get the content we want. $new_content = $content; if ( $this->context == 'channel' || $this->context == 'flat-commenting' ) { $new_content = strstr( $new_content, '<ul id="moots">' ); } else { $new_content = strstr( $new_content, '<div id="title">' ); } $new_content = substr( $new_content, 0, strpos( $new_content, '</body>' ) ); if ( $remote_path != '' ) { $slash_strpos = strrpos( $remote_path, '/' ); if ( $slash_strpos ) { $remote_path = substr( $remote_path, 0, $slash_strpos + 1 ); } else { $remote_path = ''; } } // Replace links within the threaded response with new hasbang urls (to lead to the "share" location. $new_content = str_replace( '<a href="./', '<a href="' . get_permalink() . '#!/' . $remote_path, $new_content ); if ( $new_content ) { $content = $new_content; } return $content; } public function registerCanonicalTagAction() { if ( isset( $_REQUEST['_escaped_fragment_'] ) && is_singular() && ( muut_is_forum_page() || muut_post_uses_muut() || muut_is_channel_page() ) ) { if ( function_exists( 'rel_canonical' ) ) { remove_action( 'wp_head', 'rel_canonical' ); } add_action( 'wp_head', array( $this, 'canonicalTag' ) ); } } public function canonicalTag() { if ( isset( $_REQUEST['_escaped_fragment_'] ) ) { $link = get_permalink() . "#!" . $_REQUEST['_escaped_fragment_']; echo "<link rel=\"canonical\" href=\"" . $link . "\" />\n"; } } } }
{ "content_hash": "0c16ca6c15884082193a11f63a99db57", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 202, "avg_line_length": 32.18208092485549, "alnum_prop": 0.6177817691962281, "repo_name": "ishan576/wordpress-plugin", "id": "adab27cc0ebb8b84583191d03dfb1a96af3b4ce0", "size": "11297", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/escaped-fragments.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6884" }, { "name": "JavaScript", "bytes": "48527" }, { "name": "PHP", "bytes": "301745" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Security.Authentication; namespace MQTTnet.Client { public class MqttClientTlsOptions { public bool UseTls { get; set; } public bool IgnoreCertificateRevocationErrors { get; set; } public bool IgnoreCertificateChainErrors { get; set; } public bool AllowUntrustedCertificates { get; set; } public List<byte[]> Certificates { get; set; } public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12; public Func<X509Certificate, X509Chain, SslPolicyErrors, IMqttClientOptions, bool> CertificateValidationCallback { get; set; } } }
{ "content_hash": "c8a85609fbe7be1bd21fefe8c749454c", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 134, "avg_line_length": 30.08, "alnum_prop": 0.7207446808510638, "repo_name": "JTrotta/MQTTnet", "id": "73d65cbc0dd806071b09e72721b3530e0eb8ee35", "size": "754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/MQTTnet/Client/MqttClientTlsOptions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1329" }, { "name": "C#", "bytes": "503192" }, { "name": "HTML", "bytes": "644" }, { "name": "PowerShell", "bytes": "6452" }, { "name": "TypeScript", "bytes": "1480" } ], "symlink_target": "" }
/* This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * <p/> * This library 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 * Lesser General Public License for more details. */ package org.rzo.yajsw.tray; import org.rzo.yajsw.wrapper.AbstractWrappedProcessMBean; // TODO: Auto-generated Javadoc /** * The Interface WrapperTrayIcon. */ public interface WrapperTrayIcon { /** * Checks if is inits the. * * @return true, if is inits the */ public boolean isInit(); /** * Info. * * @param caption * the caption * @param message * the message */ public void info(String caption, String message); /** * Error. * * @param caption * the caption * @param message * the message */ public void error(String caption, String message); /** * Warning. * * @param caption * the caption * @param message * the message */ public void warning(String caption, String message); /** * Message. * * @param caption * the caption * @param message * the message */ public void message(String caption, String message); /** * Sets the process. * * @param proxy * the new process */ public void setProcess(AbstractWrappedProcessMBean proxy); /** * Close console. */ public void closeConsole(); /** * Show state. * * @param state * the state */ public void showState(int state); /** * Checks if is stop. * * @return true, if is stop */ public boolean isStop(); }
{ "content_hash": "7218fe7a477fd050d32671a08671b34c", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 69, "avg_line_length": 20.896907216494846, "alnum_prop": 0.5939812530833745, "repo_name": "ColFusion/PentahoKettle", "id": "5e07405f0f20706030ec1b1bbb19436d39ef9494", "size": "2027", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "CarteService/default/src/main/java/org/rzo/yajsw/tray/WrapperTrayIcon.java", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "21071" }, { "name": "Batchfile", "bytes": "21366" }, { "name": "C", "bytes": "7006" }, { "name": "CSS", "bytes": "1952277" }, { "name": "Groff", "bytes": "684" }, { "name": "Groovy", "bytes": "33843" }, { "name": "HTML", "bytes": "197173221" }, { "name": "Java", "bytes": "3685348" }, { "name": "JavaScript", "bytes": "31972698" }, { "name": "PHP", "bytes": "224688" }, { "name": "Perl", "bytes": "6881" }, { "name": "PigLatin", "bytes": "7496" }, { "name": "Python", "bytes": "109487" }, { "name": "Shell", "bytes": "43881" }, { "name": "Smarty", "bytes": "2952" }, { "name": "XQuery", "bytes": "798" }, { "name": "XSLT", "bytes": "562453" } ], "symlink_target": "" }
/*numPass=7, numTotal=7 Verdict:ACCEPTED, Visibility:1, Input:"-12", ExpOutput:"-12.0000 is negative", Output:"-12.0000 is negative " Verdict:ACCEPTED, Visibility:1, Input:"0", ExpOutput:"input is zero", Output:"input is zero" Verdict:ACCEPTED, Visibility:1, Input:"1", ExpOutput:"1.0000 is positive", Output:"1.0000 is positive " Verdict:ACCEPTED, Visibility:1, Input:"0.0000001", ExpOutput:"0.0000 is positive", Output:"0.0000 is positive " Verdict:ACCEPTED, Visibility:0, Input:"-0.0000001", ExpOutput:"-0.0000 is negative", Output:"-0.0000 is negative " Verdict:ACCEPTED, Visibility:0, Input:"101", ExpOutput:"101.0000 is positive", Output:"101.0000 is positive " Verdict:ACCEPTED, Visibility:0, Input:"0000000", ExpOutput:"input is zero", Output:"input is zero" */ #include<stdio.h> int main() { float a; scanf("%f",&a); if(a<0.0) printf("%.4f is negative\n",a); if(a==0.0) printf("input is zero"); if(a>0.0) printf("%.4f is positive\n",a); return 0; }
{ "content_hash": "d43bfe5d8d01ef4c2e5267fb0486cc60", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 112, "avg_line_length": 34.857142857142854, "alnum_prop": 0.6977459016393442, "repo_name": "jyi/ITSP", "id": "a8b6df399b6756d2b16602472cf1023605f8cbec", "size": "976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dataset/Lab-3/2812/270357_correct.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3047" }, { "name": "C", "bytes": "2699750" }, { "name": "C++", "bytes": "538402" }, { "name": "Java", "bytes": "127851" }, { "name": "M4", "bytes": "1432" }, { "name": "Makefile", "bytes": "18622" }, { "name": "OCaml", "bytes": "819636" }, { "name": "Perl", "bytes": "1818" }, { "name": "Python", "bytes": "527926" }, { "name": "Roff", "bytes": "32" }, { "name": "Ruby", "bytes": "75" }, { "name": "Shell", "bytes": "1426606" } ], "symlink_target": "" }
package org.apache.ambari.server.serveraction.upgrades; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.ambari.server.actionmanager.ExecutionCommandWrapper; import org.apache.ambari.server.actionmanager.HostRoleCommand; import org.apache.ambari.server.agent.CommandReport; import org.apache.ambari.server.agent.ExecutionCommand; import org.apache.ambari.server.state.Cluster; import org.apache.ambari.server.state.Clusters; import org.apache.ambari.server.state.Config; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import com.google.inject.Injector; import junit.framework.Assert; /** * Tests HiveEnvClasspathAction logic */ public class HiveEnvClasspathActionTest { private Injector m_injector; private Clusters m_clusters; private Field m_clusterField; @Before public void setup() throws Exception { m_injector = EasyMock.createMock(Injector.class); m_clusters = EasyMock.createMock(Clusters.class); Cluster cluster = EasyMock.createMock(Cluster.class); Map<String, String> mockProperties = new HashMap<String, String>() {{ put("content", " export HADOOP_USER_CLASSPATH_FIRST=true #this prevents old metrics libs from mapreduce lib from bringing in old jar deps overriding HIVE_LIB\n" + " if [ \"$SERVICE\" = \"cli\" ]; then\n" + " if [ -z \"$DEBUG\" ]; then\n" + " export HADOOP_OPTS=\"$HADOOP_OPTS -XX:NewRatio=12 -XX:MaxHeapFreeRatio=40 -XX:MinHeapFreeRatio=15 -XX:+UseNUMA -XX:+UseParallelGC -XX:-UseGCOverheadLimit\"\n" + " else\n" + " export HADOOP_OPTS=\"$HADOOP_OPTS -XX:NewRatio=12 -XX:MaxHeapFreeRatio=40 -XX:MinHeapFreeRatio=15 -XX:-UseGCOverheadLimit\"\n" + " fi\n" + " fi\n" + "\n" + " # The heap size of the jvm stared by hive shell script can be controlled via:\n" + "\n" + " if [ \"$SERVICE\" = \"metastore\" ]; then\n" + " export HADOOP_HEAPSIZE={{hive_metastore_heapsize}} # Setting for HiveMetastore\n" + " else\n" + " export HADOOP_HEAPSIZE={{hive_heapsize}} # Setting for HiveServer2 and Client\n" + " fi\n" + "\n" + " export HADOOP_CLIENT_OPTS=\"$HADOOP_CLIENT_OPTS -Xmx${HADOOP_HEAPSIZE}m\"\n" + "\n" + " # Larger heap size may be required when running queries over large number of files or partitions.\n" + " # By default hive shell scripts use a heap size of 256 (MB). Larger heap size would also be\n" + " # appropriate for hive server (hwi etc).\n" + "\n" + "\n" + " # Set HADOOP_HOME to point to a specific hadoop install directory\n" + " HADOOP_HOME=${HADOOP_HOME:-{{hadoop_home}}}\n" + "\n" + " # Hive Configuration Directory can be controlled by:\n" + " export HIVE_CONF_DIR=test\n" + "\n" + " # Folder containing extra libraries required for hive compilation/execution can be controlled by:\n" + " if [ \"${HIVE_AUX_JARS_PATH}\" != \"\" ]; then\n" + " if [ -f \"${HIVE_AUX_JARS_PATH}\" ]; then\n" + " export HIVE_AUX_JARS_PATH=${HIVE_AUX_JARS_PATH}\n" + " elif [ -d \"/usr/hdp/current/hive-webhcat/share/hcatalog\" ]; then\n" + " export HIVE_AUX_JARS_PATH=/usr/hdp/current/hive-webhcat/share/hcatalog/hive-hcatalog-core.jar\n" + " fi\n" + " elif [ -d \"/usr/hdp/current/hive-webhcat/share/hcatalog\" ]; then\n" + " export HIVE_AUX_JARS_PATH=/usr/hdp/current/hive-webhcat/share/hcatalog/hive-hcatalog-core.jar\n" + " fi\n" + "\n" + " export METASTORE_PORT={{hive_metastore_port}}\n" + "\n" + " {% if sqla_db_used or lib_dir_available %}\n" + " export LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:{{jdbc_libs_dir}}\"\n" + " export JAVA_LIBRARY_PATH=\"$JAVA_LIBRARY_PATH:{{jdbc_libs_dir}}\"\n" + " {% endif %}"); }}; Config hiveEnv = EasyMock.createNiceMock(Config.class); expect(hiveEnv.getType()).andReturn("hive-env").anyTimes(); expect(hiveEnv.getProperties()).andReturn(mockProperties).anyTimes(); expect(cluster.getDesiredConfigByType("hive-env")).andReturn(hiveEnv).atLeastOnce(); expect(m_clusters.getCluster((String) anyObject())).andReturn(cluster).anyTimes(); expect(m_injector.getInstance(Clusters.class)).andReturn(m_clusters).atLeastOnce(); replay(m_injector, m_clusters, cluster, hiveEnv); m_clusterField = HiveEnvClasspathAction.class.getDeclaredField("clusters"); m_clusterField.setAccessible(true); } @Test public void testAction() throws Exception { Pattern regex = Pattern.compile("^\\s*export\\s(?<property>HIVE_HOME|HIVE_CONF_DIR)\\s*=\\s*(?<value>.*)$", Pattern.MULTILINE); Map<String, String> commandParams = new HashMap<String, String>(); commandParams.put("clusterName", "c1"); ExecutionCommand executionCommand = new ExecutionCommand(); executionCommand.setCommandParams(commandParams); executionCommand.setClusterName("c1"); HostRoleCommand hrc = EasyMock.createMock(HostRoleCommand.class); expect(hrc.getRequestId()).andReturn(1L).anyTimes(); expect(hrc.getStageId()).andReturn(2L).anyTimes(); expect(hrc.getExecutionCommandWrapper()).andReturn(new ExecutionCommandWrapper(executionCommand)).anyTimes(); replay(hrc); HiveEnvClasspathAction action = new HiveEnvClasspathAction(); m_clusterField.set(action, m_clusters); action.setExecutionCommand(executionCommand); action.setHostRoleCommand(hrc); CommandReport report = action.execute(null); assertNotNull(report); Cluster c = m_clusters.getCluster("c1"); Config config = c.getDesiredConfigByType("hive-env"); Map<String, String> map = config.getProperties(); Assert.assertTrue(map.containsKey("content")); String content = map.get("content"); Matcher m = regex.matcher(content); int matches_found = 0; while (m.find()){ if (m.group("property").equals("HIVE_HOME")){ matches_found++; assertEquals("${HIVE_HOME:-{{hive_home_dir}}}", m.group("value")); } else if (m.group("property").equals("HIVE_CONF_DIR")) { matches_found++; assertEquals("test", m.group("value")); } } Assert.assertEquals(2, matches_found); } }
{ "content_hash": "b6ed67316d45823578650469c32a8224", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 175, "avg_line_length": 42.04938271604938, "alnum_prop": 0.6485613623018203, "repo_name": "alexryndin/ambari", "id": "8926203e1524fd47204d8cfe9e586a92d7179526", "size": "7618", "binary": false, "copies": "2", "ref": "refs/heads/branch-adh-1.5", "path": "ambari-server/src/test/java/org/apache/ambari/server/serveraction/upgrades/HiveEnvClasspathActionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "44884" }, { "name": "C", "bytes": "331204" }, { "name": "C#", "bytes": "215907" }, { "name": "C++", "bytes": "257" }, { "name": "CSS", "bytes": "786184" }, { "name": "CoffeeScript", "bytes": "8465" }, { "name": "FreeMarker", "bytes": "2654" }, { "name": "Groovy", "bytes": "89958" }, { "name": "HTML", "bytes": "2514774" }, { "name": "Java", "bytes": "29565801" }, { "name": "JavaScript", "bytes": "19033151" }, { "name": "Makefile", "bytes": "11111" }, { "name": "PHP", "bytes": "149648" }, { "name": "PLpgSQL", "bytes": "316489" }, { "name": "PowerShell", "bytes": "2090340" }, { "name": "Python", "bytes": "17215686" }, { "name": "R", "bytes": "3943" }, { "name": "Roff", "bytes": "13935" }, { "name": "Ruby", "bytes": "33764" }, { "name": "SQLPL", "bytes": "4277" }, { "name": "Shell", "bytes": "886011" }, { "name": "Vim script", "bytes": "5813" }, { "name": "sed", "bytes": "2303" } ], "symlink_target": "" }
WKInteraceMovie Example for my blog https://github.com/NilStack/WKInterfaceMovieExample.git
{ "content_hash": "cadbb3038e5bdd49f2e0d7362d67c9bf", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 91, "avg_line_length": 91, "alnum_prop": 0.8681318681318682, "repo_name": "NilStack/WKInterfaceMovieExample", "id": "9cc0f3c24cad3dfbd2ef52edb8fbb418267cd780", "size": "91", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "6664" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: yosefderay * Date: 4/29/14 * Time: 9:25 PM */ namespace Yjv\TypeFactory\Tests\Fixtures; use Yjv\TypeFactory\AbstractNamedBuilder; class MockNamedBuilder extends AbstractNamedBuilder { /** * @return object */ public function build() { } }
{ "content_hash": "7596a4ed8f494505fd6cd997e482ca82", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 51, "avg_line_length": 14.227272727272727, "alnum_prop": 0.6517571884984026, "repo_name": "yjv/TypeFactory", "id": "6b0a861d54dd320a67635573f2acfae4fb42d784", "size": "313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/Fixtures/MockNamedBuilder.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "79278" } ], "symlink_target": "" }