text
stringlengths
2
1.04M
meta
dict
@interface SASound : NSObject { SystemSoundID soundID; BOOL enabled; } - (id) initWithSound:(NSString *)name; - (void) play; @end
{ "content_hash": "484a37204699ed372bc0be60664260f3", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 38, "avg_line_length": 15.333333333333334, "alnum_prop": 0.6739130434782609, "repo_name": "ktakayama/smsalert", "id": "517aad16dcd69ef6e2786b3193600413d55c7661", "size": "370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classes/libs/SASound.h", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
@extends('dashboard::layouts.tab_view') @section('title', $student->name) @section('tools') @can('edit_user_account_info') <a href="{{ route('student.account.edit', $student->id) }}" class="btn btn-primary"> <i class="fa fa-fw fa-edit"></i> {{ trans('base::common.edit') }} </a> @endcan @endsection @section('tabs') @include('students::partials.view_student_tabs') @endsection @section('tab') <div class="col-sm-6"> <dl class="row"> <dt class="col-sm-4">{{ trans('students::student.email') }}</dt> <dd class="col-sm-8">{{ $student->user->email }}</dd> </dl> </div> @endsection
{ "content_hash": "022fa9a1236ea5e1287643289a046297", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 86, "avg_line_length": 20.166666666666668, "alnum_prop": 0.6214876033057851, "repo_name": "codebreez/collejo-app", "id": "cfb1978150463f0a6461a7a644485e015d049360", "size": "605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "App/Modules/Students/resources/views/view_student_account.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "324011" }, { "name": "HTML", "bytes": "160893" }, { "name": "JavaScript", "bytes": "3241570" }, { "name": "PHP", "bytes": "267901" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>Play! 2.x Provider for Play! 2.5.x 1.0.0-beta5 Reference Package com.google.code.play2.provider.play25</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="style" /> </head> <body> <h3> <a href="package-summary.html" target="classFrame">com.google.code.play2.provider.play25</a> </h3> <h3>Classes</h3> <ul> <li> <a href="Play25LessCompiler.html" target="classFrame">CompileResult</a> </li> <li> <a href="Play25LessCompiler.html" target="classFrame">InternalCompileResult</a> </li> <li> <a href="Play25CoffeescriptCompiler.html" target="classFrame">Play25CoffeescriptCompiler</a> </li> <li> <a href="Play25EbeanEnhancer.html" target="classFrame">Play25EbeanEnhancer</a> </li> <li> <a href="Play25JavaEnhancer.html" target="classFrame">Play25JavaEnhancer</a> </li> <li> <a href="Play25JavascriptCompiler.html" target="classFrame">Play25JavascriptCompiler</a> </li> <li> <a href="Play25LessCompiler.html" target="classFrame">Play25LessCompiler</a> </li> <li> <a href="Play25Provider.html" target="classFrame">Play25Provider</a> </li> <li> <a href="Play25RoutesCompiler.html" target="classFrame">Play25RoutesCompiler</a> </li> <li> <a href="Play25Runner.html" target="classFrame">Play25Runner</a> </li> <li> <a href="Play25TemplateCompiler.html" target="classFrame">Play25TemplateCompiler</a> </li> </ul> </body> </html>
{ "content_hash": "51c9f62f8e8a3f5cbac4c0327c2f605c", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 121, "avg_line_length": 40.77358490566038, "alnum_prop": 0.5363257751041185, "repo_name": "play2-maven-plugin/play2-maven-plugin.github.io", "id": "40c607b8513cee86be315518f020cdbfec92cd50", "size": "2162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play2-maven-plugin/1.0.0-beta5/play2-providers/play2-provider-play25/xref/com/google/code/play2/provider/play25/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2793124" }, { "name": "HTML", "bytes": "178221432" }, { "name": "JavaScript", "bytes": "120742" } ], "symlink_target": "" }
There is one main concept which forms the foundation of the FlexCore library: **connectable**. Every type, which fulfils this concept can be connected. Every edge in the dataflow graph connects to connectable objects. The concept **connectable** extends two concepts from the standard library: - **callable**, described at http://en.cppreference.com/w/cpp/concept/Callable - **copyable**, described at: http://en.cppreference.com/w/cpp/types/is_copy_constructible. Examples for connectable types are: Lambdas, Function Pointers, std::function, functors etc. There is one exception to the **copyable** requirement: [lvalues][lvalue]. Callable objects which are connected as named variables need not be copyable. They will be wrapped in a `std::ref` object to establish the connection. As a consequence, lvalue connectables are **not** allowed to change address after the connection is established. ### Connections Two connectables are connected by calling the free template function **connect**, which takes two connectables as parameters. This returns an object of type **connection**, which contains both arguments of connect. A connection object is itself connectable. ~~~{.cpp} template <class L, class R> //L and R need to fulfil connectable connection<L, R> connect(L lhs, R rhs); connectable_a >> connectable_b; ~~~ Users should not call `connect` directly but instead use the overloaded `operator>>` which performs type validation and then calls `connect`. ~~~{.cpp} using fc::operator>>; connectable_a >> connectable_b; ~~~ The following UML class diagram shows the interaction between these concepts: ![CoreClassDiagram_v3](CoreClassDiagram_v3.png) By calling connect on connectables and connections repeatedly we can build **chains** of connections. ### Restrictions: Active- And Passive-Connectable Two additional concepts complete the design. These are **active_connectable** and **passive_connectable**. active_connectable and passive_connectable serve as end points of chains of connections. Types which are active_connectable do not need to be callable unlike passive_connectable and connectable. connectable types are both active_connectable and passive_connectable. Any type which is neither connectable nor passive_connectable or active_connectable is called **not_connectable**. This is not a separate concept, as it is defined purely as the negation of the three other. Both active and passive connectable types can appear on the left and right hand side of a connection. Since they form the end points of a chain of connections, active_connectable and passive_connectable restrict how connect can be called on them: ~~~{.cpp} // for push-logic, i.e. sending events (source is active (pusher), sink is passive) connect(active_connectable, connectable); // returns an active_connectable. connect(connectable, passive_connectable); // returns a passive_connectable. connect(active_connectable, passive_connectable); // connection is complete, returns a non_connectable connection. // for pull-logic, i.e. receiving states (source is passive, sink is active (puller)) connect(connectable, active_connectable); // returns an active_connectable. connect(passive_connectable, connectable); // returns a passive_connectable. connect(passive_connectable, active_connectable); // connection is complete, returns a non_connectable connection. connect(connectable, connectable); // returns a connectable as defined above. connect(active_connectable, active_connectable); // illegal. connect(passive_connectable, passive_connectable); // illegal. ~~~ ![CoreClassDiagram_v4](CoreClassDiagram_v4.png) [lvalue]: http://en.cppreference.com/w/cpp/language/value_category
{ "content_hash": "b8e4216c41dab54afbbb6a0a534b034f", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 338, "avg_line_length": 49.68421052631579, "alnum_prop": 0.767478813559322, "repo_name": "CasparKielwein/flexcore", "id": "e67ca0b2ddb5aaac78116ad2cdda3e1c0bc023ee", "size": "3828", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/CoreConcept.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "352275" }, { "name": "CMake", "bytes": "94856" } ], "symlink_target": "" }
MyNextProject::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to Rails.root.join("public/assets") # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 end
{ "content_hash": "ceef7fdd0a21faef49e02de7e677ad14", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 104, "avg_line_length": 36.71641791044776, "alnum_prop": 0.7451219512195122, "repo_name": "dmitriy-kiriyenko/MyNextProject", "id": "ec6d2612eb6cf3a1b55f6f41e6804d281c4fd6e5", "size": "2460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/environments/production.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "14970" } ], "symlink_target": "" }
#ifndef __LSHKIT_MPLSH_MODEL__ #define __LSHKIT_MPLSH_MODEL__ #include <fstream> #include <boost/math/distributions/gamma.hpp> #include <boost/math/distributions/normal.hpp> #include "matrix.h" /** * \file mplsh-model.h * \brief Model of Multi-probe LSH. * * The modeling code is not well documented because I find it hard to do so. * The code is essentially a translation of our CIKM'08 paper. If you do wish * to look into the code, beware that when the distance is used, sometime I * mean L2 distance (when Gaussian distribution of the distance between * the random projection of two points is considered) * and sometime I mean L2sqr distance because L2sqr distance between two points * in the database follows Gamma distribution. */ namespace lshkit { typedef boost::math::normal_distribution<double> GaussianDouble; typedef boost::math::gamma_distribution<double> GammaDouble; /// Maximum likelihood estimation of gamma distribution. /** * @param M sample mean. * @param G geometric mean of sample. */ GammaDouble GammaDoubleMLE (double M, double G); /// Data parameter. /** * This class represents the parameters extracted from the dataset. */ // We use l2sqr here. class DataParam { double M, G; double a_M, b_M, c_M; double a_G, b_G, c_G; /* DataParam () {} DataParam (const DataParam &dp) : M(dp.M), G(dp.G), a_M(dp.a_M), b_M(dp.b_M), c_M(dp.c_M), a_G(dp.a_G), b_G(dp.b_G), c_G(dp.c_G) {} */ public: /// Constructor. /** * For now, parameters can only be loaded from a file. */ DataParam (const std::string &path) { std::ifstream is(path.c_str()); is >> M >> G >> a_M >> b_M >> c_M >> a_G >> b_G >> c_G; } /// Estimate the global distance distribution. GammaDouble globalDist () const { return GammaDoubleMLE(M, G); } /// Estimate the distance distribution of the K-th NN. /** * @param N size of the (extraplolated) dataset. */ GammaDouble topkDist (unsigned N, unsigned K) const { double m, g; m = std::exp(a_M) * std::pow(double(N), b_M) * std::pow(double(K), c_M); g = std::exp(a_G) * std::pow(double(N), b_G) * std::pow(double(K), c_G); return GammaDoubleMLE(m,g); } void scale (double s) { M /= s; G /= s; a_M -= std::log(s); a_G -= std::log(s); } double scale () { double s = M; scale(s); return s; } }; /// Multi-probe LSH parameters. // we use l2 here. class MultiProbeLshModel { unsigned L_; double W_; unsigned M_, T_; public: MultiProbeLshModel(unsigned L, double W, unsigned M, unsigned T) : L_(L), W_(W), M_(M), T_(T) {} double recall (double l2) const; void setL (unsigned L) { L_ = L; } void setW (double W) { W_ = W; } void setT (unsigned T) { T_ = T; } void setM (unsigned M) { M_ = M; } unsigned getT () const {return T_; } }; // we use l2sqr here. class MultiProbeLshDataModel: public MultiProbeLshModel { // temporary, not thread safe GammaDouble globalDist_; std::vector<GammaDouble> topkDists_; public: MultiProbeLshDataModel(const DataParam &param, unsigned N, unsigned K) : MultiProbeLshModel(0,0,0,0), globalDist_(1.0), topkDists_(K, globalDist_) { globalDist_ = param.globalDist(); for (unsigned k = 0; k < K; k++) { topkDists_[k] = param.topkDist(N, k + 1); } } double avgRecall () const; double cost () const; }; // we use l2 here. class MultiProbeLshRecallTable { unsigned step_; double min_, max_; double lmin_, lmax_; Matrix<float> table_; public: void load (std::istream &is) { is.read((char *)&min_, sizeof(min_)); is.read((char *)&max_, sizeof(max_)); table_.load(is); step_ = table_.getDim(); lmin_ = log(min_); lmax_ = log(max_); } void save (std::ostream &os) { os.write((const char *)&min_, sizeof(min_)); os.write((const char *)&max_, sizeof(max_)); table_.save(os); } void reset (MultiProbeLshModel model, unsigned d_step, double d_min, double d_max) { if (d_min <= 0 || d_max <= 0) { throw std::logic_error("Make sure a distance is positive."); } step_ = d_step; min_ = d_min; max_ = d_max; lmin_ = log(d_min); lmax_ = log(d_max); table_.reset(d_step, model.getT()); unsigned T = model.getT(); double delta = (lmax_ - lmin_) / step_; for (unsigned t = 0; t < T; ++t) { model.setT(t+1); for (unsigned d = 0; d < step_; ++d) { table_[t][d] = model.recall(exp(lmin_ + delta * d)); } } } float lookup (float dist, int T) const { unsigned d; if (dist < min_) return 1.0; if (!(dist < max_)) return 0.0; d = std::floor((log(dist) - lmin_) * step_ / (lmax_ - lmin_) + 0.5); return table_[T-1][d]; } }; } #endif
{ "content_hash": "499ef67aa208ebe3432a0c28de63cc29", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 86, "avg_line_length": 24.861244019138756, "alnum_prop": 0.5540800615858352, "repo_name": "izenecloud/idmlib", "id": "d0f25eac0cc00f2e539d06829e3efb6ce4966e80", "size": "5951", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/idmlib/lshkit/mplsh-model.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "328998" }, { "name": "C++", "bytes": "3676439" }, { "name": "FORTRAN", "bytes": "39497" }, { "name": "Objective-C", "bytes": "2157" }, { "name": "Perl", "bytes": "25316" }, { "name": "Ruby", "bytes": "1255" }, { "name": "Shell", "bytes": "3566" } ], "symlink_target": "" }
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'bin/**/*' ] } }); grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.registerTask('default', [ 'jshint' ]); };
{ "content_hash": "5e58a509c17da07bdd9d976c302adfc6", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 46, "avg_line_length": 18.764705882352942, "alnum_prop": 0.6112852664576802, "repo_name": "lotaris/api-copilot-cli", "id": "8977ae5aa678d3b84953f35f0459ed0504f63e3f", "size": "319", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Gruntfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "635" } ], "symlink_target": "" }
package mesosphere.marathon package core.task.termination /** * Enumeration for reasons why a task has been killed. * * This is not sealed on purpose as there might be different reasons for * components build on top of the core. */ trait KillReason object KillReason { /** The task is killed because the instance count is scaled down */ case object OverCapacity extends KillReason /** Same as [[mesosphere.marathon.core.task.termination.KillReason.OverCapacity]] but during deployment */ case object DeploymentScaling extends KillReason /** The task is killed because the app has is being deleted */ case object DeletingApp extends KillReason /** The task is killed because of an incoming http request */ case object KillingTasksViaApi extends KillReason /** The task is killed because a new version is being deployed */ case object Upgrading extends KillReason /** The task is killed because the app no longer exists */ case object Orphaned extends KillReason /** The task is killed because it didn't turn running within a given time frame */ case object Overdue extends KillReason /** The task is killed because it is unknown */ case object Unknown extends KillReason /** The task is killed because it exceeded the maximum number of consecutive failures */ case object FailedHealthChecks extends KillReason }
{ "content_hash": "42ed4e3e83b45f64170e957e8c763146", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 108, "avg_line_length": 35.05128205128205, "alnum_prop": 0.7585954645208486, "repo_name": "Caerostris/marathon", "id": "462b514ac8fd12585eb244028779dc0ddd50d834", "size": "1367", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/scala/mesosphere/marathon/core/task/termination/KillReason.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "33759" }, { "name": "Groovy", "bytes": "8188" }, { "name": "HTML", "bytes": "502" }, { "name": "Java", "bytes": "778" }, { "name": "Makefile", "bytes": "641" }, { "name": "Protocol Buffer", "bytes": "108475" }, { "name": "Python", "bytes": "219881" }, { "name": "Ruby", "bytes": "652" }, { "name": "Scala", "bytes": "3951877" }, { "name": "Shell", "bytes": "32981" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using de.fhb.oll.mediacategorizer.settings; using Microsoft.Win32; namespace de.fhb.oll.mediacategorizer.tools { class DistilleryTool : ToolBase { private readonly Setup setup; private readonly string javaPath; private const float ANALYSIS_PART = 0.33f; private readonly List<string> workingTasks = new List<string>(); private int totalAnalysisSteps; private int currentAnalysisStep; private readonly Dictionary<string, Tuple<int, int>> taskStates = new Dictionary<string, Tuple<int, int>>(); private static readonly Regex TASK_GROUP_REGEX = new Regex(@"TASKGROUP\s+(.+)\s+\[(\d+)\]"); private static readonly Regex TASK_END_REGEX = new Regex(@"TASK_END\s+(.+)$"); private static readonly Regex TASK_GROUP_END_REGEX = new Regex(@"TASKGROUP_END\s+(.+)$"); private static readonly Regex PIPELINE_REGEX = new Regex(@"PIPELINE\s+(.+)\s+\[(\d+)\]"); private static readonly Regex PIPELINE_STEP_REGEX = new Regex(@"PIPELINE_STEP\s+(.+)\s+(\d+)"); public DistilleryTool(ILogWriter logWriter, Setup setup) : base(logWriter, setup.Distillery) { Name = "distillery"; this.setup = setup; javaPath = FindJava(); } public bool RunDistillery(string jobFile, Action<string> workItemHandler, Action<string> messageHandler, Action<float> progressHandler, Action<string> errorHandler) { var arguments = string.Format("-jar \"{0}\" \"{1}\"", GetAbsoluteToolPath(), jobFile); var pi = new ProcessStartInfo(javaPath, arguments); pi.CreateNoWindow = true; pi.RedirectStandardOutput = true; pi.RedirectStandardError = true; pi.UseShellExecute = false; LogProcessStart(pi); var p = Process.Start(pi); RegisterProcess(p); p.PriorityClass = ProcessPriorityClass.BelowNormal; Task.Run(() => ProcessOutput(p.StandardOutput, workItemHandler, messageHandler, progressHandler, errorHandler)); Task.Run(() => ProcessError(p.StandardError, workItemHandler, messageHandler, progressHandler, errorHandler)); p.WaitForExit(); return p.ExitCode == 0; } private void ProcessOutput(TextReader r, Action<string> workItemHandler, Action<string> messageHandler, Action<float> progressHandler, Action<string> errorHandler) { string l; while ((l = r.ReadLine()) != null) { Log(l); if (!l.StartsWith("#")) { Debug.WriteLine("distillery out: " + l); } if (l.StartsWith("# BEGIN ") && l.EndsWith("...")) { ProcessBeginMessage(l, messageHandler); } else if (l.StartsWith("# END ")) { ProcessEndMessage(l, messageHandler); } else if (l.StartsWith("# TASKGROUP ")) { ProcessTaskGroupMessage(l, progressHandler); } else if (l.StartsWith("# TASK_END ")) { ProcessTaskEndMessage(l, progressHandler); } else if (l.StartsWith("# TASKGROUP_END ")) { ProcessTaskGroupEndMessage(l, progressHandler); } else if (l.StartsWith("# PIPELINE ")) { ProcessPipelineAnalysisMessage(l, progressHandler); } else if (l.StartsWith("# PIPELINE_STEP ")) { ProcessPipelineStepMessage(l, progressHandler); } else { messageHandler(l.Substring(2)); } } } private void ProcessBeginMessage(string line, Action<string> messageHandler) { var taskName = line.Substring(8, line.Length - 11); workingTasks.Add(taskName); messageHandler(workingTasks.Count > 0 ? workingTasks[workingTasks.Count - 1] : null); } private void ProcessEndMessage(string line, Action<string> messageHandler) { var pos = line.LastIndexOf(" after "); if (pos < 0) return; var taskName = line.Substring(8, pos - 8); var taskId = workingTasks.LastIndexOf(taskName); if (taskId >= 0) { workingTasks.RemoveAt(taskId); messageHandler(workingTasks.Count > 0 ? workingTasks[workingTasks.Count - 1] : null); } } private void ProcessTaskGroupMessage(string line, Action<float> progressHandler) { var match = TASK_GROUP_REGEX.Match(line); if (!match.Success) return; var name = match.Groups[1].Value; var taskCnt = int.Parse(match.Groups[2].Value); taskStates[name] = Tuple.Create(taskCnt, 0); UpdateTaskGroupProgress(progressHandler); } private void ProcessTaskEndMessage(string line, Action<float> progressHandler) { var match = TASK_END_REGEX.Match(line); if (!match.Success) return; var name = match.Groups[1].Value; Tuple<int, int> taskState; if (!taskStates.TryGetValue(name, out taskState)) return; taskStates[name] = Tuple.Create(taskState.Item1, taskState.Item2 + 1); UpdateTaskGroupProgress(progressHandler); } private void ProcessTaskGroupEndMessage(string line, Action<float> progressHandler) { var match = TASK_GROUP_END_REGEX.Match(line); if (!match.Success) return; var name = match.Groups[1].Value; Tuple<int, int> taskState; if (!taskStates.TryGetValue(name, out taskState)) return; taskStates[name] = Tuple.Create(taskState.Item1, taskState.Item1); UpdateTaskGroupProgress(progressHandler); } private void UpdateTaskGroupProgress(Action<float> progressHandler) { var taskCnt = taskStates.Sum(t => t.Value.Item1); progressHandler(taskCnt > 0 ? ANALYSIS_PART + (float)taskStates.Sum(t => t.Value.Item2) / taskCnt * (1 - ANALYSIS_PART) : ANALYSIS_PART); } private void ProcessPipelineAnalysisMessage(string line, Action<float> progressHandler) { var match = PIPELINE_REGEX.Match(line); if (!match.Success) return; var name = match.Groups[1].Value; if (name == "Analysis") { totalAnalysisSteps = int.Parse(match.Groups[2].Value); currentAnalysisStep = 0; } UpdateAnalysisProgress(progressHandler); } private void ProcessPipelineStepMessage(string line, Action<float> progressHandler) { var match = PIPELINE_STEP_REGEX.Match(line); if (!match.Success) return; var name = match.Groups[1].Value; if (name == "Analysis") { currentAnalysisStep += 1; } UpdateAnalysisProgress(progressHandler); } private void UpdateAnalysisProgress(Action<float> progressHandler) { progressHandler(ANALYSIS_PART * currentAnalysisStep / totalAnalysisSteps); } private void ProcessError(TextReader r, Action<string> workItemHandler, Action<string> messageHandler, Action<float> progressHandler, Action<string> errorHandler) { string l; while ((l = r.ReadLine()) != null) { Log(l); errorHandler(l); Debug.WriteLine("distillery err: " + l); } } #region JAVA detection private const int JAVA_MAJOR_VERSION = 1; private const int MIN_JAVA_MINOR_VERSION = 7; private string FindJava() { return FindJavaInSetup() ?? FindJavaInEnvVarJavaHome() ?? FindJavaInRegistry() ?? FindJavaInEnvVarPath(); } private string FindJavaInSetup() { if (string.IsNullOrWhiteSpace(setup.JavaRuntime)) return null; Debug.WriteLine("JRE (Configuration): " + setup.JavaRuntime); return setup.JavaRuntime; } private static string FindJavaInRegistry() { var jreKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\JavaSoft\Java Runtime Environment"); if (jreKey == null) return null; var version = jreKey.GetValue("CurrentVersion") as string; if (version == null) return null; var versionElements = version.Split('.'); if (versionElements.Length < 2) return null; int majVersion, minVersion; if (!int.TryParse(versionElements[0], out majVersion) || !int.TryParse(versionElements[1], out minVersion)) return null; if (majVersion != JAVA_MAJOR_VERSION || minVersion < MIN_JAVA_MINOR_VERSION) return null; var jreVersionKey = jreKey.OpenSubKey(version); if (jreVersionKey == null) return null; var javaHome = jreVersionKey.GetValue("JavaHome") as string; if (javaHome == null || !Directory.Exists(javaHome)) return null; var javaPath = Path.Combine(javaHome, "bin", "java.exe"); Debug.WriteLine("JRE (Registry): " + javaPath); return javaPath; } private static string FindJavaInEnvVarJavaHome() { var javaHome = Environment.GetEnvironmentVariable("JAVA_HOME"); if (javaHome == null) return null; if (!Directory.Exists(javaHome)) return null; var javaPath = Path.Combine(javaHome, "bin", "java.exe"); Debug.WriteLine("JRE (JAVA_HOME): " + javaPath); return javaPath; } private static string FindJavaInEnvVarPath() { var envPath = Environment.GetEnvironmentVariable("PATH"); if (envPath == null) return null; var envPaths = envPath.Split(new[] { Path.PathSeparator }) .Select(Environment.ExpandEnvironmentVariables) .ToArray(); foreach (var path in envPaths) { if ((Path.GetFileName(path) ?? "").ToLowerInvariant() == "java.exe" && File.Exists(path)) { Debug.WriteLine("JRE (PATH): " + path); return path; } if (Directory.Exists(path)) { var javaPath = Path.Combine(path, "java.exe"); if (File.Exists(javaPath)) { Debug.WriteLine("JRE (PATH): " + javaPath); return javaPath; } } } return null; } #endregion public override bool CheckTool() { return base.CheckTool() && File.Exists(javaPath); } } }
{ "content_hash": "670d1ec60a1df50e1b084efcd7456f16", "timestamp": "", "source": "github", "line_count": 302, "max_line_length": 124, "avg_line_length": 38.99337748344371, "alnum_prop": 0.5467051630434783, "repo_name": "mastersign/mediacategorizer-ui", "id": "550c01035135faf9cdaa6214d61b8bd6c3691e95", "size": "11778", "binary": false, "copies": "1", "ref": "refs/heads/release", "path": "tools/DistilleryTool.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "139311" } ], "symlink_target": "" }
{- Copyright 2010-2012 Cognimeta Inc. 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. -} module Database.Perdure.TestMap( testMap ) where import Prelude hiding (null, lookup) import Database.Perdure.Data.Map import Test.QuickCheck import Data.List(foldl') testMap :: [String] -> IO () testMap _ = (quickCheckWith (Args Nothing n n n True) $ insertList [1 .. k] empty == insertList (reverse [1 .. k]) empty) >> (quickCheckWith (Args Nothing n n n True) $ deleteList [1 .. k] (insertList (reverse [1 .. k]) $ insertList [1 .. k] empty) == empty) where insertList l m = foldl' (\z v -> insert v v z) m l deleteList l m = foldl' (flip delete) m l n = 5 k = n * 10000
{ "content_hash": "2c05a7eeda78c3e5efcaa5aaf2643ea6", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 141, "avg_line_length": 39.733333333333334, "alnum_prop": 0.6996644295302014, "repo_name": "Cognimeta/perdure", "id": "e87ffd1525a1e9442e770489d2a3a0829f84c047", "size": "1192", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "exe-src/Database/Perdure/TestMap.hs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Haskell", "bytes": "149262" } ], "symlink_target": "" }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * 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 org.zaproxy.zap.extension.httppanel.view.largeresponse; import org.parosproxy.paros.Constant; import org.parosproxy.paros.network.HttpHeader; import org.zaproxy.zap.extension.httppanel.view.impl.models.http.response.ResponseStringHttpPanelViewModel; public class LargeResponseStringHttpPanelViewModel extends ResponseStringHttpPanelViewModel { @Override public String getData() { if (httpMessage == null || httpMessage.getResponseHeader().isEmpty()) { return ""; } return httpMessage.getResponseHeader().toString().replaceAll(HttpHeader.CRLF, HttpHeader.LF) + Constant.messages.getString("http.panel.view.largeresponse.all.warning"); } @Override public void setData(String data) { } }
{ "content_hash": "d47d8af102566590dfb08b601e4b2763", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 107, "avg_line_length": 35.65, "alnum_prop": 0.7573632538569425, "repo_name": "GillesMoris/OSS", "id": "481f61a53177203345c79f198f3adbfabc0cfc28", "size": "1426", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/zaproxy/zap/extension/httppanel/view/largeresponse/LargeResponseStringHttpPanelViewModel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "184" }, { "name": "HTML", "bytes": "3966192" }, { "name": "Java", "bytes": "8169772" }, { "name": "JavaScript", "bytes": "161857" }, { "name": "Lex", "bytes": "7594" }, { "name": "PHP", "bytes": "118474" }, { "name": "Perl", "bytes": "3826" }, { "name": "Python", "bytes": "54211" }, { "name": "Shell", "bytes": "5827" }, { "name": "XSLT", "bytes": "30697" } ], "symlink_target": "" }
#include "OgreStableHeaders.h" #include "OgreOptimisedUtil.h" #include "OgrePlatformInformation.h" //#define __DO_PROFILE__ #ifdef __DO_PROFILE__ #include "OgreRoot.h" #endif namespace Ogre { //--------------------------------------------------------------------- // External functions extern OptimisedUtil* _getOptimisedUtilGeneral(void); #if __OGRE_HAVE_SSE extern OptimisedUtil* _getOptimisedUtilSSE(void); //#elif __OGRE_HAVE_NEON // extern OptimisedUtil* _getOptimisedUtilNEON(void); //#elif __OGRE_HAVE_VFP // extern OptimisedUtil* _getOptimisedUtilVFP(void); #endif #ifdef __DO_PROFILE__ //--------------------------------------------------------------------- #if OGRE_COMPILER == OGRE_COMPILER_MSVC typedef unsigned __int64 uint64; #pragma warning(push) #pragma warning(disable: 4035) // no return value static FORCEINLINE uint64 getCpuTimestamp(void) { __asm rdtsc // Return values in edx:eax, No return statement requirement here for VC. } #pragma warning(pop) #elif (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) typedef unsigned long long uint64; static FORCEINLINE uint64 getCpuTimestamp(void) { uint64 result; __asm__ __volatile__ ( "rdtsc" : "=A" (result) ); return result; } #endif // OGRE_COMPILER //--------------------------------------------------------------------- class OptimisedUtilProfiler : public OptimisedUtil { protected: enum { IMPL_DEFAULT, #if __OGRE_HAVE_SSE IMPL_SSE, //#elif __OGRE_HAVE_NEON // IMPL_NEON, //#elif __OGRE_HAVE_VFP // IMPL_VFP, #endif IMPL_COUNT }; struct ProfileItem { uint mAvgTicks; uint mCount; uint64 mTotalTicks; uint64 mStartTick; ProfileItem(void) : mAvgTicks() , mCount() , mTotalTicks() { } void begin(void) { mStartTick = getCpuTimestamp(); } void end(void) { uint64 ticks = getCpuTimestamp() - mStartTick; mTotalTicks += ticks; ++mCount; mAvgTicks = mTotalTicks / mCount; } }; typedef ProfileItem ProfileItems[IMPL_COUNT]; typedef vector<OptimisedUtil*>::type OptimisedUtilList; OptimisedUtilList mOptimisedUtils; public: OptimisedUtilProfiler(void) { mOptimisedUtils.push_back(_getOptimisedUtilGeneral()); #if __OGRE_HAVE_SSE if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_SSE) { mOptimisedUtils.push_back(_getOptimisedUtilSSE()); } //#elif __OGRE_HAVE_VFP // if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_VFP) // { // mOptimisedUtils.push_back(_getOptimisedUtilVFP()); // } //#elif __OGRE_HAVE_NEON // if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_NEON) // { // mOptimisedUtils.push_back(_getOptimisedUtilNEON()); // } #endif } virtual void softwareVertexSkinning( const float *srcPosPtr, float *destPosPtr, const float *srcNormPtr, float *destNormPtr, const float *blendWeightPtr, const unsigned char* blendIndexPtr, const Matrix4* const* blendMatrices, size_t srcPosStride, size_t destPosStride, size_t srcNormStride, size_t destNormStride, size_t blendWeightStride, size_t blendIndexStride, size_t numWeightsPerVertex, size_t numVertices) { static ProfileItems results; static size_t index; index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); OptimisedUtil* impl = mOptimisedUtils[index]; ProfileItem& profile = results[index]; profile.begin(); impl->softwareVertexSkinning( srcPosPtr, destPosPtr, srcNormPtr, destNormPtr, blendWeightPtr, blendIndexPtr, blendMatrices, srcPosStride, destPosStride, srcNormStride, destNormStride, blendWeightStride, blendIndexStride, numWeightsPerVertex, numVertices); profile.end(); // You can put break point here while running test application, to // watch profile results. ++index; // So we can put break point here even if in release build } virtual void softwareVertexMorph( Real t, const float *srcPos1, const float *srcPos2, float *dstPos, size_t pos1VSize, size_t pos2VSize, size_t dstVSize, size_t numVertices, bool morphNormals) { static ProfileItems results; static size_t index; index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); OptimisedUtil* impl = mOptimisedUtils[index]; ProfileItem& profile = results[index]; profile.begin(); impl->softwareVertexMorph( t, srcPos1, srcPos2, dstPos, pos1VSize, pos2VSize, dstVSize, numVertices, morphNormals); profile.end(); // You can put break point here while running test application, to // watch profile results. ++index; // So we can put break point here even if in release build } virtual void concatenateAffineMatrices( const Matrix4& baseMatrix, const Matrix4* srcMatrices, Matrix4* dstMatrices, size_t numMatrices) { static ProfileItems results; static size_t index; index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); OptimisedUtil* impl = mOptimisedUtils[index]; ProfileItem& profile = results[index]; profile.begin(); impl->concatenateAffineMatrices( baseMatrix, srcMatrices, dstMatrices, numMatrices); profile.end(); // You can put break point here while running test application, to // watch profile results. ++index; // So we can put break point here even if in release build } /// @copydoc OptimisedUtil::calculateFaceNormals virtual void calculateFaceNormals( const float *positions, const EdgeData::Triangle *triangles, Vector4 *faceNormals, size_t numTriangles) { static ProfileItems results; static size_t index; index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); OptimisedUtil* impl = mOptimisedUtils[index]; ProfileItem& profile = results[index]; profile.begin(); impl->calculateFaceNormals( positions, triangles, faceNormals, numTriangles); profile.end(); // // Dagon SkeletonAnimation sample test results (CPU timestamp per-function call): // // Pentium 4 3.0G HT Athlon XP 2500+ // // General 657080 486494 // SSE 223559 399495 // // You can put break point here while running test application, to // watch profile results. ++index; // So we can put break point here even if in release build } /// @copydoc OptimisedUtil::calculateLightFacing virtual void calculateLightFacing( const Vector4& lightPos, const Vector4* faceNormals, char* lightFacings, size_t numFaces) { static ProfileItems results; static size_t index; index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); OptimisedUtil* impl = mOptimisedUtils[index]; ProfileItem& profile = results[index]; profile.begin(); impl->calculateLightFacing( lightPos, faceNormals, lightFacings, numFaces); profile.end(); // // Dagon SkeletonAnimation sample test results (CPU timestamp per-function call): // // Pentium 4 3.0G HT Athlon XP 2500+ // // General 171875 86998 // SSE 47934 63995 // // You can put break point here while running test application, to // watch profile results. ++index; // So we can put break point here even if in release build } virtual void extrudeVertices( const Vector4& lightPos, Real extrudeDist, const float* srcPositions, float* destPositions, size_t numVertices) { static ProfileItems results; static size_t index; index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); OptimisedUtil* impl = mOptimisedUtils[index]; ProfileItem& profile = results[index]; profile.begin(); impl->extrudeVertices( lightPos, extrudeDist, srcPositions, destPositions, numVertices); profile.end(); // // Dagon SkeletonAnimation sample test results (CPU timestamp per-function call): // // Pentium 4 3.0G HT Athlon XP 2500+ // // Directional Light, General 38106 92306 // Directional Light, SSE 27292 67055 // // Point Light, General 224209 155483 // Point Light, SSE 56817 106663 // // You can put break point here while running test application, to // watch profile results. ++index; // So we can put break point here even if in release build } }; #endif // __DO_PROFILE__ //--------------------------------------------------------------------- OptimisedUtil* OptimisedUtil::msImplementation = OptimisedUtil::_detectImplementation(); //--------------------------------------------------------------------- OptimisedUtil* OptimisedUtil::_detectImplementation(void) { // // Some speed test results (averaged number of CPU timestamp (RDTSC) per-function call): // // Dagon SkeletonAnimation sample - softwareVertexSkinning: // // Pentium 4 3.0G HT Athlon XP 2500+ Athlon 64 X2 Dual Core 3800+ // // Shared Buffers, General C 763677 462903 473038 // Shared Buffers, Unrolled SSE 210030 *best* 369762 228328 *best* // Shared Buffers, General SSE 286202 352412 *best* 302796 // // Separated Buffers, General C 762640 464840 478740 // Separated Buffers, Unrolled SSE 219222 *best* 287992 *best* 238770 *best* // Separated Buffers, General SSE 290129 341614 307262 // // PosOnly, General C 388663 257350 262831 // PosOnly, Unrolled SSE 139814 *best* 200323 *best* 168995 *best* // PosOnly, General SSE 172693 213704 175447 // // Another my own test scene - softwareVertexSkinning: // // Pentium P4 3.0G HT Athlon XP 2500+ // // Shared Buffers, General C 74527 - // Shared Buffers, Unrolled SSE 22743 *best* - // Shared Buffers, General SSE 28527 - // // // Note that speed test appears unaligned load/store instruction version // loss performance 5%-10% than aligned load/store version, even if both // of them access to aligned data. Thus, we should use aligned load/store // as soon as possible. // // // We are pick up the implementation based on test results above. // #ifdef __DO_PROFILE__ { static OptimisedUtilProfiler msOptimisedUtilProfiler; return &msOptimisedUtilProfiler; } #else // !__DO_PROFILE__ #if __OGRE_HAVE_SSE if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_SSE) { return _getOptimisedUtilSSE(); } else //#elif __OGRE_HAVE_VFP // if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_VFP) // { // return _getOptimisedUtilVFP(); // } // else //#elif __OGRE_HAVE_NEON // if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_NEON) // { // return _getOptimisedUtilNEON(); // } // else #endif // __OGRE_HAVE_SSE { return _getOptimisedUtilGeneral(); } #endif // __DO_PROFILE__ } }
{ "content_hash": "7245c75767eb7fb37e27acb20f4b90e5", "timestamp": "", "source": "github", "line_count": 400, "max_line_length": 120, "avg_line_length": 35.5575, "alnum_prop": 0.5131828728116431, "repo_name": "Kanma/Ogre", "id": "32789a33b020af105093abddbb488b492d86a62c", "size": "15586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OgreMain/OgreOptimisedUtil.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2141984" }, { "name": "C++", "bytes": "13610649" }, { "name": "CSS", "bytes": "24100" }, { "name": "Objective-C", "bytes": "86240" }, { "name": "Objective-C++", "bytes": "79422" }, { "name": "Shell", "bytes": "701" }, { "name": "TeX", "bytes": "43359" } ], "symlink_target": "" }
package alluxio.util.network; import alluxio.AlluxioConfiguration; import alluxio.Configuration; import alluxio.PropertyKey; import alluxio.exception.ConnectionFailedException; import alluxio.exception.status.UnauthenticatedException; import alluxio.network.thrift.ThriftUtils; import alluxio.security.authentication.TransportProvider; import alluxio.util.CommonUtils; import alluxio.util.OSUtils; import alluxio.wire.WorkerNetAddress; import com.google.common.base.Preconditions; import io.netty.channel.unix.DomainSocketAddress; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.Enumeration; import java.util.List; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** * Common network address related utilities shared by all components in Alluxio. */ @ThreadSafe public final class NetworkAddressUtils { private static final Logger LOG = LoggerFactory.getLogger(NetworkAddressUtils.class); public static final String WILDCARD_ADDRESS = "0.0.0.0"; /** * Checks if the underlying OS is Windows. */ public static final boolean WINDOWS = OSUtils.isWindows(); private static String sLocalHost; private static String sLocalHostMetricName; private static String sLocalIP; private NetworkAddressUtils() {} /** * Different types of services that client uses to connect. These types also indicate the service * bind address. */ public enum ServiceType { /** * Master RPC service (Thrift). */ MASTER_RPC("Alluxio Master RPC service", PropertyKey.MASTER_HOSTNAME, PropertyKey.MASTER_BIND_HOST, PropertyKey.MASTER_RPC_PORT), /** * Master web service (Jetty). */ MASTER_WEB("Alluxio Master Web service", PropertyKey.MASTER_WEB_HOSTNAME, PropertyKey.MASTER_WEB_BIND_HOST, PropertyKey.MASTER_WEB_PORT), /** * Worker RPC service (Thrift). */ WORKER_RPC("Alluxio Worker RPC service", PropertyKey.WORKER_HOSTNAME, PropertyKey.WORKER_BIND_HOST, PropertyKey.WORKER_RPC_PORT), /** * Worker data service (Netty). */ WORKER_DATA("Alluxio Worker data service", PropertyKey.WORKER_DATA_HOSTNAME, PropertyKey.WORKER_DATA_BIND_HOST, PropertyKey.WORKER_DATA_PORT), /** * Worker web service (Jetty). */ WORKER_WEB("Alluxio Worker Web service", PropertyKey.WORKER_WEB_HOSTNAME, PropertyKey.WORKER_WEB_BIND_HOST, PropertyKey.WORKER_WEB_PORT), /** * Proxy web service (Jetty). */ PROXY_WEB("Alluxio Proxy Web service", PropertyKey.PROXY_WEB_HOSTNAME, PropertyKey.PROXY_WEB_BIND_HOST, PropertyKey.PROXY_WEB_PORT), ; // service name private final String mServiceName; // the key of connect hostname private final PropertyKey mHostNameKey; // the key of bind hostname private final PropertyKey mBindHostKey; // the key of service port private final PropertyKey mPortKey; ServiceType(String serviceName, PropertyKey hostNameKey, PropertyKey bindHostKey, PropertyKey portKey) { mServiceName = serviceName; mHostNameKey = hostNameKey; mBindHostKey = bindHostKey; mPortKey = portKey; } /** * Gets service name. * * @return service name */ public String getServiceName() { return mServiceName; } /** * Gets the key of connect hostname. * * @return key of connect hostname */ public PropertyKey getHostNameKey() { return mHostNameKey; } /** * Gets the key of bind hostname. * * @return key of bind hostname */ public PropertyKey getBindHostKey() { return mBindHostKey; } /** * Gets the key of service port. * * @return key of service port */ public PropertyKey getPortKey() { return mPortKey; } /** * Gets the default port number on service. * * @return default port */ public int getDefaultPort() { return Integer.parseInt(mPortKey.getDefaultValue()); } } /** * Checks if the given port is valid. * * @param port the port to check */ public static void assertValidPort(final int port) { Preconditions.checkArgument(port < 65536, "Port must be less than 65536"); Preconditions.checkArgument(port >= 0, "Port must be non-negative"); } /** * Checks if the given port in the address is valid. * * @param address the {@link InetSocketAddress} with the port to check */ public static void assertValidPort(final InetSocketAddress address) { assertValidPort(address.getPort()); } /** * Helper method to get the {@link InetSocketAddress} address for client to communicate with the * service. * * @param service the service name used to connect * @return the service address that a client (typically outside the service machine) uses to * communicate with service. */ public static InetSocketAddress getConnectAddress(ServiceType service) { return getConnectAddress(service, Configuration.global()); } /** * Helper method to get the {@link InetSocketAddress} address for client to communicate with the * service. * * @param service the service name used to connect * @param conf the configuration to use for looking up the connect address * @return the service address that a client (typically outside the service machine) uses to * communicate with service. */ public static InetSocketAddress getConnectAddress(ServiceType service, AlluxioConfiguration conf) { return new InetSocketAddress(getConnectHost(service, conf), getPort(service, conf)); } /** * Provides an externally resolvable hostname for client to communicate with the service. If the * hostname is not explicitly specified, Alluxio will try to use the bind host. If the bind host * is wildcard, Alluxio will automatically determine an appropriate hostname from local machine. * The various possibilities shown in the following table: * <table> * <caption>Hostname Scenarios</caption> <thead> * <tr> * <th>Specified Hostname</th> * <th>Specified Bind Host</th> * <th>Returned Connect Host</th> * </tr> * </thead> <tbody> * <tr> * <td>hostname</td> * <td>hostname</td> * <td>hostname</td> * </tr> * <tr> * <td>not defined</td> * <td>hostname</td> * <td>hostname</td> * </tr> * <tr> * <td>hostname</td> * <td>0.0.0.0 or not defined</td> * <td>hostname</td> * </tr> * <tr> * <td>not defined</td> * <td>0.0.0.0 or not defined</td> * <td>localhost</td> * </tr> * </tbody> * </table> * * @param service Service type used to connect * @return the externally resolvable hostname that the client can use to communicate with the * service. */ public static String getConnectHost(ServiceType service) { return getConnectHost(service, Configuration.global()); } /** * Provides an externally resolvable hostname for client to communicate with the service. If the * hostname is not explicitly specified, Alluxio will try to use the bind host. If the bind host * is wildcard, Alluxio will automatically determine an appropriate hostname from local machine. * The various possibilities shown in the following table: * <table> * <caption>Hostname Scenarios</caption> * <thead> * <tr> * <th>Specified Hostname</th> * <th>Specified Bind Host</th> * <th>Returned Connect Host</th> * </tr> * </thead> * <tbody> * <tr> * <td>hostname</td> * <td>hostname</td> * <td>hostname</td> * </tr> * <tr> * <td>not defined</td> * <td>hostname</td> * <td>hostname</td> * </tr> * <tr> * <td>hostname</td> * <td>0.0.0.0 or not defined</td> * <td>hostname</td> * </tr> * <tr> * <td>not defined</td> * <td>0.0.0.0 or not defined</td> * <td>localhost</td> * </tr> * </tbody> * </table> * * @param service Service type used to connect * @param conf configuration * @return the externally resolvable hostname that the client can use to communicate with the * service. */ public static String getConnectHost(ServiceType service, AlluxioConfiguration conf) { if (conf.isSet(service.mHostNameKey)) { String connectHost = conf.get(service.mHostNameKey); if (!connectHost.isEmpty() && !connectHost.equals(WILDCARD_ADDRESS)) { return connectHost; } } if (conf.isSet(service.mBindHostKey)) { String bindHost = conf.get(service.mBindHostKey); if (!bindHost.isEmpty() && !bindHost.equals(WILDCARD_ADDRESS)) { return bindHost; } } return getLocalHostName(); } /** * Gets the port number on a given service type. If user defined port number is not explicitly * specified, Alluxio will use the default service port. * * @param service Service type used to connect * @return the service port number */ public static int getPort(ServiceType service) { return getPort(service, Configuration.global()); } /** * Gets the port number on a given service type. If user defined port number is not explicitly * specified, Alluxio will use the default service port. * * @param service Service type used to connect * @param config configuration * @return the service port number */ public static int getPort(ServiceType service, AlluxioConfiguration config) { return config.getInt(service.mPortKey); } /** * Helper method to get the bind hostname for a given service. * * @param service the service name * @return the InetSocketAddress the service will bind to */ public static InetSocketAddress getBindAddress(ServiceType service) { int port = getPort(service); assertValidPort(port); return new InetSocketAddress(getBindHost(service), getPort(service)); } /** * Helper method to get the {@link InetSocketAddress} bind address on a given service. * <p> * Host bind information searching order: * <ol> * <li>System properties or environment variables via alluxio-env.sh * <li>Default properties via alluxio-default.properties file * <li>A externally resolvable local hostname for the host this JVM is running on * </ol> * * @param service the service name * @return the bind hostname */ public static String getBindHost(ServiceType service) { if (Configuration.isSet(service.mBindHostKey) && !Configuration.get(service.mBindHostKey) .isEmpty()) { return Configuration.get(service.mBindHostKey); } else { return getLocalHostName(); } } /** * Gets the local hostname to be used by the client. If this isn't configured, a non-loopback * local hostname will be looked up. * * @return the local hostname for the client */ public static String getClientHostName() { if (Configuration.isSet(PropertyKey.USER_HOSTNAME)) { return Configuration.get(PropertyKey.USER_HOSTNAME); } return getLocalHostName(); } /** * Gets a local node name from configuration if it is available, falling back on localhost lookup. * * @return the local node name */ public static String getLocalNodeName() { switch (CommonUtils.PROCESS_TYPE.get()) { case CLIENT: if (Configuration.isSet(PropertyKey.USER_HOSTNAME)) { return Configuration.get(PropertyKey.USER_HOSTNAME); } break; case MASTER: if (Configuration.isSet(PropertyKey.MASTER_HOSTNAME)) { return Configuration.get(PropertyKey.MASTER_HOSTNAME); } break; case WORKER: if (Configuration.isSet(PropertyKey.WORKER_HOSTNAME)) { return Configuration.get(PropertyKey.WORKER_HOSTNAME); } break; default: break; } return getLocalHostName(); } /** * Gets a local hostname for the host this JVM is running on. * * @return the local host name, which is not based on a loopback ip address */ public static synchronized String getLocalHostName() { if (sLocalHost != null) { return sLocalHost; } int hostResolutionTimeout = (int) Configuration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS); return getLocalHostName(hostResolutionTimeout); } /** * Gets a local host name for the host this JVM is running on. * * @param timeoutMs Timeout in milliseconds to use for checking that a possible local host is * reachable * @return the local host name, which is not based on a loopback ip address */ public static synchronized String getLocalHostName(int timeoutMs) { if (sLocalHost != null) { return sLocalHost; } try { sLocalHost = InetAddress.getByName(getLocalIpAddress(timeoutMs)).getCanonicalHostName(); return sLocalHost; } catch (UnknownHostException e) { throw new RuntimeException(e); } } /** * Gets a local hostname for the host this JVM is running on with '.' replaced with '_' for * metrics usage. * * @return the metrics system friendly local host name */ public static synchronized String getLocalHostMetricName() { if (sLocalHostMetricName != null) { return sLocalHostMetricName; } sLocalHostMetricName = getLocalHostName().replace('.', '_'); return sLocalHostMetricName; } /** * Gets a local IP address for the host this JVM is running on. * * @return the local ip address, which is not a loopback address and is reachable */ public static synchronized String getLocalIpAddress() { if (sLocalIP != null) { return sLocalIP; } int hostResolutionTimeout = (int) Configuration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS); return getLocalIpAddress(hostResolutionTimeout); } /** * Gets a local IP address for the host this JVM is running on. * * @param timeoutMs Timeout in milliseconds to use for checking that a possible local IP is * reachable * @return the local ip address, which is not a loopback address and is reachable */ public static synchronized String getLocalIpAddress(int timeoutMs) { if (sLocalIP != null) { return sLocalIP; } try { InetAddress address = InetAddress.getLocalHost(); LOG.debug("address: {} isLoopbackAddress: {}, with host {} {}", address, address.isLoopbackAddress(), address.getHostAddress(), address.getHostName()); // Make sure that the address is actually reachable since in some network configurations // it is possible for the InetAddress.getLocalHost() call to return a non-reachable // address e.g. a broadcast address if (!isValidAddress(address, timeoutMs)) { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); // Make getNetworkInterfaces have the same order of network interfaces as listed on // unix-like systems. This optimization can help avoid to get some special addresses, such // as loopback address"127.0.0.1", virtual bridge address "192.168.122.1" as far as // possible. if (!WINDOWS) { List<NetworkInterface> netIFs = Collections.list(networkInterfaces); Collections.reverse(netIFs); networkInterfaces = Collections.enumeration(netIFs); } while (networkInterfaces.hasMoreElements()) { NetworkInterface ni = networkInterfaces.nextElement(); Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { address = addresses.nextElement(); // Address must not be link local or loopback. And it must be reachable if (isValidAddress(address, timeoutMs)) { sLocalIP = address.getHostAddress(); return sLocalIP; } } } LOG.warn("Your hostname, {} resolves to a loopback/non-reachable address: {}, " + "but we couldn't find any external IP address!", InetAddress.getLocalHost().getHostName(), address.getHostAddress()); } sLocalIP = address.getHostAddress(); return sLocalIP; } catch (IOException e) { throw new RuntimeException(e); } } /** * @param host the host to try to connect to * @param port the port to try to connect on * @return whether a socket connection can be made to the given host on the given port */ public static boolean isServing(String host, int port) { if (port < 0) { return false; } try { Socket socket = new Socket(host, port); socket.close(); return true; } catch (IOException e) { return false; } } /** * Tests if the address is externally resolvable. Address must not be wildcard, link local, * loopback address, non-IPv4, or other unreachable addresses. * * @param address The testing address * @param timeoutMs Timeout in milliseconds to use for checking that a possible local IP is * reachable * @return a {@code boolean} indicating if the given address is externally resolvable address */ private static boolean isValidAddress(InetAddress address, int timeoutMs) throws IOException { return !address.isAnyLocalAddress() && !address.isLinkLocalAddress() && !address.isLoopbackAddress() && address.isReachable(timeoutMs) && (address instanceof Inet4Address); } /** * Resolves a given hostname by a canonical hostname. When a hostname alias (e.g., those specified * in /etc/hosts) is given, the alias may not be resolvable on other hosts in a cluster unless the * same alias is defined there. In this situation, loadufs would break. * * @param hostname the input hostname, which could be an alias * @return the canonical form of the hostname, or null if it is null or empty * @throws UnknownHostException if the given hostname cannot be resolved */ @Nullable public static String resolveHostName(String hostname) throws UnknownHostException { if (hostname == null || hostname.isEmpty()) { return null; } return InetAddress.getByName(hostname).getCanonicalHostName(); } /** * Resolves a given hostname IP address. * * @param hostname the input hostname, which could be an alias * @return the hostname IP address * @throws UnknownHostException if the given hostname cannot be resolved */ public static String resolveIpAddress(String hostname) throws UnknownHostException { Preconditions.checkNotNull(hostname, "hostname"); Preconditions.checkArgument(!hostname.isEmpty(), "Cannot resolve IP address for empty hostname"); return InetAddress.getByName(hostname).getHostAddress(); } /** * Gets FQDN(Full Qualified Domain Name) from Java representations of network address, except * String representation which should be handled by {@link #resolveHostName(String)} which will * handle the situation where hostname is null. * * @param addr the input network address representation, can not be null * @return the resolved FQDN host name */ public static String getFqdnHost(InetSocketAddress addr) { Preconditions.checkNotNull(addr.getAddress(), "the address of " + addr + " is invalid."); return addr.getAddress().getCanonicalHostName(); } /** * Gets FQDN(Full Qualified Domain Name) from Alluxio representation of network address. * * @param addr the input network address representation * @return the resolved FQDN host name * @throws UnknownHostException if the host is not known */ public static String getFqdnHost(WorkerNetAddress addr) throws UnknownHostException { return resolveHostName(addr.getHost()); } /** * Parses {@link InetSocketAddress} from a String. * * @param address socket address to parse * @return InetSocketAddress of the String */ @Nullable public static InetSocketAddress parseInetSocketAddress(String address) throws IOException { if (address == null) { return null; } String[] strArr = address.split(":"); if (strArr.length != 2) { throw new IOException("Invalid InetSocketAddress " + address); } return new InetSocketAddress(strArr[0], Integer.parseInt(strArr[1])); } /** * Extracts rpcPort InetSocketAddress from Alluxio representation of network address. * * @param netAddress the input network address representation * @return InetSocketAddress */ public static InetSocketAddress getRpcPortSocketAddress(WorkerNetAddress netAddress) { String host = netAddress.getHost(); int port = netAddress.getRpcPort(); return new InetSocketAddress(host, port); } /** * Extracts dataPort socket address from Alluxio representation of network address. * * @param netAddress the input network address representation * @return the socket address */ public static SocketAddress getDataPortSocketAddress(WorkerNetAddress netAddress) { SocketAddress address; if (NettyUtils.isDomainSocketSupported(netAddress)) { address = new DomainSocketAddress(netAddress.getDomainSocketPath()); } else { String host = netAddress.getHost(); int port = netAddress.getDataPort(); address = new InetSocketAddress(host, port); } return address; } /** * Test if the input address is serving an Alluxio service. This method make use of the * Thrift protocol for performing service communication. * * @param address the network address to ping * @param serviceName the Alluxio service name * @throws UnauthenticatedException If the user is not authenticated * @throws ConnectionFailedException If there is a protocol transport error */ public static void pingService(InetSocketAddress address, String serviceName) throws UnauthenticatedException, ConnectionFailedException { Preconditions.checkNotNull(address, "address"); Preconditions.checkNotNull(serviceName, "serviceName"); Preconditions.checkArgument(!serviceName.isEmpty(), "Cannot resolve for empty service name"); try { TransportProvider transportProvider = TransportProvider.Factory.create(); TProtocol protocol = ThriftUtils.createThriftProtocol(transportProvider.getClientTransport(address), serviceName); protocol.getTransport().open(); protocol.getTransport().close(); } catch (TTransportException e) { throw new ConnectionFailedException(e.getMessage()); } } }
{ "content_hash": "1bcfb9da589c295432d023017cff4105", "timestamp": "", "source": "github", "line_count": 696, "max_line_length": 100, "avg_line_length": 33.0933908045977, "alnum_prop": 0.6839317500976859, "repo_name": "PasaLab/tachyon", "id": "dae22ec47f06e620bd4eda19c3fdd86f11c9aa8b", "size": "23545", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/common/src/main/java/alluxio/util/network/NetworkAddressUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2051" }, { "name": "Go", "bytes": "19061" }, { "name": "HTML", "bytes": "599" }, { "name": "Java", "bytes": "7667828" }, { "name": "JavaScript", "bytes": "1079" }, { "name": "Python", "bytes": "11471" }, { "name": "Roff", "bytes": "5797" }, { "name": "Ruby", "bytes": "22472" }, { "name": "Shell", "bytes": "134544" }, { "name": "Thrift", "bytes": "46981" } ], "symlink_target": "" }
namespace content { class JavaBridgeDispatcherHostManager; // Wrapper around a Java object. // // Represents a Java object for use in the Java bridge. Holds a global ref to // the Java object and provides the ability to invoke methods on it. // Interrogation of the Java object for its methods is done lazily. This class // is not generally threadsafe. However, it does allow for instances to be // created and destroyed on different threads. class JavaBoundObject { public: // Takes a Java object and creates a JavaBoundObject around it. If // |safe_annotation_clazz| annotation is non-null, the method is exposed // to JavaScript. Returns an NPObject with a ref count of one which owns the // JavaBoundObject. // See also comment below for |manager_|. static NPObject* Create( const base::android::JavaRef<jobject>& object, const base::android::JavaRef<jclass>& safe_annotation_clazz, const base::WeakPtr<JavaBridgeDispatcherHostManager>& manager, bool can_enumerate_methods); virtual ~JavaBoundObject(); // Gets a local ref to the underlying JavaObject from a JavaBoundObject // wrapped as an NPObject. May return null if the underlying object has // been garbage collected. static base::android::ScopedJavaLocalRef<jobject> GetJavaObject( NPObject* object); // Methods to implement the NPObject callbacks. bool CanEnumerateMethods() const { return can_enumerate_methods_; } std::vector<std::string> GetMethodNames() const; bool HasMethod(const std::string& name) const; bool Invoke(const std::string& name, const NPVariant* args, size_t arg_count, NPVariant* result); private: JavaBoundObject( const base::android::JavaRef<jobject>& object, const base::android::JavaRef<jclass>& safe_annotation_clazz, const base::WeakPtr<JavaBridgeDispatcherHostManager>& manager, bool can_enumerate_methods); void EnsureMethodsAreSetUp() const; base::android::ScopedJavaLocalRef<jclass> GetLocalClassRef(JNIEnv* env) const; static void ThrowSecurityException(const char* message); // The weak ref to the underlying Java object that this JavaBoundObject // instance represents. JavaObjectWeakGlobalRef java_object_; // Keep a pointer back to the JavaBridgeDispatcherHostManager so that we // can notify it when this JavaBoundObject is destroyed. JavaBoundObjects // may outlive the manager so keep a WeakPtr. Note the WeakPtr may only be // dereferenced on the UI thread. base::WeakPtr<JavaBridgeDispatcherHostManager> manager_; // Map of public methods, from method name to Method instance. Multiple // entries will be present for overloaded methods. Note that we can't use // scoped_ptr in STL containers as we can't copy it. typedef std::multimap<std::string, linked_ptr<JavaMethod> > JavaMethodMap; mutable JavaMethodMap methods_; mutable bool are_methods_set_up_; mutable jmethodID object_get_class_method_id_; const bool can_enumerate_methods_; base::android::ScopedJavaGlobalRef<jclass> safe_annotation_clazz_; DISALLOW_IMPLICIT_CONSTRUCTORS(JavaBoundObject); }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_JAVA_JAVA_BOUND_OBJECT_H_
{ "content_hash": "17d4624a515079018941e3362093264c", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 80, "avg_line_length": 41.15384615384615, "alnum_prop": 0.7498442367601246, "repo_name": "andykimpe/chromium-test-npapi", "id": "f29aed6df1b52037e25d7977b2ae5127e8e0a420", "size": "3822", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/browser/renderer_host/java/java_bound_object.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Assembly", "bytes": "24741" }, { "name": "Batchfile", "bytes": "6704" }, { "name": "C", "bytes": "3578395" }, { "name": "C++", "bytes": "197882186" }, { "name": "CSS", "bytes": "774304" }, { "name": "HTML", "bytes": "16781925" }, { "name": "Java", "bytes": "5176812" }, { "name": "JavaScript", "bytes": "9838003" }, { "name": "Makefile", "bytes": "36405" }, { "name": "Objective-C", "bytes": "1135377" }, { "name": "Objective-C++", "bytes": "7082902" }, { "name": "PLpgSQL", "bytes": "141320" }, { "name": "Perl", "bytes": "69392" }, { "name": "Protocol Buffer", "bytes": "360984" }, { "name": "Python", "bytes": "5577847" }, { "name": "Rebol", "bytes": "262" }, { "name": "Shell", "bytes": "434741" }, { "name": "Standard ML", "bytes": "1589" }, { "name": "nesC", "bytes": "15206" } ], "symlink_target": "" }
export default (params) => { params.mainWindow.on('focus', () => { params.mainWindow.webContents.send('isWindowFocused', true); }); params.mainWindow.on('blur', () => { params.mainWindow.webContents.send('isWindowFocused', false); }); };
{ "content_hash": "208ca184420da0de70777e26713d85ee", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 65, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6470588235294118, "repo_name": "meetfranz/franz", "id": "0b4a0d8f33b2f3db739c509b74936edce19d556e", "size": "255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/electron/ipc-api/focusState.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "4726" }, { "name": "JavaScript", "bytes": "742283" }, { "name": "SCSS", "bytes": "53645" }, { "name": "TypeScript", "bytes": "117703" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.oasp.java.dev</groupId> <artifactId>oasp4j</artifactId> <version>dev-SNAPSHOT</version> <!-- This POM will never be released --> <packaging>pom</packaging> <name>${project.artifactId}</name> <description>Open Application Standard Platform for Java (OASP4J).</description> <url>http://oasp.io/oasp4j/maven/oasp4j</url> <inceptionYear>2014</inceptionYear> <modules> <module>bom</module> <module>modules</module> </modules> <properties> <java.version>1.7</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <oasp4j.version>2.1.0</oasp4j.version> <port.range>81</port.range> <oasp.gpg.keyname>joerg.hohwiller@capgemini.com</oasp.gpg.keyname> <oasp.flatten.mode>oss</oasp.flatten.mode> <spring.boot.version>1.3.3.RELEASE</spring.boot.version> <js.client.dir>src/main/client</js.client.dir> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>${project.build.sourceEncoding}</encoding> <includeEmptyDirs>true</includeEmptyDirs> </configuration> </plugin> <!-- configure java compiler --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <encoding>${project.build.sourceEncoding}</encoding> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <!-- advanced manifests --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> </archive> </configuration> </plugin> <!-- also generate source JARs --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <phase>package</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <!-- http://mojo.codehaus.org/flatten-maven-plugin/ --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>flatten-maven-plugin</artifactId> <configuration> <flattenMode>${oasp.flatten.mode}</flattenMode> </configuration> <executions> <execution> <id>flatten</id> <phase>process-test-resources</phase> <goals> <goal>flatten</goal> </goals> </execution> <execution> <id>flatten.clean</id> <phase>clean</phase> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> <!-- avoid version in local war files, exclude development properties from WARs --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <packagingExcludes>WEB-INF/classes/config/application.properties</packagingExcludes> <warName>${project.artifactId}</warName> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- Surefire changed the default to the project.build.directory causing trouble with file paths to test resources --> <workingDirectory>${basedir}</workingDirectory> </configuration> </plugin> <!-- site generation settings --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> </plugin> </plugins> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.5</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.9.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>2.7</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.9.1</version> <configuration> <!-- http://jira.codehaus.org/browse/MJAVADOC-308 --> <!--<maxmemory>5048m</maxmemory>--> <notree>true</notree> <show>private</show> <encoding>${project.reporting.outputEncoding}</encoding> <charset>${project.build.sourceEncoding}</charset> <docfilessubdirs>true</docfilessubdirs> <!--<additionalparam>-Xdoclint:none</additionalparam>--> <links> <link>http://docs.oracle.com/javase/7/docs/api/</link> <link>http://m-m-m.sourceforge.net/apidocs/</link> </links> <doctitle>JavaDocs for ${project.name}</doctitle> <windowtitle>JavaDocs for ${project.name}</windowtitle> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.17</version> <configuration> <!-- force locale to en_EN or tests will fail in other locales --> <argLine>-Duser.language=en -Duser.region=EN</argLine> <!-- Surefire changed the default to the project.build.directory causing trouble with file paths to test resources --> <workingDirectory>${basedir}</workingDirectory> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.9</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>3.2</version> <configuration> <targetJdk>${java.version}</targetJdk> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.5</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.5</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-help-plugin</artifactId> <version>2.2</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> <version>3.0.0</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>taglist-maven-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>flatten-maven-plugin</artifactId> <version>1.0.0</version> </plugin> <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>1.3.6</version> </plugin> </plugins> </pluginManagement> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <configuration> <dependencyLocationsEnabled>false</dependencyLocationsEnabled> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <!--<notree>true</notree>--> <show>private</show> <encoding>${project.reporting.outputEncoding}</encoding> <charset>${project.build.sourceEncoding}</charset> <docfilessubdirs>true</docfilessubdirs> <stylesheetfile>${user.dir}/src/main/javadoc/stylesheet.css</stylesheetfile> <!--<additionalparam>-Xdoclint:none -source ${java.version}</additionalparam>--> <links> <link>http://docs.oracle.com/javase/7/docs/api/</link> <!--<link>http://oasp.github.io/oasp4j/maven/apidocs/</link>--> </links> <doctitle>JavaDocs for ${project.name}</doctitle> <windowtitle>JavaDocs for ${project.name}</windowtitle> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>taglist-maven-plugin</artifactId> <configuration> <tags> <tag>TODO</tag> <tag>@todo</tag> <tag>FIXME</tag> <tag>@deprecated</tag> <tag>REVIEW</tag> </tags> </configuration> </plugin> <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <reportSets> <reportSet> <reports> <!-- https://github.com/jeremylong/DependencyCheck/issues/386--> <!-- <report>aggregate</report> --> <report>check</report> </reports> </reportSet> </reportSets> </plugin> </plugins> </reporting> <profiles> <profile> <id>all</id> <activation> <file> <exists>pom.xml</exists> </file> </activation> <modules> <module>samples</module> </modules> </profile> <profile> <id>security</id> <build> <plugins> <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <configuration> <failBuildOnCVSS>8</failBuildOnCVSS> </configuration> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>deploy</id> <build> <plugins> <!-- also generate javadoc JARs --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <!-- Sign artifacts with PGP --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <configuration> <keyname>${oasp.gpg.keyname}</keyname> </configuration> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <distributionManagement> <snapshotRepository> <id>ossrh</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> <repository> <id>ossrh</id> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> </repository> </distributionManagement> </profile> <profile> <!-- separate eclipse build from command-line... --> <id>eclipse</id> <activation> <property> <name>eclipse.application</name> </property> </activation> <build> <directory>eclipse-target</directory> </build> </profile> </profiles> <issueManagement> <system>GitHub</system> <url>https://github.com/oasp/oasp4j/issues</url> </issueManagement> <scm> <url>https://github.com/oasp/oasp4j/tree/develop</url> </scm> <!-- <mailingLists> <mailingList> <name>oasp-devel</name> <subscribe>TODO</subscribe> <unsubscribe>TODO</unsubscribe> <post>TODO</post> <archive>TODO</archive> </mailingList> </mailingLists> --> <organization> <name>OASP-Team</name> <url>http://oasp.io/oasp4j/maven/team-list.html</url> </organization> <developers> <developer> <id>hohwille</id> <name>J&#246;rg Hohwiller</name> <email>hohwille@users.sourceforge.net</email> <organization></organization> <organizationUrl/> <roles> <role>admin</role> <role>designer</role> <role>developer</role> </roles> <timezone>+1</timezone> <properties/> </developer> <developer> <id>ksobkowiak</id> <name>Krzysztof Sobkowiak</name> <email>sobkowiak@onet.eu</email> <organization></organization> <organizationUrl/> <roles> <role>admin</role> <role>designer</role> <role>developer</role> </roles> <timezone>+1</timezone> <properties/> </developer> </developers> <licenses> <license> <name>Apache Software Licenese</name> <url>http://oasp.github.io/terms-of-use.html</url> <distribution>repo</distribution> <comments/> </license> </licenses> <distributionManagement> <repository> <id>oasp.releases</id> <name>OASP Releases</name> <url>http://oasp-ci.cloudapp.net/nexus/content/repositories/releases/</url> </repository> <snapshotRepository> <id>oasp.snapshots</id> <name>OASP Snapshots</name> <url>http://oasp-ci.cloudapp.net/nexus/content/repositories/snapshots/</url> </snapshotRepository> <site> <id>oasp-site</id> <url>file://${user.dir}/target/oasp4j/maven</url> </site> </distributionManagement> </project>
{ "content_hash": "b4c48828d07f42d594fcaf70951b89f7", "timestamp": "", "source": "github", "line_count": 525, "max_line_length": 130, "avg_line_length": 32.83238095238095, "alnum_prop": 0.5699367639380403, "repo_name": "devonfw/training-devon-server", "id": "e4f5e41d52a7f1a93ff83f2b9500e9b6a2a455e1", "size": "17237", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module Rumale # @!visibility private module Utils module_function # @!visibility private def choice_ids(size, probs, rng = nil) rng ||= Random.new Array.new(size) do target = rng.rand chosen = 0 probs.each_with_index do |p, idx| break (chosen = idx) if target <= p target -= p end chosen end end # @!visibility private def rand_uniform(shape, rng = nil) rng ||= Random.new if shape.is_a?(Array) rnd_vals = Array.new(shape.inject(:*)) { rng.rand } Numo::DFloat.asarray(rnd_vals).reshape(shape[0], shape[1]) else Numo::DFloat.asarray(Array.new(shape) { rng.rand }) end end # @!visibility private def rand_normal(shape, rng = nil, mu = 0.0, sigma = 1.0) rng ||= Random.new a = rand_uniform(shape, rng) b = rand_uniform(shape, rng) (Numo::NMath.sqrt(Numo::NMath.log(a) * -2.0) * Numo::NMath.sin(b * 2.0 * Math::PI)) * sigma + mu end end end
{ "content_hash": "1e719918dbff1b1ba2bbe0ecc372c84e", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 102, "avg_line_length": 25.925, "alnum_prop": 0.553519768563163, "repo_name": "yoshoku/SVMKit", "id": "9fda254149b996091d4c02e6870f8e7ec548e808", "size": "1068", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "lib/rumale/utils.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Perl", "bytes": "219" }, { "name": "Ruby", "bytes": "414070" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
import {Modal} from "angular2-modal/plugins/bootstrap"; import {Store} from "@ngrx/store"; import { ApprovingProccess, RejectionProccess } from '../list/list.actions'; export abstract class AbstractApprovable { protected abstract get modal(): Modal; protected abstract get store(): Store<any>; rejectCourse(id) { this.showPromptModal() .catch(err => console.log("ERROR")) .then(dialog => dialog.result) .then(reason => this.store.dispatch(new RejectionProccess({id, reason}))) .catch(err => console.log("CANCELED")); } showPromptModal() { return this.modal.prompt() .showClose(true) .title('Reject Reason') .open() } approveCourse(id) { this.store.dispatch(new ApprovingProccess({id})) } }
{ "content_hash": "1c5d0e2d0cc3204c032bcf2aee055a0b", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 79, "avg_line_length": 27.321428571428573, "alnum_prop": 0.6666666666666666, "repo_name": "belinef/CoursesApp", "id": "1d54101e4533d084aef2b75e14883cc5a5d00093", "size": "765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/common/abstract/abstractApprovable.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22900" }, { "name": "HTML", "bytes": "20791" }, { "name": "JavaScript", "bytes": "69545" }, { "name": "TypeScript", "bytes": "79926" } ], "symlink_target": "" }
package com.gentics.mesh.rest.client; import com.gentics.mesh.MeshVersion; import com.gentics.mesh.rest.JWTAuthentication; import com.gentics.mesh.rest.client.impl.MeshRestOkHttpClientImpl; import com.gentics.mesh.rest.client.method.*; import okhttp3.OkHttpClient; /** * Definition of the main Mesh REST client API. It aggregates all client methods interfaces to provide a full list of the whole API. */ public interface MeshRestClient extends NodeClientMethods, TagClientMethods, ProjectClientMethods, TagFamilyClientMethods, WebRootClientMethods, SchemaClientMethods, GroupClientMethods, UserClientMethods, RoleClientMethods, AuthClientMethods, SearchClientMethods, AdminClientMethods, AdminPluginClientMethods, MicroschemaClientMethods, NodeBinaryFieldClientMethods, NodeS3BinaryFieldClientMethods, UtilityClientMethods, NavigationClientMethods, NavRootClientMethods, EventbusClientMethods, BranchClientMethods, ApiInfoClientMethods, GraphQLClientMethods, JobClientMethods, GenericHttpMethods, HealthClientMethods, LocalConfigMethods, WebRootFieldClientMethods { /** * Create a new mesh rest client. * * @param host * Server host * @param port * Server port * @param ssl * Flag which is used to toggle ssl mode * @return */ static MeshRestClient create(String host, int port, boolean ssl) { return create(new MeshRestClientConfig.Builder() .setHost(host) .setPort(port) .setSsl(ssl) .build()); } /** * Create a new mesh rest client. * * @param host * Server host * @return */ static MeshRestClient create(String host) { return create(new MeshRestClientConfig.Builder().setHost(host).build()); } /** * Create a new mesh rest client. * * @param config * Client configuration * @return */ static MeshRestClient create(MeshRestClientConfig config) { return new MeshRestOkHttpClientImpl(config); } /** * Create a new mesh rest client. * * @param config * Client configuration * @param client * Ok http client to be used * @return */ static MeshRestClient create(MeshRestClientConfig config, OkHttpClient client) { return new MeshRestOkHttpClientImpl(config, client); } /** * Set the login that is used to authenticate the requests. * * @param username * @param password * @return Fluent API */ MeshRestClient setLogin(String username, String password); /** * Set the login that is used to authenticate the requests. This will also set a new password when {@link #login()} is called. Should be used when the user * has to change the password. * * @param username * @param password * @return Fluent API */ MeshRestClient setLogin(String username, String password, String newPassword); /** * Close the client. */ void close(); /** * Set the API key. This is an alternative way for authentication. Use {@link #setLogin(String, String)} if you prefer to use regular JWT tokens. * * @param apiKey * @return Fluent API */ MeshRestClient setAPIKey(String apiKey); /** * Return the set api key from the client. * * @return */ String getAPIKey(); /** * Disable the anonymous access handling. Requests will only work if you are logged in. * * @return Fluent API */ MeshRestClient disableAnonymousAccess(); /** * Enable the anonymous access handling. Requests will work if anonymous access is enabled on the Gentics Mesh serve. * * @return Fluent API */ MeshRestClient enableAnonymousAccess(); /** * Set the authentication provider. * * @param authentication * @return Fluent API */ MeshRestClient setAuthenticationProvider(JWTAuthentication authentication); /** * Return the mesh version. * * @return */ public static String getPlainVersion() { return MeshVersion.getPlainVersion(); } /** * Return the JWT Authentication provider. * * @return */ JWTAuthentication getAuthentication(); /** * Return the config that was used to create this client. * @return */ MeshRestClientConfig getConfig(); }
{ "content_hash": "af28cbe8c0db0c81fc1397072b576bdf", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 161, "avg_line_length": 26.490322580645163, "alnum_prop": 0.7150511446663419, "repo_name": "gentics/mesh", "id": "adca4ef6beb46196a19a1955f5a2b70594324f09", "size": "4106", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "rest-client/src/main/java/com/gentics/mesh/rest/client/MeshRestClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "40221" }, { "name": "Dockerfile", "bytes": "5309" }, { "name": "Erlang", "bytes": "4651" }, { "name": "HTML", "bytes": "3848" }, { "name": "Handlebars", "bytes": "6515" }, { "name": "Java", "bytes": "9074233" }, { "name": "JavaScript", "bytes": "1130" }, { "name": "Shell", "bytes": "3757" } ], "symlink_target": "" }
<Alloy> <Window fullscreen="true" class="container" onOpen="onCourseDetailOpen"> <ScrollView id="scrollContainer"> <Label id="courseDetail"/> <TextField id="course_Name"/> <TextField id="course_description"/> <Label id="timing_Offered"/> <!--<View height="Ti.UI.SIZE" layout="vertical">--> <TextField id="courseTime1" class="textFieldClass"/> <TextField id="courseTime2" class="textFieldClass"/> <TextField id="courseTime3" class="textFieldClass"/> <TextField id="courseTime4" class="textFieldClass"/> <!--</View>--> <Label id="packages"/> <!--<View height="Ti.UI.SIZE" layout="vertical">--> <TextField id="courseTime5" class="textFieldClass"/> <TextField id="courseTime6" class="textFieldClass"/> <TextField id="courseTime7" class="textFieldClass"/> <TextField id="courseTime8" class="textFieldClass"/> <!--</View>--> </ScrollView> <Button id="submitCourses"/> </Window> </Alloy>
{ "content_hash": "3ee9b545f12bbc3f806ab5a4116a2043", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 73, "avg_line_length": 39.166666666666664, "alnum_prop": 0.675531914893617, "repo_name": "amits3108/tutme", "id": "65fede1ce7340ad838d62193791ca5a238be0138", "size": "940", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/views/authentication/addCourseDetail_old.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1276" }, { "name": "JavaScript", "bytes": "181389" }, { "name": "Python", "bytes": "5251" } ], "symlink_target": "" }
import { BaseEntity } from 'app/shared/model/base-entity'; import { Participation } from 'app/entities/participation/participation.model'; import { Result } from 'app/entities/result.model'; import dayjs from 'dayjs/esm'; export const enum SubmissionType { MANUAL = 'MANUAL', TIMEOUT = 'TIMEOUT', INSTRUCTOR = 'INSTRUCTOR', EXTERNAL = 'EXTERNAL', TEST = 'TEST', ILLEGAL = 'ILLEGAL', } // IMPORTANT NOTICE: The following strings have to be consistent with the ones defined in Submission.java export const enum SubmissionExerciseType { PROGRAMMING = 'programming', MODELING = 'modeling', QUIZ = 'quiz', TEXT = 'text', FILE_UPLOAD = 'file-upload', } export abstract class Submission implements BaseEntity { public id?: number; public submitted?: boolean; public submissionDate?: dayjs.Dayjs; public type?: SubmissionType; public exampleSubmission?: boolean; public submissionExerciseType?: SubmissionExerciseType; public durationInMinutes?: number; // results is initialized by the value the server returns public results?: Result[]; public participation?: Participation; // Helper Attributes // latestResult is undefined until setLatestSubmissionResult() is called public latestResult?: undefined | Result; // only used for exam to check if it is saved to server public isSynced?: boolean; // client-side property, shows the number of elements used in the example submission public submissionSize?: number; protected constructor(submissionExerciseType: SubmissionExerciseType) { this.submissionExerciseType = submissionExerciseType; this.submitted = false; // default value } } /** * Used to access the latest submissions result * * @param submission */ export function getLatestSubmissionResult(submission: Submission | undefined): Result | undefined { return submission?.results?.last(); } /** * Used to access a submissions result for a specific correctionRound * * @param submission * @param correctionRound * @returns the results or undefined if submission or the result for the requested correctionRound is undefined */ export function getSubmissionResultByCorrectionRound(submission: Submission | undefined, correctionRound: number): Result | undefined { if (submission?.results && submission?.results.length >= correctionRound) { return submission.results[correctionRound]; } return undefined; } /** * Used to access a submissions result for a specific id * * @param submission * @param resultId * @returns the results or undefined if submission or the result for the requested id is undefined */ export function getSubmissionResultById(submission: Submission | undefined, resultId: number): Result | undefined { return submission?.results?.find((result) => result.id === resultId); } /** * Used to set / override the latest result in the results list, and set / override the * var latestResult * * @param submission * @param result */ export function setLatestSubmissionResult(submission: Submission | undefined, result: Result | undefined) { if (!submission || !result) { return; } if (submission.results && submission.results.length > 0) { submission.results[submission.results.length - 1] = result; } else { submission.results = [result]; } // make sure relationship is correct result.submission = submission; submission.latestResult = result; } export function setSubmissionResultByCorrectionRound(submission: Submission, result: Result, correctionRound: number) { if (!submission || !result || !submission.results) { return; } submission.results[correctionRound] = result; if (submission.results.length === correctionRound + 1) { submission.latestResult = result; } } export function getFirstResult(submission: Submission | undefined): Result | undefined { if (submission?.results) { const length = submission.results.length; if (length > 0) { return submission.results[0]; } } } export function getFirstResultWithComplaintFromResults(results: Result[] | undefined): Result | undefined { if (results) { const resultsWithComplaint = results.filter((result) => result.hasComplaint); if (resultsWithComplaint.length > 0) { return resultsWithComplaint[0]; } } } export function getFirstResultWithComplaint(submission: Submission | undefined): Result | undefined { if (submission?.results) { const resultsWithComplaint = submission.results.filter((result) => result.hasComplaint); if (resultsWithComplaint.length > 0) { return resultsWithComplaint[0]; } } } export function reconnectSubmissions(submissions: Submission[]): void { return submissions.forEach((submission: Submission) => { // reconnect some associations const latestResult = getLatestSubmissionResult(submission); if (latestResult) { latestResult.submission = submission; latestResult.participation = submission.participation; submission.participation!.results = [latestResult!]; setLatestSubmissionResult(submission, latestResult); } }); }
{ "content_hash": "530c7c0cca8f198232dffc6efc44ae4f", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 135, "avg_line_length": 33.31875, "alnum_prop": 0.701369349090227, "repo_name": "ls1intum/ArTEMiS", "id": "4c9ca47f8a38e9eab051b4d30f9e1477a6a55494", "size": "5331", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/webapp/app/entities/submission.model.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "77977" }, { "name": "Dockerfile", "bytes": "587" }, { "name": "HTML", "bytes": "768360" }, { "name": "Java", "bytes": "1948478" }, { "name": "JavaScript", "bytes": "24198" }, { "name": "Python", "bytes": "623" }, { "name": "Scala", "bytes": "198707" }, { "name": "Shell", "bytes": "864" }, { "name": "TypeScript", "bytes": "2685315" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jordan-curve-theorem: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.1 / jordan-curve-theorem - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> jordan-curve-theorem <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-16 04:20:23 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-16 04:20:23 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/jordan-curve-theorem&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/JordanCurveTheorem&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: combinatorial hypermaps&quot; &quot;keyword: genus&quot; &quot;keyword: planarity&quot; &quot;keyword: Euler formula&quot; &quot;keyword: Discrete Jordan Curve Theorem&quot; &quot;category: Mathematics/Geometry/General&quot; &quot;date: 2008&quot; ] authors: [ &quot;Jean-François Dufourd &lt;dufourd@lsiit.u-strasbg.fr&gt; [http://dpt-info.u-strasbg.fr/~jfd/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/jordan-curve-theorem/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/jordan-curve-theorem.git&quot; synopsis: &quot;Hypermaps, planarity and discrete Jordan curve theorem&quot; description: &quot;&quot;&quot; http://dpt-info.u-strasbg.fr/~jfd/Downloads/JORDAN_Contrib_Coq.tar.gz Constructive formalization of the combinatorial hypermaps, characterization of the planarity, genus theorem, Euler formula, ring of faces, discrete Jordan curve theorem&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/jordan-curve-theorem/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=42157391127fc6af77f7d0dfa29f7e76&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-jordan-curve-theorem.8.6.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-jordan-curve-theorem -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.02.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-jordan-curve-theorem.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "cc9cddd1e2fbcfc3a24134c9ef5bd3af", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 272, "avg_line_length": 44.78698224852071, "alnum_prop": 0.5616329766151407, "repo_name": "coq-bench/coq-bench.github.io", "id": "8daaef0c6c5dfdf414a2e8501e04e3d8d09b2e95", "size": "7595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.8.1/jordan-curve-theorem/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package main import ( "fmt" "time" ) func setDate(d string, z *time.Location) error { return fmt.Errorf("Can not set the date") }
{ "content_hash": "5e7cd83a6565c5e6fbb7a16b927fa3f3", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 48, "avg_line_length": 13.5, "alnum_prop": 0.674074074074074, "repo_name": "hugelgupf/u-root", "id": "98f10db267f67ce67963de6c9cdd6eb1ea231b78", "size": "303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmds/core/date/date_plan9.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "2717" }, { "name": "C", "bytes": "598" }, { "name": "Dockerfile", "bytes": "11562" }, { "name": "Go", "bytes": "3924400" }, { "name": "Makefile", "bytes": "185" }, { "name": "Python", "bytes": "5194" }, { "name": "Shell", "bytes": "952" } ], "symlink_target": "" }
gonfq ===== Go wrapper around libnetfilter_queue
{ "content_hash": "9bf95de7ec88e5ef248384d6419dac6f", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 36, "avg_line_length": 12.5, "alnum_prop": 0.74, "repo_name": "zllak/gonfq", "id": "a19c2786eac1db447520cd4b1c3e5ef7110e0fd0", "size": "50", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "3817" } ], "symlink_target": "" }
from openerp.osv import osv,fields class company(osv.osv): _inherit = 'res.company' _columns = { 'schedule_range': fields.float('Scheduler Range Days', required=True, help="This is the time frame analysed by the scheduler when "\ "computing procurements. All procurements that are not between "\ "today and today+range are skipped for future computation."), } _defaults = { 'schedule_range': 730.0, } company() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
{ "content_hash": "71e708c7eb0ae2cd36b139d8816dfee8", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 77, "avg_line_length": 32.470588235294116, "alnum_prop": 0.6521739130434783, "repo_name": "ntiufalara/openerp7", "id": "60e2db873e235eb937d1f0b3a22f5657cb0ed9fb", "size": "1531", "binary": false, "copies": "55", "ref": "refs/heads/master", "path": "openerp/addons/procurement/company.py", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "9611" }, { "name": "C#", "bytes": "93691" }, { "name": "C++", "bytes": "108790" }, { "name": "CSS", "bytes": "583265" }, { "name": "Groff", "bytes": "8138" }, { "name": "HTML", "bytes": "125159" }, { "name": "JavaScript", "bytes": "5109152" }, { "name": "Makefile", "bytes": "14036" }, { "name": "NSIS", "bytes": "14114" }, { "name": "PHP", "bytes": "14033" }, { "name": "Python", "bytes": "9373763" }, { "name": "Ruby", "bytes": "220" }, { "name": "Shell", "bytes": "6430" }, { "name": "XSLT", "bytes": "156761" } ], "symlink_target": "" }
from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from payg import views from user import views as user_views router = routers.DefaultRouter() router.register(r'users-profile', user_views.UserProfileViewSet) router.register(r'users', user_views.UserViewSet) router.register(r'groups', user_views.GroupViewSet) urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^404/$', views.handler404, name='404'), url(r'^500/$', views.handler500, name='500'), # Admin url(r'^admin/', include(admin.site.urls)), # REST Views url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), # My Apps url(r'^account/', include('account.urls')), url(r'',include('contact.urls')), url(r'', include('user.urls')), ]
{ "content_hash": "bccfa49885ee315ab59274af1a6a7ec3", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 83, "avg_line_length": 31.678571428571427, "alnum_prop": 0.6820744081172492, "repo_name": "aronysidoro/django-payasyougo", "id": "0e032bb13913bfb6985c8fb9f3abf7510fcd4039", "size": "887", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "payg/payg/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "58298" }, { "name": "HTML", "bytes": "13469" }, { "name": "JavaScript", "bytes": "125423" }, { "name": "Python", "bytes": "94243" } ], "symlink_target": "" }
Reservoir::Reservoir( float p, float l, float h, float n ) : m_profondeur(p), m_largeur(l), m_hauteur(h), m_niveau(n) { } Reservoir::~Reservoir(){ } void Reservoir::operer( float duree ){ float tartre = calculerAccumulationTartre(duree, m_hauteur, m_profondeur*m_largeur); addTartre(tartre); } void Reservoir::nettoyer(){ removeTartre(); }
{ "content_hash": "38fee0a3dedc39281640dfce70ccd68b", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 85, "avg_line_length": 17.45, "alnum_prop": 0.6991404011461319, "repo_name": "KevPantelakis/turbo-giggle", "id": "858409fe242a9a89eece306889eb91d32471651a", "size": "649", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "AUT2016/LOG2410/tp5/TP5-A16/Code/Reservoir.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "6191" }, { "name": "C", "bytes": "84644" }, { "name": "C++", "bytes": "1402718" }, { "name": "CSS", "bytes": "3137" }, { "name": "HTML", "bytes": "8565" }, { "name": "Java", "bytes": "35781" }, { "name": "JavaScript", "bytes": "11279" }, { "name": "M4", "bytes": "12662" }, { "name": "Makefile", "bytes": "943715" }, { "name": "Python", "bytes": "8228" }, { "name": "QMake", "bytes": "2194" }, { "name": "Roff", "bytes": "1310606" }, { "name": "SQLPL", "bytes": "5580" }, { "name": "Shell", "bytes": "2843290" } ], "symlink_target": "" }
from __future__ import unicode_literals import os import json from nikola.plugin_categories import Task from nikola import utils class ProjectPages(Task): """Render project indexes.""" name = 'projectpages' dates = {} conf_project_path = 'projects' def set_site(self, site): """Set Nikola site.""" site.register_path_handler('project', self.project_path) self.conf_project_path = site.config.get('PROJECT_PATH', 'projects') site._GLOBAL_CONTEXT['project_path'] = self.conf_project_path site._GLOBAL_CONTEXT['project_index'] = {} for lang, tpath in site.config['TRANSLATIONS'].items(): site._GLOBAL_CONTEXT['project_index'][lang] = '/' + os.path.join(tpath, self.conf_project_path, site.config['INDEX_FILE']).replace('\\', '/') # If you want to use breadcrumbs as provided by the crumbs template: # def project_breadcrumbs(p, lang, translations, project_path): # return (('/' + os.path.join(translations[lang], project_path, 'index.html').replace('\\', '/'), "Projects"), (p.permalink(), p.title())) # site._GLOBAL_CONTEXT['project_breadcrumbs'] = project_breadcrumbs return super(ProjectPages, self).set_site(site) def project_path(self, name, lang): """Generate links to project pages.""" return [_f for _f in self.projects[name].permalink(lang).split('/') if _f] def is_project(self, p): """Test projecthood of a page.""" return p.destination_path(lang=self.kw['default_lang']).startswith(self.conf_project_path) def find_projects(self): """Find all projects.""" self._projects = [p for p in self.site.timeline if self.is_project(p)] @property def projects(self): """Look for projects if we haven’t already.""" try: return self._projects except AttributeError: self.find_projects() return self._projects def generate_json(self, jdst, lang): """Generate a JSON file with all project data.""" data = {} for p in self.projects: data[p.meta[lang]['slug']] = p.meta[lang] del data[p.meta[lang]['slug']]['date'] if 'tags' in data[p.meta[lang]['slug']]: del data[p.meta[lang]['slug']]['tags'] if 'hyphenate' in data[p.meta[lang]['slug']]: del data[p.meta[lang]['slug']]['hyphenate'] data[p.meta[lang]['slug']]['permalink'] = p.permalink(lang) data[p.meta[lang]['slug']]['text'] = p.text(lang) with open(jdst, 'w') as fh: json.dump(data, fh, sort_keys=True, indent=4, separators=(',', ': ')) def gen_tasks(self): """Render project list.""" self.image_ext_list = ['.jpg', '.png', '.jpeg', '.gif', '.svg', '.bmp', '.tiff'] self.image_ext_list.extend(self.site.config.get('EXTRA_IMAGE_EXTENSIONS', [])) self.kw = { 'project_path': self.conf_project_path, 'index_file': self.site.config['INDEX_FILE'], 'strip_indexes': self.site.config['STRIP_INDEXES'], 'output_folder': self.site.config['OUTPUT_FOLDER'], 'cache_folder': self.site.config['CACHE_FOLDER'], 'default_lang': self.site.config['DEFAULT_LANG'], 'filters': self.site.config['FILTERS'], 'translations': self.site.config['TRANSLATIONS'], 'global_context': self.site.GLOBAL_CONTEXT, 'tzinfo': self.site.tzinfo, } for k, v in self.site.GLOBAL_CONTEXT['template_hooks'].items(): self.kw['||template_hooks|{0}||'.format(k)] = v._items yield self.group_task() template_name = "projects.tmpl" self.site.scan_posts() self.find_projects() # Create index.html for each language for lang in self.kw['translations']: # save navigation links as dependencies self.kw['navigation_links|{0}'.format(lang)] = self.kw['global_context']['navigation_links'](lang) short_tdst = os.path.join(self.kw['translations'][lang], self.kw['project_path'], self.kw['index_file']) short_jdst = os.path.join(self.kw['translations'][lang], self.kw['project_path'], 'projects.json') tdst = os.path.normpath(os.path.join(self.kw['output_folder'], short_tdst)) jdst = os.path.normpath(os.path.join(self.kw['output_folder'], short_jdst)) context = {} context["lang"] = lang # TODO: tranlsations? context["title"] = "Projects" context["description"] = None def sortf(p): return ((-int(p.meta('sort')) if p.meta('sort') != '' else -1), p.title()) context["featured"] = sorted((p for p in self.projects if p.meta('featured') not in ('False', '0', 'false', 'no', '')), key=sortf) context["projects"] = sorted((p for p in self.projects if p.meta('hidden') not in ('False', '0', 'false', 'no')), key=sortf) link = short_tdst.replace('\\', '/') index_len = len(self.kw['index_file']) if self.kw['strip_indexes'] and link[-(1 + index_len):] == '/' + self.kw['index_file']: link = link[:-index_len] context["permalink"] = '/' + link context["pagekind"] = ['projectpages'] all_meta = [(p.title(), p.meta('status')) for p in self.projects] all_meta += [p.meta('previewimage') for p in context["featured"]] all_meta += [p.source_path for p in context["featured"]] template_dep = self.site.template_system.template_deps(template_name) file_dep = [] for p in self.projects: file_dep += [p.translated_base_path(l) for l in self.kw['translations'] if l in p.translated_to] yield utils.apply_filters({ 'basename': self.name, 'name': tdst, 'file_dep': file_dep + template_dep, 'targets': [tdst], 'actions': [ (self.site.render_template, (template_name, tdst, context))], 'clean': True, 'uptodate': [utils.config_changed({ 1: self.kw, 2: all_meta, }, 'projectpages:html:' + tdst)], }, self.kw['filters']) yield utils.apply_filters({ 'basename': self.name, 'name': jdst, 'file_dep': file_dep, 'targets': [jdst], 'actions': [(self.generate_json, (jdst, lang))], 'clean': True, 'uptodate': [utils.config_changed({ 1: self.kw, 2: all_meta, }, 'projectpages:json:' + jdst)], }, self.kw['filters'])
{ "content_hash": "7f5e11e4e5d5e86b301a4f50f1389c4c", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 153, "avg_line_length": 42.109756097560975, "alnum_prop": 0.5454677092383434, "repo_name": "getnikola/plugins", "id": "3b1a6df02d0c5017eb19454923099a80931f13ed", "size": "8041", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v7/projectpages/projectpages.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8729" }, { "name": "Emacs Lisp", "bytes": "8804" }, { "name": "HTML", "bytes": "2470" }, { "name": "JavaScript", "bytes": "41087" }, { "name": "Python", "bytes": "1157045" }, { "name": "TeX", "bytes": "844" } ], "symlink_target": "" }
package com.eddienicole.checkers; public interface MoveInterface { @Override boolean equals(Object obj); PlayableSpaceInterface getFrom(); PlayableSpaceInterface getJumped(); PlayableSpaceInterface getTo(); boolean isJump(); void jumped(PlayableSpaceInterface jumpedSpace); }
{ "content_hash": "2e9dafe06c4fc3f32407ce4439d78b75", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 49, "avg_line_length": 17.166666666666668, "alnum_prop": 0.7443365695792881, "repo_name": "power-cosmic/cosc561_checkers", "id": "5eaa29e7928d7bd92ed5cf3a863802f9b9d8c540", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "checkers/src/com/eddienicole/checkers/MoveInterface.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "80902" } ], "symlink_target": "" }
flumen - Fluid jQuery Carousel This is a super simple responsive carousel plugin that doesn't snap to the slides. I've seen a lot of feature requests on already existing carousel plugins asking for a free flowing carousel, so I've decided to make one. **[DEMO](https://stamat.github.io/flumen/ "Demo")** The distinct features of this carousel are: * **Free flowing** - doesn't snap to slides * Centering mode - slides can bleed out the edges and the container doesn't have to have a predefined size, nor the slides have to be the same width * **Uses CSS3 for slide placement** - instead of calculating the pane width depending on the sum of slides size, and leans onto scroll feature instead of constantly managing, this enables all sorts of freedoms, like not having to worry about the size of the slides and it's container, and we didn't have to add multiple <div/> wrappers to enable the positioning * **Naturally responsive** - There is no need for implementing responsive breakpoints since the positions are recalculated on every window resize ## Dependencies * jQuery 1.8+ - https://github.com/jquery/jquery * jQuery.kinetic - https://github.com/davetayls/jquery.kinetic * jquery-mousewheel [optional] - https://github.com/jquery/jquery-mousewheel ## Tested on * IE 10 and 11 * Firefox 12 and 46 * iOS 8.3 Safari (iPhone 4s) * iOS 10.3 Safari (iPhone 5s) * Google Chrome 56 **Doesn't work on**: IE 9 and below, I might add the support for them in the future, if I'm ever bored in life... haha! :P ## Usage $('.selector').flumen({ arrows: true //example option }); ## Options There are some currently in development options. The first version of this jQuery plugin supports only the features it was specifically designed for. Future updates will bring several switches that will enable this carousel to work like all the other carousel with addition of it's distinct features. 'margin' [default: 0] - sets spacing between the slides 'loop' [default: true] //in development 'center' [default: true] //in development 'fluid' [default: true] //in development 'arrows' [default: false] //in development 'dots' [default: false] //in development 'mousewheel' [default: true] - enables jquery-mousewheel events, this makes a mess on OSX thought with their swipe between pages 'speed' [default: 300] - goTo, Left and Right movement animation speed 'resize_timeout' [default: 200] - prevent multiple resize events to be fired ## Functons $('.selector').trigger('flumen.next'); $('.selector').trigger('flumen.prev'); $('.selector').trigger('flumen.goto', slide_number); $('.selector').trigger('flumen.recalc'); - after the images load you can recalculate the positions, this function happens on each window resize $('.selector').trigger('flumen.remove'); //in development - should remove all the bindings of Flumen ## Events 'flumen.start' - reaches the start 'flumen.end' - reaches the end 'flumen.stop' - scroll stops 'flumen.beforechange' - before the slide changes on next or prev or goto 'flumen.afterchange' - after the slide changes on next or prev or goto 'flumen.slide' - slide comes into focus 'flumen.beforeresize' - is triggered before the recalculation 'flumen.afterresize' - is triggered before the recalculation ## Issues There are couple of minor issues, and couple of things I was limited with time to do right. So expect the unexpected, and be kind to report the issues: [https://github.com/stamat/flumen/issues](https://github.com/stamat/flumen/issues) ## Name Flumen, Fluminis - River or Flowing Fluid on Latin Fauré: Super Flumina Babylonis https://www.youtube.com/watch?v=7LCsLDgapFc
{ "content_hash": "fbef349bdba29ffe6fd53ca0f6e35786", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 361, "avg_line_length": 38.597938144329895, "alnum_prop": 0.7305021367521367, "repo_name": "stamat/flumen", "id": "dab2f52a4ff47fa1aacac309cfec4fa1a136c104", "size": "3754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1028" }, { "name": "HTML", "bytes": "3953" }, { "name": "JavaScript", "bytes": "54125" } ], "symlink_target": "" }
'use strict'; const chai = require('chai'), expect = chai.expect, Support = require('./support'), Sequelize = Support.Sequelize, Promise = Sequelize.Promise, cls = require('continuation-local-storage'), current = Support.sequelize; if (current.dialect.supports.transactions) { describe(Support.getTestDialectTeaser('Continuation local storage'), () => { before(function() { this.thenOriginal = Promise.prototype.then; Sequelize.useCLS(cls.createNamespace('sequelize')); }); after(() => { delete Sequelize._cls; }); beforeEach(function() { return Support.prepareTransactionTest(this.sequelize).then(sequelize => { this.sequelize = sequelize; this.ns = cls.getNamespace('sequelize'); this.User = this.sequelize.define('user', { name: Sequelize.STRING }); return this.sequelize.sync({ force: true }); }); }); describe('context', () => { it('does not use continuation storage on manually managed transactions', function() { return Sequelize._clsRun(() => { return this.sequelize.transaction().then(transaction => { expect(this.ns.get('transaction')).to.be.undefined; return transaction.rollback(); }); }); }); it('supports several concurrent transactions', function() { let t1id, t2id; return Promise.join( this.sequelize.transaction(() => { t1id = this.ns.get('transaction').id; return Promise.resolve(); }), this.sequelize.transaction(() => { t2id = this.ns.get('transaction').id; return Promise.resolve(); }), () => { expect(t1id).to.be.ok; expect(t2id).to.be.ok; expect(t1id).not.to.equal(t2id); } ); }); it('supports nested promise chains', function() { return this.sequelize.transaction(() => { const tid = this.ns.get('transaction').id; return this.User.findAll().then(() => { expect(this.ns.get('transaction').id).to.be.ok; expect(this.ns.get('transaction').id).to.equal(tid); }); }); }); it('does not leak variables to the outer scope', function() { // This is a little tricky. We want to check the values in the outer scope, when the transaction has been successfully set up, but before it has been comitted. // We can't just call another function from inside that transaction, since that would transfer the context to that function - exactly what we are trying to prevent; let transactionSetup = false, transactionEnded = false; this.sequelize.transaction(() => { transactionSetup = true; return Promise.delay(500).then(() => { expect(this.ns.get('transaction')).to.be.ok; transactionEnded = true; }); }); return new Promise(resolve => { // Wait for the transaction to be setup const interval = setInterval(() => { if (transactionSetup) { clearInterval(interval); resolve(); } }, 200); }).then(() => { expect(transactionEnded).not.to.be.ok; expect(this.ns.get('transaction')).not.to.be.ok; // Just to make sure it didn't change between our last check and the assertion expect(transactionEnded).not.to.be.ok; }); }); it('does not leak variables to the following promise chain', function() { return this.sequelize.transaction(() => { return Promise.resolve(); }).then(() => { expect(this.ns.get('transaction')).not.to.be.ok; }); }); it('does not leak outside findOrCreate', function() { return this.User.findOrCreate({ where: { name: 'Kafka' }, logging(sql) { if (/default/.test(sql)) { throw new Error('The transaction was not properly assigned'); } } }).then(() => { return this.User.findAll(); }); }); }); describe('sequelize.query integration', () => { it('automagically uses the transaction in all calls', function() { return this.sequelize.transaction(() => { return this.User.create({ name: 'bob' }).then(() => { return Promise.all([ expect(this.User.findAll({ transaction: null })).to.eventually.have.length(0), expect(this.User.findAll({})).to.eventually.have.length(1) ]); }); }); }); }); it('bluebird patch is applied', function() { expect(Promise.prototype.then).to.be.a('function'); expect(this.thenOriginal).to.be.a('function'); expect(Promise.prototype.then).not.to.equal(this.thenOriginal); }); it('CLS namespace is stored in Sequelize._cls', function() { expect(Sequelize._cls).to.equal(this.ns); }); it('promises returned by sequelize.query are correctly patched', function() { return this.sequelize.transaction(t => this.sequelize.query('select 1', {type: Sequelize.QueryTypes.SELECT}) .then(() => expect(this.ns.get('transaction')).to.equal(t)) ); }); }); }
{ "content_hash": "a2ef4138b2e3289df5969353d0c5e772", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 172, "avg_line_length": 32.8969696969697, "alnum_prop": 0.5585851142225498, "repo_name": "mikeringrose/sequelize", "id": "c2191ddba4b0064cae1240f32e1a72b122525c06", "size": "5428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/integration/cls.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "100" }, { "name": "JavaScript", "bytes": "3008827" }, { "name": "PowerShell", "bytes": "1468" } ], "symlink_target": "" }
package com.github.devmix.esb.car.plugin.builders; import com.github.devmix.esb.car.plugin.Constants; import org.apache.maven.plugin.MojoFailureException; /** * @author Sergey Grachev */ public final class SynapseConfigArtifactsBuilderTest { public static void main(String[] args) throws MojoFailureException { final ArtifactsListBuilder artifactsListBuilder = new ArtifactsListBuilder(); final String configDir = SynapseConfigArtifactsBuilderTest.class.getResource("/synapse-config") .getFile().substring(1); SynapseConfigArtifactsBuilder.newInstance() .artifactsList(artifactsListBuilder) .outputDirectory("F:\\wso2\\maven-car-plugin\\out") .configDir(configDir) .serverRole(Constants.SERVER_ROLE_ENTERPRISE_SERVICE_BUS) .version("1.0.0") .build(); System.out.println(artifactsListBuilder); } }
{ "content_hash": "71d646ad1f0ace93cda0be7ed35496d1", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 103, "avg_line_length": 34.214285714285715, "alnum_prop": 0.6774530271398748, "repo_name": "devmix/maven-car-plugin", "id": "7f4f11cb418533bd276e21834049720c907c19ec", "size": "1832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/github/devmix/esb/car/plugin/builders/SynapseConfigArtifactsBuilderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17" }, { "name": "Java", "bytes": "53248" } ], "symlink_target": "" }
require 'spec_helper' describe FbGraph2::Edge::OpenGraph::Actions do context 'included in User' do describe '#og_actions' do let(:me) { FbGraph2::User.me('token') } it 'should return an Array of FbGraph2::Post' do actions = mock_graph :get, 'me/og.likes', 'user/og_actions_likes', access_token: 'token' do me.og_actions 'og.likes' end actions.should be_instance_of FbGraph2::Edge actions.should_not be_blank actions.each do |action| action.should be_instance_of FbGraph2::OpenGraph::Action end end end describe '#og_action!' do let(:user) { FbGraph2::User.new('user_id') } it 'should return a FbGraph2::Post' do mock_graph :post, 'user_id/og.likes', 'success_with_id', access_token: 'app_token' do user.authenticate('app_token').og_action! 'og.likes', object: 'https://github.com/nov/fb_graph2/' end.should be_instance_of FbGraph2::OpenGraph::Action end end end end
{ "content_hash": "f7807eb9d595dbb571fe9dabbecdcae7", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 107, "avg_line_length": 36.357142857142854, "alnum_prop": 0.6277013752455796, "repo_name": "jurriaan/fb_graph2", "id": "8d0ad425e99237e64f3fa9c3010bd518c4e345a6", "size": "1018", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/fb_graph2/edge/open_graph/actions_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "151058" } ], "symlink_target": "" }
<?php namespace Chamilo\Core\Repository\ContentObject\Bookmark\Common\Rendition\Html; use Chamilo\Core\Repository\Common\Rendition\ContentObjectRendition; use Chamilo\Core\Repository\ContentObject\Bookmark\Common\Rendition\HtmlRenditionImplementation; class HtmlDescriptionRenditionImplementation extends HtmlRenditionImplementation { public function render() { return ContentObjectRendition::launch($this); } public function get_description() { $object = $this->get_content_object(); return '<div class="bookmark_url" style="margin-top: 1em;"><a target="about:blank" href="' . htmlentities($object->get_url()) . '">' . htmlentities($object->get_url()) . '</a></div>'; } }
{ "content_hash": "d0f9cd4c369938f0f7601d7f5676a801", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 103, "avg_line_length": 35.142857142857146, "alnum_prop": 0.7113821138211383, "repo_name": "cosnicsTHLU/cosnics", "id": "c763080f0f521eb20662d35955e360c3bcfe8329", "size": "738", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/Chamilo/Core/Repository/ContentObject/Bookmark/Common/Rendition/Html/HtmlDescriptionRenditionImplementation.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "86189" }, { "name": "C#", "bytes": "23363" }, { "name": "CSS", "bytes": "1135928" }, { "name": "CoffeeScript", "bytes": "17503" }, { "name": "Gherkin", "bytes": "24033" }, { "name": "HTML", "bytes": "542339" }, { "name": "JavaScript", "bytes": "5296016" }, { "name": "Makefile", "bytes": "3221" }, { "name": "PHP", "bytes": "21903304" }, { "name": "Ruby", "bytes": "618" }, { "name": "Shell", "bytes": "6385" }, { "name": "Smarty", "bytes": "15750" }, { "name": "XSLT", "bytes": "44115" } ], "symlink_target": "" }
"""This module contains the PandocMutagen class. """ import subprocess, sys from baseMutagen import BaseMutagen class PandocMutagenException(Exception): pass class PandocOptions: """A simple options class for configuring a PandocMutagen """ def __init__(self, **kwargs): """Setup defaults if they aren't already in kwargs. Ignore invalid options. """ # options self.read = kwargs.setdefault('read', 'markdown') self.write = kwargs.setdefault('write', 'html') self.output = kwargs.setdefault('output', '-') self.id_prefix = kwargs.setdefault('id-prefix', '') self.css = kwargs.setdefault('css', 'style.css') self.title_prefix = kwargs.setdefault('title-prefix', '') self.email_obfuscation = kwargs.setdefault('email-obfuscation', 'javascript') # flags self.standalone = kwargs.setdefault('standalone', True) self.smart = kwargs.setdefault('smart', False) self.incremental = kwargs.setdefault('incremental', False) self.number_sections = kwargs.setdefault('number-sections', False) self.no_wrap = kwargs.setdefault('no-wrap', False) self.table_of_contents = kwargs.setdefault('table-of-contents', True) self._setTables() def _setTables(self): """list of valid options and flags for the iterator """ self.OPTIONS = { 'read': self.read, 'write': self.write, 'output': self.output, 'id-prefix': self.id_prefix, 'css': self.css, 'title-prefix': self.title_prefix, 'email-obfuscation': self.email_obfuscation } self.FLAGS = { 'standalone': self.standalone, 'smart': self.smart, 'incremental': self.incremental, 'number-sections': self.number_sections, 'no-wrap': self.no_wrap, 'table-of-contents': self.table_of_contents, } def __iter__(self): self._setTables() items = self.OPTIONS.items() items.extend(self.FLAGS.items()) return items.__iter__() def __str__(self): self._setTables() cmdStr = '' for name, opt in self: if name in self.OPTIONS.keys(): if (name in ['id-prefix', 'title-prefix']) and opt == '': continue cmdStr += '--%s %s ' % (name, opt) elif opt and (name in self.FLAGS.keys()): cmdStr += '--%s ' % name return cmdStr class PandocMutagen(BaseMutagen): """Provide a simple interface to the pandoc markup translation tool. """ def __init__(self, inFname = '', outFname = '', options = PandocOptions(), executable = '/usr/bin/pandoc'): self.inFname = inFname self.outFname = outFname self.executable = executable self.options = options self.options.output = self.outFname def do(self): """ run the mutagen to create an effect """ command = '%s %s %s' % (self.executable, self.options, self.inFname) proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if stdout: sys.stdout.write(stdout + '\n') if stderr: raise PandocMutagenException('Error processing %s: %s' % (self.inFname, stderr)) result = 'failure' if proc.returncode == 0: result = 'success' sys.stdout.write('Processed File: %s: %s\n' % (self.inFname, result)) ## Functions for direct use of this module def usage(): print "Usage: pandocMutagen.py [inFname] [outFname]" def sanitizePath(path): return os.path.realpath(os.path.expanduser(path)) def main(argv): argv.pop(0) if len(argv) != 2: usage() return 1 inFname = sanitizePath(argv[0]) outFname = sanitizePath(argv[1]) mutagen = PandocMutagen(inFname, outFname) mutagen.do() return 0 if __name__=="__main__": import os.path sys.exit(main(sys.argv))
{ "content_hash": "4d274e48ba1cf64bf86b68ab3aa98746", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 100, "avg_line_length": 35.13934426229508, "alnum_prop": 0.56333100069979, "repo_name": "fretboardfreak/code", "id": "18674d6fedb9cfae3070a91bb982ee316dee8406", "size": "4309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "abandoned/webspring/mutagens/pandocMutagen.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "649" }, { "name": "C++", "bytes": "1599" }, { "name": "CSS", "bytes": "83144" }, { "name": "HTML", "bytes": "11830" }, { "name": "Java", "bytes": "379" }, { "name": "JavaScript", "bytes": "19508" }, { "name": "Makefile", "bytes": "1150" }, { "name": "PHP", "bytes": "3691" }, { "name": "Perl", "bytes": "1063" }, { "name": "Python", "bytes": "273951" }, { "name": "Shell", "bytes": "81945" } ], "symlink_target": "" }
package com.example.juanma.twessfer; import android.app.DialogFragment; import android.app.FragmentTransaction; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import twitter4j.Twitter; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; interface TweetCallback { void onUserLists( ArrayList<twitter4j.UserList> lists); void postRows(ArrayList<Tweet> rows); int currentPage(); void postAuthenticationUrl(String url); void postRequestToken(RequestToken token); void postAccessToken(AccessToken token); void authenticationFinished(); } public class MainActivity extends AppCompatActivity implements TweetCallback, PingDialogFragment.PingDialogListener { static final int OAUTH_REQUEST = 1; private String CONSUMER_KEY = ""; private String CONSUMER_SECRET = ""; final String tokenFile = ".connection"; public Context context; public Menu mainMenu; public Twitter twitter; public TweetAdapter adapter; private RequestToken requestToken = new RequestToken("",""); private AccessToken accessToken = new AccessToken("",""); public Long currentlistId = 0L; public int page = 1; private ArrayList<twitter4j.UserList> userlists = new ArrayList<>(); ProgressDialog progress; public void startProgressDialog(String title, String message) { progress = ProgressDialog.show(this, title, message, true); } public void closeProgressDialog() { progress.dismiss(); } @Override public int currentPage() { return page; } @Override public void onUserLists( ArrayList<twitter4j.UserList> lists) { closeProgressDialog(); userlists = lists; int count = 0; for (twitter4j.UserList list : lists) { String name = list.getName(); mainMenu.add(Menu.NONE, count++, Menu.NONE, name); } } @Override public void postRows(ArrayList<Tweet> rows) { closeProgressDialog(); if (rows.size() > 0) { adapter.addAll(rows); page++; } } @Override public void postRequestToken(RequestToken token) { requestToken = token; } @Override public void postAccessToken(AccessToken token) { accessToken = token; // Save Authentication token for future use writeAccessToken(tokenFile, accessToken); } @Override public void postAuthenticationUrl(String url) { if (url != "") { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivityForResult(browserIntent, OAUTH_REQUEST); } } @Override public void authenticationFinished() { // Fill menu with user lists getLists(); } @Override public boolean onCreateOptionsMenu(Menu menu) { mainMenu = menu; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, mainMenu); return super.onCreateOptionsMenu(mainMenu); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); CONSUMER_KEY = getString(R.string.CONSUMER_KEY); CONSUMER_SECRET = getString(R.string.CONSUMER_SECRET); context = this; ArrayList<Tweet> rows = new ArrayList<>(); ListView listView = (ListView) findViewById(R.id.tweet_list); adapter = new TweetAdapter(context, rows); listView.setAdapter(adapter); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view,int scrollState) {} @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int lastInScreen = firstVisibleItem + visibleItemCount; if ( totalItemCount != 0 && (lastInScreen == totalItemCount) ) { if (currentlistId > 0) new ListTimeline(currentlistId, (TweetCallback)context).execute(twitter); else new HomeTimeline((TweetCallback)context).execute(twitter); } } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) { Intent intent = new Intent(context, DisplayStatusActivity.class); Tweet currentTweet = adapter.getItem(pos); Globals.getInstance().setCurrentTweet(currentTweet); startActivity(intent); Log.v("long clicked","pos: " + pos); return true; } }); twitter = TwitterFactory.getSingleton(); //Set consumer key, consumer secret twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); // Get token from file, if any AccessToken accessToken = readAccessToken(tokenFile); if ( !accessToken.getToken().isEmpty() && !accessToken.getTokenSecret().isEmpty() ) { //not empty twitter.setOAuthAccessToken(accessToken); authenticationFinished(); } else { // Enter Pin Dialog openPinDlg(); // Authentication with OAuth new URLRequester(this).execute(twitter); } } private void getLists(){ // Get lists startProgressDialog("", ""); new ListReader(this).execute(twitter); } private void openPinDlg() { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.addToBackStack(null); DialogFragment dialog = new PingDialogFragment(); dialog.show(ft,"PingDialogFragment"); } @Override public void onDialogPositiveClick(DialogFragment dialog, String pin) { if (!pin.isEmpty()) { new SetAccessToken(this,requestToken,pin).execute(twitter); } } @Override public void onDialogNegativeClick(DialogFragment dialog) { } private void fillList(twitter4j.UserList list) { //Clean existing entries, if any page=1; adapter.clear(); adapter.notifyDataSetChanged(); currentlistId = list.getId(); startProgressDialog("",list.getName()); new ListTimeline(currentlistId,(TweetCallback) context ).execute(twitter); } private void timeline() { //Clean existing entries, if any page = 1; currentlistId = 0L; adapter.clear(); adapter.notifyDataSetChanged(); startProgressDialog("","Timeline"); new HomeTimeline((TweetCallback)context).execute(twitter); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_login: // User chose the "Settings" item, show the app settings UI... return true; case R.id.action_timeline: timeline(); return true; default: int pos = item.getItemId(); twitter4j.UserList list = userlists.get(pos); fillList(list); return true; // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. //return super.onOptionsItemSelected(item); } } private AccessToken readAccessToken(String filename) { try { FileInputStream input = openFileInput(filename); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String token = reader.readLine(); String tokenSecret = reader.readLine(); return new AccessToken(token,tokenSecret); } catch (Exception e) { e.printStackTrace(); } return new AccessToken("",""); } private void writeAccessToken(String filename, AccessToken token) { final String aToken = token.getToken(); final String aTokenSecret = token.getTokenSecret(); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filename, Context.MODE_PRIVATE)); outputStreamWriter.write(aToken); outputStreamWriter.write("\n"); outputStreamWriter.write(aTokenSecret); outputStreamWriter.close(); } catch (Exception e) { e.printStackTrace(); } } }
{ "content_hash": "f89f12c44d28a308ff6f4d7162cc082e", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 131, "avg_line_length": 29.61111111111111, "alnum_prop": 0.6282051282051282, "repo_name": "juanmahv/Twessfer", "id": "fd48199615b16a6d5ca3c38387af55f1b33c20e8", "size": "9594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/example/juanma/twessfer/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "26057" } ], "symlink_target": "" }
*> \brief \b DLA_GERFSX_EXTENDED improves the computed solution to a system of linear equations for general matrices by performing extra-precise iterative refinement and provides error bounds and backward error estimates for the solution. * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download DLA_GERFSX_EXTENDED + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dla_gerfsx_extended.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dla_gerfsx_extended.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dla_gerfsx_extended.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE DLA_GERFSX_EXTENDED( PREC_TYPE, TRANS_TYPE, N, NRHS, A, * LDA, AF, LDAF, IPIV, COLEQU, C, B, * LDB, Y, LDY, BERR_OUT, N_NORMS, * ERRS_N, ERRS_C, RES, AYB, DY, * Y_TAIL, RCOND, ITHRESH, RTHRESH, * DZ_UB, IGNORE_CWISE, INFO ) * * .. Scalar Arguments .. * INTEGER INFO, LDA, LDAF, LDB, LDY, N, NRHS, PREC_TYPE, * $ TRANS_TYPE, N_NORMS, ITHRESH * LOGICAL COLEQU, IGNORE_CWISE * DOUBLE PRECISION RTHRESH, DZ_UB * .. * .. Array Arguments .. * INTEGER IPIV( * ) * DOUBLE PRECISION A( LDA, * ), AF( LDAF, * ), B( LDB, * ), * $ Y( LDY, * ), RES( * ), DY( * ), Y_TAIL( * ) * DOUBLE PRECISION C( * ), AYB( * ), RCOND, BERR_OUT( * ), * $ ERRS_N( NRHS, * ), ERRS_C( NRHS, * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> *> DLA_GERFSX_EXTENDED improves the computed solution to a system of *> linear equations by performing extra-precise iterative refinement *> and provides error bounds and backward error estimates for the solution. *> This subroutine is called by DGERFSX to perform iterative refinement. *> In addition to normwise error bound, the code provides maximum *> componentwise error bound if possible. See comments for ERRS_N *> and ERRS_C for details of the error bounds. Note that this *> subroutine is only resonsible for setting the second fields of *> ERRS_N and ERRS_C. *> \endverbatim * * Arguments: * ========== * *> \param[in] PREC_TYPE *> \verbatim *> PREC_TYPE is INTEGER *> Specifies the intermediate precision to be used in refinement. *> The value is defined by ILAPREC(P) where P is a CHARACTER and *> P = 'S': Single *> = 'D': Double *> = 'I': Indigenous *> = 'X', 'E': Extra *> \endverbatim *> *> \param[in] TRANS_TYPE *> \verbatim *> TRANS_TYPE is INTEGER *> Specifies the transposition operation on A. *> The value is defined by ILATRANS(T) where T is a CHARACTER and *> T = 'N': No transpose *> = 'T': Transpose *> = 'C': Conjugate transpose *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of linear equations, i.e., the order of the *> matrix A. N >= 0. *> \endverbatim *> *> \param[in] NRHS *> \verbatim *> NRHS is INTEGER *> The number of right-hand-sides, i.e., the number of columns of the *> matrix B. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is DOUBLE PRECISION array, dimension (LDA,N) *> On entry, the N-by-N matrix A. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,N). *> \endverbatim *> *> \param[in] AF *> \verbatim *> AF is DOUBLE PRECISION array, dimension (LDAF,N) *> The factors L and U from the factorization *> A = P*L*U as computed by DGETRF. *> \endverbatim *> *> \param[in] LDAF *> \verbatim *> LDAF is INTEGER *> The leading dimension of the array AF. LDAF >= max(1,N). *> \endverbatim *> *> \param[in] IPIV *> \verbatim *> IPIV is INTEGER array, dimension (N) *> The pivot indices from the factorization A = P*L*U *> as computed by DGETRF; row i of the matrix was interchanged *> with row IPIV(i). *> \endverbatim *> *> \param[in] COLEQU *> \verbatim *> COLEQU is LOGICAL *> If .TRUE. then column equilibration was done to A before calling *> this routine. This is needed to compute the solution and error *> bounds correctly. *> \endverbatim *> *> \param[in] C *> \verbatim *> C is DOUBLE PRECISION array, dimension (N) *> The column scale factors for A. If COLEQU = .FALSE., C *> is not accessed. If C is input, each element of C should be a power *> of the radix to ensure a reliable solution and error estimates. *> Scaling by powers of the radix does not cause rounding errors unless *> the result underflows or overflows. Rounding errors during scaling *> lead to refining with a matrix that is not equivalent to the *> input matrix, producing error estimates that may not be *> reliable. *> \endverbatim *> *> \param[in] B *> \verbatim *> B is DOUBLE PRECISION array, dimension (LDB,NRHS) *> The right-hand-side matrix B. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> The leading dimension of the array B. LDB >= max(1,N). *> \endverbatim *> *> \param[in,out] Y *> \verbatim *> Y is DOUBLE PRECISION array, dimension *> (LDY,NRHS) *> On entry, the solution matrix X, as computed by DGETRS. *> On exit, the improved solution matrix Y. *> \endverbatim *> *> \param[in] LDY *> \verbatim *> LDY is INTEGER *> The leading dimension of the array Y. LDY >= max(1,N). *> \endverbatim *> *> \param[out] BERR_OUT *> \verbatim *> BERR_OUT is DOUBLE PRECISION array, dimension (NRHS) *> On exit, BERR_OUT(j) contains the componentwise relative backward *> error for right-hand-side j from the formula *> max(i) ( abs(RES(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) ) *> where abs(Z) is the componentwise absolute value of the matrix *> or vector Z. This is computed by DLA_LIN_BERR. *> \endverbatim *> *> \param[in] N_NORMS *> \verbatim *> N_NORMS is INTEGER *> Determines which error bounds to return (see ERRS_N *> and ERRS_C). *> If N_NORMS >= 1 return normwise error bounds. *> If N_NORMS >= 2 return componentwise error bounds. *> \endverbatim *> *> \param[in,out] ERRS_N *> \verbatim *> ERRS_N is DOUBLE PRECISION array, dimension *> (NRHS, N_ERR_BNDS) *> For each right-hand side, this array contains information about *> various error bounds and condition numbers corresponding to the *> normwise relative error, which is defined as follows: *> *> Normwise relative error in the ith solution vector: *> max_j (abs(XTRUE(j,i) - X(j,i))) *> ------------------------------ *> max_j abs(X(j,i)) *> *> The array is indexed by the type of error information as described *> below. There currently are up to three pieces of information *> returned. *> *> The first index in ERRS_N(i,:) corresponds to the ith *> right-hand side. *> *> The second index in ERRS_N(:,err) contains the following *> three fields: *> err = 1 "Trust/don't trust" boolean. Trust the answer if the *> reciprocal condition number is less than the threshold *> sqrt(n) * slamch('Epsilon'). *> *> err = 2 "Guaranteed" error bound: The estimated forward error, *> almost certainly within a factor of 10 of the true error *> so long as the next entry is greater than the threshold *> sqrt(n) * slamch('Epsilon'). This error bound should only *> be trusted if the previous boolean is true. *> *> err = 3 Reciprocal condition number: Estimated normwise *> reciprocal condition number. Compared with the threshold *> sqrt(n) * slamch('Epsilon') to determine if the error *> estimate is "guaranteed". These reciprocal condition *> numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some *> appropriately scaled matrix Z. *> Let Z = S*A, where S scales each row by a power of the *> radix so all absolute row sums of Z are approximately 1. *> *> This subroutine is only responsible for setting the second field *> above. *> See Lapack Working Note 165 for further details and extra *> cautions. *> \endverbatim *> *> \param[in,out] ERRS_C *> \verbatim *> ERRS_C is DOUBLE PRECISION array, dimension *> (NRHS, N_ERR_BNDS) *> For each right-hand side, this array contains information about *> various error bounds and condition numbers corresponding to the *> componentwise relative error, which is defined as follows: *> *> Componentwise relative error in the ith solution vector: *> abs(XTRUE(j,i) - X(j,i)) *> max_j ---------------------- *> abs(X(j,i)) *> *> The array is indexed by the right-hand side i (on which the *> componentwise relative error depends), and the type of error *> information as described below. There currently are up to three *> pieces of information returned for each right-hand side. If *> componentwise accuracy is not requested (PARAMS(3) = 0.0), then *> ERRS_C is not accessed. If N_ERR_BNDS .LT. 3, then at most *> the first (:,N_ERR_BNDS) entries are returned. *> *> The first index in ERRS_C(i,:) corresponds to the ith *> right-hand side. *> *> The second index in ERRS_C(:,err) contains the following *> three fields: *> err = 1 "Trust/don't trust" boolean. Trust the answer if the *> reciprocal condition number is less than the threshold *> sqrt(n) * slamch('Epsilon'). *> *> err = 2 "Guaranteed" error bound: The estimated forward error, *> almost certainly within a factor of 10 of the true error *> so long as the next entry is greater than the threshold *> sqrt(n) * slamch('Epsilon'). This error bound should only *> be trusted if the previous boolean is true. *> *> err = 3 Reciprocal condition number: Estimated componentwise *> reciprocal condition number. Compared with the threshold *> sqrt(n) * slamch('Epsilon') to determine if the error *> estimate is "guaranteed". These reciprocal condition *> numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some *> appropriately scaled matrix Z. *> Let Z = S*(A*diag(x)), where x is the solution for the *> current right-hand side and S scales each row of *> A*diag(x) by a power of the radix so all absolute row *> sums of Z are approximately 1. *> *> This subroutine is only responsible for setting the second field *> above. *> See Lapack Working Note 165 for further details and extra *> cautions. *> \endverbatim *> *> \param[in] RES *> \verbatim *> RES is DOUBLE PRECISION array, dimension (N) *> Workspace to hold the intermediate residual. *> \endverbatim *> *> \param[in] AYB *> \verbatim *> AYB is DOUBLE PRECISION array, dimension (N) *> Workspace. This can be the same workspace passed for Y_TAIL. *> \endverbatim *> *> \param[in] DY *> \verbatim *> DY is DOUBLE PRECISION array, dimension (N) *> Workspace to hold the intermediate solution. *> \endverbatim *> *> \param[in] Y_TAIL *> \verbatim *> Y_TAIL is DOUBLE PRECISION array, dimension (N) *> Workspace to hold the trailing bits of the intermediate solution. *> \endverbatim *> *> \param[in] RCOND *> \verbatim *> RCOND is DOUBLE PRECISION *> Reciprocal scaled condition number. This is an estimate of the *> reciprocal Skeel condition number of the matrix A after *> equilibration (if done). If this is less than the machine *> precision (in particular, if it is zero), the matrix is singular *> to working precision. Note that the error may still be small even *> if this number is very small and the matrix appears ill- *> conditioned. *> \endverbatim *> *> \param[in] ITHRESH *> \verbatim *> ITHRESH is INTEGER *> The maximum number of residual computations allowed for *> refinement. The default is 10. For 'aggressive' set to 100 to *> permit convergence using approximate factorizations or *> factorizations other than LU. If the factorization uses a *> technique other than Gaussian elimination, the guarantees in *> ERRS_N and ERRS_C may no longer be trustworthy. *> \endverbatim *> *> \param[in] RTHRESH *> \verbatim *> RTHRESH is DOUBLE PRECISION *> Determines when to stop refinement if the error estimate stops *> decreasing. Refinement will stop when the next solution no longer *> satisfies norm(dx_{i+1}) < RTHRESH * norm(dx_i) where norm(Z) is *> the infinity norm of Z. RTHRESH satisfies 0 < RTHRESH <= 1. The *> default value is 0.5. For 'aggressive' set to 0.9 to permit *> convergence on extremely ill-conditioned matrices. See LAWN 165 *> for more details. *> \endverbatim *> *> \param[in] DZ_UB *> \verbatim *> DZ_UB is DOUBLE PRECISION *> Determines when to start considering componentwise convergence. *> Componentwise convergence is only considered after each component *> of the solution Y is stable, which we definte as the relative *> change in each component being less than DZ_UB. The default value *> is 0.25, requiring the first bit to be stable. See LAWN 165 for *> more details. *> \endverbatim *> *> \param[in] IGNORE_CWISE *> \verbatim *> IGNORE_CWISE is LOGICAL *> If .TRUE. then ignore componentwise convergence. Default value *> is .FALSE.. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: Successful exit. *> < 0: if INFO = -i, the ith argument to DGETRS had an illegal *> value *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date December 2016 * *> \ingroup doubleGEcomputational * * ===================================================================== SUBROUTINE DLA_GERFSX_EXTENDED( PREC_TYPE, TRANS_TYPE, N, NRHS, A, $ LDA, AF, LDAF, IPIV, COLEQU, C, B, $ LDB, Y, LDY, BERR_OUT, N_NORMS, $ ERRS_N, ERRS_C, RES, AYB, DY, $ Y_TAIL, RCOND, ITHRESH, RTHRESH, $ DZ_UB, IGNORE_CWISE, INFO ) * * -- LAPACK computational routine (version 3.7.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * December 2016 * * .. Scalar Arguments .. INTEGER INFO, LDA, LDAF, LDB, LDY, N, NRHS, PREC_TYPE, $ TRANS_TYPE, N_NORMS, ITHRESH LOGICAL COLEQU, IGNORE_CWISE DOUBLE PRECISION RTHRESH, DZ_UB * .. * .. Array Arguments .. INTEGER IPIV( * ) DOUBLE PRECISION A( LDA, * ), AF( LDAF, * ), B( LDB, * ), $ Y( LDY, * ), RES( * ), DY( * ), Y_TAIL( * ) DOUBLE PRECISION C( * ), AYB( * ), RCOND, BERR_OUT( * ), $ ERRS_N( NRHS, * ), ERRS_C( NRHS, * ) * .. * * ===================================================================== * * .. Local Scalars .. CHARACTER TRANS INTEGER CNT, I, J, X_STATE, Z_STATE, Y_PREC_STATE DOUBLE PRECISION YK, DYK, YMIN, NORMY, NORMX, NORMDX, DXRAT, $ DZRAT, PREVNORMDX, PREV_DZ_Z, DXRATMAX, $ DZRATMAX, DX_X, DZ_Z, FINAL_DX_X, FINAL_DZ_Z, $ EPS, HUGEVAL, INCR_THRESH LOGICAL INCR_PREC * .. * .. Parameters .. INTEGER UNSTABLE_STATE, WORKING_STATE, CONV_STATE, $ NOPROG_STATE, BASE_RESIDUAL, EXTRA_RESIDUAL, $ EXTRA_Y PARAMETER ( UNSTABLE_STATE = 0, WORKING_STATE = 1, $ CONV_STATE = 2, NOPROG_STATE = 3 ) PARAMETER ( BASE_RESIDUAL = 0, EXTRA_RESIDUAL = 1, $ EXTRA_Y = 2 ) INTEGER FINAL_NRM_ERR_I, FINAL_CMP_ERR_I, BERR_I INTEGER RCOND_I, NRM_RCOND_I, NRM_ERR_I, CMP_RCOND_I INTEGER CMP_ERR_I, PIV_GROWTH_I PARAMETER ( FINAL_NRM_ERR_I = 1, FINAL_CMP_ERR_I = 2, $ BERR_I = 3 ) PARAMETER ( RCOND_I = 4, NRM_RCOND_I = 5, NRM_ERR_I = 6 ) PARAMETER ( CMP_RCOND_I = 7, CMP_ERR_I = 8, $ PIV_GROWTH_I = 9 ) INTEGER LA_LINRX_ITREF_I, LA_LINRX_ITHRESH_I, $ LA_LINRX_CWISE_I PARAMETER ( LA_LINRX_ITREF_I = 1, $ LA_LINRX_ITHRESH_I = 2 ) PARAMETER ( LA_LINRX_CWISE_I = 3 ) INTEGER LA_LINRX_TRUST_I, LA_LINRX_ERR_I, $ LA_LINRX_RCOND_I PARAMETER ( LA_LINRX_TRUST_I = 1, LA_LINRX_ERR_I = 2 ) PARAMETER ( LA_LINRX_RCOND_I = 3 ) * .. * .. External Subroutines .. EXTERNAL DAXPY, DCOPY, DGETRS, DGEMV, BLAS_DGEMV_X, $ BLAS_DGEMV2_X, DLA_GEAMV, DLA_WWADDW, DLAMCH, $ CHLA_TRANSTYPE, DLA_LIN_BERR DOUBLE PRECISION DLAMCH CHARACTER CHLA_TRANSTYPE * .. * .. Intrinsic Functions .. INTRINSIC ABS, MAX, MIN * .. * .. Executable Statements .. * IF ( INFO.NE.0 ) RETURN TRANS = CHLA_TRANSTYPE(TRANS_TYPE) EPS = DLAMCH( 'Epsilon' ) HUGEVAL = DLAMCH( 'Overflow' ) * Force HUGEVAL to Inf HUGEVAL = HUGEVAL * HUGEVAL * Using HUGEVAL may lead to spurious underflows. INCR_THRESH = DBLE( N ) * EPS * DO J = 1, NRHS Y_PREC_STATE = EXTRA_RESIDUAL IF ( Y_PREC_STATE .EQ. EXTRA_Y ) THEN DO I = 1, N Y_TAIL( I ) = 0.0D+0 END DO END IF DXRAT = 0.0D+0 DXRATMAX = 0.0D+0 DZRAT = 0.0D+0 DZRATMAX = 0.0D+0 FINAL_DX_X = HUGEVAL FINAL_DZ_Z = HUGEVAL PREVNORMDX = HUGEVAL PREV_DZ_Z = HUGEVAL DZ_Z = HUGEVAL DX_X = HUGEVAL X_STATE = WORKING_STATE Z_STATE = UNSTABLE_STATE INCR_PREC = .FALSE. DO CNT = 1, ITHRESH * * Compute residual RES = B_s - op(A_s) * Y, * op(A) = A, A**T, or A**H depending on TRANS (and type). * CALL DCOPY( N, B( 1, J ), 1, RES, 1 ) IF ( Y_PREC_STATE .EQ. BASE_RESIDUAL ) THEN CALL DGEMV( TRANS, N, N, -1.0D+0, A, LDA, Y( 1, J ), 1, $ 1.0D+0, RES, 1 ) ELSE IF ( Y_PREC_STATE .EQ. EXTRA_RESIDUAL ) THEN CALL BLAS_DGEMV_X( TRANS_TYPE, N, N, -1.0D+0, A, LDA, $ Y( 1, J ), 1, 1.0D+0, RES, 1, PREC_TYPE ) ELSE CALL BLAS_DGEMV2_X( TRANS_TYPE, N, N, -1.0D+0, A, LDA, $ Y( 1, J ), Y_TAIL, 1, 1.0D+0, RES, 1, PREC_TYPE ) END IF ! XXX: RES is no longer needed. CALL DCOPY( N, RES, 1, DY, 1 ) CALL DGETRS( TRANS, N, 1, AF, LDAF, IPIV, DY, N, INFO ) * * Calculate relative changes DX_X, DZ_Z and ratios DXRAT, DZRAT. * NORMX = 0.0D+0 NORMY = 0.0D+0 NORMDX = 0.0D+0 DZ_Z = 0.0D+0 YMIN = HUGEVAL * DO I = 1, N YK = ABS( Y( I, J ) ) DYK = ABS( DY( I ) ) IF ( YK .NE. 0.0D+0 ) THEN DZ_Z = MAX( DZ_Z, DYK / YK ) ELSE IF ( DYK .NE. 0.0D+0 ) THEN DZ_Z = HUGEVAL END IF YMIN = MIN( YMIN, YK ) NORMY = MAX( NORMY, YK ) IF ( COLEQU ) THEN NORMX = MAX( NORMX, YK * C( I ) ) NORMDX = MAX( NORMDX, DYK * C( I ) ) ELSE NORMX = NORMY NORMDX = MAX( NORMDX, DYK ) END IF END DO IF ( NORMX .NE. 0.0D+0 ) THEN DX_X = NORMDX / NORMX ELSE IF ( NORMDX .EQ. 0.0D+0 ) THEN DX_X = 0.0D+0 ELSE DX_X = HUGEVAL END IF DXRAT = NORMDX / PREVNORMDX DZRAT = DZ_Z / PREV_DZ_Z * * Check termination criteria * IF (.NOT.IGNORE_CWISE $ .AND. YMIN*RCOND .LT. INCR_THRESH*NORMY $ .AND. Y_PREC_STATE .LT. EXTRA_Y) $ INCR_PREC = .TRUE. IF ( X_STATE .EQ. NOPROG_STATE .AND. DXRAT .LE. RTHRESH ) $ X_STATE = WORKING_STATE IF ( X_STATE .EQ. WORKING_STATE ) THEN IF ( DX_X .LE. EPS ) THEN X_STATE = CONV_STATE ELSE IF ( DXRAT .GT. RTHRESH ) THEN IF ( Y_PREC_STATE .NE. EXTRA_Y ) THEN INCR_PREC = .TRUE. ELSE X_STATE = NOPROG_STATE END IF ELSE IF ( DXRAT .GT. DXRATMAX ) DXRATMAX = DXRAT END IF IF ( X_STATE .GT. WORKING_STATE ) FINAL_DX_X = DX_X END IF IF ( Z_STATE .EQ. UNSTABLE_STATE .AND. DZ_Z .LE. DZ_UB ) $ Z_STATE = WORKING_STATE IF ( Z_STATE .EQ. NOPROG_STATE .AND. DZRAT .LE. RTHRESH ) $ Z_STATE = WORKING_STATE IF ( Z_STATE .EQ. WORKING_STATE ) THEN IF ( DZ_Z .LE. EPS ) THEN Z_STATE = CONV_STATE ELSE IF ( DZ_Z .GT. DZ_UB ) THEN Z_STATE = UNSTABLE_STATE DZRATMAX = 0.0D+0 FINAL_DZ_Z = HUGEVAL ELSE IF ( DZRAT .GT. RTHRESH ) THEN IF ( Y_PREC_STATE .NE. EXTRA_Y ) THEN INCR_PREC = .TRUE. ELSE Z_STATE = NOPROG_STATE END IF ELSE IF ( DZRAT .GT. DZRATMAX ) DZRATMAX = DZRAT END IF IF ( Z_STATE .GT. WORKING_STATE ) FINAL_DZ_Z = DZ_Z END IF * * Exit if both normwise and componentwise stopped working, * but if componentwise is unstable, let it go at least two * iterations. * IF ( X_STATE.NE.WORKING_STATE ) THEN IF ( IGNORE_CWISE) GOTO 666 IF ( Z_STATE.EQ.NOPROG_STATE .OR. Z_STATE.EQ.CONV_STATE ) $ GOTO 666 IF ( Z_STATE.EQ.UNSTABLE_STATE .AND. CNT.GT.1 ) GOTO 666 END IF IF ( INCR_PREC ) THEN INCR_PREC = .FALSE. Y_PREC_STATE = Y_PREC_STATE + 1 DO I = 1, N Y_TAIL( I ) = 0.0D+0 END DO END IF PREVNORMDX = NORMDX PREV_DZ_Z = DZ_Z * * Update soluton. * IF ( Y_PREC_STATE .LT. EXTRA_Y ) THEN CALL DAXPY( N, 1.0D+0, DY, 1, Y( 1, J ), 1 ) ELSE CALL DLA_WWADDW( N, Y( 1, J ), Y_TAIL, DY ) END IF END DO * Target of "IF (Z_STOP .AND. X_STOP)". Sun's f77 won't EXIT. 666 CONTINUE * * Set final_* when cnt hits ithresh. * IF ( X_STATE .EQ. WORKING_STATE ) FINAL_DX_X = DX_X IF ( Z_STATE .EQ. WORKING_STATE ) FINAL_DZ_Z = DZ_Z * * Compute error bounds * IF (N_NORMS .GE. 1) THEN ERRS_N( J, LA_LINRX_ERR_I ) = FINAL_DX_X / (1 - DXRATMAX) END IF IF ( N_NORMS .GE. 2 ) THEN ERRS_C( J, LA_LINRX_ERR_I ) = FINAL_DZ_Z / (1 - DZRATMAX) END IF * * Compute componentwise relative backward error from formula * max(i) ( abs(R(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) ) * where abs(Z) is the componentwise absolute value of the matrix * or vector Z. * * Compute residual RES = B_s - op(A_s) * Y, * op(A) = A, A**T, or A**H depending on TRANS (and type). * CALL DCOPY( N, B( 1, J ), 1, RES, 1 ) CALL DGEMV( TRANS, N, N, -1.0D+0, A, LDA, Y(1,J), 1, 1.0D+0, $ RES, 1 ) DO I = 1, N AYB( I ) = ABS( B( I, J ) ) END DO * * Compute abs(op(A_s))*abs(Y) + abs(B_s). * CALL DLA_GEAMV ( TRANS_TYPE, N, N, 1.0D+0, $ A, LDA, Y(1, J), 1, 1.0D+0, AYB, 1 ) CALL DLA_LIN_BERR ( N, N, 1, RES, AYB, BERR_OUT( J ) ) * * End of loop for each RHS. * END DO * RETURN END
{ "content_hash": "b3d574b6cba64004addb5780c066b26f", "timestamp": "", "source": "github", "line_count": 688, "max_line_length": 238, "avg_line_length": 37.02906976744186, "alnum_prop": 0.5385853352174595, "repo_name": "grisuthedragon/OpenBLAS", "id": "d6af490255b68682e0c2389506e86c1ebcbed504", "size": "25476", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "lapack-netlib/SRC/dla_gerfsx_extended.f", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "26217073" }, { "name": "C", "bytes": "19459665" }, { "name": "C++", "bytes": "1282767" }, { "name": "CMake", "bytes": "355140" }, { "name": "Fortran", "bytes": "50636253" }, { "name": "Makefile", "bytes": "808560" }, { "name": "Matlab", "bytes": "9066" }, { "name": "Perl", "bytes": "108676" }, { "name": "Perl6", "bytes": "1924" }, { "name": "Python", "bytes": "28928" }, { "name": "R", "bytes": "3209" }, { "name": "Shell", "bytes": "3889" }, { "name": "TeX", "bytes": "71637" } ], "symlink_target": "" }
package com.jme3.post; import com.jme3.asset.AssetManager; import com.jme3.export.*; import com.jme3.material.Material; import com.jme3.renderer.*; import com.jme3.renderer.queue.RenderQueue; import com.jme3.texture.FrameBuffer; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture; import com.jme3.texture.Texture.MagFilter; import com.jme3.texture.Texture2D; import com.jme3.ui.Picture; import com.jme3.util.SafeArrayList; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A FilterPostProcessor is a processor that can apply several {@link Filter}s to a rendered scene<br> * It manages a list of filters that will be applied in the order in which they've been added to the list * @author Rémy Bouquet aka Nehon */ public class FilterPostProcessor implements SceneProcessor, Savable { private RenderManager renderManager; private Renderer renderer; private ViewPort viewPort; private FrameBuffer renderFrameBufferMS; private int numSamples = 1; private FrameBuffer renderFrameBuffer; private Texture2D filterTexture; private Texture2D depthTexture; private SafeArrayList<Filter> filters = new SafeArrayList<Filter>(Filter.class); private AssetManager assetManager; private Picture fsQuad; private boolean computeDepth = false; private FrameBuffer outputBuffer; private int width; private int height; private float bottom; private float left; private float right; private float top; private int originalWidth; private int originalHeight; private int lastFilterIndex = -1; private boolean cameraInit = false; private boolean multiView = false; private Format fbFormat = Format.RGB111110F; /** * Create a FilterProcessor * @param assetManager the assetManager */ public FilterPostProcessor(AssetManager assetManager) { this.assetManager = assetManager; } /** * Don't use this constructor, use {@link #FilterPostProcessor(AssetManager assetManager)}<br> * This constructor is used for serialization only */ public FilterPostProcessor() { } /** * Adds a filter to the filters list<br> * @param filter the filter to add */ public void addFilter(Filter filter) { if (filter == null) { throw new IllegalArgumentException("Filter cannot be null."); } filters.add(filter); if (isInitialized()) { initFilter(filter, viewPort); } setFilterState(filter, filter.isEnabled()); } /** * removes this filters from the filters list * @param filter */ public void removeFilter(Filter filter) { if (filter == null) { throw new IllegalArgumentException("Filter cannot be null."); } filters.remove(filter); filter.cleanup(renderer); updateLastFilterIndex(); } public Iterator<Filter> getFilterIterator() { return filters.iterator(); } public void initialize(RenderManager rm, ViewPort vp) { renderManager = rm; renderer = rm.getRenderer(); viewPort = vp; fsQuad = new Picture("filter full screen quad"); fsQuad.setWidth(1); fsQuad.setHeight(1); if (!renderer.getCaps().contains(Caps.PackedFloatTexture)) { fbFormat = Format.RGB8; } Camera cam = vp.getCamera(); //save view port diensions left = cam.getViewPortLeft(); right = cam.getViewPortRight(); top = cam.getViewPortTop(); bottom = cam.getViewPortBottom(); originalWidth = cam.getWidth(); originalHeight = cam.getHeight(); //first call to reshape reshape(vp, cam.getWidth(), cam.getHeight()); } /** * init the given filter * @param filter * @param vp */ private void initFilter(Filter filter, ViewPort vp) { filter.setProcessor(this); if (filter.isRequiresDepthTexture()) { if (!computeDepth && renderFrameBuffer != null) { depthTexture = new Texture2D(width, height, Format.Depth24); renderFrameBuffer.setDepthTexture(depthTexture); } computeDepth = true; filter.init(assetManager, renderManager, vp, width, height); filter.setDepthTexture(depthTexture); } else { filter.init(assetManager, renderManager, vp, width, height); } } /** * renders a filter on a fullscreen quad * @param r * @param buff * @param mat */ private void renderProcessing(Renderer r, FrameBuffer buff, Material mat) { if (buff == outputBuffer) { viewPort.getCamera().resize(originalWidth, originalHeight, false); viewPort.getCamera().setViewPort(left, right, bottom, top); // update is redundant because resize and setViewPort will both // run the appropriate (and same) onXXXChange methods. // Also, update() updates some things that don't need to be updated. //viewPort.getCamera().update(); renderManager.setCamera( viewPort.getCamera(), false); if (mat.getAdditionalRenderState().isDepthWrite()) { mat.getAdditionalRenderState().setDepthTest(false); mat.getAdditionalRenderState().setDepthWrite(false); } }else{ viewPort.getCamera().resize(buff.getWidth(), buff.getHeight(), false); viewPort.getCamera().setViewPort(0, 1, 0, 1); // update is redundant because resize and setViewPort will both // run the appropriate (and same) onXXXChange methods. // Also, update() updates some things that don't need to be updated. //viewPort.getCamera().update(); renderManager.setCamera( viewPort.getCamera(), false); mat.getAdditionalRenderState().setDepthTest(true); mat.getAdditionalRenderState().setDepthWrite(true); } fsQuad.setMaterial(mat); fsQuad.updateGeometricState(); r.setFrameBuffer(buff); r.clearBuffers(true, true, true); renderManager.renderGeometry(fsQuad); } public boolean isInitialized() { return viewPort != null; } public void postQueue(RenderQueue rq) { for (Filter filter : filters.getArray()) { if (filter.isEnabled()) { filter.postQueue(rq); } } } /** * iterate through the filter list and renders filters * @param r * @param sceneFb */ private void renderFilterChain(Renderer r, FrameBuffer sceneFb) { Texture2D tex = filterTexture; FrameBuffer buff = sceneFb; boolean msDepth = depthTexture != null && depthTexture.getImage().getMultiSamples() > 1; for (int i = 0; i < filters.size(); i++) { Filter filter = filters.get(i); if (filter.isEnabled()) { if (filter.getPostRenderPasses() != null) { for (Iterator<Filter.Pass> it1 = filter.getPostRenderPasses().iterator(); it1.hasNext();) { Filter.Pass pass = it1.next(); pass.beforeRender(); if (pass.requiresSceneAsTexture()) { pass.getPassMaterial().setTexture("Texture", tex); if (tex.getImage().getMultiSamples() > 1) { pass.getPassMaterial().setInt("NumSamples", tex.getImage().getMultiSamples()); } else { pass.getPassMaterial().clearParam("NumSamples"); } } if (pass.requiresDepthAsTexture()) { pass.getPassMaterial().setTexture("DepthTexture", depthTexture); if (msDepth) { pass.getPassMaterial().setInt("NumSamplesDepth", depthTexture.getImage().getMultiSamples()); } else { pass.getPassMaterial().clearParam("NumSamplesDepth"); } } renderProcessing(r, pass.getRenderFrameBuffer(), pass.getPassMaterial()); } } filter.postFrame(renderManager, viewPort, buff, sceneFb); Material mat = filter.getMaterial(); if (msDepth && filter.isRequiresDepthTexture()) { mat.setInt("NumSamplesDepth", depthTexture.getImage().getMultiSamples()); } if (filter.isRequiresSceneTexture()) { mat.setTexture("Texture", tex); if (tex.getImage().getMultiSamples() > 1) { mat.setInt("NumSamples", tex.getImage().getMultiSamples()); } else { mat.clearParam("NumSamples"); } } boolean wantsBilinear = filter.isRequiresBilinear(); if (wantsBilinear) { tex.setMagFilter(Texture.MagFilter.Bilinear); tex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps); } buff = outputBuffer; if (i != lastFilterIndex) { buff = filter.getRenderFrameBuffer(); tex = filter.getRenderedTexture(); } renderProcessing(r, buff, mat); filter.postFilter(r, buff); if (wantsBilinear) { tex.setMagFilter(Texture.MagFilter.Nearest); tex.setMinFilter(Texture.MinFilter.NearestNoMipMaps); } } } } public void postFrame(FrameBuffer out) { FrameBuffer sceneBuffer = renderFrameBuffer; if (renderFrameBufferMS != null && !renderer.getCaps().contains(Caps.OpenGL32)) { renderer.copyFrameBuffer(renderFrameBufferMS, renderFrameBuffer, true); } else if (renderFrameBufferMS != null) { sceneBuffer = renderFrameBufferMS; } renderFilterChain(renderer, sceneBuffer); renderer.setFrameBuffer(outputBuffer); //viewport can be null if no filters are enabled if (viewPort != null) { renderManager.setCamera(viewPort.getCamera(), false); } } public void preFrame(float tpf) { if (filters.isEmpty() || lastFilterIndex == -1) { //If the camera is initialized and there are no filter to render, the camera viewport is restored as it was if (cameraInit) { viewPort.getCamera().resize(originalWidth, originalHeight, true); viewPort.getCamera().setViewPort(left, right, bottom, top); viewPort.setOutputFrameBuffer(outputBuffer); cameraInit = false; } } else { setupViewPortFrameBuffer(); //if we are ina multiview situation we need to resize the camera //to the viewportsize so that the backbuffer is rendered correctly if (multiView) { viewPort.getCamera().resize(width, height, false); viewPort.getCamera().setViewPort(0, 1, 0, 1); viewPort.getCamera().update(); renderManager.setCamera(viewPort.getCamera(), false); } } for (Filter filter : filters.getArray()) { if (filter.isEnabled()) { filter.preFrame(tpf); } } } /** * sets the filter to enabled or disabled * @param filter * @param enabled */ protected void setFilterState(Filter filter, boolean enabled) { if (filters.contains(filter)) { filter.enabled = enabled; updateLastFilterIndex(); } } /** * compute the index of the last filter to render */ private void updateLastFilterIndex() { lastFilterIndex = -1; for (int i = filters.size() - 1; i >= 0 && lastFilterIndex == -1; i--) { if (filters.get(i).isEnabled()) { lastFilterIndex = i; //the Fpp is initialized, but the viwport framebuffer is the //original out framebuffer so we must recover from a situation //where no filter was enabled. So we set th correc framebuffer //on the viewport if(isInitialized() && viewPort.getOutputFrameBuffer()==outputBuffer){ setupViewPortFrameBuffer(); } return; } } if (isInitialized() && lastFilterIndex == -1) { //There is no enabled filter, we restore the original framebuffer //to the viewport to bypass the fpp. viewPort.setOutputFrameBuffer(outputBuffer); } } public void cleanup() { if (viewPort != null) { //reseting the viewport camera viewport to its initial value viewPort.getCamera().resize(originalWidth, originalHeight, true); viewPort.getCamera().setViewPort(left, right, bottom, top); viewPort.setOutputFrameBuffer(outputBuffer); viewPort = null; renderFrameBuffer.dispose(); if(depthTexture!=null){ depthTexture.getImage().dispose(); } filterTexture.getImage().dispose(); if(renderFrameBufferMS != null){ renderFrameBufferMS.dispose(); } for (Filter filter : filters.getArray()) { filter.cleanup(renderer); } } } public void reshape(ViewPort vp, int w, int h) { Camera cam = vp.getCamera(); //this has no effect at first init but is useful when resizing the canvas with multi views cam.setViewPort(left, right, bottom, top); //resizing the camera to fit the new viewport and saving original dimensions cam.resize(w, h, false); left = cam.getViewPortLeft(); right = cam.getViewPortRight(); top = cam.getViewPortTop(); bottom = cam.getViewPortBottom(); originalWidth = w; originalHeight = h; //computing real dimension of the viewport and resizing the camera width = (int) (w * (Math.abs(right - left))); height = (int) (h * (Math.abs(bottom - top))); width = Math.max(1, width); height = Math.max(1, height); //Testing original versus actual viewport dimension. //If they are different we are in a multiview situation and //camera must be handled differently if(originalWidth!=width || originalHeight!=height){ multiView = true; } cameraInit = true; computeDepth = false; if (renderFrameBuffer == null) { outputBuffer = viewPort.getOutputFrameBuffer(); } Collection<Caps> caps = renderer.getCaps(); //antialiasing on filters only supported in opengl 3 due to depth read problem if (numSamples > 1 && caps.contains(Caps.FrameBufferMultisample)) { renderFrameBufferMS = new FrameBuffer(width, height, numSamples); if (caps.contains(Caps.OpenGL32)) { Texture2D msColor = new Texture2D(width, height, numSamples, fbFormat); Texture2D msDepth = new Texture2D(width, height, numSamples, Format.Depth); renderFrameBufferMS.setDepthTexture(msDepth); renderFrameBufferMS.setColorTexture(msColor); filterTexture = msColor; depthTexture = msDepth; } else { renderFrameBufferMS.setDepthBuffer(Format.Depth); renderFrameBufferMS.setColorBuffer(fbFormat); } } if (numSamples <= 1 || !caps.contains(Caps.OpenGL32)) { renderFrameBuffer = new FrameBuffer(width, height, 1); renderFrameBuffer.setDepthBuffer(Format.Depth); filterTexture = new Texture2D(width, height, fbFormat); renderFrameBuffer.setColorTexture(filterTexture); } for (Filter filter : filters.getArray()) { initFilter(filter, vp); } setupViewPortFrameBuffer(); } /** * return the number of samples for antialiasing * @return numSamples */ public int getNumSamples() { return numSamples; } /** * * Removes all the filters from this processor */ public void removeAllFilters() { filters.clear(); updateLastFilterIndex(); } /** * Sets the number of samples for antialiasing * @param numSamples the number of Samples */ public void setNumSamples(int numSamples) { if (numSamples <= 0) { throw new IllegalArgumentException("numSamples must be > 0"); } this.numSamples = numSamples; } /** * Sets the asset manager for this processor * @param assetManager */ public void setAssetManager(AssetManager assetManager) { this.assetManager = assetManager; } public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(numSamples, "numSamples", 0); oc.writeSavableArrayList(new ArrayList(filters), "filters", null); } public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); numSamples = ic.readInt("numSamples", 0); filters = new SafeArrayList<Filter>(Filter.class, ic.readSavableArrayList("filters", null)); for (Filter filter : filters.getArray()) { filter.setProcessor(this); setFilterState(filter, filter.isEnabled()); } assetManager = im.getAssetManager(); } /** * For internal use only<br> * returns the depth texture of the scene * @return the depth texture */ public Texture2D getDepthTexture() { return depthTexture; } /** * For internal use only<br> * returns the rendered texture of the scene * @return the filter texture */ public Texture2D getFilterTexture() { return filterTexture; } /** * returns the first filter in the list assignable form the given type * @param <T> * @param filterType the filter type * @return a filter assignable form the given type */ public <T extends Filter> T getFilter(Class<T> filterType) { for (Filter c : filters.getArray()) { if (filterType.isAssignableFrom(c.getClass())) { return (T) c; } } return null; } /** * returns an unmodifiable version of the filter list. * @return the filters list */ public List<Filter> getFilterList(){ return Collections.unmodifiableList(filters); } private void setupViewPortFrameBuffer() { if (renderFrameBufferMS != null) { viewPort.setOutputFrameBuffer(renderFrameBufferMS); } else { viewPort.setOutputFrameBuffer(renderFrameBuffer); } } }
{ "content_hash": "b61971d50d51c90b833979d7beb835d8", "timestamp": "", "source": "github", "line_count": 557, "max_line_length": 124, "avg_line_length": 36.42190305206463, "alnum_prop": 0.5657810420466308, "repo_name": "d235j/jmonkeyengine", "id": "c5dd39ae604ce98d200512edca4d2daa660e25e3", "size": "21895", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jme3-core/src/main/java/com/jme3/post/FilterPostProcessor.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "36480" }, { "name": "C++", "bytes": "336392" }, { "name": "GLSL", "bytes": "215501" }, { "name": "HTML", "bytes": "1599217" }, { "name": "Java", "bytes": "15652902" }, { "name": "Makefile", "bytes": "6895" }, { "name": "Python", "bytes": "307608" }, { "name": "Shell", "bytes": "1442" } ], "symlink_target": "" }
namespace blink { namespace { // A helper method which is used to trigger a violation report for cases where // the |element.animate| API is used to animate a CSS property which is blocked // by the permissions policy 'layout-animations'. void ReportPermissionsPolicyViolationsIfNecessary( ExecutionContext& context, const KeyframeEffectModelBase& effect) { for (const auto& property_handle : effect.Properties()) { if (!property_handle.IsCSSProperty()) continue; const auto& css_property = property_handle.GetCSSProperty(); if (LayoutAnimationsPolicy::AffectedCSSProperties().Contains( &css_property)) { LayoutAnimationsPolicy::ReportViolation(css_property, context); } } } V8UnionKeyframeEffectOptionsOrUnrestrictedDouble* CoerceEffectOptions( const V8UnionKeyframeAnimationOptionsOrUnrestrictedDouble* options) { switch (options->GetContentType()) { case V8UnionKeyframeAnimationOptionsOrUnrestrictedDouble::ContentType:: kKeyframeAnimationOptions: return MakeGarbageCollected< V8UnionKeyframeEffectOptionsOrUnrestrictedDouble>( options->GetAsKeyframeAnimationOptions()); case V8UnionKeyframeAnimationOptionsOrUnrestrictedDouble::ContentType:: kUnrestrictedDouble: return MakeGarbageCollected< V8UnionKeyframeEffectOptionsOrUnrestrictedDouble>( options->GetAsUnrestrictedDouble()); } NOTREACHED(); return nullptr; } } // namespace // https://w3.org/TR/web-animations-1/#dom-animatable-animate Animation* Animatable::animate( ScriptState* script_state, const ScriptValue& keyframes, const V8UnionKeyframeAnimationOptionsOrUnrestrictedDouble* options, ExceptionState& exception_state) { if (!script_state->ContextIsValid()) return nullptr; Element* element = GetAnimationTarget(); if (!element->GetExecutionContext()) return nullptr; KeyframeEffect* effect = KeyframeEffect::Create(script_state, element, keyframes, CoerceEffectOptions(options), exception_state); if (exception_state.HadException()) return nullptr; // Creation of the keyframe effect parses JavaScript, which could result // in destruction of the execution context. Recheck that it is still valid. if (!element->GetExecutionContext()) return nullptr; ReportPermissionsPolicyViolationsIfNecessary(*element->GetExecutionContext(), *effect->Model()); if (!options->IsKeyframeAnimationOptions()) return element->GetDocument().Timeline().Play(effect, exception_state); Animation* animation; const KeyframeAnimationOptions* options_dict = options->GetAsKeyframeAnimationOptions(); if (!options_dict->hasTimeline()) { animation = element->GetDocument().Timeline().Play(effect, exception_state); } else if (AnimationTimeline* timeline = options_dict->timeline()) { animation = timeline->Play(effect, exception_state); } else { animation = Animation::Create(element->GetExecutionContext(), effect, nullptr, exception_state); } if (!animation) return nullptr; animation->setId(options_dict->id()); return animation; } // https://w3.org/TR/web-animations-1/#dom-animatable-animate Animation* Animatable::animate(ScriptState* script_state, const ScriptValue& keyframes, ExceptionState& exception_state) { if (!script_state->ContextIsValid()) return nullptr; Element* element = GetAnimationTarget(); if (!element->GetExecutionContext()) return nullptr; KeyframeEffect* effect = KeyframeEffect::Create(script_state, element, keyframes, exception_state); if (exception_state.HadException()) return nullptr; // Creation of the keyframe effect parses JavaScript, which could result // in destruction of the execution context. Recheck that it is still valid. if (!element->GetExecutionContext()) return nullptr; ReportPermissionsPolicyViolationsIfNecessary(*element->GetExecutionContext(), *effect->Model()); return element->GetDocument().Timeline().Play(effect, exception_state); } // https://w3.org/TR/web-animations-1/#dom-animatable-getanimations HeapVector<Member<Animation>> Animatable::getAnimations( GetAnimationsOptions* options) { bool use_subtree = options && options->subtree(); return GetAnimationsInternal( GetAnimationsOptionsResolved{.use_subtree = use_subtree}); } HeapVector<Member<Animation>> Animatable::GetAnimationsInternal( GetAnimationsOptionsResolved options) { Element* element = GetAnimationTarget(); if (options.use_subtree) element->GetDocument().UpdateStyleAndLayoutTreeForSubtree(element); else element->GetDocument().UpdateStyleAndLayoutTreeForNode(element); HeapVector<Member<Animation>> animations; if (!options.use_subtree && !element->HasAnimations()) return animations; for (const auto& animation : element->GetDocument().GetDocumentAnimations().getAnimations( element->GetTreeScope())) { DCHECK(animation->effect()); // TODO(gtsteel) make this use the idl properties Element* target = To<KeyframeEffect>(animation->effect())->EffectTarget(); if (element == target || (options.use_subtree && element->contains(target))) { // DocumentAnimations::getAnimations should only give us animations that // are either current or in effect. DCHECK(animation->effect()->IsCurrent() || animation->effect()->IsInEffect()); animations.push_back(animation); } } return animations; } } // namespace blink
{ "content_hash": "7f9deedf6bb4ea76bd44a9e1ba08b007", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 80, "avg_line_length": 38.43624161073826, "alnum_prop": 0.7082242011524358, "repo_name": "chromium/chromium", "id": "1b64fd6ae8eacc7007e3583cf358ba36ea0aed88", "size": "7374", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "third_party/blink/renderer/core/animation/animatable.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/assert.h" #include "ns3/address-utils.h" #include "arp-header.h" #include "ns3/log.h" NS_LOG_COMPONENT_DEFINE ("ArpHeader"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (ArpHeader); void ArpHeader::SetRequest (Address sourceHardwareAddress, Ipv4Address sourceProtocolAddress, Address destinationHardwareAddress, Ipv4Address destinationProtocolAddress) { NS_LOG_FUNCTION (this << sourceHardwareAddress << sourceProtocolAddress << destinationHardwareAddress << destinationProtocolAddress); m_type = ARP_TYPE_REQUEST; m_macSource = sourceHardwareAddress; m_macDest = destinationHardwareAddress; m_ipv4Source = sourceProtocolAddress; m_ipv4Dest = destinationProtocolAddress; } void ArpHeader::SetReply (Address sourceHardwareAddress, Ipv4Address sourceProtocolAddress, Address destinationHardwareAddress, Ipv4Address destinationProtocolAddress) { NS_LOG_FUNCTION (this << sourceHardwareAddress << sourceProtocolAddress << destinationHardwareAddress << destinationProtocolAddress); m_type = ARP_TYPE_REPLY; m_macSource = sourceHardwareAddress; m_macDest = destinationHardwareAddress; m_ipv4Source = sourceProtocolAddress; m_ipv4Dest = destinationProtocolAddress; } bool ArpHeader::IsRequest (void) const { NS_LOG_FUNCTION (this); return (m_type == ARP_TYPE_REQUEST) ? true : false; } bool ArpHeader::IsReply (void) const { NS_LOG_FUNCTION (this); return (m_type == ARP_TYPE_REPLY) ? true : false; } Address ArpHeader::GetSourceHardwareAddress (void) { NS_LOG_FUNCTION (this); return m_macSource; } Address ArpHeader::GetDestinationHardwareAddress (void) { NS_LOG_FUNCTION (this); return m_macDest; } Ipv4Address ArpHeader::GetSourceIpv4Address (void) { NS_LOG_FUNCTION (this); return m_ipv4Source; } Ipv4Address ArpHeader::GetDestinationIpv4Address (void) { NS_LOG_FUNCTION (this); return m_ipv4Dest; } TypeId ArpHeader::GetTypeId (void) { static TypeId tid = TypeId ("ns3::ArpHeader") .SetParent<Header> () .AddConstructor<ArpHeader> () ; return tid; } TypeId ArpHeader::GetInstanceTypeId (void) const { NS_LOG_FUNCTION (this); return GetTypeId (); } void ArpHeader::Print (std::ostream &os) const { NS_LOG_FUNCTION (this << &os); if (IsRequest ()) { os << "request " << "source mac: " << m_macSource << " " << "source ipv4: " << m_ipv4Source << " " << "dest ipv4: " << m_ipv4Dest ; } else { NS_ASSERT (IsReply ()); os << "reply " << "source mac: " << m_macSource << " " << "source ipv4: " << m_ipv4Source << " " << "dest mac: " << m_macDest << " " << "dest ipv4: " <<m_ipv4Dest ; } } uint32_t ArpHeader::GetSerializedSize (void) const { NS_LOG_FUNCTION (this); NS_ASSERT((m_macSource.GetLength () == 6) || (m_macSource.GetLength () == 8)); NS_ASSERT (m_macSource.GetLength () == m_macDest.GetLength ()); uint32_t length = 16; // Length minus two hardware addresses length += m_macSource.GetLength () * 2; return length; } void ArpHeader::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION (this << &start); Buffer::Iterator i = start; NS_ASSERT (m_macSource.GetLength () == m_macDest.GetLength ()); /* ethernet */ i.WriteHtonU16 (0x0001); /* ipv4 */ i.WriteHtonU16 (0x0800); i.WriteU8 (m_macSource.GetLength ()); i.WriteU8 (4); i.WriteHtonU16 (m_type); WriteTo (i, m_macSource); WriteTo (i, m_ipv4Source); WriteTo (i, m_macDest); WriteTo (i, m_ipv4Dest); } uint32_t ArpHeader::Deserialize (Buffer::Iterator start) { NS_LOG_FUNCTION (this << &start); Buffer::Iterator i = start; i.Next (2); // Skip HRD uint32_t protocolType = i.ReadNtohU16 (); // Read PRO uint32_t hardwareAddressLen = i.ReadU8 (); // Read HLN uint32_t protocolAddressLen = i.ReadU8 (); // Read PLN // // It is implicit here that we have a protocol type of 0x800 (IP). // It is also implicit here that we are using Ipv4 (PLN == 4). // If this isn't the case, we need to return an error since we don't want to // be too fragile if we get connected to real networks. // if (protocolType != 0x800 || protocolAddressLen != 4) { return 0; } m_type = i.ReadNtohU16 (); // Read OP ReadFrom (i, m_macSource, hardwareAddressLen); // Read SHA (size HLN) ReadFrom (i, m_ipv4Source); // Read SPA (size PLN == 4) ReadFrom (i, m_macDest, hardwareAddressLen); // Read THA (size HLN) ReadFrom (i, m_ipv4Dest); // Read TPA (size PLN == 4) return GetSerializedSize (); } } // namespace ns3
{ "content_hash": "f09d886cc9926dd5ec9a032a41a7f4cd", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 135, "avg_line_length": 28.678571428571427, "alnum_prop": 0.6516634050880626, "repo_name": "Chiru/NVE_Simulation", "id": "21ca72f20ba8423f89da8161890173b0cfe8186a", "size": "5621", "binary": false, "copies": "41", "ref": "refs/heads/master", "path": "NS3/src/internet/model/arp-header.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "587430" }, { "name": "C++", "bytes": "15139819" }, { "name": "DOT", "bytes": "2792" }, { "name": "M", "bytes": "5446" }, { "name": "Matlab", "bytes": "18438" }, { "name": "Objective-C", "bytes": "15035" }, { "name": "Perl", "bytes": "302841" }, { "name": "Prolog", "bytes": "2793" }, { "name": "Python", "bytes": "32484684" }, { "name": "Scala", "bytes": "51" }, { "name": "Shell", "bytes": "7282" } ], "symlink_target": "" }
<?php if (!defined('PGV_PHPGEDVIEW')) { header('HTTP/1.0 403 Forbidden'); exit; } $pgv_lang["module_admin"] = "Administración de módulos"; $pgv_lang["mod_admin_installed"] = "Módulos instalados"; $pgv_lang["mod_admin_tabs"] = "Gestionar pestañas"; $pgv_lang["mod_admin_menus"] = "Gestionar menús"; $pgv_lang["mod_admin_intro"] = "A continuación se muestra la lista de todos los módulos instalados en esta instalación de PhpGedView. Los módulos se instalan colocándolos en el directorio <i>modules</i>. Aquí puede fijar el nivel de acceso en cada GEDCOM para cada módulo. Si un módulo incluye pestañas para la página de persona o menús para la barra de menús, también puede fijar el nivel de acceso y el orden de cada uno de ellos."; $pgv_lang["mod_admin_active"] = "Activo"; $pgv_lang["mod_admin_name"] = "Nombre del módulo"; $pgv_lang["mod_admin_description"] = "Descripción"; $pgv_lang["mod_admin_version"] = "Versión / PGV"; $pgv_lang["mod_admin_hastab"] = "¿Pestaña?"; $pgv_lang["mod_admin_hasmenu"] = "¿Menú?"; $pgv_lang["mod_admin_access_level"] = "Nivel de acceso"; $pgv_lang["mod_admin_order"] = "Orden"; $pgv_lang["mod_admin_config"] = "Ajustes de módulos"; $pgv_lang["mod_admin_settings"] = "Ajustes de configuración de módulos"; $pgv_lang["ret_module_admin"] = "Volver a la página de Administración de Módulos"; $pgv_lang["ret_admin"] = "Volver a la página de Administración"; $pgv_lang["enter_comment"] = "Aquí puede introducir un comentario."; $pgv_lang["upload_a_gedcom"] = "Subir un archivo GEDCOM"; $pgv_lang["start_entering"] = "Comenzar la introducción de datos"; $pgv_lang["add_gedcom_from_path"] = "Añadir un GEDCOM a partir de un archivo ya subido"; $pgv_lang["get_started_instructions"] = "Elija una de las opciones siguientes para comenzar a utilizar PhpGedView"; $pgv_lang["admin_users_exists"] = "Ya existen los siguientes usuarios administradores:"; $pgv_lang["install_step_1"] = "Comprobación del entorno"; $pgv_lang["install_step_2"] = "Conexión con la base de datos"; $pgv_lang["install_step_3"] = "Creación de tablas"; $pgv_lang["install_step_4"] = "Configuración del sitio"; $pgv_lang["install_step_5"] = "Idiomas"; $pgv_lang["install_step_6"] = "Guardar la configuración"; $pgv_lang["install_step_7"] = "Creación del usuario administrador"; $pgv_lang["install_wizard"] = "Ayudante de instalación"; $pgv_lang["basic_site_config"] = "Ajustes básicos"; $pgv_lang["adv_site_config"] = "Ajustes avanzados"; $pgv_lang["config_not_saved"] = "Sus ajustes no se salvarán<br />hasta el paso 6"; $pgv_lang["download_config"] = "Descargar config.php"; $pgv_lang["site_unavailable"] = "El sitio no está disponible en este momento"; $pgv_lang["to_manage_users"] = "Para gestionar los usuarios, utilice la página <a href=\"useradmin.php\">Administración de usuarios</a>."; $pgv_lang["db_tables_created"] = "Se crearon con éxito las tablas de la base de datos"; $pgv_lang["config_saved"] = "Se salvó con éxito la configuración"; $pgv_lang["checking_errors"] = "Comprobando si hay errores..."; $pgv_lang["checking_php_version"] = "Comprobando la versión requerida de PHP:"; $pgv_lang["failed"] = "Falló"; $pgv_lang["pgv_requires_version"] = "PhpGedView requiere la versión de PHP #PGV_REQUIRED_PHP_VERSION# o superior."; $pgv_lang["using_php_version"] = "Está utilizando la versión #PGV_ACTUAL_PHP_VERSION# de PHP"; $pgv_lang["checking_db_support"] = "Comprobando las capacidades de base de datos:"; $pgv_lang["no_db_extensions"] = "Vd. no tiene ninguna de las extensiones de base de datos que puede utilizar este programa."; $pgv_lang["db_ext_support"] = "Vd. tiene la extensión #DBEXT#"; $pgv_lang["checking_config.php"] = "Comprobando config.php:"; $pgv_lang["config.php_missing"] = "No se encontró el archivo config.php."; $pgv_lang["config.php_missing_instr"] = "Este ayudante de instalación no podrá guardar sus ajustes en el archivo config.php. Puede hacer una copia del archivo config.dist y cambiarle el nombre a config.php. O bien, tras completar este ayudante, tendrá oportunidad de descargar sus ajustes y subir el archivo config.php resultante."; $pgv_lang["config.php_not_writable"] = "No se puede escribir en el archivo config.php."; $pgv_lang["config.php_not_writable_instr"] = "Este ayudante de instalación no podrá guardar sus ajustes en el archivo config.php. Puede dar permiso de escritura al archivo o, tras completar este ayudante, tendrá la oportunidad de descargar sus ajustes y subir el archivo config.php resultante."; $pgv_lang["passed"] = "Correcto"; $pgv_lang["config.php_writable"] = "El archivo config.php está presente y se puede escribir en él."; $pgv_lang["checking_warnings"] = "Comprobando si hay deficiencias..."; $pgv_lang["checking_timelimit"] = "Comprobando si se puede cambiar el límite de tiempo:"; $pgv_lang["cannot_change_timelimit"] = "No se puede cambiar el límite de tiempo."; $pgv_lang["cannot_change_timelimit_instr"] = "Quizá no pueda utilizar todas las funciones en grandes GEDCOMs con muchas personas."; $pgv_lang["current_max_timelimit"] = "Su límite máximo de tiempo es"; $pgv_lang["check_memlimit"] = "Comprobando si se puede cambiar el límite de memoria:"; $pgv_lang["cannot_change_memlimit"] = "No se puede cambiar el límite de memoria."; $pgv_lang["cannot_change_memlimit_instr"] = "Quizá no pueda usar todas las funciones en grandes GEDCOMs con muchas personas."; $pgv_lang["current_max_memlimit"] = "Su límite de memoria actual es"; $pgv_lang["check_upload"] = "Comprobando si se pueden subir archivos"; $pgv_lang["current_max_upload"] = "El tamaño máximo de archivo que se puede subir es:"; $pgv_lang["check_gd"] = "Comprobando la biblioteca de tratamiento de imágenes GD:"; $pgv_lang["cannot_use_gd"] = "Vd. no tiene la biblioteca de tratamiento de imágenes GD. No podrá crear automáticamente miniaturas para las imágenes."; $pgv_lang["check_sax"] = "Comprobando la biblioteca XML SAX:"; $pgv_lang["cannot_use_sax"] = "Vd. no tiene la biblioteca XML SAX. No podrá generar informes o utilizar algunas funciones auxiliares."; $pgv_lang["check_dom"] = "Comprobando la biblioteca XML DOM:"; $pgv_lang["cannot_use_dom"] = "Vd. no tiene la biblioteca XML DOM. No podrá exportar en formato XML."; $pgv_lang["check_calendar"] = "Comprobando la biblioteca avanzada de calendario:"; $pgv_lang["cannot_use_calendar"] = "Vd. no tiene la biblioteca avanzada de calendario. No podrá utilizar algunas funciones avanzadas de calendario."; $pgv_lang["warnings_passed"] = "Superadas todas las pruebas de deficiencias."; $pgv_lang["warning_instr"] = "Si se detectó alguna deficiencia, puede de todos modos utilizar PhpGedView en este servidor, pero algunas funciones pueden estar desactivadas o el rendimiento puede ser deficiente."; $pgv_lang["associated_files"] = "Archivos asociados:"; $pgv_lang["remove_all_files"] = "Borrar todos los archivos no esenciales"; $pgv_lang["warn_file_delete"] = "Este archivo contiene información importante como ajustes de idioma o datos de los cambios pendientes. ¿Está seguro de que desea borrar este archivo?"; $pgv_lang["deleted_files"] = "Archivos borrados:"; $pgv_lang["index_dir_cleanup_inst"] = "Para borrar un archivo del directorio de índice, arrástrelo a la basura o marque su casilla de selección. Haga clic en el botón Borrar para eliminar permanentemente los archivos de la basura.<br /><br />Los archivos marcados con <img src=\"./images/RESN_confidential.gif\" /> se requieren para el correcto funcionamiento y no pueden eliminarse.<br />Los archivos marcados con <img src=\"./images/RESN_locked.gif\" /> tienen ajustes importantes o datos de cambios pendientes y sólo debería borrarlos si está seguro de lo que hace.<br /><br />"; $pgv_lang["index_dir_cleanup"] = "Limpieza del directorio de índice"; $pgv_lang["clear_cache_succes"] = "Se han borrado los archivos recordados."; $pgv_lang["clear_cache"] = "Limpiar los archivos de recuerdo"; $pgv_lang["sanity_err0"] = "Errores:"; $pgv_lang["sanity_err1"] = "Necesita tener PHP versión #PGV_REQUIRED_PHP_VERSION# o superior."; $pgv_lang["sanity_err2"] = "El archivo o directorio <i>#GLOBALS[whichFile]#</i> no existe. Verifique por favor que el archivo o directorio existe, su nombre esté escrito correctamente y que los permisos de lectura sean los adecuados."; $pgv_lang["sanity_err3"] = "No se pudo subir correctamente el archivo <i>#GLOBALS[whichFile]#</i>. Intente por favor subirlo nuevamente."; $pgv_lang["sanity_err4"] = "El archivo <i>config.php</i> está corrupto."; $pgv_lang["sanity_err5"] = "No se puede escribir en el archivo <i>config.php</i>."; $pgv_lang["sanity_err6"] = "No se puede escribir el directorio <i>#GLOBALS[INDEX_DIRECTORY]#</i>."; $pgv_lang["sanity_warn0"] = "Advertencias:"; $pgv_lang["sanity_warn1"] = "No se puede escribir en el directorio <i>#GLOBALS[MEDIA_DIRECTORY]#</i>. No podrá subir archivos audiovisuales o generar miniaturas en PhpGedView."; $pgv_lang["sanity_warn2"] = "El directorio <i>#GLOBALS[MEDIA_DIRECTORY]#thumbs</i> no se puede escribir. No podrá subir miniaturas ni generarlas con PhpGedView."; $pgv_lang["sanity_warn3"] = "No existe la biblioteca de manejo de imágenes GD. PhpGedView funcionará a pesar de ello, pero algunas funciones, como la generación de miniaturas y el diagrama en círculo, no funcionarán sin la biblioteca GD. Para más información, por favor consulte <a href='http://www.php.net/manual/en/ref.image.php'>http://www.php.net/manual/en/ref.image.php</a> (en inglés)."; $pgv_lang["sanity_warn4"] = "No existe la biblioteca XML Parser. PhpGedView funcionará a pesar de ello, pero algunas de las funciones, como la generación de informes y los servicios web, no funcionarán sin la biblioteca XML Parser. Para más información, por favor consulte <a href='http://www.php.net/manual/en/ref.xml.php'>http://www.php.net/manual/en/ref.xml.php</a> (en inglés)."; $pgv_lang["sanity_warn5"] = "No existe la biblioteca DOM XML. PhpGedView funcionará a pesar de ello, pero algunas funciones, como la exportación en formato Gramps en el carrito genealógico, la descarga y los servicios web no funcionarán. Para más información, por favor consulte <a href='http://www.php.net/manual/en/ref.domxml.php'>http://www.php.net/manual/en/ref.domxml.php</a> (en inglés)."; $pgv_lang["sanity_warn6"] = "No existe la biblioteca Calendar. PhpGedView funcionará a pesar de ello, pero algunas funciones, como la conversión a otros calendarios como el hebreo o el francés revolucionario, no funcionarán. No es esencial para utilizar PhpGedView. Para más información, por favor consulte <a href='http://www.php.net/manual/es/ref.calendar.php'>http://www.php.net/manual/es/ref.calendar.php</a>."; $pgv_lang["ip_address"] = "Dirección IP"; $pgv_lang["date_time"] = "Fecha y hora"; $pgv_lang["log_message"] = "Mensaje en el registro"; $pgv_lang["searchtype"] = "Tipo de búsqueda"; $pgv_lang["query"] = "Búsqueda"; $pgv_lang["user"] = "Usuario autenticado"; $pgv_lang["editors"] = "Modificadores"; $pgv_lang["gedcom_admins"] = "Administradores del GEDCOM"; $pgv_lang["site_admins"] = "Administradores del sitio"; $pgv_lang["nobody"] = "Nadie"; $pgv_lang["thumbnail_deleted"] = "Archivo de miniatura borrado con éxito."; $pgv_lang["thumbnail_not_deleted"] = "No se pudo borrar el archivo de miniatura."; $pgv_lang["step2"] = "Paso 2 de 4:"; $pgv_lang["refresh"] = "Refrescar"; $pgv_lang["move_file_success"] = "Archivos principal y miniatura movidos con éxito."; $pgv_lang["media_folder_corrupt"] = "La carpeta de archivos audiovisuales está corrupta."; $pgv_lang["media_file_not_deleted"] = "No se pudo borrar el archivo audiovisual."; $pgv_lang["gedcom_deleted"] = "GEDCOM [#GED#] eliminado correctamente."; $pgv_lang["gedadmin"] = "Administrador del GEDCOM"; $pgv_lang["full_name"] = "Nombre completo"; $pgv_lang["error_header"] = "El archivo GEDCOM, <b>#GEDCOM#</b>, no existe en la ubicación especificada."; $pgv_lang["confirm_delete_file"] = "¿Está seguro de querer borrar este archivo?"; $pgv_lang["confirm_folder_delete"] = "¿Está seguro de querer borrar esta carpeta?"; $pgv_lang["confirm_remove_links"] = "¿Está seguro de querer borrar todos los vínculos a este objeto?"; $pgv_lang["PRIV_PUBLIC"] = "Mostrar a todos"; $pgv_lang["PRIV_USER"] = "Mostrar sólo a usuarios registrados"; $pgv_lang["PRIV_NONE"] = "Mostrar sólo a administradores"; $pgv_lang["PRIV_HIDE"] = "Ocultar incluso a los administradores"; $pgv_lang["manage_gedcoms"] = "Administrar GEDCOMs"; $pgv_lang["keep_media"] = "Conservar los vínculos a objetos audiovisuales"; $pgv_lang["current_links"] = "Vínculos"; $pgv_lang["add_more_links"] = "Agregar más vínculos"; $pgv_lang["enter_pid_or_name"] = "Introduzca el ID o el nombre de una persona"; $pgv_lang["set_links"] = "Fijar vínculos"; $pgv_lang["add_or_remove_links"] = "Administrar vínculos"; $pgv_lang["keep"] = "Mantener"; $pgv_lang["unlink"] = "Desvincular"; $pgv_lang["nav"] = "Navegador"; $pgv_lang["fam_nav"] = "Navegador de familias"; $pgv_lang["remove"] = "Borrar"; $pgv_lang["keep_link"] = "Mantener el vínculo en la lista"; $pgv_lang["remove_link"] = "Borrar el vínculo de la lista"; $pgv_lang["open_nav"] = "Abrir el navegador de familias"; $pgv_lang["link_exists"] = "Este vínculo ya existe"; $pgv_lang["id_not_valid"] = "No es un ID válido de persona, familia o fuente"; $pgv_lang["add_fam_other_links"] = "Agregar vínculos de agregar familia y de buscar"; $pgv_lang["search_add_links"] = "Buscar personas a agregar a la lista de Agregar Vínculos."; $pgv_lang["enter_name"] = "Introduzca un nombre"; $pgv_lang["add_indi_to_link_list"] = "Haga clic en el nombre para agregar la persona a la lista de Agregar Vínculos."; $pgv_lang["click_choose_head"] = "Haga clic en #GLOBALS[tempStringHead]# para escoger la persona como cabeza de familia."; $pgv_lang["click_choose_head_text"] = "Haga clic para escoger la persona como cabeza de familia."; $pgv_lang["head"] = "Cabeza"; $pgv_lang["id_empty"] = "No se puede dejar el campo ID en blanco al agregar un vínculo."; $pgv_lang["link_deleted"] = "Vínculo a #GLOBALS[remLinkId]# borrado"; $pgv_lang["link_added"] = "Vínculo a #GLOBALS[addLinkId]# agregado"; $pgv_lang["no_update_CHANs"] = "No actualizar los registros CHAN (último cambio)"; $pgv_lang["no_CHANs_update"] = "No se actualizó ningún registro CHAN (último cambio)"; $pgv_lang["files_in_backup"] = "Archivos incluidos en esta copia de seguridad"; $pgv_lang["created_remotelinks"] = "Creada la tabla <i>Vínculos remotos</i> con éxito."; $pgv_lang["created_remotelinks_fail"] = "No se pudo crear la tabla de <i>Vínculos remotos</i>."; $pgv_lang["created_indis"] = "Tabla de <i>Personas</i> creada con éxito."; $pgv_lang["created_indis_fail"] = "No se pudo crear la tabla de <i>Personas</i>"; $pgv_lang["created_fams"] = "Tabla de <i>Familias</i> creada con éxito."; $pgv_lang["created_fams_fail"] = "No se pudo crear la tabla de <i>Familias</i>."; $pgv_lang["created_sources"] = "Tabla de <i>Fuentes</i> creada con éxito."; $pgv_lang["created_sources_fail"] = "No se pudo crear la tabla de <i>Fuentes</i>."; $pgv_lang["created_other"] = "Tabla de <i>Otros</i> creada con éxito."; $pgv_lang["created_other_fail"] = "No se pudo crear la tabla de <i>Otros</i>."; $pgv_lang["created_places"] = "Tabla de <i>Lugares</i> creada con éxito."; $pgv_lang["created_places_fail"] = "No se pudo crear la tabla de <i>Lugares</i>."; $pgv_lang["created_placelinks"] = "Tabla de <i>Vínculos a lugares</i> creada con éxito."; $pgv_lang["created_placelinks_fail"] = "No se pudo crear la tabla de <i>Vínculos a lugares</i>."; $pgv_lang["created_media_fail"] = "No se pudo crear la tabla de <i>Objetos</i>."; $pgv_lang["created_media_mapping_fail"] = "No se pudo crear la tabla <i>Media mappings</i>."; $pgv_lang["no_thumb_dir"] = " directorio para miniaturas no existe y no se pudo crear."; $pgv_lang["folder_created"] = "Directorio creado"; $pgv_lang["folder_no_create"] = "No se pudo crear el directorio"; $pgv_lang["security_no_create"] = "Advertencia de seguridad: No existe el archivo <b><i>index.php</i></b> en "; $pgv_lang["security_not_exist"] = "Advertencia de seguridad: No se pudo crear el archivo <b><i>index.php</i></b> en "; $pgv_lang["label_delete"] = "Borrar"; $pgv_lang["progress_bars_info"] = "Las barras de estado que aparecen abajo le permiten ver el progreso de la importación. Si se alcanza el límite de tiempo, se detendrá la importación y se le pedirá que haga clic en el botón <b>Continuar</b>. Si no ve el botón <b>Continuar</b>, debe reintentar la importación con un límite de tiempo más pequeño."; $pgv_lang["upload_replacement"] = "Subir sustitución"; $pgv_lang["about_user"] = "Primero debe crear el usuario de administración principal. Este usuario tendrá privilegios para actualizar los archivos de configuración, ver datos privados, y crear otros usuarios."; $pgv_lang["access"] = "Acceso"; $pgv_lang["add_gedcom"] = "Añadir GEDCOM"; $pgv_lang["add_new_gedcom"] = "Crear un nuevo GEDCOM"; $pgv_lang["add_new_language"] = "Agregar archivos y ajustes para un nuevo idioma"; $pgv_lang["add_user"] = "Agregar un nuevo usuario"; $pgv_lang["admin_gedcom"] = "Administrar GEDCOM"; $pgv_lang["admin_gedcoms"] = "Haga clic aquí para administrar los GEDCOMs."; $pgv_lang["admin_geds"] = "Administración de datos y GEDCOMs"; $pgv_lang["admin_info"] = "Informativo"; $pgv_lang["admin_site"] = "Administración del sitio"; $pgv_lang["admin_user_warnings"] = "Una o más cuentas tienen avisos"; $pgv_lang["admin_verification_waiting"] = "Cuenta(s) de usuario(s) esperando verificación del Administrador"; $pgv_lang["administration"] = "Administración"; $pgv_lang["ALLOW_CHANGE_GEDCOM"] = "Permitir a los visitantes cambiar de GEDCOM"; $pgv_lang["ALLOW_USER_THEMES"] = "Permitir a los usuarios seleccionar su propio tema"; $pgv_lang["ansi_encoding_detected"] = "Archivo detectado con codificación ANSI. PhpGedView funciona mejor con archivos codificados en UTF-8."; $pgv_lang["ansi_to_utf8"] = "¿Quiere convertir este GEDCOM desde ANSI (ISO-8859-1) a UTF-8?"; $pgv_lang["apply_privacy"] = "¿Aplicar ajustes de privacidad?"; $pgv_lang["back_useradmin"] = "Volver a Administración de usuarios"; $pgv_lang["bytes_read"] = "Octetos leídos:"; $pgv_lang["can_admin"] = "El usuario puede administrar"; $pgv_lang["can_edit"] = "Nivel de acceso"; $pgv_lang["change_id"] = "Cambiar el ID de persona a:"; $pgv_lang["choose_priv"] = "Escoja nivel de privacidad:"; $pgv_lang["cleanup_places"] = "Limpiar lugares"; $pgv_lang["cleanup_users"] = "Limpiar usuarios"; $pgv_lang["click_here_to_continue"] = "Haga clic aquí para continuar."; $pgv_lang["click_here_to_go_to_pedigree_tree"] = "Haga clic aquí para ir al Árbol de ascendientes."; $pgv_lang["comment"] = "Comentarios del administrador acerca del usuario"; $pgv_lang["comment_exp"] = "Avisar al administrador en la fecha"; $pgv_lang["config_help"] = "Ayuda de la configuración"; $pgv_lang["config_still_writable"] = "Su archivo <i>config.php</i> todavía se puede escribir. Por seguridad, si ha finalizado la configuración de su sitio, debería modificar los permisos de escritura de este archivo a sólo-lectura."; $pgv_lang["configuration"] = "Configuración"; $pgv_lang["configure"] = "Configurar PhpGedView"; $pgv_lang["configure_head"] = "Configuración de PhpGedView"; $pgv_lang["confirm_gedcom_delete"] = "Está seguro de querer eliminar este GEDCOM"; $pgv_lang["confirm_user_delete"] = "Seguro que quiere borrar el usuario"; $pgv_lang["create_user"] = "Crear usuario"; $pgv_lang["current_users"] = "Lista de usuarios"; $pgv_lang["daily"] = "Diariamente"; $pgv_lang["dataset_exists"] = "Un archivo GEDCOM con este nombre ya ha sido importado en esta Base de datos."; $pgv_lang["unsync_warning"] = "Este archivo GEDCOM <em>no</em> está sincronizado con la base de datos. Puede que no contenga la última versión de sus datos. Para reimportar desde la base de datos en vez de desde el archivo, descargue el archivo desde la base de datos y vuelva a subir el archivo resultante."; $pgv_lang["date_registered"] = "Fecha de registro"; $pgv_lang["day_before_month"] = "Día antes del mes (DD MM AAAA)"; $pgv_lang["DEFAULT_GEDCOM"] = "GEDCOM por omisión"; $pgv_lang["default_user"] = "Cree el usuario de administración por omisión."; $pgv_lang["del_gedrights"] = "El GEDCOM ya no está activo, eliminar referencias de usuarios."; $pgv_lang["del_proceed"] = "Continuar"; $pgv_lang["del_unvera"] = "Usuario no verificado por un administrador."; $pgv_lang["del_unveru"] = "El usuario no verificó su dirección en 7 días."; $pgv_lang["do_not_change"] = "No modificar"; $pgv_lang["download_gedcom"] = "Descargar GEDCOM"; $pgv_lang["download_here"] = "Haga clic aquí para descargar el archivo."; $pgv_lang["download_note"] = "NOTA: Los archivos GEDCOM de gran tamaño pueden demorar mucho tiempo de proceso antes de su descarga. Si expira el plazo para el proceso PHP antes de que termine la descarga, ésta podría quedar incompleta.<br /><br />Para asegurarse de que el archivo se descargó correctamente, compruebe la existencia de la línea <b>0&nbsp;TRLR</b> al final del archivo si tiene formato GEDCOM o que la última línea de un archivo en formato XML sea <b>&lt;/database&gt;</b>. Estos archivos son de texto, puede utilizar cualquier editor de texto para comprobarlo, pero asegúrese de <u>no guardar</u> el archivo después de haberlo inspeccionado.<br /><br />En general, podría costar tanto tiempo descargarlo como costó importar su archivo GEDCOM."; $pgv_lang["editaccount"] = "Permitir que este usuario modifique la información de su cuenta"; $pgv_lang["empty_dataset"] = "¿Desea borrar la información anterior y reemplazarla con la nueva información?"; $pgv_lang["empty_lines_detected"] = "Se detectaron líneas vacías en su archivo GEDCOM. Al realizar limpieza, se eliminarán las líneas vacías."; $pgv_lang["enable_disable_lang"] = "Configurar los idiomas del sitio"; $pgv_lang["error_ban_server"] = "Dirección IP inválida."; $pgv_lang["error_delete_person"] = "Debe seleccionar la persona cuyo vínculo remoto desee borrar."; $pgv_lang["error_header_write"] = "El archivo GEDCOM, [#GEDCOM#], no es grabable. Controle sus atributos y privilegios de acceso."; $pgv_lang["error_remove_site"] = "No se pudo suprimir el servidor remoto."; $pgv_lang["error_remove_site_linked"] = "El servidor remoto no se pudo suprimir porque no está vacía su lista de conexiones."; $pgv_lang["error_remote_duplicate"] = "Esta base de datos remota ya se encuentra en la lista como <i>#GLOBALS[whichFile]#</i>"; $pgv_lang["error_siteauth_failed"] = "Falló la autenticación con el sitio remoto"; $pgv_lang["error_url_blank"] = "Por favor, no deje en blanco ni el título del sitio remoto ni la URL"; $pgv_lang["error_view_info"] = "Debe seleccionar la persona cuya información desee ver."; $pgv_lang["example_date"] = "Ejemplo de fecha inválida en su GEDCOM:"; $pgv_lang["example_place"] = "Ejemplo de lugar inválido en su GEDCOM:"; $pgv_lang["fbsql"] = "FrontBase"; $pgv_lang["found_record"] = "Registro encontrado"; $pgv_lang["ged_download"] = "Descargar"; $pgv_lang["ged_import"] = "Importar"; $pgv_lang["ged_export"] = "Exportar"; $pgv_lang["ged_check"] = "Comprobar"; $pgv_lang["gedcom_adm_head"] = "Administración GEDCOM"; $pgv_lang["gedcom_config_write_error"] = "¡¡¡ E R R O R !!!<br />No se pudo escribir el archivo <i>#GLOBALS[whichFile]#</i>. Verifique si posee permisos de escritura adecuados."; $pgv_lang["gedcom_downloadable"] = "¡Este archivo GEDCOM puede descargarse desde Internet!<br />Por favor, vea la sección SECURITY del archivo <a href=\"readme.txt\">readme.txt</a> para solventar este problema"; $pgv_lang["gedcom_file"] = "Archivo GEDCOM:"; $pgv_lang["gedcom_not_imported"] = "Este GEDCOM no ha sido importado todavía."; $pgv_lang["ibase"] = "InterBase"; $pgv_lang["ifx"] = "Informix"; $pgv_lang["img_admin_settings"] = "Editar la configuración de manejo de imágenes"; $pgv_lang["autoContinue"] = "Pulsar automáticamente el botón «Continuar»"; $pgv_lang["import_complete"] = "Importación completa"; $pgv_lang["import_options"] = "Opciones de importación"; $pgv_lang["import_progress"] = "Progreso de la importación..."; $pgv_lang["import_statistics"] = "Estadísticas de la importación"; $pgv_lang["import_time_exceeded"] = "Se sobrepasó el tiempo límite de ejecución. Haga clic en el botón Continuar para proseguir la importación del archivo GEDCOM."; $pgv_lang["inc_languages"] = " Idiomas"; $pgv_lang["INDEX_DIRECTORY"] = "Directorio de los archivos de índice"; $pgv_lang["invalid_dates"] = "Se detectaron formatos de fecha inválidos, al realizar limpieza se cambiarán al formato DD MMM AAAA (p.ej. 1 ENE 2004)."; $pgv_lang["BOM_detected"] = "Se detectó una Marca de Orden de Octetos (BOM) al principio del archivo. Al limpiar, este código especial se eliminará."; $pgv_lang["invalid_header"] = "Se detectaron registros antes del encabezamiento GEDCOM <b>0&nbsp;HEAD</b>. Al realizar limpieza, estos registros se eliminarán."; $pgv_lang["label_added_servers"] = "Servidores remotos"; $pgv_lang["label_banned_servers"] = "Excluir sitios por IP"; $pgv_lang["label_families"] = "Familias"; $pgv_lang["label_gedcom_id2"] = "ID de la base de datos:"; $pgv_lang["label_individuals"] = "Personas"; $pgv_lang["label_manual_search_engines"] = "Identificar manualmente motores de búsqueda por IP"; $pgv_lang["label_new_server"] = "Agregar nuevo sitio"; $pgv_lang["label_password_id"] = "Contraseña"; $pgv_lang["label_server_info"] = "Todas las personas vinculadas remotamente a través de este sitio: "; $pgv_lang["label_server_url"] = "URL/IP del sitio"; $pgv_lang["label_username_id"] = "Identificador de usuario"; $pgv_lang["label_view_local"] = "Ver la información local de la persona"; $pgv_lang["label_view_remote"] = "Ver la información remota de la persona"; $pgv_lang["LANG_SELECTION"] = "Idiomas seleccionables"; $pgv_lang["LANGUAGE_DEFAULT"] = "No ha configurado los idiomas de su sitio.<br />PhpGedView utilizará sus opciones por omisión."; $pgv_lang["last_login"] = "Última entrada"; $pgv_lang["lasttab"] = "Última pestaña visitada en Personas"; $pgv_lang["leave_blank"] = "Deje la contraseña en blanco si quiere conservar la contraseña actual."; $pgv_lang["link_manage_servers"] = "Gestionar sitios"; $pgv_lang["logfile_content"] = "Contenido del archivo de registro"; $pgv_lang["macfile_detected"] = "Se detectó un archivo Macintosh. Al realizar limpieza será convertido a archivo DOS."; $pgv_lang["mailto"] = "Vínculo mailto"; $pgv_lang["merge_records"] = "Mezclar registros"; $pgv_lang["message_to_all"] = "Enviar un mensaje a todos los usuarios"; $pgv_lang["messaging"] = "Mensajes internos de PhpGedView"; $pgv_lang["messaging2"] = "Mensajes internos con correo electrónico"; $pgv_lang["messaging3"] = "PhpGedView envía correo electrónico sin almacenamiento"; $pgv_lang["month_before_day"] = "Mes antes del día (MM DD AAAA)"; $pgv_lang["monthly"] = "Mensualmente"; $pgv_lang["msql"] = "Mini SQL"; $pgv_lang["mssql"] = "Microsoft SQL server"; $pgv_lang["mysql"] = "MySQL"; $pgv_lang["never"] = "Nunca"; $pgv_lang["no_logs"] = "Registro de usuarios desactivado"; $pgv_lang["no_messaging"] = "Ningún método de contacto"; $pgv_lang["oci8"] = "Oracle 7+"; $pgv_lang["page_views"] = "&nbsp;&nbsp;visualizaciones de páginas en&nbsp;&nbsp;"; $pgv_lang["performing_validation"] = "Realizando validación del GEDCOM..."; $pgv_lang["pgsql"] = "PostgreSQL"; $pgv_lang["pgv_config_write_error"] = "¡¡¡Error!!! No se pudo escribir el archivo de configuración de PhpGedView. Por favor, compruebe los permisos de archivo y directorio y pruebe nuevamente."; $pgv_lang["PGV_MEMORY_LIMIT"] = "Límite máximo de memoria."; $pgv_lang["PGV_SESSION_SAVE_PATH"] = "Ruta para Guardar Sesión:"; $pgv_lang["PGV_SESSION_TIME"] = "Duración de la Sesión"; $pgv_lang["PGV_SIMPLE_MAIL"] = "Usar encabezamientos simples en los correos electrónicos externos"; $pgv_lang["PGV_SMTP_ACTIVE"] = "Utilizar SMTP para enviar el correo externo"; $pgv_lang["PGV_SMTP_HOST"] = "Nombre del servidor de correo electrónico saliente (SMTP)"; $pgv_lang["PGV_SMTP_HELO"] = "Nombre de dominio para el envío"; $pgv_lang["PGV_SMTP_PORT"] = "Puerto de SMTP"; $pgv_lang["PGV_SMTP_AUTH"] = "Utilizar identificador y contraseña"; $pgv_lang["PGV_SMTP_AUTH_USER"] = "Identificador de usuario"; $pgv_lang["PGV_SMTP_AUTH_PASS"] = "Contraseña"; $pgv_lang["PGV_SMTP_SSL"] = "Usar SSL"; $pgv_lang["PGV_SMTP_FROM_NAME"] = "Nombre del remitente"; $pgv_lang["PGV_STORE_MESSAGES"] = "Permitir el almacenamiento de mensajes en línea:"; $pgv_lang["phpinfo"] = "Información de PHP"; $pgv_lang["place_cleanup_detected"] = "Se detectaron codificaciones de lugar incorrectas. Estos errores deberían corregirse."; $pgv_lang["please_be_patient"] = "POR FAVOR SEA PACIENTE"; $pgv_lang["privileges"] = "Privilegios"; $pgv_lang["reading_file"] = "Leyendo archivo GEDCOM"; $pgv_lang["readme_documentation"] = "Documentación LÉAME"; $pgv_lang["remove_ip"] = "Eliminar IP"; $pgv_lang["REQUIRE_ADMIN_AUTH_REGISTRATION"] = "Requerir que un administrador apruebe el registro de nuevos usuarios"; $pgv_lang["review_readme"] = "Debería revisar primero el archivo <a href=\"readme.txt\" target=\"_blank\">readme.txt</a> antes de continuar configurando PhpGedView.<br /><br />"; $pgv_lang["seconds"] = "&nbsp;&nbsp;segundos"; $pgv_lang["select_an_option"] = "Seleccione una opción:"; $pgv_lang["SERVER_URL"] = "URL de PhpGedView"; $pgv_lang["show_phpinfo"] = "Ver la página de información de PHP"; $pgv_lang["siteadmin"] = "Administrador del sitio"; $pgv_lang["sqlite"] = "SQLite"; $pgv_lang["sybase"] = "Sybase"; $pgv_lang["sync_gedcom"] = "Sincronizar los ajustes de usuario con los datos GEDCOM"; $pgv_lang["system_time"] = "Hora actual del servidor:"; $pgv_lang["user_time"] = "Hora actual del usuario:"; $pgv_lang["TBLPREFIX"] = "Prefijo de las tablas de la base de datos"; $pgv_lang["themecustomization"] = "Personalización del tema"; $pgv_lang["time_limit"] = "Límite de tiempo:"; $pgv_lang["title_manage_servers"] = "Gestionar sitios"; $pgv_lang["title_view_conns"] = "Ver conexiones"; $pgv_lang["translator_tools"] = "Herramientas para el traductor"; $pgv_lang["update_myaccount"] = "Actualizar mi cuenta"; $pgv_lang["update_user"] = "Actualizar usuario"; $pgv_lang["upload_gedcom"] = "Subir GEDCOM"; $pgv_lang["USE_REGISTRATION_MODULE"] = "Permitir registrarse a los usuarios:"; $pgv_lang["user_auto_accept"] = "Aceptar automáticamente los cambios hechos por este usuario"; $pgv_lang["user_contact_method"] = "Método preferido de contacto"; $pgv_lang["user_create_error"] = "No es posible agregar el usuario. Por favor, inténtelo nuevamente."; $pgv_lang["user_created"] = "Usuario creado correctamente."; $pgv_lang["user_default_tab"] = "Pestaña a mostrar por omisión en la página de información de una persona"; $pgv_lang["user_path_length"] = "Máxima longitud de la ruta de privacidad por parentesco"; $pgv_lang["user_relationship_priv"] = "Limitar el acceso a familiares"; $pgv_lang["users_admin"] = "Administradores del sitio"; $pgv_lang["users_gedadmin"] = "Administradores de GEDCOM"; $pgv_lang["users_total"] = "Número total de usuarios"; $pgv_lang["users_unver"] = "No verificados por el usuario"; $pgv_lang["users_unver_admin"] = "No verificados por un administrador"; $pgv_lang["usr_deleted"] = "Usuario borrado: "; $pgv_lang["usr_idle"] = "Número de meses desde la última conexión para que una cuenta de usuario se considere inactiva: "; $pgv_lang["usr_idle_toolong"] = "La cuenta de usuario ha estado inactiva demasiado tiempo: "; $pgv_lang["usr_no_cleanup"] = "No se encontró nada que limpiar"; $pgv_lang["usr_unset_gedcomid"] = "Borrando el ID GEDCOM de "; $pgv_lang["usr_unset_rights"] = "Eliminando derechos de acceso GEDCOM de "; $pgv_lang["usr_unset_rootid"] = "Eliminando el ID raíz de "; $pgv_lang["valid_gedcom"] = "Se detectó un GEDCOM válido. No se requiere 'Limpieza'."; $pgv_lang["validate_gedcom"] = "Validar GEDCOM"; $pgv_lang["verified"] = "Usuario autoverificado"; $pgv_lang["verified_by_admin"] = "Usuario aprobado por el administrador"; $pgv_lang["verify_gedcom"] = "Verificar el GEDCOM"; $pgv_lang["verify_upload_instructions"] = "Se ha encontrado un archivo GEDCOM con el mismo nombre. Si decide continuar, el viejo archivo GEDCOM será reemplazado por el archivo que subió y el proceso de Importación comenzará de nuevo. Si decide cancelar, el viejo GEDCOM permanecerá sin cambios."; $pgv_lang["view_changelog"] = "Ver el archivo changelog.txt"; $pgv_lang["view_logs"] = "Ver archivos de registro"; $pgv_lang["view_readme"] = "Ver el archivo readme.txt"; $pgv_lang["visibleonline"] = "Visible para los demás usuarios cuando esté conectado"; $pgv_lang["visitor"] = "Visitante"; $pgv_lang["warn_users"] = "Usuarios con avisos"; $pgv_lang["weekly"] = "Semanalmente"; $pgv_lang["welcome_new"] = "Bienvenido a su nuevo sitio PhpGedView."; $pgv_lang["yearly"] = "Anualmente"; $pgv_lang["admin_OK_subject"] = "Aprobación de la cuenta en #SERVER_NAME#"; $pgv_lang["admin_OK_message"] = "El administrador del sitio PhpGedView #SERVER_NAME# ha aprobado su solicitud de cuenta. Ya puede entrar de forma identificada accediendo al siguiente vínculo:\r\n\r\n#SERVER_NAME#\r\n"; $pgv_lang["batch_update"]="Realizar cambios en bloque a su GEDCOM"; // Text for the Gedcom Checker $pgv_lang["gedcheck"] = "Comprobador de Gedcom"; // Module title $pgv_lang["gedcheck_text"]= "Este módulo comprueba el formato de un archivo GEDCOM contra la <a href=\"http://phpgedview.sourceforge.net/ged551-5.pdf\">Especificación GEDCOM 5.5.1</a>. También comprueba la existencia de una serie de errores corrientes en sus datos. Nótese que hay muchas versiones, extensiones y variaciones de la especificación, así que no debería preocuparse por problemas salvo los señalados como \"Críticos\". La explicación para cada uno de los errores se encuentra en la especificación. Consúltela, por favor, antes de solicitar ayuda."; $pgv_lang["gedcheck_sync"] = "Las modificaciones a la base de datos no se reflejan en el archivo #GLOBALS[ged]#. El contenido del archivo puede estar desactualizado. Puede sincronizarlo con la base de datos ahora realizando una <b><a \"#GLOBALS[ged_link]#\">exportación</a></b>."; $pgv_lang["gedcheck_nothing"] = "No se encontraron errores a este nivel."; $pgv_lang["level"] = "Nivel"; // Levels of checking $pgv_lang["critical"] = "Crítico"; $pgv_lang["error"] = "Error"; $pgv_lang["warning"] = "Aviso"; $pgv_lang["info"] = "Información"; $pgv_lang["open_link"] = "Abrir vínculos en"; // Where to open links $pgv_lang["same_win"] = "La misma pestaña/ventana"; $pgv_lang["new_win"] = "Una nueva pestaña/ventana"; $pgv_lang["context_lines"]= "Líneas de contexto GEDCOM"; // Number of lines either side of error $pgv_lang["all_rec"] = "Todos los registros"; // What to show $pgv_lang["err_rec"] = "Registros con errores"; $pgv_lang["missing"] = "faltan"; // General error messages $pgv_lang["multiple"] = "múltiples"; $pgv_lang["invalid"] = "inválido"; $pgv_lang["too_many"] = "demasiados"; $pgv_lang["too_few"] = "insuficientes"; $pgv_lang["no_link"] = "no vincula de vuelta"; $pgv_lang["data"] = "datos"; // Specific errors (used with general errors) $pgv_lang["see"] = "ver"; $pgv_lang["noref"] = "Ningún registro hace referencia a éste"; $pgv_lang["tag"] = "etiqueta"; $pgv_lang["spacing"] = "espaciado"; $pgv_lang["ADVANCED_NAME_FACTS"] = "Hechos avanzados para nombres"; $pgv_lang["ADVANCED_PLAC_FACTS"] = "Hechos avanzados para los nombres de lugares"; $pgv_lang["SURNAME_TRADITION"] = "Tradición de apellidos"; // Default surname inheritance $pgv_lang["tradition_spanish"] = "Español"; $pgv_lang["tradition_portuguese"] = "Portugués"; $pgv_lang["tradition_icelandic"] = "Islandés"; $pgv_lang["tradition_paternal"] = "Paterno"; $pgv_lang["tradition_polish"] = "Polaca"; $pgv_lang["tradition_none"] = "Ninguno"; // -- The following text is used to build the phrase "i years, j months, k days, l hours, m minutes" // -- for use in text such as "xxx ago" or "after xxx" or "in xxx" $pgv_lang["elapsedYear1"] = "1 año"; $pgv_lang["elapsedYear2"] = "#pgv_lang[global_num1]# años"; // used in Polish for 2,3,4 or 22,23,24 or 32,33,34 etc. $pgv_lang["elapsedYears"] = "#pgv_lang[global_num1]# años"; $pgv_lang["elapsedMonth1"] = "1 mes"; $pgv_lang["elapsedMonth2"] = "#pgv_lang[global_num1]# meses"; // used in Polish for 2,3,4 or 22,23,24 or 32,33,34 etc. $pgv_lang["elapsedMonths"] = "#pgv_lang[global_num1]# meses"; $pgv_lang["elapsedDay1"] = "1 día"; $pgv_lang["elapsedDay2"] = "#pgv_lang[global_num1]# días"; // used in Polish for 2,3,4 or 22,23,24 or 32,33,34 etc. $pgv_lang["elapsedDays"] = "#pgv_lang[global_num1]# días"; $pgv_lang["elapsedHour1"] = "1 hora"; $pgv_lang["elapsedHour2"] = "#pgv_lang[global_num1]# horas"; // used in Polish for 2,3,4 or 22,23,24 or 32,33,34 etc. $pgv_lang["elapsedHours"] = "#pgv_lang[global_num1]# horas"; $pgv_lang["elapsedMinute1"] = "1 minuto"; $pgv_lang["elapsedMinute2"] = "#pgv_lang[global_num1]# minutos"; // used in Polish for 2,3,4 or 22,23,24 or 32,33,34 etc. $pgv_lang["elapsedMinutes"] = "#pgv_lang[global_num1]# minutos"; $pgv_lang["elapsedAgo"] = "#pgv_lang[global_string1]# atrás"; ?>
{ "content_hash": "553e77b64eecf9adbbbcf86357d32384", "timestamp": "", "source": "github", "line_count": 467, "max_line_length": 766, "avg_line_length": 83.29978586723769, "alnum_prop": 0.685020950618236, "repo_name": "fweber1/Annies-Ancestors", "id": "e44c699649c7f47239ea04f16e06fd38de2b0dbc", "size": "40384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PhpGedView/languages/admin.es.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1064" }, { "name": "Awk", "bytes": "4697" }, { "name": "Batchfile", "bytes": "6467" }, { "name": "CSS", "bytes": "1554235" }, { "name": "ColdFusion", "bytes": "51038" }, { "name": "HTML", "bytes": "2801894" }, { "name": "JavaScript", "bytes": "7729578" }, { "name": "Makefile", "bytes": "7342" }, { "name": "PHP", "bytes": "36634191" }, { "name": "Python", "bytes": "16289" }, { "name": "Roff", "bytes": "29" }, { "name": "Shell", "bytes": "755" }, { "name": "Smarty", "bytes": "38024" }, { "name": "XSLT", "bytes": "11742" } ], "symlink_target": "" }
class MethodCallLogger def initialize @recorders = [] @method_log = [] end def register(*rec_objects) rec_objects.each do |rec| rec._on_method_call{|r| method_log << [r, r._last_method] } recorders << rec end end attr_reader :recorders, :method_log end
{ "content_hash": "4d2a1c31991fa766b12819bf5fdebb10", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 65, "avg_line_length": 17.764705882352942, "alnum_prop": 0.5993377483443708, "repo_name": "markevans/method_call_recorder", "id": "5856a9f0dcea7ce98ea526f7ccaa78d776685623", "size": "302", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/method_call_recorder/method_call_logger.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "15310" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `ctrtri` fn in crate `lapack`."> <meta name="keywords" content="rust, rustlang, rust-lang, ctrtri"> <title>lapack::ctrtri - Rust</title> <link rel="stylesheet" type="text/css" href="../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <p class='location'><a href='index.html'>lapack</a></p><script>window.sidebarCurrent = {name: 'ctrtri', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='index.html'>lapack</a>::<wbr><a class='fn' href=''>ctrtri</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-3055' class='srclink' href='../src/lapack/lib.rs.html#2871-2876' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub fn ctrtri(uplo: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.u8.html'>u8</a>, diag: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.u8.html'>u8</a>, n: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.usize.html'>usize</a>, a: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.slice.html'>&amp;mut [</a><a class='type' href='../lapack/type.c32.html' title='lapack::c32'>c32</a><a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.slice.html'>]</a>, lda: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.usize.html'>usize</a>, info: &amp;mut <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.i32.html'>i32</a>)</pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "lapack"; window.playgroundUrl = ""; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script async src="../search-index.js"></script> </body> </html>
{ "content_hash": "689e28c36d21940c881ab78fc4813b94", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 831, "avg_line_length": 40.82727272727273, "alnum_prop": 0.5328434647071921, "repo_name": "ssgrn/Rust-Matrix-Computations", "id": "f383341fb3c0afa84e1c56c0f4e0dd56a75ada54", "size": "4501", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "target/doc/lapack/fn.ctrtri.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "131093" }, { "name": "C++", "bytes": "1072731" }, { "name": "CMake", "bytes": "137" }, { "name": "CSS", "bytes": "15103" }, { "name": "HTML", "bytes": "39670398" }, { "name": "JavaScript", "bytes": "83160" }, { "name": "Makefile", "bytes": "31497" }, { "name": "Python", "bytes": "421" }, { "name": "Rust", "bytes": "39623" } ], "symlink_target": "" }
package ru.job4j.chess; import static java.lang.Math.abs; /** * Класс для слона. */ public class Bishop extends Figure { /** * Слоновий конструктор. * @param position позиция на доске. */ public Bishop(Cell position) { super(position); } /** * Метод для перезаписи состояния слона в ячейке массива Figures. * @param dist новая позиция на доске. * @return новый объект слона для массива. */ public Figure clone(Cell dist) { return new Bishop(dist); } @Override public Cell[] way(Cell dist) throws ImpossibleMoveException { Cell[] trueWay; //проверяем нахождение координат цели пути на одной диагонали сщ стартовой точкой. if (abs(dist.getPositionX() - getPosition().getPositionX()) == abs(dist.getPositionY() - getPosition().getPositionY())) { trueWay = new Cell[abs(getPosition().getPositionX() - dist.getPositionX())]; //слон идет вправо вверх. if (dist.getPositionX() - getPosition().getPositionX() > 0 && dist.getPositionY() - getPosition().getPositionY() > 0) { for (int i = 0; i < trueWay.length; i++) { trueWay[i] = new Cell(getPosition().getPositionX() + i + 1, getPosition().getPositionY() + i + 1); } //слон идет вправо вниз. } else if (dist.getPositionX() - getPosition().getPositionX() > 0 && dist.getPositionY() - getPosition().getPositionY() < 0) { for (int i = 0; i < trueWay.length; i++) { trueWay[i] = new Cell(getPosition().getPositionX() + i + 1, getPosition().getPositionY() - i - 1); } //слон идет влево вверх } else if ((dist.getPositionX() - getPosition().getPositionX() < 0 && dist.getPositionY() - getPosition().getPositionY() > 0)) { for (int i = 0; i < trueWay.length; i++) { trueWay[i] = new Cell(getPosition().getPositionX() - i - 1, getPosition().getPositionY() + i + 1); } //слон идет влево вниз } else if ((dist.getPositionX() - getPosition().getPositionX() < 0 && dist.getPositionY() - getPosition().getPositionY() < 0)) { for (int i = 0; i < trueWay.length; i++) { trueWay[i] = new Cell(getPosition().getPositionX() - i - 1, getPosition().getPositionY() - i - 1); } } else { throw new ImpossibleMoveException("Wrong way!"); } } else { throw new ImpossibleMoveException("Wrong way!"); } return trueWay; } }
{ "content_hash": "9c144e2ab3a9ca36a2fa390b28fc6791", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 144, "avg_line_length": 39.642857142857146, "alnum_prop": 0.5304504504504505, "repo_name": "yaegorko/Egor-Kuznetcov", "id": "17921877176963f439f88bc04c87d7dc464a609c", "size": "3053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_002/src/main/java/ru.job4j/chess/Bishop.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "278260" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>groups: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.2 / groups - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> groups <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-20 20:17:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-20 20:17:06 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.5.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/groups&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Groups&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: group theory&quot; &quot;category: Miscellaneous/Coq Use Examples&quot; ] authors: [ &quot;Pierre Castéran&quot; ] bug-reports: &quot;https://github.com/coq-contribs/groups/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/groups.git&quot; synopsis: &quot;An exercise on groups&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/groups/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=7c202ef21c698a4549d7d29b427b6e8c&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-groups.8.8.0 coq.8.5.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2). The following dependencies couldn&#39;t be met: - coq-groups -&gt; coq &gt;= 8.8 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-groups.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "d91c2675fb7130ba5c6198dba4c0fc4b", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 159, "avg_line_length": 40.97546012269939, "alnum_prop": 0.5318161401407396, "repo_name": "coq-bench/coq-bench.github.io", "id": "15c1f2ef04e923f9e06b102f4ed574bb7c9c81f5", "size": "6705", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.2/groups/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package monitoring import ( "context" "fmt" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" dclService "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/monitoring/alpha" "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured" ) type Service struct{} func ServiceToUnstructured(r *dclService.Service) *unstructured.Resource { u := &unstructured.Resource{ STV: unstructured.ServiceTypeVersion{ Service: "monitoring", Version: "alpha", Type: "Service", }, Object: make(map[string]interface{}), } if r.DisplayName != nil { u.Object["displayName"] = *r.DisplayName } if r.Name != nil { u.Object["name"] = *r.Name } if r.Project != nil { u.Object["project"] = *r.Project } if r.Telemetry != nil && r.Telemetry != dclService.EmptyServiceTelemetry { rTelemetry := make(map[string]interface{}) if r.Telemetry.ResourceName != nil { rTelemetry["resourceName"] = *r.Telemetry.ResourceName } u.Object["telemetry"] = rTelemetry } if r.UserLabels != nil { rUserLabels := make(map[string]interface{}) for k, v := range r.UserLabels { rUserLabels[k] = v } u.Object["userLabels"] = rUserLabels } return u } func UnstructuredToService(u *unstructured.Resource) (*dclService.Service, error) { r := &dclService.Service{} if _, ok := u.Object["displayName"]; ok { if s, ok := u.Object["displayName"].(string); ok { r.DisplayName = dcl.String(s) } else { return nil, fmt.Errorf("r.DisplayName: expected string") } } if _, ok := u.Object["name"]; ok { if s, ok := u.Object["name"].(string); ok { r.Name = dcl.String(s) } else { return nil, fmt.Errorf("r.Name: expected string") } } if _, ok := u.Object["project"]; ok { if s, ok := u.Object["project"].(string); ok { r.Project = dcl.String(s) } else { return nil, fmt.Errorf("r.Project: expected string") } } if _, ok := u.Object["telemetry"]; ok { if rTelemetry, ok := u.Object["telemetry"].(map[string]interface{}); ok { r.Telemetry = &dclService.ServiceTelemetry{} if _, ok := rTelemetry["resourceName"]; ok { if s, ok := rTelemetry["resourceName"].(string); ok { r.Telemetry.ResourceName = dcl.String(s) } else { return nil, fmt.Errorf("r.Telemetry.ResourceName: expected string") } } } else { return nil, fmt.Errorf("r.Telemetry: expected map[string]interface{}") } } if _, ok := u.Object["userLabels"]; ok { if rUserLabels, ok := u.Object["userLabels"].(map[string]interface{}); ok { m := make(map[string]string) for k, v := range rUserLabels { if s, ok := v.(string); ok { m[k] = s } } r.UserLabels = m } else { return nil, fmt.Errorf("r.UserLabels: expected map[string]interface{}") } } return r, nil } func GetService(ctx context.Context, config *dcl.Config, u *unstructured.Resource) (*unstructured.Resource, error) { c := dclService.NewClient(config) r, err := UnstructuredToService(u) if err != nil { return nil, err } r, err = c.GetService(ctx, r) if err != nil { return nil, err } return ServiceToUnstructured(r), nil } func ListService(ctx context.Context, config *dcl.Config, project string) ([]*unstructured.Resource, error) { c := dclService.NewClient(config) l, err := c.ListService(ctx, project) if err != nil { return nil, err } var resources []*unstructured.Resource for { for _, r := range l.Items { resources = append(resources, ServiceToUnstructured(r)) } if !l.HasNext() { break } if err := l.Next(ctx, c); err != nil { return nil, err } } return resources, nil } func ApplyService(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { c := dclService.NewClient(config) r, err := UnstructuredToService(u) if err != nil { return nil, err } if ush := unstructured.FetchStateHint(opts); ush != nil { sh, err := UnstructuredToService(ush) if err != nil { return nil, err } opts = append(opts, dcl.WithStateHint(sh)) } r, err = c.ApplyService(ctx, r, opts...) if err != nil { return nil, err } return ServiceToUnstructured(r), nil } func ServiceHasDiff(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { c := dclService.NewClient(config) r, err := UnstructuredToService(u) if err != nil { return false, err } if ush := unstructured.FetchStateHint(opts); ush != nil { sh, err := UnstructuredToService(ush) if err != nil { return false, err } opts = append(opts, dcl.WithStateHint(sh)) } opts = append(opts, dcl.WithLifecycleParam(dcl.BlockDestruction), dcl.WithLifecycleParam(dcl.BlockCreation), dcl.WithLifecycleParam(dcl.BlockModification)) _, err = c.ApplyService(ctx, r, opts...) if err != nil { if _, ok := err.(dcl.ApplyInfeasibleError); ok { return true, nil } return false, err } return false, nil } func DeleteService(ctx context.Context, config *dcl.Config, u *unstructured.Resource) error { c := dclService.NewClient(config) r, err := UnstructuredToService(u) if err != nil { return err } return c.DeleteService(ctx, r) } func ServiceID(u *unstructured.Resource) (string, error) { r, err := UnstructuredToService(u) if err != nil { return "", err } return r.ID() } func (r *Service) STV() unstructured.ServiceTypeVersion { return unstructured.ServiceTypeVersion{ "monitoring", "Service", "alpha", } } func (r *Service) SetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Service) GetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, role, member string) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Service) DeletePolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) error { return unstructured.ErrNoSuchMethod } func (r *Service) SetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Service) SetPolicyWithEtag(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Service) GetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Service) Get(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { return GetService(ctx, config, resource) } func (r *Service) Apply(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { return ApplyService(ctx, config, resource, opts...) } func (r *Service) HasDiff(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { return ServiceHasDiff(ctx, config, resource, opts...) } func (r *Service) Delete(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) error { return DeleteService(ctx, config, resource) } func (r *Service) ID(resource *unstructured.Resource) (string, error) { return ServiceID(resource) } func init() { unstructured.Register(&Service{}) }
{ "content_hash": "11d71d61cc5f1278cb0a13631174899b", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 174, "avg_line_length": 30.472, "alnum_prop": 0.6972958781832502, "repo_name": "GoogleCloudPlatform/declarative-resource-client-library", "id": "98373c606d1f13a62001a2b925c572acda1a5629", "size": "8230", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "unstructured/google/monitoring/alpha/service.go", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2560" }, { "name": "C++", "bytes": "3947" }, { "name": "Go", "bytes": "116489733" }, { "name": "Python", "bytes": "17240408" }, { "name": "Starlark", "bytes": "319733" } ], "symlink_target": "" }
from a10sdk.common.A10BaseClass import A10BaseClass class PortList(A10BaseClass): """This class does not support CRUD Operations please use parent. :param action: {"type": "string", "format": "string"} :param ethernet: {"type": "number", "format": "number"} :param management: {"type": "number", "format": "number"} :param ve: {"type": "number", "format": "number"} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.b_key = "port-list" self.DeviceProxy = "" self.action = "" self.ethernet = "" self.management = "" self.ve = "" for keys, value in kwargs.items(): setattr(self,keys, value) class Oper(A10BaseClass): """This class does not support CRUD Operations please use parent. :param port_list: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"action": {"type": "string", "format": "string"}, "ethernet": {"type": "number", "format": "number"}, "management": {"type": "number", "format": "number"}, "optional": true, "ve": {"type": "number", "format": "number"}}}]} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.b_key = "oper" self.DeviceProxy = "" self.port_list = [] for keys, value in kwargs.items(): setattr(self,keys, value) class AclIpv4(A10BaseClass): """Class Description:: Operational Status for the object acl-ipv4. Class acl-ipv4 supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/enable-management/acl-ipv4/oper`. """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.required=[] self.b_key = "acl-ipv4" self.a10_url="/axapi/v3/enable-management/acl-ipv4/oper" self.DeviceProxy = "" self.oper = {} for keys, value in kwargs.items(): setattr(self,keys, value)
{ "content_hash": "83773ea5d811ea95aa579d8e8d9c8707", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 353, "avg_line_length": 29.857142857142858, "alnum_prop": 0.5925039872408293, "repo_name": "a10networks/a10sdk-python", "id": "ea8758c3ffa583b550b5669f7dcf8eada24c032a", "size": "2508", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "a10sdk/core/enable/enable_management_acl_ipv4_oper.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "6956372" } ], "symlink_target": "" }
<!-- Preloader --> <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com"> <div id="preloader"> <div class="loader"> <svg class="circle-loader" height="50" width="50"> <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="6" stroke-miterlimit="10" /> </svg> </div> </div><!--preloader end--> <!-- Main Container --> <main id="app" class="main-section"> <!-- header navigation start --> <header id="navigation" class="root-sec white nav"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="nav-inner"> <nav class="primary-nav"> <div class="clearfix nav-wrapper"> <a href="#home" class="left brand-logo menu-smooth-scroll" data-section="#home"><img src="<?php echo base_url();?>assets/images/logo.png" alt=""> </a> <a href="<?php echo base_url();?>" data-activates="mobile-demo" class="button-collapse"><i class="fa fa-bars" aria-hidden="true"></i></a> <ul class="inline-menu side-nav" id="mobile-demo"> <!-- Mini Profile // only visible in Tab and Mobile --> <li class="mobile-profile"> <div class="profile-inner"> <div class="pp-container"> <img src="<?php echo base_url();?>assets/images/logo.png" alt=""> </div> <h3>Monitor Ciudadano</h3> </div> </li><!-- mini profile end--> <li><a href="<?php echo base_url();?>inicio/publicos"><i class="fa fa-user fa-fw"></i>Servidores Públicos</a> </li> <li><a href="<?php echo base_url();?>inicio/candidatos"><i class="fa fa-file-text fa-fw"></i>Candidatos</a> </li> <li><a href="blog-with-sidebar.html">A cerca de nosotros</a> </li> <li><a href="<?php echo base_url();?>inicio/nosotros">A cerca de nosotros</a> </li> <li><a href="#!" onclick="iniciar_sesion()">Iniciar Sesión</a> </li> </ul> </div> </nav> </div> </div> </div> </div> <!-- .container end --> </header> <!-- #header navigation end --> <div id="login" class="modal plr-10"> <div class="modal-content"> <div class="row"> <div class="col l12 center"> <h5 style="font-size: 24px; color: #000;"><strong style="font-weight: bold; font-size: 32px;">Monitor Ciudadano</strong><br>Iniciar sesión:</h5> <div class="divider"></div> </div> <div class="col l12"> <div class="group"> <center><div class="fb-login-button" data-max-rows="1" data-size="large" data-width="205px" data-button-type="continue_with" data-show-faces="false" data-auto-logout-link="false" data-use-continue-as="false"></div> <br><br> <div class="g-signin2" data-onsuccess="onSignIn"></div> </center> </div> </div> </div> </div> </div>
{ "content_hash": "6c128688e7b9f3bae16698af9e29e45b", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 228, "avg_line_length": 42.282051282051285, "alnum_prop": 0.4948453608247423, "repo_name": "Nydia28/Morelia-Hacks-Bots", "id": "9ded0aaa7ff77ee47b94ccde7493735f606e3670", "size": "3301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/theme/nav.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "528" }, { "name": "CSS", "bytes": "51090" }, { "name": "HTML", "bytes": "5633" }, { "name": "JavaScript", "bytes": "569879" }, { "name": "PHP", "bytes": "1822954" } ], "symlink_target": "" }
namespace bombali.infrastructure.logging.custom { using ILog = log4net.ILog; public class Log4NetLogger : logging.ILog { private readonly ILog logger; public Log4NetLogger(ILog logger) { this.logger = logger; //logger.DebugFormat("Initializing {0}<{1}>", GetType().FullName, logger.Logger.Name); } public void Debug(string message, params object[] args) { logger.DebugFormat(message, args); } public void Info(string message, params object[] args) { logger.InfoFormat(message, args); } public void Warn(string message, params object[] args) { logger.WarnFormat(message, args); } public void Error(string message, params object[] args) { logger.ErrorFormat(message, args); } public void Fatal(string message, params object[] args) { logger.FatalFormat(message, args); } } }
{ "content_hash": "849482f15f1dc52d7fdc0000641558d3", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 98, "avg_line_length": 26.75, "alnum_prop": 0.5476635514018692, "repo_name": "ferventcoder/bombali", "id": "1060361732dd5e006c9a49fc6225bbca900b86a8", "size": "1070", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "product/bombali/infrastructure/logging/custom/Log4NetLogger.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8185" }, { "name": "C#", "bytes": "161048" }, { "name": "CSS", "bytes": "347" }, { "name": "Groff", "bytes": "522" }, { "name": "HTML", "bytes": "108962" }, { "name": "XSLT", "bytes": "34815" } ], "symlink_target": "" }
using System; namespace RestSharp { public sealed class RestResponseCookie { /// <summary> /// Comment of the cookie /// </summary> public string Comment { get; set; } /// <summary> /// Comment of the cookie /// </summary> public Uri CommentUri { get; set; } /// <summary> /// Indicates whether the cookie should be discarded at the end of the session /// </summary> public bool Discard { get; set; } /// <summary> /// Domain of the cookie /// </summary> public string Domain { get; set; } /// <summary> /// Indicates whether the cookie is expired /// </summary> public bool Expired { get; set; } /// <summary> /// Date and time that the cookie expires /// </summary> public DateTimeOffset Expires { get; set; } /// <summary> /// Indicates that this cookie should only be accessed by the server /// </summary> public bool HttpOnly { get; set; } /// <summary> /// Name of the cookie /// </summary> public string Name { get; set; } /// <summary> /// Path of the cookie /// </summary> public string Path { get; set; } /// <summary> /// Port of the cookie /// </summary> public string Port { get; set; } /// <summary> /// Indicates that the cookie should only be sent over secure channels /// </summary> public bool Secure { get; set; } /// <summary> /// Date and time the cookie was created /// </summary> public DateTimeOffset TimeStamp { get; set; } /// <summary> /// Value of the cookie /// </summary> public string Value { get; set; } /// <summary> /// Version of the cookie /// </summary> public int Version { get; set; } } }
{ "content_hash": "71a9d3f972b95af0c0d38c0117c5a8f0", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 80, "avg_line_length": 26.6875, "alnum_prop": 0.5878220140515222, "repo_name": "devinrader/RestSharpRTExperimental", "id": "b5331293931e2f079b40d21ed81ffe9aedb83d38", "size": "1708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RestSharp.WinRT/RestResponseCookie.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1191967" }, { "name": "Shell", "bytes": "2530" } ], "symlink_target": "" }
CopyRight (C) 2017 - Leonardo Soares e Silva - lsoaresesilva@gmail.com ## Sumary Creating user interfaces for busines apps on Corona can be hard task if you compare to Android Activity Design, for example. This library was inspired on Android and JavaFX user interface creation, and enables the creation of user interfaces through XML files. ### Resources: *** Support for Corona components: buttons, textfields, textbox, texts and images. Create corona components directly through XML. *** Layout organizations horizontaly and verticaly with left and center aligns. Corona components can be organized horizontaly and verticaly with left and center aligns. *** Support for nested layouts. Supports for layouts, with diferents organizations, inside other layouts *** Defining components listeners through XML. Define component listeners without needing to call :addEventListener manualy. *** Support for css-like stylishing of components. Stylish components using a css-like syntax. You can even reuse definitions in many components. *** Support for one-way binding between lua variables and corona components. You can define a bind between a variable and a input component like textfield. Everytime this component changes it values the variable will also change. *** Support for binding xml to components in lua Every component added to layout will automatically create a reference as a lua variable. Kind of a dependency injection. *** Support for minimal input field validation You can define which input fields (Text Fields or box) cannot be empty and if it is empty a message will be shown to user. ## Instalation Copy view.lua and libs folder to your project folder. Import view.lua to use it. ## Usage Example: ## Loading a view: ```lua -- in your main.lua local viewLoader = require("view") local view = viewLoader:setView("layout.xml") ``` -- Create a file with .xml extension in your project's folder, example: ```xml <LinearLayout id="layoutLinear" orientation="vertical" align="center" paddingX="10"> <Text id="txtUsername" x="10" y="10" text="Username" /> <TextField /> <Text id="txtPassword" x="10" y="50" text="Password" /> <TextField /> <Button label="Login" /> </LinearLayout> ``` And it is done. ![A login example](http://i36.photobucket.com/albums/e43/leonardo_soares4/screenshot_xmllayout_zpshkhn0ix0.png) ## Inserting components programmatically ```lua -- in your main.lua local widget = require("widget") local viewLoader = require("view") local view = viewLoader:setView("layout.xml") local layout = view:findLayoutById("layoutLinear") local recoverPasswordButton = widget.newButton({label="Recover"}) layout:insert(recoverPasswordButton) ``` ## Updating components programmatically ```lua -- in your main.lua local widget = require("widget") local viewLoader = require("view") local view = viewLoader:setView("layout.xml") local textUsername = view:findLayoutById("txtUsername") textUsername.text = "New Text!" ``` ## Use with composer ```lua -- in your scene.lua local composer = require("composer") local viewLoader = require("view") local view = viewLoader:setView("layout.xml") local scene = composer.newScene() function scene:create( event ) local sceneGroup = self.view -- Code here runs when the scene is first created but has not yet appeared on screen sceneGroup:insert(view) end return scene ``` ## Example using inner layouts, blankSpace component and images. * A XML file with layout definition. ```xml <!-- An calculator example --> <LinearLayout id="layoutLinear" orientation="vertical" align="center"> <TextField id="txtField"/> <BlankSpace width="10" height="20"/> <LinearLayout id="layoutFirstRow" orientation="horizontal" align="center"> <Image filename="btn_1.png" width="50" height="50" touch="pressButton"/> <Image filename="btn_2.png" width="50" height="50" /> <Image filename="btn_3.png" width="50" height="50" /> <Image filename="btn_sum.png" width="50" height="50" /> </LinearLayout> <BlankSpace width="10" height="20"/> <LinearLayout id="layoutSecondRow" orientation="horizontal" align="center"> <Image filename="btn_4.png" width="50" height="50" /> <Image filename="btn_5.png" width="50" height="50" /> <Image filename="btn_6.png" width="50" height="50" /> <Image filename="btn_minus.png" width="50" height="50" /> </LinearLayout> </LinearLayout> ``` ## Listener definition * In your lua file. ```lua controller = {} function controller.doLogin(event) -- will be called when button is touched! end local viewLoader = require("view") local view = viewLoader:setView("layout.xml", controller) ``` * A XML file with layout definition. ```xml <LinearLayout id="layoutLinear" orientation="vertical" align="center"> <Button touch="doLogin" label="Login"/> </LinearLayout> ``` ## CSS example This resource is based on CSS principles and you can define a css 'class' like with properties to stylish your elements. Actually only text component can be stylished. You have to create a file named style.lua inside your main folder. A lua table will be used to define the stylish of your components. Each property inside this table must be a lua table and will have properties to stylish our components. ```lua -- style.lua styles = { myTextStyle = { color = "00bfd0", fontSize = "20" } } return styles ``` * A XML file with layout definition. ```xml [..] <LinearLayout id="layoutLinear" orientation="vertical" align="center"> <TextField id="txtField" class="myTextStyle"/> <TextField id="otherField" class="myTextStyle"/> [..] </LinearLayout> ``` ## One-way binding ```lua controller = { login = "", password = "" } function controller.login(event) if event.phase == "ended" then print(controller.login) print(controller.password) end end local viewLoader = require("view") local view = viewLoader:setView("layout.xml", controller) ``` ```xml <LinearLayout id="layoutLinear" orientation="vertical" align="center"> <Text id="txtLogin" text="Login" class="alterandoCores"/> <TextField model="login" /> <Text id="txtPassword" text="Password" class="alterandoCores"/> <TextField model="password" /> <BlankSpace height="30" width="100"/> <Button touch="login" label="Login"/> </LinearLayout> ``` ## Component bind (dependency injection) ```xml <LinearLayout id="layoutLinear" orientation="vertical" align="center"> <Text id="txtLogin" text="Login" class="alterandoCores"/> </LinearLayout> ``` ```lua controller = {} local viewLoader = require("view") local view = viewLoader:setView("layout.xml", controller) -- Use the id defined to have access for the component in your controller print(controller.txtLogin.text) -- will print "Login" ``` ## APIDoc ```lua -- View functions -- Loads a layout from XML and displays on screen. -- @param layout : XML file within layout declaration (required) -- @param controller : A Lua table which contains listeners functions. (optional) -- @return : A Lua table within all elements extracted from layout. setView(layout, [controller]) -- Searchs if there is a layout with the specified identifier. -- @param id : String which contains the layout's identifier we want to search. -- @return : If a layout is found, returns it. If not returns nil. findLayoutById(id) -- Searchs if there is a component with the specified identifier. -- @param id : String which contains the component's identifier we want to search. -- @return : If a component is found, returns it. If not returns nil. findComponentById(id) ``` ## Changelog * 0.3.5 - 23/03/2017 ** Added a dependency injection like to map components defined in XML into lua variables for easy access. * 0.3 - 22/03/2017 ** Minor modifications on BlankSpace component, still backward compatibility. ** Added one-way binding between lua variables and corona components. ** Improved the README. * 0.2 - 15/03/2017 ** Added support for nested/inner layouts; ** Added support for a css-like style (experimental); ** Added support for listeners definition through XML (works for tap, touch and userinput events); ** Added a two new components: Image and BlankSpace (inserts a blank space in yout layout); ** Refactored the function to position components on screen, its much better now :)
{ "content_hash": "efad9b86370dbd4e1525795bcfcc013b", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 238, "avg_line_length": 29.589473684210525, "alnum_prop": 0.719672714336535, "repo_name": "lsoaresesilva/corona_view", "id": "44eb22b671f3e8a78d2e9412cbae6cf61db6bad1", "size": "8461", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "readme.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Lua", "bytes": "80483" } ], "symlink_target": "" }
<h1>This is the partial for Register</h1> <p>Can create teams or organizations</p>
{ "content_hash": "b32e6d7e0d992868f7cc38ccf3bb48c9", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 41, "avg_line_length": 41.5, "alnum_prop": 0.7469879518072289, "repo_name": "rkalin/SolsRecycling", "id": "cd361ede9c08eac76287bb860358a1687799ff5b", "size": "83", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/partials/protected/register/register.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "196" }, { "name": "HTML", "bytes": "4539" }, { "name": "JavaScript", "bytes": "2325" }, { "name": "PHP", "bytes": "4514" } ], "symlink_target": "" }
package me.chris.SimpleChat.PartyHandler; import java.util.ArrayList; import me.chris.SimpleChat.SimpleChatAPI; import me.chris.SimpleChat.SimpleChatHelperMethods; import me.chris.SimpleChat.Variables; import org.bukkit.entity.Player; public class PartyChat { public static void togglePartyChat(Player p) { if (!Variables.lockedPartyChat.containsKey(p)) { if (PartyAPI.isPlayerInAParty(p)) { if (Variables.lockedPM.containsKey(p)) { Variables.lockedPM.remove(p); p.sendMessage("§a[SimpleChat] §7Locked PM has been turned §4§lOFF§7."); } if (Variables.adminChat.contains(p)) { Variables.adminChat.remove(p); p.sendMessage("§a[SimpleChat] §7Admin chat has been turned §4§lOFF§7."); } Variables.lockedPartyChat.put(p, PartyAPI.findPartyofPlayer(p)); p.sendMessage("§a[SimpleChat] §7Party chat has been turned §2§lON§7."); } else { p.sendMessage("§a[SimpleChat] §4You are not in a party."); } } else { Variables.lockedPartyChat.remove(p); p.sendMessage("§a[SimpleChat] §7Party chat has been turned §4§lOFF§7."); } } public static void partyChat(Player p, String msg) { if (PartyAPI.isPlayerInAParty(p)) { Party pty = PartyAPI.findPartyofPlayer(p); ArrayList<Player> onlineMembers = pty.onlineMembers; //Regular members for (Player member : onlineMembers) { if (member == null) { continue; } if (!member.isOnline()) { pty.removeOnlineMember(member); continue; } String[] vars = { "+pname", "+dname", "+pre", "+suf", "+gro", "+msg", "+partyname", "&" }; String[] replace = { p.getName(), p.getDisplayName(), SimpleChatAPI.getPrefix(p), SimpleChatAPI.getSuffix(p), SimpleChatAPI.getGroup(p), msg, PartyAPI.findPartyofPlayer(p).partyName, "§" }; String chat = SimpleChatHelperMethods.replaceVars(Variables.PartyChatFormat, vars, replace); member.sendMessage(chat); } // Invisible Members ArrayList<String> invisibleMembers = pty.invisibleMembers; for (String member : invisibleMembers) { if (member.equalsIgnoreCase(p.getName())) { continue; } Player partyMember = Variables.plugin.getServer().getPlayer(member); if (partyMember != null && partyMember.isOnline()) { String[] vars = { "+pname", "+dname", "+pre", "+suf", "+gro", "+msg", "+partyname", "&" }; String[] replace = { p.getName(), p.getDisplayName(), SimpleChatAPI.getPrefix(p), SimpleChatAPI.getSuffix(p), SimpleChatAPI.getGroup(p), msg, PartyAPI.findPartyofPlayer(p).partyName, "§" }; String chat = SimpleChatHelperMethods.replaceVars(Variables.PartyChatFormat, vars, replace); partyMember.sendMessage(chat); } } for (Player onlineSocialSpy : Variables.onlineSocialSpy) { if (onlineSocialSpy == p) { continue; } if(pty.members.contains(onlineSocialSpy.getName())) { continue; } if(Variables.socialSpyOffParty.contains(onlineSocialSpy.getName())) { continue; } onlineSocialSpy.sendMessage("§8§l[§7" + pty.partyName + "§8§l] §7" + p.getName() + ": §e§o" + msg); } } else { p.sendMessage("§a[SimpleChat] §4You are not in a party."); } } }
{ "content_hash": "48c3d72e2b02dfd7eb58b8b185b8ba14", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 103, "avg_line_length": 26.450381679389313, "alnum_prop": 0.6126984126984127, "repo_name": "hotshot2162/SimpleChat", "id": "951e611c9c890f29d3440f93a891c3711f79a5ad", "size": "3465", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/me/chris/SimpleChat/PartyHandler/PartyChat.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "280494" } ], "symlink_target": "" }
namespace Appleseed.Framework.Web.UI.WebControls { using System.Collections; using System.Web; using System.Web.UI.WebControls; using Appleseed.Framework.Settings.Cache; using Appleseed.Framework.Site.Configuration; /// <summary> /// A PortalModuleControl that supports CustomUserSettings for authenticated users. (Users can specify /// settings for the module instance that will apply only to them when they interact with the module). /// </summary> public class PortalModuleControlCustom : PortalModuleControl { // provide a custom Hash table that will store user-specific settings for this instance // of the module. #region Constants and Fields /// <summary> /// The custom user settings. /// </summary> protected Hashtable CustomUserSettings; /// <summary> /// The customize button. /// </summary> private ModuleButton customizeButton; #endregion #region Properties /// <summary> /// Gets Module Properties button /// </summary> /// <value>The customize button.</value> public ModuleButton CustomizeButton { get { if (this.customizeButton == null && HttpContext.Current != null) { // check authority if (this.HasCustomizeableSettings && PortalSettings.CurrentUser.Identity.IsOnline) { // create the button this.customizeButton = new ModuleButton { Group = ModuleButton.ButtonGroup.Admin, EnglishName = "Customize", TranslationKey = "CUSTOMIZE", Image = this.CurrentTheme.GetImage("Buttons_Properties", "Properties.gif") }; if (this.PropertiesUrl.IndexOf("?") >= 0) { // Do not change if the query string is present (shortcut patch) // if ( this.ModuleID != this.OriginalModuleID ) // shortcut this.customizeButton.HRef = this.PropertiesUrl; } else { this.customizeButton.HRef = HttpUrlBuilder.BuildUrl( "~/DesktopModules/CoreModules/Admin/CustomPropertyPage.aspx", this.PageID, string.Format("mID={0}", this.ModuleID)); } this.customizeButton.Target = this.PropertiesTarget; this.customizeButton.RenderAs = this.ButtonsRenderAs; } } return this.customizeButton; } } /// <summary> /// Gets the customized user settings. /// </summary> /// <value>The customized user settings.</value> public Hashtable CustomizedUserSettings { get { if (this.CustomUserSettings != null) { return this.CustomUserSettings; } var tempSettings = new Hashtable(); // refresh this module's settings on every call in case they logged off, so it will // retrieve the 'default' settings from the database. // Invalidate cache CurrentCache.Remove(Key.ModuleSettings(this.ModuleID)); // this._baseSettings = ModuleSettings.GetModuleSettings(this.ModuleID, this._baseSettings); foreach (string str in this.Settings.Keys) { var thedefault = this.Settings[str] as SettingItem<string, TextBox>; if (thedefault != null) { if (thedefault.Group == SettingItemGroup.CUSTOM_USER_SETTINGS) { // It's one we want to customize tempSettings.Add(str, thedefault); // insert the 'default' value } } } // Now, replace the default settings with the custom settings for this user from the database. return ModuleSettingsCustom.GetModuleUserSettings( this.ModuleConfiguration.ModuleID, PortalSettings.CurrentUser.Identity.ProviderUserKey, tempSettings); } } /// <summary> /// Gets a value indicating whether this instance has customizable settings. /// </summary> /// <value> /// <c>true</c> if this instance has customizable settings; otherwise, <c>false</c>. /// </value> public bool HasCustomizeableSettings { get { return this.CustomizedUserSettings.Count > 0; } } #endregion #region Methods /// <summary> /// Builds the three public button lists /// </summary> protected override void BuildButtonLists() { if (this.CustomizeButton != null) { this.ButtonListAdmin.Add(this.CustomizeButton); } base.BuildButtonLists(); } #endregion } }
{ "content_hash": "cf646695a6d18f1ea36d5452ac8859de", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 110, "avg_line_length": 36.746753246753244, "alnum_prop": 0.4983212581728221, "repo_name": "Appleseed/portal", "id": "476737a6012c1b9c2f3582e5760c27b4cb16ca05", "size": "6262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Master/Appleseed/Projects/Appleseed.Framework.Core/UI/WebControls/PortalModuleControlCustom.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "701416" }, { "name": "Batchfile", "bytes": "5824" }, { "name": "C#", "bytes": "5437355" }, { "name": "CSS", "bytes": "3097267" }, { "name": "ColdFusion", "bytes": "166069" }, { "name": "Gherkin", "bytes": "225" }, { "name": "HTML", "bytes": "1084272" }, { "name": "JavaScript", "bytes": "5781627" }, { "name": "Lasso", "bytes": "34435" }, { "name": "PHP", "bytes": "111194" }, { "name": "PLpgSQL", "bytes": "353788" }, { "name": "Perl", "bytes": "38719" }, { "name": "Perl 6", "bytes": "25708" }, { "name": "PowerShell", "bytes": "3737" }, { "name": "Python", "bytes": "46471" }, { "name": "SQLPL", "bytes": "6479" }, { "name": "Smalltalk", "bytes": "25790" }, { "name": "XSLT", "bytes": "39762" } ], "symlink_target": "" }
<div id="top-resources"> <div class="top-resource" v-for="res in Resources" :data-overlimit="res.Value >= Overlimit ? 1 : 0"> <img class="resource-icon" :src="'modules/top-resource/icon_'+res.LowerName+'.png'" /> <div class="resource-value">{{res.Value}}</div> </div> </div>
{ "content_hash": "40e6edbbea99945d80094b54c0a5b8c6", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 88, "avg_line_length": 36, "alnum_prop": 0.6388888888888888, "repo_name": "WolfgangKurz/BeerViewer", "id": "74de567d1c05734f0c3548002d62a6e6bb7e83c3", "size": "290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WindowFrame/source/modules/top-resource/top-resource.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "214733" }, { "name": "CSS", "bytes": "34822" }, { "name": "HTML", "bytes": "29833" }, { "name": "JavaScript", "bytes": "2429" }, { "name": "PowerShell", "bytes": "2019" }, { "name": "TypeScript", "bytes": "196318" } ], "symlink_target": "" }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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. using System.Reflection; #if !W8CORE using System; using System.IO; using SharpDX.Toolkit.Graphics; using System.Collections.Generic; namespace SharpDX.Toolkit { public partial class EffectCompilerSystem { #region Fields private readonly Dictionary<Effect, List<FileSystemWatcher>> effectsToWatcher = new Dictionary<Effect, List<FileSystemWatcher>>(); private readonly Dictionary<FileSystemWatcher, List<Effect>> watcherToEffects = new Dictionary<FileSystemWatcher, List<Effect>>(); #endregion #region Methods private void InitializeCompiler() { var assemblyDirectory = Path.GetDirectoryName(typeof(EffectCompilerSystem).Assembly.Location); if(assemblyDirectory != null) { var assemblyPath = Path.Combine(assemblyDirectory, "SharpDX.Toolkit.Compiler.dll"); if(File.Exists(assemblyPath)) { var assembly = Assembly.LoadFile(assemblyPath); var type = assembly.GetType("SharpDX.Toolkit.Graphics.EffectCompiler"); if(type != null) { compiler = (IEffectCompiler)Activator.CreateInstance(type); } } } } protected virtual void TrackEffect(Effect effect) { var fileList = compiler.LoadDependency(effect.RawEffectData.Arguments.DependencyFilePath); List<FileSystemWatcher> watchers; if (!effectsToWatcher.TryGetValue(effect, out watchers)) { watchers = new List<FileSystemWatcher>(); effectsToWatcher.Add(effect, watchers); } var dirList = GetDirectoryList(fileList); var currentWatchers = new List<FileSystemWatcher>(); foreach (var dirPath in dirList) { // Try to find an existing watcher var watcher = FindWatcher(watchers, dirPath) ?? FindWatcher(watcherToEffects.Keys, dirPath); if (watcher == null) { watcher = new FileSystemWatcher(dirPath); var effectPerWatch = new List<Effect> { effect }; watcherToEffects.Add(watcher, effectPerWatch); watcher.Changed += watcher_Changed; watcher.EnableRaisingEvents = true; } else { var effectPerWatch = watcherToEffects[watcher]; if (!effectPerWatch.Contains(effect)) { effectPerWatch.Add(effect); } } if (!watchers.Contains(watcher)) { watchers.Add(watcher); } if (!currentWatchers.Contains(watcher)) { currentWatchers.Add(watcher); } } // Release any previous watcher allocated that are no longer needed. foreach (var watcher in watchers) { if (!currentWatchers.Contains(watcher)) { RemoveEffectFromWatcher(effect, watcher); } } // Update the list of watchers for the specified effect watchers.Clear(); watchers.AddRange(currentWatchers); } protected virtual void UnTrackEffect(Effect effect) { var watchersPerEffect = effectsToWatcher[effect]; foreach (var watcher in watchersPerEffect) { RemoveEffectFromWatcher(effect, watcher); } effectsToWatcher.Remove(effect); } private FileSystemWatcher FindWatcher(IEnumerable<FileSystemWatcher> watchers, string path) { foreach (var watcher in watchers) { if (string.Compare(watcher.Path, path, StringComparison.InvariantCultureIgnoreCase) == 0) { return watcher; } } return null; } private void RemoveEffectFromWatcher(Effect effect, FileSystemWatcher watcher) { var listOfEffect = watcherToEffects[watcher]; listOfEffect.Remove(effect); if (listOfEffect.Count == 0) { watcher.EnableRaisingEvents = false; watcher.Changed -= watcher_Changed; watcher.Dispose(); watcherToEffects.Remove(watcher); } } private void watcher_Changed(object sender, FileSystemEventArgs e) { if (e.ChangeType == WatcherChangeTypes.Changed) { bool notityRecompiler = false; var effectListToCheck = watcherToEffects[(FileSystemWatcher)sender]; lock (effectListToCheck) { foreach (var effect in effectListToCheck) { var args = effect.RawEffectData.Arguments; bool checkForCompiler = false; lock (effectsToCheck) { if (!effectsToCheck.Contains(effect)) { checkForCompiler = true; } } if (checkForCompiler) { if (compiler.CheckForChanges(args.DependencyFilePath)) { lock (effectsToCheck) { if (!effectsToCheck.Contains(effect)) { effectsToCheck.Add(effect); notityRecompiler = true; } } } } } } if (notityRecompiler) { resetEvent.Set(); } } } #endregion } } #endif
{ "content_hash": "2e3cd7b5ff5587c777ac1029abb8db99", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 138, "avg_line_length": 36.004784688995215, "alnum_prop": 0.5258471760797342, "repo_name": "wyrover/SharpDX", "id": "78b8acf0305e3a989915272a5d93765930d2f43f", "size": "7527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Toolkit/SharpDX.Toolkit.Game/EffectCompilerSystem.Desktop.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2165038" }, { "name": "C#", "bytes": "10840548" }, { "name": "C++", "bytes": "6556094" }, { "name": "CSS", "bytes": "10347" }, { "name": "FLUX", "bytes": "79643" }, { "name": "Shell", "bytes": "4192" } ], "symlink_target": "" }
@interface ViewController () @property(nonatomic,strong) AFHTTPSessionManager *manager ; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } //懒加载初始化一个对象 - (AFHTTPSessionManager *) manager{ if(_manager) return _manager; //1.创建manager对象 _manager=[AFHTTPSessionManager manager]; // _manager.responseSerializer = [AFJSONRequestSerializer serializer]; return _manager; } //Get方式向服务器请求数据 -(IBAction)getBtn:(id)sender{ //方式1:通过字典的形式以参数传值 // //1.设置请求参数 // //NSDictionary *pars=@{@"page":@"1"}; // NSDictionary *pars=@{@"foo":@"bar"}; // //2.设置响应接收的类型 // [self.manager GET:BASE_URL parameters:pars progress:^(NSProgress * progress){ // // } success:^(NSURLSessionDataTask * task,id responseObject){ // NSLog(@"数据请求成功%@",responseObject); // //下一步要做的工作是json数据的解析 到Model层 // } failure:^(NSURLSessionDataTask * task,NSError *error){ // NSLog(@"网络错误 %@",error); // }]; // //方式2.通过接口的方式 传值参数 //1.设置请求参数 //NSDictionary *pars=@{@"page":@"1"}; // NSDictionary *pars=@{@"foo":@"bar"}; //2.设置响应接收的类型 // NSString *strUrl=[NSString stringWithFormat:@"%@?foo=%@",BASE_URL,@"bar"]; [self.manager GET:Server_Zhihu_Last parameters:nil progress:^(NSProgress * progress){ } success:^(NSURLSessionDataTask * task,id responseObject){ NSLog(@"数据请求成功%@",responseObject); //下一步要做的工作是json数据的解析 到Model层 // NSString *strObject=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; //手动解析Json // NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingAllowFragments error:nil]; NSDictionary *dict=(NSDictionary *) responseObject; // NSLog(@"%@",dict); // NSMutableArray *storyArr =[StoryEntity parseJson:dict]; // NSLog(@"解析数据的元素个数%ld",storyArr.count); NSDictionary *dDict=[StoryEntity parse:dict]; NSLog(@"%ld",dDict.count); } failure:^(NSURLSessionDataTask * task,NSError *error){ NSLog(@"网络错误 %@",error); }]; } //POST请求向服务器提交数据 -(IBAction)postBtn:(id)sender{ //1.设置请求参数 //NSDictionary *pars=@{@"page":@"1"}; NSDictionary *pars=@{@"foo":@"bar"}; //2.设置响应接收的类型 [self.manager POST:BASE_URL parameters:pars progress:^(NSProgress * progress){ } success:^(NSURLSessionDataTask * task,id responseObject){ NSLog(@"数据请求成功%@",responseObject); //下一步要做的工作是json数据的解析 到Model层 } failure:^(NSURLSessionDataTask * task,NSError *error){ NSLog(@"网络错误 %@",error); }]; } //向服务器提交多个文件 -(IBAction) multiUploadFileBtn:(id) sender{ //1.设置请求参数 //NSDictionary *pars=@{@"page":@"1"}; // NSDictionary *pars=@{@"foo":@"bar"}; //2.设置响应接收的类型 [self.manager POST:BASE_URL parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData> formData){ //向formData添加数据 //img1.jpg文件添加到fromData NSData *data1=[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"img1" ofType:@"jpg"] ]; // NSData *data1=[NSData dataWithContentsOfFile:imgPath]; [formData appendPartWithFormData:data1 name:@"image1"]; NSData *data2=[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"logo_news" ofType:@"png"]]; [formData appendPartWithFormData:data2 name:@"logo_news"]; } progress: ^(NSProgress * _Nonnull uploadProgress){ } success:^(NSURLSessionDataTask * task,id responseObject){ NSLog(@"数据请求成功%@",responseObject); //下一步要做的工作是json数据的解析 到Model层 } failure:^(NSURLSessionDataTask * task,NSError *error){ NSLog(@"网络错误 %@",error); }]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
{ "content_hash": "8a6f0c34e13a142d10ebc838acfbbf34", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 141, "avg_line_length": 34.92982456140351, "alnum_prop": 0.644650929181316, "repo_name": "wjl0421/-app", "id": "10cba1aead96ad4120e053aef8cd530210625e05", "size": "4862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AFNetworking的使用/ViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "437846" }, { "name": "Ruby", "bytes": "560" }, { "name": "Shell", "bytes": "33486" } ], "symlink_target": "" }
package com.github.twitch4j.chat; import com.github.philippheuer.events4j.core.EventManager; import com.github.philippheuer.events4j.simple.SimpleEventHandler; import com.github.twitch4j.chat.events.channel.ChannelJoinFailureEvent; import com.github.twitch4j.chat.events.channel.IRCMessageEvent; import com.github.twitch4j.chat.util.TestUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Collections; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; @Tag("unittest") public class ChatJoinRetryTest { private static final String FAKE_CHANNEL_NAME = "twitch4jtestchannelthatisnotreall"; // should exceed the max account length to make sure no such account can be created private static TwitchChat getChatInstance(int maxRetries, boolean removeChannelOnJoinFailure) { // spy on EventManager EventManager eventManager = new EventManager(); eventManager.autoDiscovery(); eventManager.setDefaultEventHandler(SimpleEventHandler.class); // synchronous execution is best suited for tests // spy on TwitchChat TwitchChat twitchChat = Mockito.spy( TwitchChatBuilder.builder() .withEventManager(Mockito.spy(eventManager)) .withRemoveChannelOnJoinFailure(removeChannelOnJoinFailure) .withMaxJoinRetries(maxRetries) .withChatJoinTimeout(100L) // reduce the duration of test executions .build() ); return twitchChat; } private static IRCMessageEvent testIRCMessageEvent(String raw) { return new IRCMessageEvent(raw, Collections.singletonMap("149223493", FAKE_CHANNEL_NAME), Collections.singletonMap(FAKE_CHANNEL_NAME, "149223493"), null); } @Test @DisplayName("successfully join a channel") public void testChannelJoinSuccess() { // init TwitchChat twitchChat = getChatInstance(1, false); // join channel and wait for the command to be processed twitchChat.joinChannel(FAKE_CHANNEL_NAME); verify(twitchChat, timeout(1_000)).issueJoin(FAKE_CHANNEL_NAME, 0); TestUtils.sleepFor(50); // check that we kept track of the join attempt in joinAttemptsByChannelName Assertions.assertNotNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be in joinAttemptsByChannelName while the join attempt is in an unknown state"); // fake a successful join twitchChat.getEventManager().publish(testIRCMessageEvent("@emote-only=0;followers-only=-1;r9k=0;rituals=0;room-id=149223493;slow=0;subs-only=0 :tmi.twitch.tv ROOMSTATE #"+FAKE_CHANNEL_NAME)); // should be gone from joinAttemptsByChannelName after successful join Assertions.assertNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be gone from joinAttemptsByChannelName after successful join"); Assertions.assertTrue(twitchChat.currentChannels.contains(FAKE_CHANNEL_NAME), "channel should remain in currentChannels after successful join"); // cleanup twitchChat.close(); } @Test @DisplayName("failed to join a channel because of unknown reasons") public void testChannelJoinFailedByExpire() { // init TwitchChat twitchChat = getChatInstance(1, true); // join channel and wait for the command to be processed twitchChat.joinChannel(FAKE_CHANNEL_NAME); verify(twitchChat, timeout(1_000)).issueJoin(FAKE_CHANNEL_NAME, 0); TestUtils.sleepFor(50); // check that we kept track of the join attempt in joinAttemptsByChannelName Assertions.assertNotNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be in joinAttemptsByChannelName while the join attempt is in an unknown state"); // should see a ChannelRemovedPostJoinFailureEvent and entry should have expired verify(twitchChat.getEventManager(), timeout(30_000)).publish(new ChannelJoinFailureEvent(FAKE_CHANNEL_NAME, ChannelJoinFailureEvent.Reason.RETRIES_EXHAUSTED)); Assertions.assertNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be gone from joinAttemptsByChannelName after it expired"); Assertions.assertFalse(twitchChat.currentChannels.contains(FAKE_CHANNEL_NAME), "channel should be gone from currentChannels after retries have been exhausted"); // cleanup twitchChat.close(); } @Test @DisplayName("fail to join a channel two times before successfully joining it") public void testChannelJoinFailedBeforeSuccess() { // init TwitchChat twitchChat = getChatInstance(3, true); // join channel and wait for the command to be processed twitchChat.joinChannel(FAKE_CHANNEL_NAME); verify(twitchChat, timeout(1_000)).issueJoin(FAKE_CHANNEL_NAME, 0); TestUtils.sleepFor(50); // check that we kept track of the join attempt in joinAttemptsByChannelName Assertions.assertNotNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be in joinAttemptsByChannelName while the join attempt is in an unknown state"); // wait for 2 failed join attempts await().until(() -> Integer.valueOf(2).equals(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME))); // fake a successful join twitchChat.getEventManager().publish(testIRCMessageEvent("@emote-only=0;followers-only=-1;r9k=0;rituals=0;room-id=149223493;slow=0;subs-only=0 :tmi.twitch.tv ROOMSTATE #"+FAKE_CHANNEL_NAME)); // should be gone from joinAttemptsByChannelName after successful join Assertions.assertNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be gone from joinAttemptsByChannelName after successful join"); Assertions.assertTrue(twitchChat.currentChannels.contains(FAKE_CHANNEL_NAME), "channel should remain in currentChannels after successful join"); // cleanup twitchChat.close(); } @Test @DisplayName("failed to join a channel because we are banned") public void testChannelJoinFailedByBannedUser() { // init TwitchChat twitchChat = getChatInstance(1, true); // join channel and wait for the command to be processed twitchChat.joinChannel(FAKE_CHANNEL_NAME); verify(twitchChat, timeout(1_000)).issueJoin(FAKE_CHANNEL_NAME, 0); TestUtils.sleepFor(50); // check that we kept track of the join attempt in joinAttemptsByChannelName Assertions.assertNotNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be in joinAttemptsByChannelName while the join attempt is in an unknown state"); // fake a banned notice twitchChat.getEventManager().publish(testIRCMessageEvent("@msg-id=msg_banned :tmi.twitch.tv NOTICE #"+FAKE_CHANNEL_NAME+" :You are permanently banned from talking in "+FAKE_CHANNEL_NAME+".")); // should be gone from joinAttemptsByChannelName because of the ban notice Assertions.assertNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be gone from joinAttemptsByChannelName after the ban notice"); // should have received an event about the removal of the channel verify(twitchChat.getEventManager(), timeout(30_000)).publish(new ChannelJoinFailureEvent(FAKE_CHANNEL_NAME, ChannelJoinFailureEvent.Reason.USER_BANNED)); Assertions.assertFalse(twitchChat.currentChannels.contains(FAKE_CHANNEL_NAME), "channel should be gone from currentChannels after the ban notice"); // cleanup twitchChat.close(); } @Test @DisplayName("failed to join a channel because the channel is suspended") public void testChannelJoinFailedChannelSuspended() { // init TwitchChat twitchChat = getChatInstance(1, true); // join channel and wait for the command to be processed twitchChat.joinChannel(FAKE_CHANNEL_NAME); verify(twitchChat, timeout(1_000)).issueJoin(FAKE_CHANNEL_NAME, 0); TestUtils.sleepFor(50); // check that we kept track of the join attempt in joinAttemptsByChannelName Assertions.assertNotNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be in joinAttemptsByChannelName while the join attempt is in an unknown state"); // fake a banned notice twitchChat.getEventManager().publish(testIRCMessageEvent("@msg-id=msg_channel_suspended :tmi.twitch.tv NOTICE #"+FAKE_CHANNEL_NAME+" :This channel has been suspended.")); // should be gone from joinAttemptsByChannelName because of the ban notice Assertions.assertNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be gone from joinAttemptsByChannelName after the channel suspension notice"); // should have received an event about the removal of the channel verify(twitchChat.getEventManager(), timeout(30_000)).publish(new ChannelJoinFailureEvent(FAKE_CHANNEL_NAME, ChannelJoinFailureEvent.Reason.CHANNEL_SUSPENDED)); Assertions.assertFalse(twitchChat.currentChannels.contains(FAKE_CHANNEL_NAME), "channel should be gone from currentChannels after the channel suspension notice"); // cleanup twitchChat.close(); } @Test @DisplayName("failed to join a channel because it was closed due to TOS violations") public void testChannelJoinFailedTOS() { // init TwitchChat twitchChat = getChatInstance(1, true); // join channel and wait for the command to be processed twitchChat.joinChannel(FAKE_CHANNEL_NAME); verify(twitchChat, timeout(1_000)).issueJoin(FAKE_CHANNEL_NAME, 0); TestUtils.sleepFor(50); // check that we kept track of the join attempt in joinAttemptsByChannelName Assertions.assertNotNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be in joinAttemptsByChannelName while the join attempt is in an unknown state"); // fake a banned notice twitchChat.getEventManager().publish(testIRCMessageEvent("@msg-id=tos_ban :tmi.twitch.tv NOTICE #"+FAKE_CHANNEL_NAME+" :The community has closed channel "+FAKE_CHANNEL_NAME+" due to Terms of Service violations.")); // should be gone from joinAttemptsByChannelName because of the ban notice Assertions.assertNull(twitchChat.joinAttemptsByChannelName.getIfPresent(FAKE_CHANNEL_NAME), "channel should be gone from joinAttemptsByChannelName after the channel suspension notice"); // should have received an event about the removal of the channel verify(twitchChat.getEventManager(), timeout(30_000)).publish(new ChannelJoinFailureEvent(FAKE_CHANNEL_NAME, ChannelJoinFailureEvent.Reason.CHANNEL_SUSPENDED)); Assertions.assertFalse(twitchChat.currentChannels.contains(FAKE_CHANNEL_NAME), "channel should be gone from currentChannels after the channel suspension notice"); // cleanup twitchChat.close(); } }
{ "content_hash": "a0fc5a8c7c2d17a7301c620333d9bc01", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 222, "avg_line_length": 54.88461538461539, "alnum_prop": 0.7395760336370008, "repo_name": "PhilippHeuer/twitch4j", "id": "809ccc36b1216ed5a5eba06cc871b836efe28dbe", "size": "11416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chat/src/test/java/com/github/twitch4j/chat/ChatJoinRetryTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "350710" } ], "symlink_target": "" }
package com.inmobi.messaging; import java.nio.ByteBuffer; /** * Message class holding the data. * */ public final class Message implements MessageBase { private ByteBuffer data; public Message() { } /** * Create new message with {@link ByteBuffer} * * @param data The {@link ByteBuffer} */ public Message(ByteBuffer data) { this.data = data; } /** * Create new message with byte array * * @param data The byte array. */ public Message(byte[] data) { this.data = ByteBuffer.wrap(data); } /** * Get the data associated with message. * * @return {@link ByteBuffer} holding the data. */ public ByteBuffer getData() { return data; } public synchronized void set(ByteBuffer data) { this.data = data; } public synchronized void clear() { data.clear(); } public long getSize() { return data.limit(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Message other = (Message) obj; if (data == null) { if (other.data != null) { return false; } } else if (!data.equals(other.data)) { return false; } return true; } @Override public Message clone() { Message m = new Message(data.duplicate()); return m; } }
{ "content_hash": "bfb2811561486eed736aa51f3b59e772", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 69, "avg_line_length": 17.565217391304348, "alnum_prop": 0.5816831683168316, "repo_name": "sreedishps/pintail", "id": "1fd57ce040d4fea17618ace180f9878ba2910bd7", "size": "2267", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "messaging-client-core/src/main/java/com/inmobi/messaging/Message.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1365322" }, { "name": "Shell", "bytes": "9235" }, { "name": "Thrift", "bytes": "5091" } ], "symlink_target": "" }
<header class="header"> <div class="header__inner app__layout"> <h1 class="title header__slogan">@@slogan</h1> </div> </header>
{ "content_hash": "39cfd02b86da45405003ad099cbd68c5", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 48, "avg_line_length": 26.2, "alnum_prop": 0.6564885496183206, "repo_name": "werty1001/bemgo", "id": "4f5211ffcfe000385cadd48c0c647e432f61228e", "size": "131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/blocks/develop/header/header.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2030" }, { "name": "HTML", "bytes": "1881" }, { "name": "JavaScript", "bytes": "72744" } ], "symlink_target": "" }
$(document).ready(function() { $(".ezieEditButton").ezie(); })
{ "content_hash": "01f340e7394392510e755757d4c4d280", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 32, "avg_line_length": 22.333333333333332, "alnum_prop": 0.582089552238806, "repo_name": "SnceGroup/snce-website", "id": "97694d6747887ee14690be9baf575009ed5690f9", "size": "1110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/extension/ezie/design/standard/javascript/ezie.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import { Stack } from '../../'; import { script as bscript } from '../../'; import { opcodes } from '../../'; import { ecc } from '../../noble_ecc'; export function check(script: Buffer | Stack, allowIncomplete?: boolean): boolean { const chunks = bscript.decompile(script) as Stack; if (chunks.length < 3) return false; const ops = chunks.filter((_, index) => index % 2 === 1); if (ops[ops.length - 1] !== opcodes.OP_CHECKSIG) return false; if (!ops.slice(0, -1).every((op) => op === opcodes.OP_CHECKSIGVERIFY)) return false; if (chunks.length / 2 > 16) return false; if (allowIncomplete) return true; const keys = chunks.filter((_, index) => index % 2 === 0) as Buffer[]; return keys.every(ecc.isXOnlyPoint); } check.toJSON = (): string => { return 'taproot n-of-n output'; };
{ "content_hash": "23380c3428d2620d9c218fd85ca6702a", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 86, "avg_line_length": 36.5, "alnum_prop": 0.6288916562889165, "repo_name": "BitGo/BitGoJS", "id": "6c6e7cae63f9e3dd23c4f0188d90ef1e347cceb9", "size": "867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/utxo-lib/src/templates/taprootnofn/output.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "9929" }, { "name": "HTML", "bytes": "1098" }, { "name": "JavaScript", "bytes": "1585981" }, { "name": "SCSS", "bytes": "223" }, { "name": "Shell", "bytes": "10497" }, { "name": "TypeScript", "bytes": "10276438" }, { "name": "WebAssembly", "bytes": "100004" } ], "symlink_target": "" }
References ==== + Nguyen, M., Sun, N., Alexander D.C., Feng J., Yeo B.T.T., 2018. [**Modeling Alzheimer’s disease progression using deep recurrent neural networks**](https://doi.org/10.1109/prni.2018.8423955), PRNI, 2018. + Nguyen, M., He T., An L., Alexander D.C., Feng J., Yeo B.T.T., 2020. [**Predicting Alzheimer’s disease progression using deep recurrent neural networks**](https://doi.org/10.1016/j.neuroimage.2020.117203), NeuroImage, 117203. ---- Data ==== - Running this example requires the data from the [Alzheimer's Disease Neuroimaging Initiative](http://adni.loni.usc.edu) (ADNI) - After getting the spreadsheets from ADNI, follow the [instructions](https://github.com/noxtoby/TADPOLE/blob/master/TADPOLE_readme.txt) to generate the *TADPOLE_D1_D2.csv* file - This file is the standard dataset of the [TADPOLE Challenge 2017](http://tadpole.grand-challenge.org) - Copy the *TADPOLE_D1_D2.csv* file generated to the *data* folder ---- Run ==== - After setting up the Python environment, run the *CBIG_RNN_example.sh* file - The result should be as followed - RNN on validation set: - mAUC 0.9463 bca 0.8930 adasMAE 3.9777 ventsMAE 0.002248 - RNN on test set: - mAUC 0.9335 bca 0.8772 adasMAE 4.2398 ventsMAE 0.002389 - Constant prediction baseline on test set - mAUC 0.8799 bca 0.8772 adasMAE 4.8312 ventsMAE 0.002712 - SVM baseline on test set - mAUC 0.9182 bca 0.8307 adasMAE 4.9428 ventsMAE 0.002334
{ "content_hash": "06543f4c98e7445d5a44806725870332", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 227, "avg_line_length": 45.5, "alnum_prop": 0.7177197802197802, "repo_name": "ThomasYeoLab/CBIG", "id": "d8bd1ae254f7e3b8cca10853c2fc5c5eef5167a0", "size": "1555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stable_projects/predict_phenotypes/Nguyen2020_RNNAD/examples/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "35378" }, { "name": "C", "bytes": "2076236" }, { "name": "C++", "bytes": "1461097" }, { "name": "CSS", "bytes": "6852" }, { "name": "Fortran", "bytes": "598090" }, { "name": "HTML", "bytes": "287918" }, { "name": "Jupyter Notebook", "bytes": "569200" }, { "name": "MATLAB", "bytes": "10013692" }, { "name": "Makefile", "bytes": "7902" }, { "name": "Objective-C", "bytes": "77" }, { "name": "PostScript", "bytes": "8416" }, { "name": "Python", "bytes": "2499129" }, { "name": "R", "bytes": "33929" }, { "name": "Shell", "bytes": "1923688" }, { "name": "TeX", "bytes": "8993" }, { "name": "Vim Script", "bytes": "2859" }, { "name": "XSLT", "bytes": "19506" } ], "symlink_target": "" }
package br.edu.ifmt.cba.alphalab.gui.javafx.controller.login; /** * @author Stévillis Sousa */ import java.net.URL; import java.util.ResourceBundle; import br.edu.ifmt.cba.alphalab.gui.javafx.Main; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class FrmLogin implements Initializable { @FXML private TextField txtLogin; @FXML private PasswordField pswSenha; @FXML private Button btnSair; @FXML private Button btnEntrar; @FXML private Button btnCadastrar; @FXML void btnCadastrar_onAction(ActionEvent event) { } @FXML void btnCadastrar_onKeyPressed(KeyEvent event) { } @FXML void btnCdastrar_onMouseClicked(MouseEvent event) { } @FXML void btnEntrar_onAction(ActionEvent event) { if (txtLogin.getText().equals("admin") && pswSenha.getText().equals("admin")) { efetuarLogin(); Main.login.close();// Fecha a Tela de Login } else { senhaInvalida(); } } @FXML void btnEntrar_onKeyPressed(KeyEvent event) { } @FXML void btnEntrar_onMousecClicked(MouseEvent event) { } @FXML void btnSair_onAction(ActionEvent event) { } @FXML void btnSair_onKeyPressed(KeyEvent event) { } @FXML void btnSair_onMouseClicked(MouseEvent event) { } @FXML void pswSenha_onKeyPressed(KeyEvent event) { } @FXML void txtLogin_onKeyPressed(KeyEvent event) { } @Override public void initialize(URL location, ResourceBundle resources) { } private void efetuarLogin() { BorderPane frmPrincipal = null; Stage primaryStage = new Stage(); try { frmPrincipal = FXMLLoader.load(Main.class.getClassLoader().getResource("gui/FrmPrincipal.fxml"), ResourceBundle.getBundle("gui/i18N_pt_BR")); } catch (Exception ex) { System.out.println("Exception on FXMLLoader.load()"); System.out.println(ex.getMessage()); } primaryStage.setTitle("Tela Principal do Sistema"); Scene scene = new Scene(frmPrincipal); primaryStage.setScene(scene); primaryStage.show(); } private void senhaInvalida() { if (txtLogin.getText().equals("") && !pswSenha.getText().equals("")) { caixaAlerta(AlertType.ERROR, "Erro ao fazer login", "Login deve ser informado", "Informe o login!"); } if (pswSenha.getText().equals("") && !txtLogin.getText().equals("")) { caixaAlerta(AlertType.ERROR, "Erro ao fazer login", "Senha deve ser informada", "Informe a senha!"); } if (txtLogin.getText().equals("") && pswSenha.getText().equals("")) { caixaAlerta(AlertType.ERROR, "Erro ao fazer login", "Login e senha devem ser informados", "Informe o login e a senha!"); } if (!txtLogin.getText().equals("") && !pswSenha.getText().equals("")) { caixaAlerta(AlertType.ERROR, "Erro ao fazer login", "Login e senha inválidos", "Informe login e senha válidos!"); } } /** * Caixa de diálogo Alert. * * @param alertType * é o tipo to alerta. * @param titulo * é o título da caixa de diálogo. * @param headerText * é o cabeçalho da caixa de diálogo. * @param contentText * é o conteúdo da caixa de diálogo. */ private void caixaAlerta(AlertType alertType, String titulo, String headerText, String contentText) { Alert alerta = new Alert(alertType); alerta.setTitle(titulo); alerta.setHeaderText(headerText); alerta.setContentText(contentText); alerta.showAndWait(); } }
{ "content_hash": "237f35c1531260365cf993f8d9737d4e", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 103, "avg_line_length": 23.634730538922156, "alnum_prop": 0.6795034203192298, "repo_name": "dev-andremonteiro/AlphaLab", "id": "399a5486ac9b826ae531c1411b0763f32d6e4085", "size": "3947", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/br/edu/ifmt/cba/alphalab/gui/javafx/controller/login/FrmLogin.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "267960" } ], "symlink_target": "" }
var path = require('path'), pkg = require('./package.json'), webpack = require('webpack'), Babili = require('babili-webpack-plugin'), LibrarySourcePlugin = require('library-src-plugin'); let buildConfig = (useBabel, minify, name) => ({ context: __dirname, entry: { [name]: './index.js' }, output: { path: path.join(__dirname, '/dist/'), filename: '[name].js', library: 'dparser', libraryTarget: 'umd' }, module: { rules: (useBabel ? [ { test: /\.js$/i, use: ['babel-loader'] } ] : []).concat( [ { test: /\.pegjs$/i, use: ['pegjs-loader'] } ] ) }, plugins: [ minify ? new Babili() : null ].filter(Boolean), performance: false }); module.exports = [ buildConfig(false, false, pkg.name), buildConfig(true, false, `${pkg.name}.compat`), buildConfig(false, true, `${pkg.name}.min`), buildConfig(true, true, `${pkg.name}.compat.min`) ];
{ "content_hash": "e00490d7f279d0a3a38133c73fa5cd55", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 56, "avg_line_length": 22.953488372093023, "alnum_prop": 0.5400202634245187, "repo_name": "jtenner/d-parser", "id": "13fc53fd0edc8f85e3d19ef1bef901276f41df03", "size": "987", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webpack.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2857" } ], "symlink_target": "" }
package com.intellij.psi.impl.source.resolve.reference; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReferenceService; import org.jetbrains.annotations.NotNull; import java.util.List; /** * Created by IntelliJ IDEA. * User: ik * Date: 01.04.2003 * Time: 16:52:28 * To change this template use Options | File Templates. */ public interface ProviderBinding<T> { void addAcceptableReferenceProviders(@NotNull PsiElement position, @NotNull List list, PsiReferenceService.Hints hints); void unregisterProvider(final T provider); }
{ "content_hash": "8c9421a647dcb15eeb895408196052ad", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 88, "avg_line_length": 26.043478260869566, "alnum_prop": 0.7228714524207012, "repo_name": "joewalnes/idea-community", "id": "4effe87b38e137b14aba9dbf1174380116db0e01", "size": "1199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/ProviderBinding.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "387" }, { "name": "C", "bytes": "136045" }, { "name": "C#", "bytes": "103" }, { "name": "C++", "bytes": "40449" }, { "name": "Emacs Lisp", "bytes": "2507" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "361320" }, { "name": "Java", "bytes": "89694599" }, { "name": "JavaScript", "bytes": "978" }, { "name": "Objective-C", "bytes": "1877" }, { "name": "PHP", "bytes": "145" }, { "name": "Perl", "bytes": "6523" }, { "name": "Python", "bytes": "1699274" }, { "name": "Shell", "bytes": "6965" }, { "name": "VimL", "bytes": "5950" } ], "symlink_target": "" }
""" Autogenerated IBEISController functions TemplateInfo: autogen_time = 13:31:28 2015/04/28 autogen_key = annotgroup ToRegenerate: python -m ibeis.templates.template_generator --key annotgroup --Tcfg with_web_api=True with_api_cache=False with_deleters=True no_extern_deleters=True --diff python -m ibeis.templates.template_generator --key annotgroup --Tcfg with_web_api=True with_api_cache=False with_deleters=True no_extern_deleters=True --write """ from __future__ import absolute_import, division, print_function, unicode_literals from six.moves import zip from ibeis import constants as const import utool as ut from ibeis.control import controller_inject from ibeis.control import accessor_decors # NOQA print, rrr, profile = ut.inject2(__name__) # Create dectorator to inject functions in this module into the IBEISController CLASS_INJECT_KEY, register_ibs_method = controller_inject.make_ibs_register_decorator(__name__) register_api = controller_inject.get_ibeis_flask_api(__name__) def testdata_ibs(defaultdb='testdb1'): import ibeis ibs = ibeis.opendb(defaultdb=defaultdb) config2_ = None # qreq_.qparams return ibs, config2_ # AUTOGENED CONSTANTS: GAR_ROWID = 'gar_rowid' ANNOTGROUP_NOTE = 'annotgroup_note' ANNOTGROUP_ROWID = 'annotgroup_rowid' ANNOTGROUP_TEXT = 'annotgroup_text' ANNOTGROUP_UUID = 'annotgroup_uuid' ANNOT_ROWID = 'annot_rowid' @register_ibs_method # @register_api('/api/annotgroup/', methods=['GET']) def _get_all_annotgroup_rowids(ibs): """ all_annotgroup_rowids <- annotgroup.get_all_rowids() Returns: list_ (list): unfiltered annotgroup_rowids TemplateInfo: Tider_all_rowids tbl = annotgroup Example: >>> # ENABLE_DOCTEST >>> from ibeis.control.manual_annotgroup_funcs import * # NOQA >>> ibs, config2_ = testdata_ibs() >>> ibs._get_all_annotgroup_rowids() """ all_annotgroup_rowids = ibs.db.get_all_rowids(const.ANNOTGROUP_TABLE) return all_annotgroup_rowids @register_ibs_method # @register_api('/api/annotgroup/', methods=['POST']) def add_annotgroup(ibs, annotgroup_uuid_list, annotgroup_text_list, annotgroup_note_list): """ Returns: returns annotgroup_rowid_list of added (or already existing annotgroups) TemplateInfo: Tadder_native tbl = annotgroup """ # WORK IN PROGRESS colnames = (ANNOTGROUP_UUID, ANNOTGROUP_TEXT, ANNOTGROUP_NOTE,) params_iter = ( (annotgroup_uuid, annotgroup_text, annotgroup_note,) for (annotgroup_uuid, annotgroup_text, annotgroup_note,) in zip(annotgroup_uuid_list, annotgroup_text_list, annotgroup_note_list) ) get_rowid_from_superkey = ibs.get_annotgroup_rowid_from_superkey # FIXME: encode superkey paramx superkey_paramx = (1,) annotgroup_rowid_list = ibs.db.add_cleanly( const.ANNOTGROUP_TABLE, colnames, params_iter, get_rowid_from_superkey, superkey_paramx) return annotgroup_rowid_list @register_ibs_method # @register_api('/api/annotgroup/', methods=['DELETE']) def delete_annotgroup(ibs, annotgroup_rowid_list, config2_=None): """ annotgroup.delete(annotgroup_rowid_list) delete annotgroup rows Args: annotgroup_rowid_list Returns: int: num_deleted TemplateInfo: Tdeleter_native_tbl tbl = annotgroup Example: >>> # DISABLE_DOCTEST >>> from ibeis.control.manual_annotgroup_funcs import * # NOQA >>> ibs, config2_ = testdata_ibs() >>> annotgroup_rowid_list = ibs._get_all_annotgroup_rowids()[:2] >>> num_deleted = ibs.delete_annotgroup(annotgroup_rowid_list) >>> print('num_deleted = %r' % (num_deleted,)) """ #from ibeis.algo.preproc import preproc_annotgroup # NO EXTERN IMPORT if ut.VERBOSE: print('[ibs] deleting %d annotgroup rows' % len(annotgroup_rowid_list)) # Prepare: Delete externally stored data (if any) #preproc_annotgroup.on_delete(ibs, annotgroup_rowid_list, config2_=config2_) # NO EXTERN DELETE # Finalize: Delete self ibs.db.delete_rowids(const.ANNOTGROUP_TABLE, annotgroup_rowid_list) num_deleted = len(ut.filter_Nones(annotgroup_rowid_list)) return num_deleted @register_ibs_method @accessor_decors.getter_1toM # @register_api('/api/annotgroup/gar/rowids/', methods=['GET']) def get_annotgroup_gar_rowids(ibs, annotgroup_rowid_list, eager=True, nInput=None): """ Auto-docstr for 'get_annotgroup_gar_rowids' RESTful: Method: GET URL: /api/annotgroup/gar/rowids/ """ colnames = (GAR_ROWID,) gar_rowid_list = ibs.db.get(const.GA_RELATION_TABLE, colnames, annotgroup_rowid_list, id_colname=ANNOTGROUP_ROWID, unpack_scalars=False) return gar_rowid_list @register_ibs_method @accessor_decors.getter_1to1 # @register_api('/api/annotgroup/note/', methods=['GET']) def get_annotgroup_note(ibs, annotgroup_rowid_list, eager=True, nInput=None): """ annotgroup_note_list <- annotgroup.annotgroup_note[annotgroup_rowid_list] gets data from the "native" column "annotgroup_note" in the "annotgroup" table Args: annotgroup_rowid_list (list): Returns: list: annotgroup_note_list TemplateInfo: Tgetter_table_column col = annotgroup_note tbl = annotgroup Example: >>> # ENABLE_DOCTEST >>> from ibeis.control.manual_annotgroup_funcs import * # NOQA >>> ibs, config2_ = testdata_ibs() >>> annotgroup_rowid_list = ibs._get_all_annotgroup_rowids() >>> eager = True >>> annotgroup_note_list = ibs.get_annotgroup_note(annotgroup_rowid_list, eager=eager) >>> assert len(annotgroup_rowid_list) == len(annotgroup_note_list) """ id_iter = annotgroup_rowid_list colnames = (ANNOTGROUP_NOTE,) annotgroup_note_list = ibs.db.get( const.ANNOTGROUP_TABLE, colnames, id_iter, id_colname='rowid', eager=eager, nInput=nInput) return annotgroup_note_list @register_ibs_method def get_annotgroup_rowid_from_superkey(ibs, annotgroup_text_list, eager=True, nInput=None): """ annotgroup_rowid_list <- annotgroup[annotgroup_text_list] Args: superkey lists: annotgroup_text_list Returns: annotgroup_rowid_list TemplateInfo: Tgetter_native_rowid_from_superkey tbl = annotgroup """ colnames = (ANNOTGROUP_ROWID,) # FIXME: col_rowid is not correct params_iter = zip(annotgroup_text_list) andwhere_colnames = [ANNOTGROUP_TEXT] annotgroup_rowid_list = ibs.db.get_where_eq( const.ANNOTGROUP_TABLE, colnames, params_iter, andwhere_colnames, eager=eager, nInput=nInput) return annotgroup_rowid_list @register_ibs_method @accessor_decors.getter_1to1 # @register_api('/api/annotgroup/text/', methods=['GET']) def get_annotgroup_text(ibs, annotgroup_rowid_list, eager=True, nInput=None): """ annotgroup_text_list <- annotgroup.annotgroup_text[annotgroup_rowid_list] gets data from the "native" column "annotgroup_text" in the "annotgroup" table Args: annotgroup_rowid_list (list): Returns: list: annotgroup_text_list TemplateInfo: Tgetter_table_column col = annotgroup_text tbl = annotgroup Example: >>> # ENABLE_DOCTEST >>> from ibeis.control.manual_annotgroup_funcs import * # NOQA >>> ibs, config2_ = testdata_ibs() >>> annotgroup_rowid_list = ibs._get_all_annotgroup_rowids() >>> eager = True >>> annotgroup_text_list = ibs.get_annotgroup_text(annotgroup_rowid_list, eager=eager) >>> assert len(annotgroup_rowid_list) == len(annotgroup_text_list) """ id_iter = annotgroup_rowid_list colnames = (ANNOTGROUP_TEXT,) annotgroup_text_list = ibs.db.get( const.ANNOTGROUP_TABLE, colnames, id_iter, id_colname='rowid', eager=eager, nInput=nInput) return annotgroup_text_list @register_ibs_method @accessor_decors.getter_1to1 # @register_api('/api/annotgroup/uuid/', methods=['GET']) def get_annotgroup_uuid(ibs, annotgroup_rowid_list, eager=True, nInput=None): """ annotgroup_uuid_list <- annotgroup.annotgroup_uuid[annotgroup_rowid_list] gets data from the "native" column "annotgroup_uuid" in the "annotgroup" table Args: annotgroup_rowid_list (list): Returns: list: annotgroup_uuid_list TemplateInfo: Tgetter_table_column col = annotgroup_uuid tbl = annotgroup Example: >>> # ENABLE_DOCTEST >>> from ibeis.control.manual_annotgroup_funcs import * # NOQA >>> ibs, config2_ = testdata_ibs() >>> annotgroup_rowid_list = ibs._get_all_annotgroup_rowids() >>> eager = True >>> annotgroup_uuid_list = ibs.get_annotgroup_uuid(annotgroup_rowid_list, eager=eager) >>> assert len(annotgroup_rowid_list) == len(annotgroup_uuid_list) """ id_iter = annotgroup_rowid_list colnames = (ANNOTGROUP_UUID,) annotgroup_uuid_list = ibs.db.get( const.ANNOTGROUP_TABLE, colnames, id_iter, id_colname='rowid', eager=eager, nInput=nInput) return annotgroup_uuid_list @register_ibs_method @accessor_decors.setter # @register_api('/api/annotgroup/note/', methods=['PUT']) def set_annotgroup_note(ibs, annotgroup_rowid_list, annotgroup_note_list, duplicate_behavior='error'): """ annotgroup_note_list -> annotgroup.annotgroup_note[annotgroup_rowid_list] Args: annotgroup_rowid_list annotgroup_note_list TemplateInfo: Tsetter_native_column tbl = annotgroup col = annotgroup_note """ id_iter = annotgroup_rowid_list colnames = (ANNOTGROUP_NOTE,) ibs.db.set(const.ANNOTGROUP_TABLE, colnames, annotgroup_note_list, id_iter, duplicate_behavior=duplicate_behavior) @register_ibs_method @accessor_decors.setter # @register_api('/api/annotgroup/uuid/', methods=['PUT']) def set_annotgroup_uuid(ibs, annotgroup_rowid_list, annotgroup_uuid_list, duplicate_behavior='error'): """ annotgroup_uuid_list -> annotgroup.annotgroup_uuid[annotgroup_rowid_list] Args: annotgroup_rowid_list annotgroup_uuid_list TemplateInfo: Tsetter_native_column tbl = annotgroup col = annotgroup_uuid """ id_iter = annotgroup_rowid_list colnames = (ANNOTGROUP_UUID,) ibs.db.set(const.ANNOTGROUP_TABLE, colnames, annotgroup_uuid_list, id_iter, duplicate_behavior=duplicate_behavior) if __name__ == '__main__': """ CommandLine: python -m ibeis.control.manual_annotgroup_funcs python -m ibeis.control.manual_annotgroup_funcs --allexamples """ import multiprocessing multiprocessing.freeze_support() import utool as ut ut.doctest_funcs()
{ "content_hash": "c495a4c635ade3798694abe99d2d8c04", "timestamp": "", "source": "github", "line_count": 325, "max_line_length": 162, "avg_line_length": 33.575384615384614, "alnum_prop": 0.6727456011730205, "repo_name": "Erotemic/ibeis", "id": "5eeb8e07210e3c515f57d64e00ab7ea1fc3167ee", "size": "10936", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "ibeis/control/manual_annotgroup_funcs.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "331" }, { "name": "CSS", "bytes": "4676" }, { "name": "Dockerfile", "bytes": "13018" }, { "name": "Inno Setup", "bytes": "1585" }, { "name": "Python", "bytes": "6661573" }, { "name": "Shell", "bytes": "56171" } ], "symlink_target": "" }
@extends('auth.template') @section('title', 'Login') @section('body_heading', 'Please login') @section('body_content') <form method="POST"> {!! csrf_field() !!} <fieldset> <div class="form-group"> <input class="form-control" placeholder="Username" name="name" autofocus> </div> <div class="form-group"> <input class="form-control" placeholder="Password" name="password" type="password" value=""> </div> <div class="checkbox"> <label> <input name="remember" type="checkbox" value="Remember Me">Remember Me </label> </div> <!-- Change this to a button or input when using this as a form --> <div class="row"> <div class="col-lg-6"> <button type="submit" class="btn btn-success btn-block">Login</button> </div> <div class="col-lg-6"> <a href="{{ $register_root }}"><span class="btn btn-primary btn-block">Register</span></a> </div> </div> </fieldset> </form> @endsection
{ "content_hash": "3327c9969acb2a21c13d062d86423d22", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 106, "avg_line_length": 33.27272727272727, "alnum_prop": 0.5391621129326047, "repo_name": "gingzai/Laravel-CMF", "id": "4bee94776420edd1d3eb6b737916cd108afce38e", "size": "1098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/auth/login.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "72" }, { "name": "JavaScript", "bytes": "1785" }, { "name": "PHP", "bytes": "212760" } ], "symlink_target": "" }
@charset "UTF-8"; /* Legacy variables. Discontinue to use these: */ /** * Convert font-size from px to rem with px fallback * @param $size - the value in pixel you want to convert * e.g. p {@include fontSize(12px);} * courtesy of https://github.com/stubbornella/oocss/blob/master/oocss/src/components/utils/_fontSize.scss */ /* line 1, app/stylesheets/pages/assignments/_assignments.scss */ .lock_date { color: #444; padding-left: 20px; font-weight: bold; } /* line 8, app/stylesheets/pages/assignments/_assignments.scss */ #submit_assignment .submission_comment_textarea { width: 300px; height: 20px; padding: 4px 6px; } /* line 12, app/stylesheets/pages/assignments/_assignments.scss */ #submit_assignment .submission_comment_textarea.focus_or_content { width: 100%; height: 72px; } /* line 19, app/stylesheets/pages/assignments/_assignments.scss */ #point_change_warning { margin-top: 15px; margin-bottom: 0px; display: none; } /* line 25, app/stylesheets/pages/assignments/_assignments.scss */ #edit_assignment_form { margin: 0; } /* line 27, app/stylesheets/pages/assignments/_assignments.scss */ #edit_assignment_form .advanced-togglable-true { margin-top: 18px; border-top: 1px solid #ccc; padding-top: 18px; } /* line 32, app/stylesheets/pages/assignments/_assignments.scss */ #edit_assignment_form .advanced-togglable-false { margin-top: 18px; } /* line 35, app/stylesheets/pages/assignments/_assignments.scss */ #edit_assignment_form #group_category_selector, #edit_assignment_form #assignment_peer_reviews_fields { margin-bottom: 0; } /* line 39, app/stylesheets/pages/assignments/_assignments.scss */ #edit_assignment_form .frozen-description { padding: 15px; overflow-y: auto; height: 200px; border: 1px solid #AAA; resize: vertical; } /* line 46, app/stylesheets/pages/assignments/_assignments.scss */ #edit_assignment_form .explanation { font-size: 0.8em; color: #888; } /* line 52, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_turnitin_settings { min-width: 400px; } /* line 54, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_turnitin_settings label { width: 95%; } /* line 57, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_turnitin_settings .js-exclude-small-matches-options { margin-left: 21px; } /* line 59, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_turnitin_settings .js-exclude-small-matches-options input[type="radio"] { margin-top: 13px; } /* line 66, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .assignment-title { display: table-row; width: 100%; } /* line 70, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .title-content { display: table-cell; width: 100%; vertical-align: bottom; } /* line 75, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .assignment-buttons { display: table-cell; vertical-align: bottom; text-align: right; min-width: 335px; padding-bottom: 12px; } /* line 82, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .undo-main-margins { margin-left: -1em; margin-right: -1em; margin-bottom: -1em; } /* line 87, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .student-assignment-overview { list-style: none; width: 100%; border-top: 1px solid #BBB; border-bottom: 1px solid #BBB; font-size: 1.1em; padding: 0.5em 0.25em; margin: 0 0 1em 0; } /* line 95, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .student-assignment-overview li { display: inline-block; } /* line 98, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .student-assignment-overview .title { font-weight: bold; padding-right: 0.5em; } /* line 102, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .student-assignment-overview .value { padding-right: 2.5em; } /* line 106, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .form-horizontal.display-only .control-group { margin-bottom: 0; } /* line 109, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .description.student-version { min-height: 260px; } /* line 112, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .description.teacher-version { padding: 15px; overflow-y: auto; height: 200px; border: 1px solid #AAA; border-radius: 4px; resize: vertical; } /* line 121, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .control-group .control-label { font-weight: bold; } /* line 124, app/stylesheets/pages/assignments/_assignments.scss */ #assignment_show .control-group .controls .value { display: block; padding-top: 5px; } /* line 132, app/stylesheets/pages/assignments/_assignments.scss */ .control-group .controls-url { padding-top: 5px; word-wrap: break-word; } /* line 138, app/stylesheets/pages/assignments/_assignments.scss */ .omit-from-final-warning { padding: 12px; border-width: 1px; margin: 5px; } /* line 144, app/stylesheets/pages/assignments/_assignments.scss */ #assignment-draft-state { padding: 10px; line-height: 33px; } /* line 149, app/stylesheets/pages/assignments/_assignments.scss */ #sequence_footer.module-sequence-footer { padding-top: 0px; } /* line 155, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details h3 { margin: 0; } /* line 158, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .header { font-size: 1.2em; font-weight: bold; margin-top: 2px; } /* line 163, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content { padding-left: 5px; } /* line 165, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content h4 { font-size: 11px; font-size: 0.6875rem; font-weight: bold; margin-bottom: 0; } /* line 170, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content .module { padding-top: 10px; } /* line 173, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content .late { color: #880000; font-weight: bold; } /* line 177, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content .unstyled_list { margin: 5px 10px 0 10px; } /* line 180, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content .comments { font-size: 11px; font-size: 0.6875rem; max-height: 300px; overflow: auto; } /* line 184, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content .comments .comment { margin-left: 10px; } /* line 186, app/stylesheets/pages/assignments/_assignments.scss */ #sidebar_content .details .content .comments .comment .signature { color: #888888; font-size: 0.8em; text-align: right; } /* line 8, app/stylesheets/pages/shared/_grading_standards.scss */ #standards .grading_standard { border-bottom: 1px dotted #ccc; margin-bottom: 25px; } /* line 11, app/stylesheets/pages/shared/_grading_standards.scss */ #standards .grading_standard .links { opacity: 0.5; } /* line 15, app/stylesheets/pages/shared/_grading_standards.scss */ #standards .grading_standard:hover .links { opacity: 1; } /* line 19, app/stylesheets/pages/shared/_grading_standards.scss */ #standards .grading_standard .standard_title { font-weight: bold; font-size: 1.2em; } /* line 25, app/stylesheets/pages/shared/_grading_standards.scss */ #standards.react_grading_standards .cancel_button { margin-right: 6px; } /* line 32, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard .read_only { display: none; } /* line 35, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard .editing_box { display: none; } /* line 38, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard .editing_td { display: none; } /* line 41, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard .editing_tr { display: none; } /* line 44, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard .min_score, .grading_standard .max_score { width: 100px; } /* line 48, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.editing .displaying { display: none; } /* line 51, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.editing .editing_box { display: block; } /* line 54, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.editing td.editing_box { display: table-cell; } /* line 57, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.editing tr.editing_box { display: table-row; } /* line 60, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.editing .standard_title div { float: left; } /* line 65, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .alert-message:focus { outline: none; } /* line 68, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .grading_standard_title { width: 175px; } /* line 71, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .name_header { text-align: left; padding-right: 10px; width: 24%; } /* line 76, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .insert_row_container { padding: 2px 5px; width: 4%; } /* line 80, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .links { float: right; } /* line 83, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .disabled-buttons { float: right; opacity: 0.5; } /* line 87, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .cannot-manage-notification { font-weight: normal; margin-left: 4px; } /* line 91, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .icon-edit { margin-right: 5px; } /* line 94, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .form-actions { background-color: transparent; margin-bottom: 0px; padding-bottom: 0px; } /* line 99, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .range_container { width: 72%; } /* line 101, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard .range_container .range_label { float: left; margin-left: 10px; } /* line 106, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard table { width: 100%; } /* line 108, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard.react_grading_standard table.grading_standard_data { margin-bottom: 20px; } /* line 117, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row input { margin-top: 5px; margin-bottom: 5px; } /* line 121, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row .insert_row_icon_container { padding: 2px 2px; width: 4%; } /* line 125, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row .row_name_container { width: 24%; } /* line 128, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row .standard_name { width: 25px; } /* line 131, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row .standard_value { width: 37px; } /* line 134, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row .last_row_cell { padding-left: 15px; } /* line 137, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row .row_cell { padding: 2px 2px; width: 24%; } /* line 140, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row .row_cell .range_to { padding-right: 5px; } /* line 144, app/stylesheets/pages/shared/_grading_standards.scss */ .grading_standard_row.react_grading_standard_row.border_below { border-bottom: dashed; border-bottom-width: 2px; border-bottom-color: #999; } /* line 2, app/stylesheets/pages/shared/_mark_as_done.scss */ .mark-done-labels span { display: none; } /* line 6, app/stylesheets/pages/shared/_mark_as_done.scss */ .mark-done-labels .visible { display: inline; } /* line 1, app/stylesheets/vendor/_embed_content.scss */ .embed_content { padding: 0; } /* line 4, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table { width: 100%; border-collapse: collapse; } /* line 8, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td { vertical-align: top; } /* line 11, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td > .content { overflow: auto; } /* line 14, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_title { font-size: 0.8em; } /* line 17, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_results { position: relative; } /* line 20, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result { width: 40%; float: left; margin: 3px; padding: 3px; overflow: hidden; position: relative; cursor: pointer; } /* line 29, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result.search_result_assignment { padding-left: 22px; background: url(/dist/images/binder-6ef0937025.png) no-repeat 3px 3px; } /* line 33, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result.search_result_discussion_topic, .embed_content > table td.search .search_result.search_result_discussion_entry, .embed_content > table td.search .search_result.search_result_announcement { padding-left: 22px; background: url(/dist/images/word_bubble-2ac7184a98.png) no-repeat 3px 3px; } /* line 40, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result.search_result_calendar_event { padding-left: 22px; background: url(/dist/images/history-214ab216d9.png) no-repeat 3px 3px; } /* line 44, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result.search_result_wiki_page { padding-left: 22px; background: url(/dist/images/file-95ff332fb8.png) no-repeat 3px 3px; } /* line 48, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result:hover { background-color: #DADADA; -moz-border-radius: 3px; } /* line 53, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result .title { white-space: nowrap; font-weight: bold; } /* line 57, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result .links { text-align: right; font-size: 1.0em; font-weight: bold; opacity: 0.5; margin-right: 10px; } /* line 64, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result:hover .links { opacity: 1.0; } /* line 67, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result .teaser { max-height: 40px; overflow: hidden; font-size: 0.8em; margin-left: 10px; color: #888; } /* line 74, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result:hover .teaser { color: #444; } /* line 77, app/stylesheets/vendor/_embed_content.scss */ .embed_content > table td.search .search_result .image_preview { overflow: hidden; } /* line 80, app/stylesheets/vendor/_embed_content.scss */ .embed_content .content_options { margin: 0; padding: 5px; } /* line 84, app/stylesheets/vendor/_embed_content.scss */ .embed_content .content_options li { cursor: pointer; white-space: nowrap; padding: 2px 20px; list-style-type: none; } /* line 90, app/stylesheets/vendor/_embed_content.scss */ .embed_content .content_options li:hover { background: #ddd; } /* line 93, app/stylesheets/vendor/_embed_content.scss */ .embed_content .content_options li.selected { background: #bbb; } /* line 96, app/stylesheets/vendor/_embed_content.scss */ .embed_content .content_options li .search_title, .embed_content .content_options li .models { display: none; } /* line 100, app/stylesheets/vendor/_embed_content.scss */ .embed_content .content_options ul { display: none; padding-left: 20px; } /* line 104, app/stylesheets/vendor/_embed_content.scss */ .embed_content .content_options ul.opened { display: block; } /* line 1, app/stylesheets/components/_conditional_release.scss */ #canvas-conditional-release-editor { height: 675px; padding-top: 12px; display: -webkit-flex; display: flex; overflow-x: scroll; } /* line 1, app/stylesheets/components/_conditional_release_stats.scss */ #crs-graphs { margin-top: 50px; } /* line 4, app/stylesheets/components/_conditional_release_stats.scss */ #crs-graphs:first-child { margin: 0px; } /* line 9, app/stylesheets/components/_conditional_release_stats.scss */ .crs-breakdown-graph { display: -webkit-flex; display: flex; -webkit-flex-direction: column; flex-direction: column; } /* line 14, app/stylesheets/components/_conditional_release_stats.scss */ .crs-breakdown-graph .crs-breakdown-graph__loading p { float: left; padding-top: 8px; padding-left: 10px; } /* line 20, app/stylesheets/components/_conditional_release_stats.scss */ .crs-breakdown-graph .crs-breakdown-graph__loading > div { float: left; } /* line 26, app/stylesheets/components/_conditional_release_stats.scss */ .crs-breakdown-details__header { margin-top: 10px; font-weight: lighter; border-bottom: 1px solid #C7CDD1; padding: 2px; text-align: center; display: -webkit-flex; display: flex; } /* line 35, app/stylesheets/components/_conditional_release_stats.scss */ .crs-breakdown-details__header-text { margin-left: 20px; margin-right: 10px; } /* line 40, app/stylesheets/components/_conditional_release_stats.scss */ .crs-bar__horizontal-outside { position: relative; height: 14px; border-radius: 25px; padding: 5px 0; } /* line 47, app/stylesheets/components/_conditional_release_stats.scss */ .crs-bar__horizontal-inside-fill { position: absolute; height: 50%; border-radius: 20px; background-color: #394B58; overflow: hidden; } /* line 56, app/stylesheets/components/_conditional_release_stats.scss */ .crs-bar__horizontal-inside { position: absolute; height: 50%; width: 100%; border-radius: 20px; background-color: #F5F5F5; overflow: hidden; } /* line 66, app/stylesheets/components/_conditional_release_stats.scss */ .crs-bar__bottom { position: relative; display: -webkit-flex; display: flex; -webkit-flex-direction: row; flex-direction: row; -webkit-justify-content: space-between; justify-content: space-between; font-size: 14px; color: #2D3B45; margin-left: 4px; margin-bottom: 15px; } /* line 77, app/stylesheets/components/_conditional_release_stats.scss */ .crs-bar__info { height: 50%; } /* line 81, app/stylesheets/components/_conditional_release_stats.scss */ .crs-link-button { background: transparent; border: none; color: #008EE2; } /* line 86, app/stylesheets/components/_conditional_release_stats.scss */ .crs-link-button:focus, .crs-link-button:hover { text-decoration: underline; color: #006eaf; } /* line 93, app/stylesheets/components/_conditional_release_stats.scss */ .crs-sticky-sidebar { width: 365px; height: 100%; position: fixed; right: 0; top: 0; transition: all .5s; box-shadow: -2px 0px 15px #73818C; background: #FFFFFF; z-index: 10; } /* line 104, app/stylesheets/components/_conditional_release_stats.scss */ .crs-sticky-sidebar.crs-sticky-sidebar__hidden { right: -365px; opacity: 0; } /* line 109, app/stylesheets/components/_conditional_release_stats.scss */ .crs-sticky-sidebar .crs-sticky-sidebar__close { position: absolute; top: 20px; right: 15px; z-index: 20; } /* line 118, app/stylesheets/components/_conditional_release_stats.scss */ .crs-ranges-view .crs-ranges-view__header { font-weight: lighter; padding: 15px 10px; color: #73818C; text-indent: 10px; } /* line 125, app/stylesheets/components/_conditional_release_stats.scss */ .crs-ranges-view [class*="-Tab__accordion"] { border-radius: 0; font-weight: bold; margin: 0 0 1px; text-indent: 10px; border: none; box-shadow: 0 0 0 1px #C7CDD1 !important; } /* line 134, app/stylesheets/components/_conditional_release_stats.scss */ .crs-ranges-view [class*="-TabPanel__accordion"] { margin-bottom: 1px; } /* line 138, app/stylesheets/components/_conditional_release_stats.scss */ .crs-ranges-view [class*="-TabPanel__accordion"][aria-hidden="true"] { margin-bottom: 0; } /* line 142, app/stylesheets/components/_conditional_release_stats.scss */ .crs-ranges-view [class*="-TabPanel__content"] { background: transparent; border: none; padding: 5px 0; } /* line 149, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-range__item { margin: 15px 15px; } /* line 153, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__avatar { width: 35px; height: 35px; border-radius: 50%; margin-right: 10px; } /* line 160, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__trend-icon { width: 30px; height: 30px; font-size: 18px; font-weight: bold; float: right; } /* line 167, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__trend-icon.crs-student__trend-icon__positive { color: #00AC18; } /* line 170, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__trend-icon.crs-student__trend-icon__positive:before { content: '▲'; } /* line 175, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__trend-icon.crs-student__trend-icon__neutral { color: #73818C; font-family: monospace; font-size: 40px; line-height: 25px; text-indent: -3px; } /* line 182, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__trend-icon.crs-student__trend-icon__neutral:before { content: '-'; } /* line 187, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__trend-icon.crs-student__trend-icon__negative { color: #FC5E13; } /* line 190, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__trend-icon.crs-student__trend-icon__negative:before { content: '▼'; } /* line 196, app/stylesheets/components/_conditional_release_stats.scss */ .crs-icon-x { margin: auto; } /* line 200, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details { width: 365px; height: 100%; position: fixed; right: 0px; top: 0px; transition: all .5s; background: #FFFFFF; } /* line 209, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details.crs-student-details__hidden { right: -365px; opacity: 0; } /* line 215, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__header { margin-top: 10px; padding: 15px 10px; display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: space-between; justify-content: space-between; border-bottom: 1px solid #C7CDD1; } /* line 224, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__name { margin: 5px 0px 0px 0px; } /* line 228, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student__range-item { margin: 15px 5px; } /* line 232, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__profile-content { display: -webkit-flex; display: flex; -webkit-flex-direction: row; flex-direction: row; -webkit-align-items: center; align-items: center; -webkit-justify-content: space-around; justify-content: space-around; border-bottom: 1px solid #C7CDD1; background-color: #F5F5F5; padding: 17px 10px; } /* line 242, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__profile-image { width: 70px; height: 70px; border-radius: 50%; } /* line 248, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__profile-inner-content { display: -webkit-flex; display: flex; -webkit-flex-direction: column; flex-direction: column; -webkit-align-items: center; align-items: center; background-color: #F5F5F5; } /* line 255, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__score-content { display: -webkit-flex; display: flex; -webkit-flex-direction: column; flex-direction: column; -webkit-align-items: center; align-items: center; border-bottom: 1px solid #C7CDD1; padding: 10px; } /* line 263, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__score-date { opacity: .6; } /* line 267, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__score-number { margin: 2px 0px; font-weight: bolder; font-size: 25px; } /* line 273, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__score-title { font-weight: normal; } /* line 277, app/stylesheets/components/_conditional_release_stats.scss */ .crs-breakdown__link { text-decoration: none; font-weight: normal; color: #008EE2; } /* line 282, app/stylesheets/components/_conditional_release_stats.scss */ .crs-breakdown__link:focus, .crs-breakdown__link:hover { color: #006eaf; text-decoration: underline; } /* line 289, app/stylesheets/components/_conditional_release_stats.scss */ .crs-back-button { background: #FFFFFF; border: none; } /* line 294, app/stylesheets/components/_conditional_release_stats.scss */ i.crs-student-details__assignment-icon { background: #394B58; width: 32px; height: 32px; text-align: center; line-height: 32px; border-radius: 50%; color: #FFFFFF; float: left; margin-left: 5px; } /* line 305, app/stylesheets/components/_conditional_release_stats.scss */ i.crs-student-details__assignment-icon:before { font-size: 14px; } /* line 310, app/stylesheets/components/_conditional_release_stats.scss */ i.crs-icon-assignment { background: #BF32A4; } /* line 314, app/stylesheets/components/_conditional_release_stats.scss */ i.crs-icon-quiz { background: #EE0612; } /* line 318, app/stylesheets/components/_conditional_release_stats.scss */ i.crs-icon-discussion { background: #FC5E13; } /* line 322, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__assignment-name { -webkit-flex: 0.9; flex: 0.9; } /* line 326, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__assignment { display: -webkit-flex; display: flex; -webkit-flex-direction: row; flex-direction: row; -webkit-justify-content: space-between; justify-content: space-between; padding: 15px 15px; border-bottom: 1px solid #C7CDD1; } /* line 334, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__assignment-score { display: -webkit-flex; display: flex; -webkit-flex-direction: column; flex-direction: column; -webkit-align-items: center; align-items: center; margin-right: 10px; font-weight: bold; } /* line 342, app/stylesheets/components/_conditional_release_stats.scss */ .crs-student-details__loading { display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; margin-top: 200px; -webkit-justify-content: center; justify-content: center; } /* line 349, app/stylesheets/components/_conditional_release_stats.scss */ .crs-icon-email { padding-right: 5px; }
{ "content_hash": "4f47bfa6e4eb68cbcf8b086c4a1e1ed4", "timestamp": "", "source": "github", "line_count": 1067, "max_line_length": 106, "avg_line_length": 27.343955014058107, "alnum_prop": 0.6996846723334247, "repo_name": "goranagojic/koturato-front", "id": "c13b696f1ef4509b9fd5b567936ecb97c07ed5dd", "size": "29180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/canvas_css/new_styles_normal_contrast/bundles/assignments-82c48e2e7b.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5033435" }, { "name": "HTML", "bytes": "14371" }, { "name": "JavaScript", "bytes": "78450" } ], "symlink_target": "" }
source /home/vagrant/.bash_profile sqlplus sys/manager as sysdba <<EOT CREATE TABLESPACE STERLING94 DATAFILE '/u01/app/oracle/oradata/XE/STERLING94.dbf' SIZE 512M AUTOEXTEND ON NEXT 1024K MAXSIZE UNLIMITED LOGGING DEFAULT STORAGE(MAXEXTENTS UNLIMITED) ONLINE PERMANENT; CREATE USER STERLING94 IDENTIFIED BY sterling94 DEFAULT TABLESPACE STERLING94; GRANT DBA TO STERLING94 WITH ADMIN OPTION; exit; EOT
{ "content_hash": "5f0cba0f30c9b160e8a4d090620596cb", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 198, "avg_line_length": 57.285714285714285, "alnum_prop": 0.8354114713216958, "repo_name": "pawandeepthind/dev-multivm", "id": "71225c2fc9e4458794b3bb2800a9957a40142757", "size": "401", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/roles/oracle/files/execute_2.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "1393" }, { "name": "Shell", "bytes": "1506" } ], "symlink_target": "" }
require "aws-sdk-s3" module Alephant module Harness module Service module S3 def self.create(id) client.create_bucket(bucket: id) end def self.delete(id) s3 = Aws::S3::Resource.new(client: client) s3.bucket(id).delete end def self.add_object(id, object_id, data) client.put_object( body: data, bucket: id, key: object_id ) end def self.get_object(id, object_id) client.get_object( bucket: id, key: object_id ) end def self.bucket_exists?(bucket_id) begin client.head_bucket( bucket: bucket_id ) yield if block_given? true rescue => e false end end private def self.client @client ||= ::Aws::S3::Client.new(AWS.s3_config) end end end end end
{ "content_hash": "1e9dda0c53d26b02bb8534c130c136fc", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 58, "avg_line_length": 20, "alnum_prop": 0.4666666666666667, "repo_name": "BBC-News/alephant-harness", "id": "2e04a07e9fd869ec30f7e9cd3678fc69f2ff19c5", "size": "1020", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/alephant/harness/service/s3.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "17053" } ], "symlink_target": "" }
import rclpy from rclpy.node import Node from humanoid_league_msgs.msg import HeadMode from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement class HeadModeDecision(AbstractDecisionElement): """ Decides in which general "mode" the head currently operates. Meaning what should be searched for or^ if any searching should be done at all. """ def __init__(self, blackboard, dsd, parameters=None): super(HeadModeDecision, self).__init__(blackboard, dsd, parameters) @staticmethod def _register(): return ['BALL_MODE', 'POST_MODE', 'BALL_GOAL_TRACKING', 'FIELD_FEATURES', 'NON_FIELD_FEATURES', 'LOOK_DOWN', 'LOOK_UP', 'LOOK_FORWARD', 'DONT_MOVE', 'RECORD_VISUAL_COMPASS', 'BALL_MODE_PENALTY', 'VISUAL_COMPASS_FEATURES'] def perform(self, reevaluate=False): """ Map the saved head_mode from blackboard to corresponding decision results """ # Ensure that a head_mode value is set if self.blackboard.head_capsule.head_mode is None: # configured default value self.publish_debug_data('using_default', True) head_mode = self.blackboard.config['defaults']['head_mode'] else: head_mode = self.blackboard.head_capsule.head_mode self.publish_debug_data('using_default', False) # map results to all possible values of head_mode if head_mode == HeadMode.BALL_MODE: return 'BALL_MODE' elif head_mode == HeadMode.BALL_MODE_PENALTY: return 'BALL_MODE_PENALTY' elif head_mode == HeadMode.POST_MODE: return 'POST_MODE' elif head_mode == HeadMode.BALL_GOAL_TRACKING: return 'BALL_GOAL_TRACKING' elif head_mode == HeadMode.FIELD_FEATURES: return 'FIELD_FEATURES' elif head_mode == HeadMode.NON_FIELD_FEATURES: return 'NON_FIELD_FEATURES' elif head_mode == HeadMode.LOOK_DOWN: return 'LOOK_DOWN' elif head_mode == HeadMode.LOOK_UP: return 'LOOK_UP' elif head_mode == HeadMode.LOOK_FORWARD: return 'LOOK_FORWARD' elif head_mode == HeadMode.DONT_MOVE: return 'DONT_MOVE' elif head_mode == HeadMode.RECORD_VISUAL_COMPASS: return 'RECORD_VISUAL_COMPASS' elif head_mode == HeadMode.VISUAL_COMPASS_FEATURES: return 'VISUAL_COMPASS_FEATURES' elif head_mode == HeadMode.LOOK_FRONT: return 'LOOK_FRONT' else: self.blackboard.node.get_logger().error('the set head_mode ({}) is not known'.format(head_mode)) def get_reevaluate(self): """ True because we always need to know when the role changes as soon as possible """ return True
{ "content_hash": "a2fa45cadb6f07cccb1cd277c65d1e58", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 108, "avg_line_length": 39.12328767123287, "alnum_prop": 0.6218487394957983, "repo_name": "bit-bots/bitbots_behaviour", "id": "5fd444bf162d969367aaf51c8a1b9d1966fc3012", "size": "2856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bitbots_head_behavior/bitbots_head_behavior/decisions/head_mode_decision.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CMake", "bytes": "12619" }, { "name": "Python", "bytes": "92540" } ], "symlink_target": "" }
#ifndef __ABSTRACT_DOMAINS_HH__ #define __ABSTRACT_DOMAINS_HH__ #include "crab_llvm/crab_cfg.hh" #include "crab/domains/linear_constraints.hpp" #include "crab/domains/intervals.hpp" #include "crab/domains/dis_intervals.hpp" #include "crab/domains/sparse_dbm.hpp" #include "crab/domains/split_dbm.hpp" #include "crab/domains/boxes.hpp" #include "crab/domains/apron_domains.hpp" #include "crab/domains/array_smashing.hpp" #include "crab/domains/term_equiv.hpp" #include "crab/domains/combined_domains.hpp" /* Definition of the abstract domains */ namespace crab_llvm { //// // Base (non-array) numerical domains for user options //// enum CrabDomain { INTERVALS , INTERVALS_CONGRUENCES , BOXES , DIS_INTERVALS , ZONES_SPARSE_DBM , ZONES_SPLIT_DBM , TERMS_INTERVALS , TERMS_DIS_INTERVALS , TERMS_ZONES // TERMS_INTERVALS x ZONES_SPLIT_DBM , ADAPT_TERMS_ZONES // (#live vars < threshold ? TERMS_INTERVALSxZONES_SPLIT_DBM, INTERVALS) , OPT_OCT_APRON , PK_APRON }; ////// /// Definition of the abstract domains ////// using namespace crab::domains; using namespace ikos; /// --- Types for linear constraints and expressions typedef ikos::linear_expression<z_number, varname_t> z_lin_exp_t; typedef ikos::linear_constraint<z_number, varname_t> z_lin_cst_t; typedef ikos::linear_constraint_system<z_number, varname_t> z_lin_cst_sys_t; ////// //// Base domains ////// /// -- Intervals typedef interval_domain< z_number, varname_t> interval_domain_t; /// -- Zones with sparse DBM typedef SpDBM_impl::DefaultParams<z_number> SparseDBMGraph; typedef SparseDBM<z_number, varname_t, SparseDBMGraph> dbm_domain_t; /// -- Zones with split DBM typedef SDBM_impl::DefaultParams<z_number> SplitDBMGraph; typedef SplitDBM<z_number, varname_t, SplitDBMGraph> split_dbm_domain_t; /// -- Boxes typedef boxes_domain<z_number, varname_t> boxes_domain_t; /// -- DisIntervals typedef dis_interval_domain <z_number, varname_t> dis_interval_domain_t; /// -- Apron domains typedef apron_domain< z_number, varname_t, apron_domain_id_t::APRON_OPT_OCT > opt_oct_apron_domain_t; typedef apron_domain< z_number, varname_t, apron_domain_id_t::APRON_PK > pk_apron_domain_t; ////// /// Combination/functor of domains ////// /// -- Reduced product of intervals with congruences typedef numerical_congruence_domain<interval_domain_t> ric_domain_t; /// -- Term functor domain with Intervals typedef crab::cfg::var_factory_impl::str_var_alloc_col::varname_t str_varname_t; typedef interval_domain<z_number, str_varname_t> str_interval_dom_t; typedef term::TDomInfo<z_number, varname_t, str_interval_dom_t> idom_info; typedef term_domain<idom_info> term_int_domain_t; /// -- Term functor domain with DisIntervals typedef dis_interval_domain<z_number, str_varname_t> str_dis_interval_dom_t; typedef term::TDomInfo<z_number, varname_t, str_dis_interval_dom_t> dis_idom_info; typedef term_domain<dis_idom_info> term_dis_int_domain_t; /// -- Reduced product of Term(DisIntervals) with split zones typedef reduced_numerical_domain_product2<term_dis_int_domain_t, split_dbm_domain_t> num_domain_t; /// -- Array smashing functor domain typedef array_smashing<interval_domain_t> arr_interval_domain_t; typedef array_smashing<ric_domain_t> arr_ric_domain_t; typedef array_smashing<dbm_domain_t> arr_dbm_domain_t; typedef array_smashing<split_dbm_domain_t> arr_split_dbm_domain_t; typedef array_smashing<term_int_domain_t> arr_term_int_domain_t; typedef array_smashing<term_dis_int_domain_t> arr_term_dis_int_domain_t; typedef array_smashing<boxes_domain_t> arr_boxes_domain_t; typedef array_smashing<dis_interval_domain_t> arr_dis_interval_domain_t; typedef array_smashing<num_domain_t> arr_num_domain_t; typedef array_smashing<opt_oct_apron_domain_t> arr_opt_oct_apron_domain_t; typedef array_smashing<pk_apron_domain_t> arr_pk_apron_domain_t; } // end namespace crab-llvm #endif
{ "content_hash": "6576871f08c849c7eb6befbed547e03d", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 103, "avg_line_length": 38.61682242990654, "alnum_prop": 0.6982090997095838, "repo_name": "caballa/crab-llvm", "id": "0c86815e1130d6f9b5c21b99659029b583558ae8", "size": "4132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/crab_llvm/crab_domains.hh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "14163" }, { "name": "C++", "bytes": "202264" }, { "name": "CMake", "bytes": "182639" }, { "name": "Python", "bytes": "31176" } ], "symlink_target": "" }
/* tslint:disable:jsx-no-multiline-js */ import React from 'react'; import assign from 'object-assign'; import { View, Image, Text, TextInput, TouchableWithoutFeedback } from 'react-native'; import variables from '../style/themes/default'; import TextAreaItemProps from './PropsType'; import TextAreaItemStyle from './style/index'; function fixControlledValue(value) { if (typeof value === 'undefined' || value === null) { return ''; } return value; } export default class TextAreaItem extends React.Component<TextAreaItemProps, any> { static defaultProps = { onChange() { }, onFocus() { }, onBlur() { }, onErrorClick() { }, clear: true, error: false, editable: true, rows: 1, count: 0, keyboardType: 'default', autoHeight: false, last: false, styles: TextAreaItemStyle, }; constructor(props) { super(props); this.state = { inputCount: 0, height: props.rows > 1 ? 6 * props.rows * 4 : variables.list_item_height, }; } onChange = (event) => { const text = event.nativeEvent.text; let height; const { autoHeight, rows, onChange } = this.props; if (autoHeight) { height = event.nativeEvent.contentSize.height; } else if (rows > 1) { height = 6 * rows * 4; } else { height = variables.list_item_height; } this.setState({ inputCount: text.length, height, }); if (onChange) { onChange(text); } } render() { const { inputCount } = this.state; const { value, defaultValue, rows, error, clear, count, autoHeight, last, onErrorClick, styles, } = this.props; let valueProps; if ('value' in this.props) { valueProps = { value: fixControlledValue(value), }; } else { valueProps = { defaultValue, }; } const containerStyle = { borderBottomWidth: last ? 0 : variables.border_width_sm, }; const textareaStyle = { color: error ? '#f50' : variables.color_text_base, paddingRight: error ? 2 * variables.h_spacing_lg : 0, }; const maxLength = count > 0 ? count : undefined; const restProps = assign({}, this.props); [ 'rows', 'error', 'clear', 'count', 'autoHeight', 'last', 'onErrorClick', 'styles', ].forEach(prop => { if (restProps.hasOwnProperty(prop)) { delete restProps[prop]; } }); return ( <View style={[styles.container, containerStyle, { position: 'relative' }]}> <TextInput clearButtonMode={clear ? 'while-editing' : 'never'} underlineColorAndroid="transparent" style={[styles.input, textareaStyle, { height: Math.max(45, this.state.height) }]} {...restProps} {...valueProps} onChange={(event) => this.onChange(event)} multiline={rows > 1 || autoHeight} numberOfLines={rows} maxLength={maxLength} /> {error ? <TouchableWithoutFeedback onPress={onErrorClick}> <View style={[styles.errorIcon]}> <Image source={require('../style/images/error.png')} style={{ width: variables.icon_size_xs, height:variables.icon_size_xs }} /> </View> </TouchableWithoutFeedback> : null} {rows > 1 && count > 0 ? <View style={[styles.count]}> <Text> {inputCount} / {count} </Text> </View> : null} </View> ); } }
{ "content_hash": "ca485e6a6476a79085a4c5a19d671906", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 92, "avg_line_length": 26.413533834586467, "alnum_prop": 0.5730145175064048, "repo_name": "ddcat1115/ant-design-mobile", "id": "42ed77f06c9ebb2173d7fcf61b33395c557b0ac5", "size": "3513", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/textarea-item/index.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "147116" }, { "name": "HTML", "bytes": "8156" }, { "name": "Java", "bytes": "4761" }, { "name": "JavaScript", "bytes": "90206" }, { "name": "Objective-C", "bytes": "24702" }, { "name": "Python", "bytes": "1632" }, { "name": "TypeScript", "bytes": "382687" } ], "symlink_target": "" }
This folder contains examples using the [VSPK-Python](https://github.com/nuagenetworks/vspk-python)
{ "content_hash": "d4a9deb3510e9e657070b47ea5d99674", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 99, "avg_line_length": 100, "alnum_prop": 0.81, "repo_name": "nuagenetworks/vspk-examples", "id": "8939bd08c87b9f1f55b946ef11824b3f6d5fcd59", "size": "124", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "python/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "26956" }, { "name": "Go", "bytes": "5153" }, { "name": "Java", "bytes": "123797" }, { "name": "PowerShell", "bytes": "4797" }, { "name": "Python", "bytes": "351476" } ], "symlink_target": "" }
'use strict'; var util = require('../util/util'); var Tile = require('./tile'); var LngLat = require('../geo/lng_lat'); var Point = require('point-geometry'); var Evented = require('../util/evented'); var ajax = require('../util/ajax'); module.exports = VideoSource; /** * Create a Video data source instance given an options object * @class VideoSource * @param {Object} [options] * @param {string|Array} options.url A string or array of URL(s) to video files * @param {Array} options.coordinates lng, lat coordinates in order clockwise starting at the top left: tl, tr, br, bl * @example * var sourceObj = new mapboxgl.VideoSource({ * url: [ * 'https://www.mapbox.com/videos/baltimore-smoke.mp4', * 'https://www.mapbox.com/videos/baltimore-smoke.webm' * ], * coordinates: [ * [-76.54335737228394, 39.18579907229748], * [-76.52803659439087, 39.1838364847587], * [-76.5295386314392, 39.17683392507606], * [-76.54520273208618, 39.17876344106642] * ] * }); * map.addSource('some id', sourceObj); // add * map.removeSource('some id'); // remove */ function VideoSource(options) { this.coordinates = options.coordinates; ajax.getVideo(options.urls, function(err, video) { // @TODO handle errors via event. if (err) return; this.video = video; this.video.loop = true; var loopID; // start repainting when video starts playing this.video.addEventListener('playing', function() { loopID = this.map.style.animationLoop.set(Infinity); this.map._rerender(); }.bind(this)); // stop repainting when video stops this.video.addEventListener('pause', function() { this.map.style.animationLoop.cancel(loopID); }.bind(this)); this._loaded = true; if (this.map) { this.video.play(); this.createTile(); this.fire('change'); } }.bind(this)); } VideoSource.prototype = util.inherit(Evented, /** @lends VideoSource.prototype */{ roundZoom: true, /** * Return the HTML video element. * * @returns {Object} */ getVideo: function() { return this.video; }, onAdd: function(map) { this.map = map; if (this.video) { this.video.play(); this.createTile(); } }, createTile: function() { /* * Calculate which mercator tile is suitable for rendering the video in * and create a buffer with the corner coordinates. These coordinates * may be outside the tile, because raster tiles aren't clipped when rendering. */ var map = this.map; var coords = this.coordinates.map(function(lnglat) { var loc = LngLat.convert(lnglat); return map.transform.locationCoordinate(loc).zoomTo(0); }); var center = util.getCoordinatesCenter(coords); var tileExtent = 4096; var tileCoords = coords.map(function(coord) { var zoomedCoord = coord.zoomTo(center.zoom); return new Point( Math.round((zoomedCoord.column - center.column) * tileExtent), Math.round((zoomedCoord.row - center.row) * tileExtent)); }); var gl = map.painter.gl; var maxInt16 = 32767; var array = new Int16Array([ tileCoords[0].x, tileCoords[0].y, 0, 0, tileCoords[1].x, tileCoords[1].y, maxInt16, 0, tileCoords[3].x, tileCoords[3].y, 0, maxInt16, tileCoords[2].x, tileCoords[2].y, maxInt16, maxInt16 ]); this.tile = new Tile(); this.tile.buckets = {}; this.tile.boundsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.tile.boundsBuffer); gl.bufferData(gl.ARRAY_BUFFER, array, gl.STATIC_DRAW); this.center = center; }, loaded: function() { return this.video && this.video.readyState >= 2; }, update: function() { // noop }, reload: function() { // noop }, render: function(layers, painter) { if (!this._loaded) return; if (this.video.readyState < 2) return; // not enough data for current position var c = this.center; this.tile.calculateMatrices(c.zoom, c.column, c.row, this.map.transform, painter); var gl = painter.gl; if (!this.tile.texture) { this.tile.texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, this.tile.texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.video); } else { gl.bindTexture(gl.TEXTURE_2D, this.tile.texture); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video); } painter.drawLayers(layers, this.tile.posMatrix, this.tile); }, featuresAt: function(point, params, callback) { return callback(null, []); }, featuresIn: function(bbox, params, callback) { return callback(null, []); } });
{ "content_hash": "b8da82c7bc49c1e5df6e20a218b0ef50", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 118, "avg_line_length": 32.1764705882353, "alnum_prop": 0.5903107861060329, "repo_name": "gbif/map-gl", "id": "c5180f3739e11f4fec07d65b622b0cd245fa3cee", "size": "5470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/mapbox-gl-js/js/source/video_source.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8253" }, { "name": "GLSL", "bytes": "18542" }, { "name": "HTML", "bytes": "68805" }, { "name": "Java", "bytes": "15678" }, { "name": "JavaScript", "bytes": "671574" }, { "name": "Protocol Buffer", "bytes": "987" }, { "name": "Ruby", "bytes": "200" }, { "name": "Shell", "bytes": "1595" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/xaevman/log.svg?branch=master)](https://travis-ci.org/xaevman/log) ## Overview Log is a Go package which provides logging interfaces and common implementations. ### Flog Flog is a submodule which provides file-backed logging capabilities for go applications. FLog is built on top of the standard log library, and includes facilities for buffered logging, managing separate logs and log files, as well as periodic log rotation. ### License These Go packages are released under a BSD-style license, the contents of which are in the repo's LICENSE file. ## API Documentation http://godoc.org/github.com/xaevman/log http://godoc.org/github.com/xaevman/flog
{ "content_hash": "b7b66620d0e953bbc66697704287197b", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 256, "avg_line_length": 46.46666666666667, "alnum_prop": 0.7819225251076041, "repo_name": "xaevman/log", "id": "3e9bc74f749d46f928a3c2b51c4b29fc812fa14a", "size": "720", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Go", "bytes": "18046" } ], "symlink_target": "" }
using System; using System.Collections.Generic; namespace LinqToDB.SchemaProvider { public class DatabaseSchema { public string DataSource { get; set; } public string Database { get; set; } public string ServerVersion { get; set; } public List<TableSchema> Tables { get; set; } public List<ProcedureSchema> Procedures { get; set; } } }
{ "content_hash": "fb73d6f7020565b2197e5e1ab0c95ff8", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 29.857142857142858, "alnum_prop": 0.6100478468899522, "repo_name": "MarcoRosenberger/linq2dbCrud", "id": "bd1476e3e1f8c72f34a47d6ccac4c878c7c28951", "size": "420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/SchemaProvider/DatabaseSchema.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3208081" }, { "name": "HTML", "bytes": "1671" }, { "name": "Shell", "bytes": "2660" }, { "name": "Visual Basic", "bytes": "1475" }, { "name": "XML", "bytes": "4488758" } ], "symlink_target": "" }
module RoomComments class CreateService < BaseService def initialize(comment_params, room_id) @comment_params = comment_params.dup @room_id = room_id end def execute room_comment = RoomComment.new(@comment_params) room = Room.find(@room_id) room.room_comments << room_comment room_comment.save room_comment end end end
{ "content_hash": "934a2b9a9d1c908ada1d75007d2bdb70", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 53, "avg_line_length": 23.875, "alnum_prop": 0.6570680628272252, "repo_name": "totutote/pso2-fixed-room-adjuster", "id": "c8e73fbf8ee66d0580527cd6fa47ab92f9578ad5", "size": "382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/services/room_comments/create_service.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1328" }, { "name": "CoffeeScript", "bytes": "633" }, { "name": "HTML", "bytes": "22261" }, { "name": "JavaScript", "bytes": "1233" }, { "name": "Ruby", "bytes": "51892" } ], "symlink_target": "" }
package org.lnu.is.dao.builder.person.pension; import org.lnu.is.dao.annotations.QBuilder; import org.lnu.is.dao.builder.AbstractQueryBuilder; import org.lnu.is.dao.builder.BaseQueryBuilder; import org.lnu.is.domain.person.pension.PersonPension; /** * Person Pension Query Builder. * @author ivanursul * */ @QBuilder("personPensionQueryBuilder") public class PersonPensionQueryBuilder extends AbstractQueryBuilder<PersonPension> { private static final String PERSON_CONDITION = "e.person = :person "; private static final String CONTACTTYPE_CONDITION = "e.contactType = :addressType "; private static final String BEGDATE_CONDITION = "e.begDate <= :begDate "; private static final String ENDDATE_CONDITION = "e.endDate >= :endDate"; @Override protected String getBaseQuery() { return "SELECT e FROM PersonPension e %s"; } @Override protected BaseQueryBuilder build(final PersonPension context, final BaseQueryBuilder builder) { return builder .where() .openBracket() .addAndCondition(PERSON_CONDITION, context.getPerson()) .addAndCondition(CONTACTTYPE_CONDITION, context.getPensionType()) .addAndCondition(BEGDATE_CONDITION, context.getBegDate()) .addAndCondition(ENDDATE_CONDITION, context.getEndDate()) .closeBracket(); } }
{ "content_hash": "c04e05be2657b1e5453e6af0c20bb222", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 96, "avg_line_length": 34.7027027027027, "alnum_prop": 0.7624610591900312, "repo_name": "ifnul/ums-backend", "id": "07e8492e3789818baecacdd9341fd6aa4a7fed8e", "size": "1284", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "is-lnu-persistence/src/main/java/org/lnu/is/dao/builder/person/pension/PersonPensionQueryBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "7045" }, { "name": "Java", "bytes": "4184188" }, { "name": "Scala", "bytes": "217850" }, { "name": "Shell", "bytes": "1100" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Platyopuntia conjungens F.Ritter ### Remarks null
{ "content_hash": "35cf891160783507e23b055af50dc6dc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 32, "avg_line_length": 11.846153846153847, "alnum_prop": 0.7402597402597403, "repo_name": "mdoering/backbone", "id": "c7fea5c74dad97665d4993695bfd89cdd87964d6", "size": "227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Opuntia/Opuntia conjungens/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Magento\Customer\Controller\Adminhtml\Group; class Edit extends \Magento\Customer\Controller\Adminhtml\Group { /** * Edit customer group action. Forward to new action. * * @return \Magento\Backend\Model\View\Result\Forward */ public function execute() { return $this->resultForwardFactory->create()->forward('new'); } }
{ "content_hash": "80b898b05050095de8f9292bbe8c3f66", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 69, "avg_line_length": 23.875, "alnum_prop": 0.6701570680628273, "repo_name": "j-froehlich/magento2_wk", "id": "8635561af818ae88f6ab453fec2bd94913e8ba40", "size": "493", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/magento/module-customer/Controller/Adminhtml/Group/Edit.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
<?php /** * The followings are the available columns in table 'chat': * @property integer $id * @property string $name * @property integer $frequency */ class Chat extends CActiveRecord { /** * Returns the static model of the specified AR class. * @return static the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'chat'; } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'user' => array(self::BELONGS_TO, 'user', 'user_id'), 'chatCount' => array(self::STAT, 'praise', 'a_id', 'condition'=>'type=0'), ); } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('user_id', 'required'), array('date', 'checkattr'), ); } /** * 校验发言间隔 */ public function checkattr($attribute, $params) { $model = self::model()->find(array( 'order' => 'date DESC', 'condition' => 'user_id='.$this->user_id, )); $lastdate = $model->date; if ($this->date - $lastdate < 5) { $this->addError($attribute, '磨叽个什么?'); } } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'NO.', 'user_id' => 'By', 'praise' => '贊', 'parent_id' => '上層', 'content' => '內容', 'date' => '發佈時間' ); } public function praiseCount() { self::model()->updateByPk($this->id, array('praise' => $this->praise + 1)); } public static function getUserById($id){ return User::getNameById(self::model()->findByPk($id)->user_id); } }
{ "content_hash": "debf37bcf529564aa5f6ae0154e215dc", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 83, "avg_line_length": 23.569767441860463, "alnum_prop": 0.6013813517513567, "repo_name": "GsHatRed/Yiitest", "id": "11eeaf231f0e43d95fbdbf64926075d6c0bc896e", "size": "2067", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "protected/models/Chat.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "455" }, { "name": "Batchfile", "bytes": "1905" }, { "name": "CSS", "bytes": "253884" }, { "name": "HTML", "bytes": "257116" }, { "name": "JavaScript", "bytes": "1813424" }, { "name": "PHP", "bytes": "23023726" }, { "name": "TeX", "bytes": "12618" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9f268783ef9127ab45d6eb00d8345bd0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "3cfa93cd256b7cafccf2d1154ce75562d40bab94", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Solanum/Solanum chromatophilum/Solanum chromatophilum subnivale/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Naucon\Utility\Tests; use Naucon\Utility\Observable; use Naucon\Utility\ObservableInterface; use Naucon\Utility\ObserverAbstract; class ObserverTest extends \PHPUnit_Framework_TestCase { /** * @var array */ static protected $observer = null; /** * method is called before test class. */ static public function setUpBeforeClass() { self::$observer = array(); self::$observer[1] = new YourObserverFoo(); self::$observer[2] = new YourObserverBar(); } /** * method is called after test class. */ public static function tearDownAfterClass() { self::$observer = null; } /** * @return YourObservableSubject */ public function testInit() { // instance of observable subject $observableSubjectObject = new YourObservableSubject(); // hook up observer $observableSubjectObject->getObservableObject()->addObserver(self::$observer[1]); $observableSubjectObject->getObservableObject()->addObserver(self::$observer[2]); return $observableSubjectObject; } /** * @depends testInit * @param YourObservableSubject * @return void */ public function testCount(YourObservableSubject $observableSubjectObject) { $this->assertEquals(2, $observableSubjectObject->getObservableObject()->countObservers()); } /** * @depends testInit * @param YourObservableSubject * @return void */ public function testNotifation(YourObservableSubject $observableSubjectObject) { $observableSubjectObject->setState('start'); $this->assertEquals(2, count($observableSubjectObject->result)); $this->assertEquals('Foo:start', $observableSubjectObject->result[0]); $this->assertEquals('Bar:start', $observableSubjectObject->result[1]); $observableSubjectObject->setState('stop'); $this->assertEquals(2, count($observableSubjectObject->result)); $this->assertEquals('Foo:stop', $observableSubjectObject->result[0]); $this->assertEquals('Bar:stop', $observableSubjectObject->result[1]); $observableSubjectObject->setState('stop'); $this->assertEquals(0, count($observableSubjectObject->result)); } /** * @depends testInit * @param YourObservableSubject * @return void */ public function testRemove(YourObservableSubject $observableSubjectObject) { // remove observer $observableSubjectObject->getObservableObject()->removeObserver(self::$observer[1]); $this->assertEquals(1, $observableSubjectObject->getObservableObject()->countObservers()); $observableSubjectObject->setState('start'); $this->assertEquals(1, count($observableSubjectObject->result)); $this->assertEquals('Bar:start', $observableSubjectObject->result[0]); } } class YourObservableSubject { protected $observableObject = null; private $yourstate = null; public $result = null; public function getObservableObject() { if (is_null($this->observableObject)) { $this->observableObject = new Observable(); } return $this->observableObject; } public function getState() { return $this->yourstate; } public function setState($value) { $this->result = array(); if ($this->yourstate != $value) { $this->yourstate = $value; $this->getObservableObject()->setChanged(); } $this->getObservableObject()->notifyObservers($this); } } class YourObserverFoo extends ObserverAbstract { public function update(ObservableInterface $observableObject, $arg) { $arg->result[] = 'Foo:' . $arg->getState(); } } class YourObserverBar extends ObserverAbstract { public function update(ObservableInterface $observableObject, $arg) { $arg->result[] = 'Bar:' . $arg->getState(); } }
{ "content_hash": "a5337b448c984f54c023f7e2a9bb96fa", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 98, "avg_line_length": 26.66013071895425, "alnum_prop": 0.6344692326550625, "repo_name": "naucon/Utility", "id": "54057531419891f59fd465ea89a4986ac22cd47e", "size": "4298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/ObserverTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "307510" } ], "symlink_target": "" }
using System.Linq; using CppSharp.AST; using CppSharp.Generators; namespace CppSharp.Passes { public class MarshalPrimitivePointersAsRefTypePass : TranslationUnitPass { public override bool VisitFunctionDecl(Function function) { if (!base.VisitFunctionDecl(function) || function.OperatorKind == CXXOperatorKind.Conversion || function.OperatorKind == CXXOperatorKind.ExplicitConversion) return false; foreach (var param in function.Parameters.Where( p => !p.IsOut && p.Type.IsPrimitiveTypeConvertibleToRef())) param.Usage = ParameterUsage.InOut; return true; } } }
{ "content_hash": "b876dafd6eebc59c2c87c1c2d0154ae7", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 76, "avg_line_length": 31.217391304347824, "alnum_prop": 0.6364902506963789, "repo_name": "mydogisbox/CppSharp", "id": "244d4a9c8646e818fdafbf0aa71d0f9f4fa64fcf", "size": "718", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Generator/Passes/MarshalPrimitivePointersAsRefTypePass.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1693" }, { "name": "C", "bytes": "668" }, { "name": "C#", "bytes": "3670526" }, { "name": "C++", "bytes": "940403" }, { "name": "Lua", "bytes": "14989" }, { "name": "Ruby", "bytes": "3470" }, { "name": "Shell", "bytes": "165" } ], "symlink_target": "" }
set -e docker pull nginx docker pull gliderlabs/registrator:v6
{ "content_hash": "0966ffbe91b621415e2fad8fd2028670", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 37, "avg_line_length": 13, "alnum_prop": 0.8, "repo_name": "robert0714/ms-lifecycle-192.168.57.27", "id": "95d5838e1d1279377f9e55b4f53ef5fcbe83e47a", "size": "86", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/preload_serv_disc.sh", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "39903" }, { "name": "Groovy", "bytes": "23793" }, { "name": "HTML", "bytes": "29230" }, { "name": "Python", "bytes": "2381" }, { "name": "Shell", "bytes": "11045" } ], "symlink_target": "" }
<?php namespace App\Service\File; class TextFileExporter implements FileExporterInterface { /** * @param string $path * @param string $text * @return void */ public function exportToFile(string $path, string $text) { file_put_contents($path, $text); } }
{ "content_hash": "18da6a711628c3b9e945cef9a4d6c62a", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 60, "avg_line_length": 18.6875, "alnum_prop": 0.6254180602006689, "repo_name": "damiankamela/BuddySchoolCrawler", "id": "4698764e8f21672459e388cf7d6b381910880d55", "size": "299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Service/File/TextFileExporter.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3513" }, { "name": "JavaScript", "bytes": "852" }, { "name": "PHP", "bytes": "29777" }, { "name": "Shell", "bytes": "124" } ], "symlink_target": "" }
using ElectronicObserver.Backfire.Data.Battle.Detail; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicObserver.Backfire.Data.Battle.Phase { /// <summary> /// 航空戦フェーズの処理を行います。 /// </summary> public class PhaseAirBattle : PhaseBase { public PhaseAirBattle( BattleData data, string title, string suffix = "" ) : base( data, title ) { AirBattleData = RawData.IsDefined( "api_kouku" + suffix ) ? RawData["api_kouku" + suffix] : null; StageFlag = RawData.IsDefined( "api_stage_flag" + suffix ) ? (int[])RawData["api_stage_flag" + suffix] : null; TorpedoFlags = ConcatStage3Array( "api_frai_flag", "api_erai_flag" ); BomberFlags = ConcatStage3Array( "api_fbak_flag", "api_ebak_flag" ); Criticals = ConcatStage3Array( "api_fcl_flag", "api_ecl_flag" ); Damages = ConcatStage3Array( "api_fdam", "api_edam" ); } public override bool IsAvailable { get { int[] stageFlag = StageFlag; return StageFlag != null && !stageFlag.All( i => i == 0 ); } } public override void EmulateBattle( int[] hps, int[] damages ) { if ( !IsAvailable ) return; CalculateAttack( 0, hps, damages ); CalculateAttackDamage( damages ); } /// <summary> /// 攻撃の共通処理を行います。 /// </summary> protected void CalculateAttack( int waveIndex, int[] hps, int[] damages ) { for ( int i = 0; i < hps.Length; i++ ) { int attackType = ( TorpedoFlags[i] > 0 ? 1 : 0 ) | ( BomberFlags[i] > 0 ? 2 : 0 ); if ( attackType > 0 ) { // 航空戦は miss/hit=0, critical=1 のため +1 する(通常は miss=0, hit=1, critical=2) BattleDetails.Add( new BattleAirDetail( _battleData, waveIndex, i, Damages[i], Criticals[i] + 1, attackType, hps[i] ) ); AddDamage( hps, i, Damages[i] ); } } } /// <summary> /// 航空戦での与ダメージを推測します。 /// </summary> /// <param name="damages">与ダメージリスト。</param> private void CalculateAttackDamage( int[] damages ) { // 敵はめんどくさすぎるので省略 // 仮想火力を求め、それに従って合計ダメージを分配 var firepower = new int[6]; var members = _battleData.Initial.FriendFleet.MembersWithoutEscaped; for ( int i = 0; i < members.Count; i++ ) { var ship = members[i]; if ( ship == null ) continue; var slots = ship.SlotInstanceMaster; var aircrafts = ship.Aircraft; for ( int s = 0; s < slots.Count; s++ ) { if ( slots[s] == null ) continue; switch ( slots[s].CategoryType ) { case 7: //艦上爆撃機 case 11: //水上爆撃機 firepower[i] += (int)( 1.0 * ( slots[s].Bomber * Math.Sqrt( aircrafts[s] ) + 25 ) ); break; case 8: //艦上攻撃機 (80%と150%はランダムのため係数は平均値) firepower[i] += (int)( 1.15 * ( slots[s].Torpedo * Math.Sqrt( aircrafts[s] ) + 25 ) ); break; } } } int totalFirepower = firepower.Sum(); int totalDamage = Damages.Skip( 6 ).Take( 6 ).Sum() + damages.Skip( 18 ).Take( 6 ).Sum(); for ( int i = 0; i < 6; i++ ) { damages[i] += (int)Math.Round( (double)totalDamage * firepower[i] / Math.Max( totalFirepower, 1 ) ); } } protected override IEnumerable<BattleDetail> SearchBattleDetails( int index ) { return BattleDetails.Where( d => d.DefenderIndex == index ); } /// <summary> /// 各Stageが存在するか /// </summary> public int[] StageFlag { get; protected set; } /// <summary> /// 航空戦の生データ /// </summary> public virtual dynamic AirBattleData { get; protected set; } //stage 1 /// <summary> /// Stage1(空対空戦闘)が存在するか /// </summary> public bool IsStage1Available { get { return StageFlag != null && StageFlag[0] != 0 && AirBattleData.api_stage1() && AirBattleData.api_stage1 != null; } } /// <summary> /// 自軍Stage1参加機数 /// </summary> public int AircraftTotalStage1Friend { get { return (int)AirBattleData.api_stage1.api_f_count; } } /// <summary> /// 敵軍Stage1参加機数 /// </summary> public int AircraftTotalStage1Enemy { get { return (int)AirBattleData.api_stage1.api_e_count; } } /// <summary> /// 自軍Stage1撃墜機数 /// </summary> public int AircraftLostStage1Friend { get { return (int)AirBattleData.api_stage1.api_f_lostcount; } } /// <summary> /// 敵軍Stage1撃墜機数 /// </summary> public int AircraftLostStage1Enemy { get { return (int)AirBattleData.api_stage1.api_e_lostcount; } } /// <summary> /// 制空権 /// </summary> public int AirSuperiority { get { return (int)AirBattleData.api_stage1.api_disp_seiku; } } /// <summary> /// 自軍触接機ID /// </summary> public int TouchAircraftFriend { get { return (int)AirBattleData.api_stage1.api_touch_plane[0]; } } /// <summary> /// 敵軍触接機ID /// </summary> public int TouchAircraftEnemy { get { return (int)AirBattleData.api_stage1.api_touch_plane[1]; } } //stage 2 /// <summary> /// Stage2(艦対空戦闘)が存在するか /// </summary> public bool IsStage2Available { get { return StageFlag != null && StageFlag[1] != 0 && AirBattleData.api_stage2() && AirBattleData.api_stage2 != null; } } /// <summary> /// 自軍Stage2参加機数 /// </summary> public int AircraftTotalStage2Friend { get { return (int)AirBattleData.api_stage2.api_f_count; } } /// <summary> /// 敵軍Stage2参加機数 /// </summary> public int AircraftTotalStage2Enemy { get { return (int)AirBattleData.api_stage2.api_e_count; } } /// <summary> /// 自軍Stage2撃墜機数 /// </summary> public int AircraftLostStage2Friend { get { return (int)AirBattleData.api_stage2.api_f_lostcount; } } /// <summary> /// 敵軍Stage2撃墜機数 /// </summary> public int AircraftLostStage2Enemy { get { return (int)AirBattleData.api_stage2.api_e_lostcount; } } /// <summary> /// 対空カットインが発動したか /// </summary> public bool IsAACutinAvailable { get { return AirBattleData.api_stage2.api_air_fire(); } } /// <summary> /// 対空カットイン発動艦番号 /// </summary> public int AACutInIndex { get { return (int)AirBattleData.api_stage2.api_air_fire.api_idx; } } /// <summary> /// 対空カットイン発動艦 /// </summary> public ShipData AACutInShip { get { int index = AACutInIndex; return index < 6 ? _battleData.Initial.FriendFleet.MembersInstance[index] : _battleData.Initial.FriendFleetEscort.MembersInstance[index - 6]; } } /// <summary> /// 対空カットイン種別 /// </summary> public int AACutInKind { get { return (int)AirBattleData.api_stage2.api_air_fire.api_kind; } } //stage 3 /// <summary> /// Stage3(航空攻撃)が存在するか /// </summary> public bool IsStage3Available { get { return StageFlag != null && StageFlag[2] != 0 && AirBattleData.api_stage3() && AirBattleData.api_stage3 != null; } } /// <summary> /// Stage3(航空攻撃)(対随伴艦隊)が存在するか /// </summary> public bool IsStage3CombinedAvailable { get { return StageFlag != null && StageFlag[2] != 0 && AirBattleData.api_stage3_combined() && AirBattleData.api_stage3_combined != null; } } protected int[] ConcatStage3Array( string friendName, string enemyName ) { int[] ret = new int[24]; if ( IsStage3CombinedAvailable ) { int[] friend = AirBattleData.api_stage3.IsDefined( friendName ) ? (int[])AirBattleData.api_stage3[friendName] : new int[7]; int[] enemy = AirBattleData.api_stage3.IsDefined( enemyName ) ? (int[])AirBattleData.api_stage3[enemyName] : new int[7]; int[] friendescort = AirBattleData.api_stage3_combined.IsDefined( friendName ) ? (int[])AirBattleData.api_stage3_combined[friendName] : new int[7]; int[] enemyescort = AirBattleData.api_stage3_combined.IsDefined( enemyName ) ? (int[])AirBattleData.api_stage3_combined[enemyName] : new int[7]; for ( int i = 0; i < 6; i++ ) { ret[i] = Math.Max( friend[i + 1], 0 ); ret[i + 6] = Math.Max( enemy[i + 1], 0 ); ret[i + 12] = Math.Max( friendescort[i + 1], 0 ); ret[i + 18] = Math.Max( enemyescort[i + 1], 0 ); } } else if ( IsStage3Available ) { int[] friend = AirBattleData.api_stage3.IsDefined( friendName ) ? (int[])AirBattleData.api_stage3[friendName] : new int[7]; int[] enemy = AirBattleData.api_stage3.IsDefined( enemyName ) ? (int[])AirBattleData.api_stage3[enemyName] : new int[7]; for ( int i = 0; i < 6; i++ ) { ret[i] = Math.Max( friend[i + 1], 0 ); ret[i + 6] = Math.Max( enemy[i + 1], 0 ); ret[i + 12] = ret[i + 18] = 0; } } return ret; } /// <summary> /// 被雷撃フラグ /// </summary> public int[] TorpedoFlags { get; protected set; } /// <summary> /// 被爆撃フラグ /// </summary> public int[] BomberFlags { get; protected set; } /// <summary> /// 各艦のクリティカルフラグ /// </summary> public int[] Criticals { get; protected set; } /// <summary> /// 各艦の被ダメージ /// </summary> public int[] Damages { get; protected set; } } }
{ "content_hash": "b7e4f041ed91fbfeb840f60bffef5733", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 182, "avg_line_length": 29.77854671280277, "alnum_prop": 0.6300255635603068, "repo_name": "CNA-Bld/ElectronicObserver", "id": "ee5e9aca086f92a632d53786be5924a988f49d0a", "size": "9274", "binary": false, "copies": "1", "ref": "refs/heads/backfire-2.4.4.2", "path": "ElectronicObserver/Backfire/Data/Battle/Phase/PhaseAirBattle.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1884629" } ], "symlink_target": "" }
package org.openehealth.ipf.commons.ihe.xds.core.validate; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.fail; /** * Tests for {@link RecipientListValidator}. * @author Jens Riemschneider */ public class RecipientListValidatorTest { private static final RecipientListValidator validator = new RecipientListValidator(); @Test public void testValidateGoodCases() throws XDSMetaDataException { validator.validate(Arrays.asList("Some Hospital|^Welby")); validator.validate(Arrays.asList("|^Welby")); validator.validate(Arrays.asList("|ONLYID")); validator.validate(Arrays.asList("Some Hospital")); validator.validate(Arrays.asList("Some Hospital", "|^Welby")); } @Test public void testValidateBadCases() throws XDSMetaDataException { // This check is disabled for compatibility with older versions. // assertFails(Arrays.<String>asList()); assertFails(Arrays.asList("")); assertFails(Arrays.asList("^LOL")); assertFails(Arrays.asList("Some Hospital|^Welby||")); assertFails(Arrays.asList("|Some Hospital|^Welby|")); assertFails(Arrays.asList("Some Hospital", "")); } private static void assertFails(List<String> value) { try { validator.validate(value); fail("Expected exception: " + XDSMetaDataException.class + " for " + value); } catch (XDSMetaDataException e) { // Expected } } }
{ "content_hash": "f26629dfd9d7968b8f6adeff483ee623", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 89, "avg_line_length": 34.47826086956522, "alnum_prop": 0.6475409836065574, "repo_name": "krasserm/ipf", "id": "9bbc2b41236aaeb27a803b392a70f987d9452351", "size": "2220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "commons/ihe/xds/src/test/java/org/openehealth/ipf/commons/ihe/xds/core/validate/RecipientListValidatorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1891019" }, { "name": "Java", "bytes": "4710701" }, { "name": "Shell", "bytes": "12378" }, { "name": "XML", "bytes": "554629" }, { "name": "XQuery", "bytes": "15044" } ], "symlink_target": "" }
require 'rails/generators/migration' class SimplePaymentsTrackerGenerator < Rails::Generators::Base include Rails::Generators::Migration def self.source_root @_simple_payments_trackers_source_root ||= File.expand_path("../templates", __FILE__) end def self.next_migration_number(path) Time.now.utc.strftime("%Y%m%d%H%M%S") end def create_model_file template "general_payment_item.rb", "app/models/general_payment_item.rb" template "payer_payment.rb", "app/models/payer_payment.rb" template "payment_installment.rb", "app/models/payment_installment.rb" template "payment_item.rb", "app/models/payment_item.rb" migration_template "create_payments_tracker_schema.rb", "db/migrate/create_payments_tracker_schema.rb" end end
{ "content_hash": "382ce679d1c62f5f9f8432d6978a6aff", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 106, "avg_line_length": 34.86363636363637, "alnum_prop": 0.7327249022164276, "repo_name": "sirwin-examtime/simple_payments_tracker", "id": "a6ef27d304095ed18b512ccb6ba23220b083ec1d", "size": "767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/generators/simple_payments_tracker/simple_payments_tracker_generator.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9739" } ], "symlink_target": "" }
 #pragma once #include <aws/ssm/SSM_EXPORTS.h> #include <aws/ssm/SSMRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace SSM { namespace Model { /** */ class AWS_SSM_API GetConnectionStatusRequest : public SSMRequest { public: GetConnectionStatusRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "GetConnectionStatus"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The instance ID.</p> */ inline const Aws::String& GetTarget() const{ return m_target; } /** * <p>The instance ID.</p> */ inline bool TargetHasBeenSet() const { return m_targetHasBeenSet; } /** * <p>The instance ID.</p> */ inline void SetTarget(const Aws::String& value) { m_targetHasBeenSet = true; m_target = value; } /** * <p>The instance ID.</p> */ inline void SetTarget(Aws::String&& value) { m_targetHasBeenSet = true; m_target = std::move(value); } /** * <p>The instance ID.</p> */ inline void SetTarget(const char* value) { m_targetHasBeenSet = true; m_target.assign(value); } /** * <p>The instance ID.</p> */ inline GetConnectionStatusRequest& WithTarget(const Aws::String& value) { SetTarget(value); return *this;} /** * <p>The instance ID.</p> */ inline GetConnectionStatusRequest& WithTarget(Aws::String&& value) { SetTarget(std::move(value)); return *this;} /** * <p>The instance ID.</p> */ inline GetConnectionStatusRequest& WithTarget(const char* value) { SetTarget(value); return *this;} private: Aws::String m_target; bool m_targetHasBeenSet; }; } // namespace Model } // namespace SSM } // namespace Aws
{ "content_hash": "db5f42f2c581e916920f670d83039274", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 116, "avg_line_length": 26.975609756097562, "alnum_prop": 0.6546112115732369, "repo_name": "awslabs/aws-sdk-cpp", "id": "56f6e5c1a37aee31a7cbb6ab163ab9872cf79ded", "size": "2331", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-ssm/include/aws/ssm/model/GetConnectionStatusRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7596" }, { "name": "C++", "bytes": "61740540" }, { "name": "CMake", "bytes": "337520" }, { "name": "Java", "bytes": "223122" }, { "name": "Python", "bytes": "47357" } ], "symlink_target": "" }
2017-06-19, Version 2.8.4 ========================= * Add null checks (Setogit) * Housekeeping (Tetsuo Seto) * Blacklist strong-globalize in deep extraction (Setogit) 2017-04-22, Version 2.8.3 ========================= * Fix typo in the lint CLI messages (Setogit) * Extract improvement: bug fix and dependency (Tetsuo Seto) 2017-02-01, Version 2.8.2 ========================= * Improve console logs in browser (Miroslav Bajtoš) 2017-02-01, Version 2.8.1 ========================= * Fix rfc5424 loggers in browser (Miroslav Bajtoš) * Set theme jekyll-theme-cayman (Tetsuo Seto) * Set theme jekyll-theme-slate (Tetsuo Seto) * Delete CNAME (Tetsuo Seto) * Update (Tetsuo Seto) * Set theme jekyll-theme-cayman and migrate Page Generator content (Tetsuo Seto) * Create CNAME (Tetsuo Seto) * Create master branch via GitHub (Tetsuo Seto) * Avoid insecure minmatch 2.x dependency (Setogit) 2016-09-21, Version 2.8.0 ========================= * Update README (Setogit) * Allow root dir instead of an option (Sam Roberts) * Remove Unicode BOM (Setogit) * Remove 32 char hash from file name in -d mode (Setogit) 2016-09-15, Version 2.7.0 ========================= * Detect strong-globalize in shared module (Miroslav Bajtoš) 2016-09-02, Version 2.6.10 ========================== * Fall back to md5 if getHash is undefined (Setogit) 2016-08-31, Version 2.6.9 ========================= * Use string notation for one line regex (Setogit) * Add comment to say why some have '\n' (Setogit) * Suppress the heart-beat dots in the log (Setogit) * Remove headerIncluded test (Setogit) * Add plain text and other test cases (Setogit) * Make it work for windows (Setogit) * Clean up lint (Setogit) * Remove commented-out functions (Setogit) * Add more extract test cases (Setogit) * Add unhappy extract cases (Setogit) * Remove old debug code; add pseudoloc tests (Setogit) * Improve HTML extraction test (Setogit) * Improve test coverage (Setogit) * deps: import globalize and cldrjs packages (Ryan Graham) * Sort extracted and translated msges by keys (Setogit) * deps: upgrade to tap v7 (Ryan Graham) * test: report coverage for untested files (Ryan Graham) * test: use inclusive filter for coverage (Ryan Graham) * test: use tap's coverage instead of nyc (Ryan Graham) * Add regex test and fix a bug (Setogit) * Fix a bug in headerIncluded and add test (Setogit) * Cache results of md5 calls (Miroslav Bajtoš) * Reuse messages formatters (Miroslav Bajtoš) * benchmark: fix format benchmark (Miroslav Bajtoš) * Enable translate tests on travis (Setogit) * Add two more string test cases (Setogit) * Add test (Setogit) * Round to positive integer then bound (Setogit) * Handle null case (Setogit) 2016-08-20, Version 2.6.8 ========================= * Silent API Calls and Tests (Setogit) * fix eslint config and all the linting errors (Ryan Graham) 2016-08-15, Version 2.6.7 ========================= * Avoid JSON.stringify when debug is disabled (Miroslav Bajtoš) * Speed up formatMsg for lang=EN and path not found (Miroslav Bajtoš) * Add benchmark for g.f() (Miroslav Bajtoš) 2016-08-08, Version 2.6.6 ========================= * Move mktmpdir to dependencies (Miroslav Bajtoš) 2016-08-07, Version 2.6.5 ========================= * Split messages.json to mitigate GPB restriction (Setogit) * Improve require resolution performance (Tetsuo Seto) 2016-08-06, Version 2.6.4 ========================= * Use non-greedy {{ }} matching (Setogit) 2016-08-06, Version 2.6.3 ========================= * Improve lint logic and update README (Setogit) 2016-08-03, Version 2.6.2 ========================= * Keep empty string in mapping args (Setogit) * Fix left & right orphan detecton logic (Setogit) 2016-08-01, Version 2.6.1 ========================= * Keep 'undefined' and 'null' values in mapping args (Setogit) * Improve README (Setogit) 2016-07-28, Version 2.6.0 ========================= * Remove {{ }} if falls back to original literal (Setogit) * Clean up README (Setogit) * Expand the out-of-box CLDR to 31 languages (Setogit) * Rename to avoid GPB confict; Del gz in .gitignore (Setogit) * test: fix empty subtest in TAP output (Ryan Graham) * test: don't polute TAP output with test debug (Ryan Graham) * remove references to gzip'd CLDR data (Ryan Graham) 2016-07-25, Version 2.5.8 ========================= * Support windows for cldr data postinstall (Setogit) 2016-07-24, Version 2.5.7 ========================= * Use unzipped JSON and remove zlib-backport (Setogit) * Adjust test cases for GPB GA (Setogit) 2016-07-21, Version 2.5.6 ========================= * Bump the version to get swagger-client bug fix (Setogit) * Fix a link in README (Setogit) * Use html build badge link for npmjs.com (Setogit) 2016-07-11, Version 2.5.5 ========================= * Update g11n-pipeline to 1.2.0 (Setogit) * Use coveralls to monitor test coverage (Setogit) * Add browser.js (Setogit) 2016-07-10, Version 2.5.4 ========================= * Add minimal browser support (Setogit) 2016-07-10, Version 2.5.3 ========================= * Avoid redundant zlib require in Node v0.10 (Setogit) * Fix a windows json/yaml extract test failure (Setogit) 2016-07-07, Version 2.5.2 ========================= * Support yaml extension; skip if non-GLB_FN arguments (Setogit) 2016-06-28, Version 2.5.1 ========================= * Support YAML File Globalization (Setogit) * Improve JSON file globalization sample code (Tetsuo Seto) 2016-06-26, Version 2.5.0 ========================= * Add 'JSON File Globalization' section to README (Setogit) * Support extract from json file (Setogit) * Add format json test for multiple languages (Setogit) * Add normalizeKeyArrays validation (Setogit) * Remove an extra semicolon (Setogit) * Add scanJson, replaceJson and unit test (Tetsuo Seto) * Catch error if invalid path is passed to realpathSync (Setogit) 2016-06-17, Version 2.4.7 ========================= * Explain sample codes and three strong-globalize coding patterns (Setogit) * Enable travis-ci.org build (Setogit) * Deprecated Node 0.10; added 4.4.5, 5.11.1, 6.2.1 to the tested versions (Setogit) * Format JavaScript code piece as JS in README (Setogit) * Add examples (Setogit) * Update readme and add callee information to zz/messages*.json (Setogit) 2016-06-04, Version 2.4.6 ========================= * Use realpath to see if the file has been checked (perf) (Setogit) * Convert to array if string in inverting position text (Setogit) * Add setRootDir test (Setogit) * Fix typo (Candy) * Make sure intl directory exists in setRootDir (Setogit) * Relax test target to accomodate to GPB change (Setogit) * Remove unused code (Setogit) * Remove duplicate code (Setogit) 2016-05-25, Version 2.4.5 ========================= * Emit JS and HTML syntax errors in regular exraction mode (Setogit) * Pass temporary GPB connection failure (Setogit) 2016-05-22, Version 2.4.4 ========================= * Skip translate tests when offline (Setogit) 2016-05-22, Version 2.4.3 ========================= * Add failure-case translate tests stubbing service response (Setogit) 2016-05-18, Version 2.4.2 ========================= * Add more lint tests: (Setogit) * Update to CLDR 29.0.1 (Setogit) 2016-05-16, Version 2.4.1 ========================= * Add more lint, extract, globalize, and translate tests (Setogit) * All packages are created equal (Setogit) * Skip translate test if internet access fails (Setogit) 2016-05-10, Version 2.4.0 ========================= * Autonomous Message Loading (Setogit) 2016-05-07, Version 2.3.3 ========================= * update copyright notices and license (Ryan Graham) 2016-05-06, Version 2.3.2 ========================= * Support filtering of extracted hard-coded strings (Setogit) * Resolve multi-level symbolic links (Setogit) * Generate zz/messages_inverted.json in -e and -d modes (Setogit) * Assert if nothing is passed to setRootDir (Setogit) 2016-04-30, Version 2.3.1 ========================= * Scan Html in 'slt-globalize -e' mode only (Setogit) * Avoid redundant directory scan (perf) (Setogit) * Skip redundant En lint check against En (Setogit) 2016-04-26, Version 2.3.0 ========================= * Deep String Resource Extraction (Setogit) 2016-04-23, Version 2.2.9 ========================= * Remove assert (Tetsuo Seto) 2016-04-22, Version 2.2.8 ========================= * Record all literal positions appear in the first argument of calls (Setogit) 2016-04-19, Version 2.2.7 ========================= * Unlist 'zz' from supported languages (Tetsuo Seto) * Clean up lint errors detected on windows (Setogit) 2016-04-19, Version 2.2.6 ========================= * Record positions of all detected messages: hashed or not (Setogit) 2016-04-17, Version 2.2.5 ========================= * Add notes for 'pseudo localization support' (Setogit) * Pseudoloc: Get a string from env variable and add to every message (Setogit) * Improve the sample code (Setogit) * Support variations in 'globalize' html filter; Check max number of msges per file (Setogit) * Cleanup for readability (Setogit) * Adjust spacing in user messages (Setogit) * Exit from infinite check loop in case GPB is out of sync (Setogit) * Delete formatting conflict with Mark-Down styles (Setogit) * Simplify the iteration in test-extract (Setogit) * Make SetRootDir the single required entry point (Setogit) 2016-04-01, Version 2.2.4 ========================= * Add test to load msges in child process and fixed the argument order of logFn (Setogit) 2016-03-25, Version 2.2.3 ========================= * Remove backslash escape from quotation marks in MT results (Setogit) * Disable dependency scan in loadMsgFromFile by default (perf) (Setogit) * Add well known lang check to msg loading test (Setogit) 2016-03-22, Version 2.2.2 ========================= * Add missing deep dependency (Setogit) 2016-03-22, Version 2.2.1 ========================= * Add test to load msges from dependencies (Setogit) 2016-03-21, Version 2.2.0 ========================= * Support npm v3 dependency resolution (Setogit) * Add npm package badge (Setogit) * Record version info of globalize packages (Setogit) * Rreturn null if package.json does not exist (Tetsuo Seto) * Minor fix up for language property of persistent logging (Setogit) 2016-02-21, Version 2.1.0 ========================= * Update README (Setogit) * Generalize SetRootDir for indirect dependencies to load messages (Setogit) * Pass language to persistent logging callback (Setogit) * Fix a bug in sample code in README (Setogit) * Make extract error msg directly actionable (Tetsuo Seto) * Empty json shouldn't be created if no msgs are extracted (Tetsuo Seto) * Remove extra space in README (Setogit) 2016-02-17, Version 2.0.2 ========================= * Remove extra indent from js code in README (Tetsuo Seto) 2016-02-17, Version 2.0.1 ========================= * Fix typos and clean up README (Tetsuo Seto) 2016-02-16, Version 2.0.0 ========================= * Support multiple StrongGlobalize instances (Tetsuo Seto) 2016-02-14, Version 1.4.1 ========================= * Fix a lint error (Setogit) * Clean up README (Tetsuo Seto) 2016-02-13, Version 1.4.0 ========================= * Support language customization (Tetsuo Seto) 2016-02-13, Version 1.3.1 ========================= * Add more links and fix typos in README (Tetsuo Seto) 2016-02-12, Version 1.3.0 ========================= * Make zlb backport optional consistency and readme cleanup (Tetsuo Seto) * Implement getSupportedLanguages (Setogit) * Use zlib backport to support Node v0.10 (merge v1.2.1) (Tetsuo Seto) * Make console log client controlable with enumerateFilesSync (Tetsuo Seto) * Add persistent logging test (Tetsuo Seto) * RFC 5424 syslog levels and misc logging levels (Tetsuo Seto) * Support persistent logging (Tetsuo Seto) 2016-02-12, Version 1.2.1 ========================= * Use zlib backport to support Node v0.10 (Tetsuo Seto) 2016-02-10, Version 1.2.0 ========================= 2016-02-10, Version 1.1.0 ========================= * merge initial release (Setogit) * Remove cldr-data dependency Keep cldr-data 28.0.3 locally for the supported languages only Add alias 'f' for 'format' (Tetsuo Seto) * Move shared variables to global (Tetsuo Seto) 2016-02-04, Version 1.0.0 ========================= * First release!
{ "content_hash": "b1cd6bfc1e96b9fdc2034a4531d953e5", "timestamp": "", "source": "github", "line_count": 595, "max_line_length": 134, "avg_line_length": 21.339495798319327, "alnum_prop": 0.6348743797747499, "repo_name": "mattjbrad/mb-ale-trail", "id": "069a8ca7d83f2bb11feb837cd491622c492843dc", "size": "12707", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/strong-globalize/CHANGES.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1272" }, { "name": "HTML", "bytes": "2989" }, { "name": "JavaScript", "bytes": "10217" } ], "symlink_target": "" }
/** * Problem: RMID2 (SPOJ) * Author: babhishek21 * Lang: C++11 */ #include <bits/stdc++.h> // using GCC/G++ // #include "custom/prettyprint.hpp" // G++11 only using namespace std; #define MOD 1000000007 #define pb push_back #define eb emplace_back #define mp make_pair #define debug(x) cout << #x << " : " << x << endl; priority_queue<int, vector<int>> pql; priority_queue<int, vector<int>, greater<int>> pqr; inline void clear_pq() { // C++11 and above priority_queue<int, vector<int>> ().swap(pql); priority_queue<int, vector<int>, greater<int>> ().swap(pqr); } /** * The idea is to keep two heaps. One (pql) will be max heap which keeps all elements less than or equal to current * median. The other (pqr) will be a min heap which keeps all elements greater than or equal to current median. This way * we can always get median by looking at the root of both the heaps. */ int get_running_median(int num, int median) { int diff = pql.size() - pqr.size(); if(num == -1) { // deletion if(!pql.empty() && !pqr.empty() && median == pql.top() && median == pqr.top()) { // even number of elements if(diff < 0) pqr.pop(); else pql.pop(); } // odd number of elements else if(!pql.empty() && median == pql.top()) pql.pop(); else if(!pqr.empty() && median == pqr.top()) pqr.pop(); // return new median if(pql.empty() && pqr.empty()) return 0; else if(pql.size() >= pqr.size()) return pql.top(); else return pqr.top(); } // find new median if(diff == 0) { // guaranteed odd number of elements after insertion if(num < median) { pql.push(num); median = pql.top(); } else { pqr.push(num); median = pqr.top(); } } else if(diff > 0) { if(num < median) { // need to balance both heaps, so that top() hold medians pqr.push(pql.top()); pql.pop(); pql.push(num); } else pqr.push(num); median = min(pql.top(), pqr.top()); // even number of elements after insertion } else { if(num < median) pql.push(num); else { // need to balance both heaps, so that top() hold medians pql.push(pqr.top()); pqr.pop(); pqr.push(num); } median = min(pql.top(), pqr.top()); // even number of elements after insertion } return median; } int main() { ios_base::sync_with_stdio(false); // for fast I/O int t, num, median; cin >> t; while(t--) { median = 0; while(cin >> num, num != 0) { if(num == -1) // cout << median << "\n"; printf("%d\n", median); // stupid spoj with stupid time limits median = get_running_median(num, median); } clear_pq(); } return 0; }
{ "content_hash": "1dedd0fe89dae4a6b9dd59f45bc04d13", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 120, "avg_line_length": 23.921739130434784, "alnum_prop": 0.5725190839694656, "repo_name": "babhishek21/oj-sols", "id": "874193191af946499e5acc6ea4b341f301bb89eb", "size": "2751", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spoj/RMID2.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "315211" }, { "name": "Java", "bytes": "9009" }, { "name": "Python", "bytes": "11675" } ], "symlink_target": "" }
layout: post title: "Delayed Blast Fireball" date: 2015-01-11 source: PHB.230 tags: [sorcerer, wizard, level7, evocation] --- **7th-level evocation** **Casting Time**: 1 action **Range**: 150 feet **Components**: V, S, M (a tiny ball of bat guano and sulfur) **Duration**: Concentration, up to 1 minute A beam of yellow light flashes from your pointing finger, then condenses to linger at a chosen point within range as a glowing bead for the duration. When the spell ends, either because your concentration is broken or because you decide to end it, the bead blossoms with a low roar into an explosion of flame that spreads around corners. Each creature in a 20-foot-radius sphere centered on that point must make a Dexterity saving throw. A creature takes fire damage equal to the total accumulated damage on a failed save, or half as much damage on a successful one. The spell's base damage is 12d6. If at the end of your turn the bead has not yet detonated, the damage increases by 1d6. If the glowing bead is touched before the interval has expired, the creature touching it must make a Dexterity saving throw. On a failed save, the spell ends immediately, causing the bead to erupt in flame. On a successful save, the creature can throw the bead up to 40 feet. When it strikes a creature or a solid object, the spell ends, and the bead explodes. The fire damages objects in the area and ignites flammable objects that aren't being worn or carried. **At Higher Levels.** When you cast this spell using a spell slot of 8th level or higher, the base damage increases by 1d6 for each slot level above 7th.
{ "content_hash": "71444065d51b4118e3bf8611e3839ccf", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 566, "avg_line_length": 62.42307692307692, "alnum_prop": 0.7689463955637708, "repo_name": "ozyx/desktop-grimoire", "id": "1602439ba4e097d60c27bbca273fd4605cc3cc94", "size": "1627", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/_posts/2015-01-11-delayed-blast-fireball.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13320" }, { "name": "HTML", "bytes": "7920" }, { "name": "JavaScript", "bytes": "3035" }, { "name": "Ruby", "bytes": "1828" }, { "name": "TypeScript", "bytes": "1614" } ], "symlink_target": "" }
require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/ads/googleads/v12/enums/user_list_date_rule_item_operator.proto", :syntax => :proto3) do add_message "google.ads.googleads.v12.enums.UserListDateRuleItemOperatorEnum" do end add_enum "google.ads.googleads.v12.enums.UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator" do value :UNSPECIFIED, 0 value :UNKNOWN, 1 value :EQUALS, 2 value :NOT_EQUALS, 3 value :BEFORE, 4 value :AFTER, 5 end end end module Google module Ads module GoogleAds module V12 module Enums UserListDateRuleItemOperatorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v12.enums.UserListDateRuleItemOperatorEnum").msgclass UserListDateRuleItemOperatorEnum::UserListDateRuleItemOperator = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v12.enums.UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator").enummodule end end end end end
{ "content_hash": "ee5e2cede511dd4db1525b86f4a48c7b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 238, "avg_line_length": 38.10344827586207, "alnum_prop": 0.746606334841629, "repo_name": "googleads/google-ads-ruby", "id": "df9e98b6401e5e76dae4c227bbb5da18aaa21f06", "size": "1246", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "lib/google/ads/google_ads/v12/enums/user_list_date_rule_item_operator_pb.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "12358" }, { "name": "Ruby", "bytes": "10304247" }, { "name": "Shell", "bytes": "1082" } ], "symlink_target": "" }
Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js ) Rails.application.config.assets.precompile += %w( result.css )
{ "content_hash": "cd60e1f8c5489eb52fa8fb37bb79f342", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 93, "avg_line_length": 41.2, "alnum_prop": 0.7669902912621359, "repo_name": "24-timmarsseglingarna/giona", "id": "bcef92ec3d2bc3139c589758f450d57d0a3ee46b", "size": "550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/initializers/assets.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1009" }, { "name": "CoffeeScript", "bytes": "2954" }, { "name": "HTML", "bytes": "38875" }, { "name": "Haml", "bytes": "87252" }, { "name": "JavaScript", "bytes": "3491" }, { "name": "Procfile", "bytes": "39" }, { "name": "Ruby", "bytes": "267414" }, { "name": "SCSS", "bytes": "5250" } ], "symlink_target": "" }
require 'json' module VagrantPlugins module Salt class Provisioner < Vagrant.plugin("2", :provisioner) # Default path values to set within configuration only # if configuration value is unset and local path exists OPTIMISTIC_PATH_DEFAULTS = Hash[*[ "minion_config", "salt/minion", "minion_key", "salt/key/minion.key", "minion_pub", "salt/key/minion.pub", "master_config", "salt/master", "master_key", "salt/key/master.key", "master_pub", "salt/key/master.pub" ].map(&:freeze)].freeze def provision set_default_configs upload_configs upload_keys run_bootstrap_script call_overstate call_highstate call_orchestrate end # Return a list of accepted keys def keys(group='minions') out = @machine.communicate.sudo("salt-key --out json") do |type, output| begin if type == :stdout out = JSON::load(output) break out[group] end end end return out end ## Utilities def expanded_path(rel_path) Pathname.new(rel_path).expand_path(@machine.env.root_path) end def binaries_found ## Determine States, ie: install vs configure desired_binaries = [] if !@config.no_minion if @machine.config.vm.communicator == :winrm desired_binaries.push('C:\\salt\\salt-minion.bat') desired_binaries.push('C:\\salt\\salt-call.bat') else desired_binaries.push('salt-minion') desired_binaries.push('salt-call') end end if @config.install_master if @machine.config.vm.communicator == :winrm raise Vagrant::Errors::ProvisionerWinRMUnsupported, name: "salt.install_master" else desired_binaries.push('salt-master') end end if @config.install_syndic if @machine.config.vm.communicator == :winrm raise Vagrant::Errors::ProvisionerWinRMUnsupported, name: "salt.install_syndic" else desired_binaries.push('salt-syndic') end end found = true for binary in desired_binaries @machine.env.ui.info "Checking if %s is installed" % binary if !@machine.communicate.test("which %s" % binary) @machine.env.ui.info "%s was not found." % binary found = false else @machine.env.ui.info "%s found" % binary end end return found end def need_configure @config.minion_config or @config.minion_key or @config.master_config or @config.master_key or @config.grains_config or @config.version or @config.minion_json_config or @config.master_json_config end def need_install if @config.always_install return true else return !binaries_found() end end def temp_config_dir if @machine.config.vm.communicator == :winrm return @config.temp_config_dir || "C:\\tmp" else return @config.temp_config_dir || "/tmp" end end # Generates option string for bootstrap script def bootstrap_options(install, configure, config_dir) # Any extra options passed to bootstrap if @config.bootstrap_options options = @config.bootstrap_options else options = "" end if @config.master_json_config && @machine.config.vm.communicator != :winrm config = @config.master_json_config options = "%s -J '#{config}'" % [options] end if @config.minion_json_config && @machine.config.vm.communicator != :winrm config = @config.minion_json_config options = "%s -j '#{config}'" % [options] end if configure && @machine.config.vm.communicator != :winrm options = "%s -F -c %s" % [options, config_dir] end if @config.seed_master && @config.install_master && @machine.config.vm.communicator != :winrm seed_dir = "/tmp/minion-seed-keys" @machine.communicate.sudo("mkdir -p -m777 #{seed_dir}") @config.seed_master.each do |name, keyfile| sourcepath = expanded_path(keyfile).to_s dest = "#{seed_dir}/#{name}" @machine.communicate.upload(sourcepath, dest) end options = "#{options} -k #{seed_dir}" end if configure && !install && @machine.config.vm.communicator != :winrm options = "%s -C" % options end if @config.install_master && @machine.config.vm.communicator != :winrm options = "%s -M" % options end if @config.install_syndic && @machine.config.vm.communicator != :winrm options = "%s -S" % options end if @config.no_minion && @machine.config.vm.communicator != :winrm options = "%s -N" % options end if @config.install_type && @machine.config.vm.communicator != :winrm options = "%s %s" % [options, @config.install_type] end if @config.install_args && @machine.config.vm.communicator != :winrm options = "%s %s" % [options, @config.install_args] end if @config.verbose @machine.env.ui.info "Using Bootstrap Options: %s" % options end return options end ## Actions # Get pillar string to pass with the salt command def get_pillar if !@config.pillar_data.empty? if @machine.config.vm.communicator == :winrm # ' doesn't have any special behavior on the command prompt, # so '{"x":"y"}' becomes '{x:y}' with literal single quotes. # However, """ will become " , and \\""" will become \" . # Use \\"" instead of \\""" for literal inner-value quotes # to avoid issue with odd number of quotes. # --% disables special PowerShell parsing on the rest of the line. " --% pillar=#{@config.pillar_data.to_json.gsub(/(?<!\\)\"/, '"""').gsub(/\\\"/, %q(\\\\\""))}" else " pillar='#{@config.pillar_data.to_json}'" end end end # Get colorization option string to pass with the salt command def get_colorize @config.colorize ? " --force-color" : " --no-color" end # Get log output level option string to pass with the salt command def get_loglevel log_levels = ["all", "garbage", "trace", "debug", "info", "warning", "error", "quiet"] if log_levels.include? @config.log_level " --log-level=#{@config.log_level}" else " --log-level=debug" end end # Get command-line options for masterless provisioning def get_masterless options = "" if @config.masterless options = " --local" if @config.minion_id options += " --id #{@config.minion_id}" end end return options end # Append additional arguments to the salt command def get_salt_args " " + Array(@config.salt_args).join(" ") end # Append additional arguments to the salt-call command def get_call_args " " + Array(@config.salt_call_args).join(" ") end # Copy master and minion configs to VM def upload_configs if @config.minion_config @machine.env.ui.info "Copying salt minion config to vm." @machine.communicate.upload(expanded_path(@config.minion_config).to_s, temp_config_dir + "/minion") end if @config.master_config @machine.env.ui.info "Copying salt master config to vm." @machine.communicate.upload(expanded_path(@config.master_config).to_s, temp_config_dir + "/master") end if @config.grains_config @machine.env.ui.info "Copying salt grains config to vm." @machine.communicate.upload(expanded_path(@config.grains_config).to_s, temp_config_dir + "/grains") end end # Copy master and minion keys to VM def upload_keys if @config.minion_key and @config.minion_pub @machine.env.ui.info "Uploading minion keys." @machine.communicate.upload(expanded_path(@config.minion_key).to_s, temp_config_dir + "/minion.pem") @machine.communicate.sudo("chmod u+w #{temp_config_dir}/minion.pem") @machine.communicate.upload(expanded_path(@config.minion_pub).to_s, temp_config_dir + "/minion.pub") end if @config.master_key and @config.master_pub @machine.env.ui.info "Uploading master keys." @machine.communicate.upload(expanded_path(@config.master_key).to_s, temp_config_dir + "/master.pem") @machine.communicate.sudo("chmod u+w #{temp_config_dir}/master.pem") @machine.communicate.upload(expanded_path(@config.master_pub).to_s, temp_config_dir + "/master.pub") end end # Get bootstrap file location, bundled or custom def get_bootstrap if @config.bootstrap_script bootstrap_abs_path = expanded_path(@config.bootstrap_script) else if @machine.config.vm.communicator == :winrm bootstrap_abs_path = Pathname.new("../bootstrap-salt.ps1").expand_path(__FILE__) else bootstrap_abs_path = Pathname.new("../bootstrap-salt.sh").expand_path(__FILE__) end end return bootstrap_abs_path end # Determine if we are configure and/or installing, then do either def run_bootstrap_script install = need_install() configure = need_configure() config_dir = temp_config_dir() options = bootstrap_options(install, configure, config_dir) if configure or install if configure and !install @machine.env.ui.info "Salt binaries found. Configuring only." else @machine.env.ui.info "Bootstrapping Salt... (this may take a while)" end bootstrap_path = get_bootstrap if @machine.config.vm.communicator == :winrm if @config.version options += " -version %s" % @config.version end if @config.python_version options += " -pythonVersion %s" % @config.python_version end if @config.run_service @machine.env.ui.info "Salt minion will be stopped after installing." options += " -runservice %s" % @config.run_service end if @config.minion_id @machine.env.ui.info "Setting minion to @config.minion_id." options += " -minion %s" % @config.minion_id end if @config.master_id @machine.env.ui.info "Setting master to @config.master_id." options += " -master %s" % @config.master_id end bootstrap_destination = File.join(config_dir, "bootstrap_salt.ps1") else if @config.version options += " %s" % @config.version end bootstrap_destination = File.join(config_dir, "bootstrap_salt.sh") end if @machine.communicate.test("test -f %s" % bootstrap_destination) @machine.communicate.sudo("rm -f %s" % bootstrap_destination) end @machine.communicate.upload(bootstrap_path.to_s, bootstrap_destination) @machine.communicate.sudo("chmod +x %s" % bootstrap_destination) if @machine.config.vm.communicator == :winrm bootstrap = @machine.communicate.sudo("powershell.exe -NonInteractive -NoProfile -executionpolicy bypass -file %s %s" % [bootstrap_destination, options]) do |type, data| if data[0] == "\n" # Remove any leading newline but not whitespace. If we wanted to # remove newlines and whitespace we would have used data.lstrip data = data[1..-1] end if @config.verbose @machine.env.ui.info(data.rstrip) end end else bootstrap = @machine.communicate.sudo("%s %s" % [bootstrap_destination, options]) do |type, data| if data[0] == "\n" # Remove any leading newline but not whitespace. If we wanted to # remove newlines and whitespace we would have used data.lstrip data = data[1..-1] end if @config.verbose @machine.env.ui.info(data.rstrip) end end end if !bootstrap raise Salt::Errors::SaltError, :bootstrap_failed end if configure and !install @machine.env.ui.info "Salt successfully configured!" elsif configure and install @machine.env.ui.info "Salt successfully configured and installed!" elsif !configure and install @machine.env.ui.info "Salt successfully installed!" end else @machine.env.ui.info "Salt did not need installing or configuring." end end def call_overstate if @config.run_overstate # If verbose is on, do not duplicate a failed command's output in the error message. ssh_opts = {} if @config.verbose ssh_opts = { error_key: :ssh_bad_exit_status_muted } end if @config.install_master @machine.env.ui.info "Calling state.overstate... (this may take a while)" @machine.communicate.sudo("salt '*' saltutil.sync_all") @machine.communicate.sudo("salt-run state.over", ssh_opts) do |type, data| if @config.verbose @machine.env.ui.info(data) end end else @machine.env.ui.info "run_overstate does not make sense on a minion. Not running state.overstate." end else @machine.env.ui.info "run_overstate set to false. Not running state.overstate." end end def call_highstate if @config.run_highstate # If verbose is on, do not duplicate a failed command's output in the error message. ssh_opts = {} if @config.verbose ssh_opts = { error_key: :ssh_bad_exit_status_muted } end @machine.env.ui.info "Calling state.highstate... (this may take a while)" if @config.install_master unless @config.masterless @machine.communicate.sudo("salt '*' saltutil.sync_all") end options = "#{get_masterless}#{get_loglevel}#{get_colorize}#{get_pillar}#{get_salt_args}" @machine.communicate.sudo("salt '*' state.highstate --verbose#{options}", ssh_opts) do |type, data| if @config.verbose @machine.env.ui.info(data.rstrip) end end else if @machine.config.vm.communicator == :winrm opts = { elevated: true } unless @config.masterless @machine.communicate.execute("C:\\salt\\salt-call.bat saltutil.sync_all", opts) end # TODO: something equivalent to { error_key: :ssh_bad_exit_status_muted }? options = "#{get_masterless}#{get_loglevel}#{get_colorize}#{get_pillar}#{get_call_args}" @machine.communicate.execute("C:\\salt\\salt-call.bat state.highstate --retcode-passthrough#{options}", opts) do |type, data| if @config.verbose @machine.env.ui.info(data.rstrip) end end else unless @config.masterless @machine.communicate.sudo("salt-call saltutil.sync_all") end options = "#{get_masterless}#{get_loglevel}#{get_colorize}#{get_pillar}#{get_call_args}" @machine.communicate.sudo("salt-call state.highstate --retcode-passthrough#{options}", ssh_opts) do |type, data| if @config.verbose @machine.env.ui.info(data.rstrip) end end end end else @machine.env.ui.info "run_highstate set to false. Not running state.highstate." end end def call_orchestrate if !@config.orchestrations @machine.env.ui.info "orchestrate is nil. Not running state.orchestrate." return end if !@config.install_master @machine.env.ui.info "orchestrate does not make sense on a minion. Not running state.orchestrate." return end log_output = lambda do |type, data| if @config.verbose @machine.env.ui.info(data) end end # If verbose is on, do not duplicate a failed command's output in the error message. ssh_opts = {} if @config.verbose ssh_opts = { error_key: :ssh_bad_exit_status_muted } end @machine.env.ui.info "Running the following orchestrations: #{@config.orchestrations}" @machine.env.ui.info "Running saltutil.sync_all before orchestrating" @machine.communicate.sudo("salt '*' saltutil.sync_all", ssh_opts, &log_output) @config.orchestrations.each do |orchestration| cmd = "salt-run -l info state.orchestrate #{orchestration}" @machine.env.ui.info "Calling #{cmd}... (this may take a while)" @machine.communicate.sudo(cmd, ssh_opts, &log_output) end end # Sets optimistic default values into config def set_default_configs OPTIMISTIC_PATH_DEFAULTS.each do |config_key, config_default| if config.send(config_key) == Config::UNSET_VALUE config_value = File.exist?(expanded_path(config_default)) ? config_default : nil config.send("#{config_key}=", config_value) end end end end end end
{ "content_hash": "b8e73c2c66ab449f6dc08148745bfbe2", "timestamp": "", "source": "github", "line_count": 487, "max_line_length": 202, "avg_line_length": 37.41889117043121, "alnum_prop": 0.5712561049223509, "repo_name": "gitebra/vagrant", "id": "8b69b7915fe1c1c3d7566fa28bcb56a5a644962a", "size": "18223", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "plugins/provisioners/salt/provisioner.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25874" }, { "name": "Emacs Lisp", "bytes": "420" }, { "name": "HTML", "bytes": "129249" }, { "name": "JavaScript", "bytes": "1834" }, { "name": "Makefile", "bytes": "535" }, { "name": "PowerShell", "bytes": "56347" }, { "name": "Ruby", "bytes": "3726791" }, { "name": "Shell", "bytes": "17175" }, { "name": "Vim script", "bytes": "309" } ], "symlink_target": "" }
package com.korshyadoo.musicFileNamer.controller; import java.awt.EventQueue; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.korshyadoo.musicFileNamer.conf.Configuration; import com.korshyadoo.musicFileNamer.view.MainFrame; /** * Hello world! * */ public class ProgramLauncher { static { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); config = (Configuration) context.getBean("config"); ((ConfigurableApplicationContext) context).close(); } public static final Configuration config; private static final Logger logger = LogManager.getLogger(); public static void main(String[] args) { getLogger().info("App started"); EventQueue.invokeLater(new Runnable() { public void run() { try { MainFrame frame = new MainFrame(); frame.setVisible(true); } catch(Exception e) { e.printStackTrace(); } } }); } public static Logger getLogger() { return logger; } }
{ "content_hash": "68476e715501fe8d54c86eb35c88f7f8", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 79, "avg_line_length": 25.404255319148938, "alnum_prop": 0.7546063651591289, "repo_name": "korshyadoo/MusicFileNamer", "id": "22b23a1bf421693c1266c34f50fde4bad4c1b530", "size": "1194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/korshyadoo/musicFileNamer/controller/ProgramLauncher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "93" }, { "name": "Java", "bytes": "26911" } ], "symlink_target": "" }
import unittest import mock from six.moves import http_client import requests class Test__request(unittest.TestCase): @staticmethod def _call_fut(*args, **kwargs): from google.cloud.datastore._http import _request return _request(*args, **kwargs) def test_success(self): from google.cloud import _http as connection_module from google.cloud.datastore._http import _CLIENT_INFO project = "PROJECT" method = "METHOD" data = b"DATA" base_url = "http://api-url" response_data = "CONTENT" http = _make_requests_session([_make_response(content=response_data)]) # Call actual function under test. response = self._call_fut(http, project, method, data, base_url) self.assertEqual(response, response_data) # Check that the mocks were called as expected. expected_url = _build_expected_url(base_url, project, method) expected_headers = { "Content-Type": "application/x-protobuf", "User-Agent": connection_module.DEFAULT_USER_AGENT, connection_module.CLIENT_INFO_HEADER: _CLIENT_INFO, } http.request.assert_called_once_with( method="POST", url=expected_url, headers=expected_headers, data=data ) def test_failure(self): from google.cloud.exceptions import BadRequest from google.rpc import code_pb2 from google.rpc import status_pb2 project = "PROJECT" method = "METHOD" data = "DATA" uri = "http://api-url" error = status_pb2.Status() error.message = "Entity value is indexed." error.code = code_pb2.FAILED_PRECONDITION http = _make_requests_session( [_make_response(http_client.BAD_REQUEST, content=error.SerializeToString())] ) with self.assertRaises(BadRequest) as exc: self._call_fut(http, project, method, data, uri) expected_message = "400 Entity value is indexed." self.assertEqual(str(exc.exception), expected_message) class Test__rpc(unittest.TestCase): @staticmethod def _call_fut(*args, **kwargs): from google.cloud.datastore._http import _rpc return _rpc(*args, **kwargs) def test_it(self): from google.cloud.datastore_v1.proto import datastore_pb2 http = object() project = "projectOK" method = "beginTransaction" base_url = "test.invalid" request_pb = datastore_pb2.BeginTransactionRequest(project_id=project) response_pb = datastore_pb2.BeginTransactionResponse(transaction=b"7830rmc") patch = mock.patch( "google.cloud.datastore._http._request", return_value=response_pb.SerializeToString(), ) with patch as mock_request: result = self._call_fut( http, project, method, base_url, request_pb, datastore_pb2.BeginTransactionResponse, ) self.assertEqual(result, response_pb) mock_request.assert_called_once_with( http, project, method, request_pb.SerializeToString(), base_url ) class TestHTTPDatastoreAPI(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore._http import HTTPDatastoreAPI return HTTPDatastoreAPI def _make_one(self, *args, **kwargs): return self._get_target_class()(*args, **kwargs) @staticmethod def _make_query_pb(kind): from google.cloud.datastore_v1.proto import query_pb2 return query_pb2.Query(kind=[query_pb2.KindExpression(name=kind)]) def test_constructor(self): client = object() ds_api = self._make_one(client) self.assertIs(ds_api.client, client) def test_lookup_single_key_empty_response(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" key_pb = _make_key_pb(project) rsp_pb = datastore_pb2.LookupResponse() read_options = datastore_pb2.ReadOptions() # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.lookup(project, [key_pb], read_options=read_options) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "lookup") self.assertEqual(len(response.found), 0) self.assertEqual(len(response.missing), 0) self.assertEqual(len(response.deferred), 0) request = _verify_protobuf_call(http, uri, datastore_pb2.LookupRequest()) self.assertEqual(list(request.keys), [key_pb]) self.assertEqual(request.read_options, read_options) def test_lookup_single_key_empty_response_w_eventual(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" key_pb = _make_key_pb(project) rsp_pb = datastore_pb2.LookupResponse() read_options = datastore_pb2.ReadOptions( read_consistency=datastore_pb2.ReadOptions.EVENTUAL ) # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.lookup(project, [key_pb], read_options=read_options) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "lookup") self.assertEqual(len(response.found), 0) self.assertEqual(len(response.missing), 0) self.assertEqual(len(response.deferred), 0) request = _verify_protobuf_call(http, uri, datastore_pb2.LookupRequest()) self.assertEqual(list(request.keys), [key_pb]) self.assertEqual(request.read_options, read_options) def test_lookup_single_key_empty_response_w_transaction(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" transaction = b"TRANSACTION" key_pb = _make_key_pb(project) rsp_pb = datastore_pb2.LookupResponse() read_options = datastore_pb2.ReadOptions(transaction=transaction) # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.lookup(project, [key_pb], read_options=read_options) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "lookup") self.assertEqual(len(response.found), 0) self.assertEqual(len(response.missing), 0) self.assertEqual(len(response.deferred), 0) request = _verify_protobuf_call(http, uri, datastore_pb2.LookupRequest()) self.assertEqual(list(request.keys), [key_pb]) self.assertEqual(request.read_options, read_options) def test_lookup_single_key_nonempty_response(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore_v1.proto import entity_pb2 project = "PROJECT" key_pb = _make_key_pb(project) rsp_pb = datastore_pb2.LookupResponse() entity = entity_pb2.Entity() entity.key.CopyFrom(key_pb) rsp_pb.found.add(entity=entity) read_options = datastore_pb2.ReadOptions() # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.lookup(project, [key_pb], read_options=read_options) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "lookup") self.assertEqual(len(response.found), 1) self.assertEqual(len(response.missing), 0) self.assertEqual(len(response.deferred), 0) found = response.found[0].entity self.assertEqual(found.key.path[0].kind, "Kind") self.assertEqual(found.key.path[0].id, 1234) request = _verify_protobuf_call(http, uri, datastore_pb2.LookupRequest()) self.assertEqual(list(request.keys), [key_pb]) self.assertEqual(request.read_options, read_options) def test_lookup_multiple_keys_empty_response(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" key_pb1 = _make_key_pb(project) key_pb2 = _make_key_pb(project, id_=2345) rsp_pb = datastore_pb2.LookupResponse() read_options = datastore_pb2.ReadOptions() # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.lookup(project, [key_pb1, key_pb2], read_options=read_options) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "lookup") self.assertEqual(len(response.found), 0) self.assertEqual(len(response.missing), 0) self.assertEqual(len(response.deferred), 0) request = _verify_protobuf_call(http, uri, datastore_pb2.LookupRequest()) self.assertEqual(list(request.keys), [key_pb1, key_pb2]) self.assertEqual(request.read_options, read_options) def test_lookup_multiple_keys_w_missing(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" key_pb1 = _make_key_pb(project) key_pb2 = _make_key_pb(project, id_=2345) rsp_pb = datastore_pb2.LookupResponse() er_1 = rsp_pb.missing.add() er_1.entity.key.CopyFrom(key_pb1) er_2 = rsp_pb.missing.add() er_2.entity.key.CopyFrom(key_pb2) read_options = datastore_pb2.ReadOptions() # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.lookup(project, [key_pb1, key_pb2], read_options=read_options) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "lookup") self.assertEqual(len(response.found), 0) self.assertEqual(len(response.deferred), 0) missing_keys = [result.entity.key for result in response.missing] self.assertEqual(missing_keys, [key_pb1, key_pb2]) request = _verify_protobuf_call(http, uri, datastore_pb2.LookupRequest()) self.assertEqual(list(request.keys), [key_pb1, key_pb2]) self.assertEqual(request.read_options, read_options) def test_lookup_multiple_keys_w_deferred(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" key_pb1 = _make_key_pb(project) key_pb2 = _make_key_pb(project, id_=2345) rsp_pb = datastore_pb2.LookupResponse() rsp_pb.deferred.add().CopyFrom(key_pb1) rsp_pb.deferred.add().CopyFrom(key_pb2) read_options = datastore_pb2.ReadOptions() # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.lookup(project, [key_pb1, key_pb2], read_options=read_options) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "lookup") self.assertEqual(len(response.found), 0) self.assertEqual(len(response.missing), 0) self.assertEqual(list(response.deferred), [key_pb1, key_pb2]) request = _verify_protobuf_call(http, uri, datastore_pb2.LookupRequest()) self.assertEqual(list(request.keys), [key_pb1, key_pb2]) self.assertEqual(request.read_options, read_options) def test_run_query_w_eventual_no_transaction(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.datastore_v1.proto import query_pb2 project = "PROJECT" kind = "Nonesuch" cursor = b"\x00" query_pb = self._make_query_pb(kind) partition_id = entity_pb2.PartitionId(project_id=project) read_options = datastore_pb2.ReadOptions( read_consistency=datastore_pb2.ReadOptions.EVENTUAL ) rsp_pb = datastore_pb2.RunQueryResponse( batch=query_pb2.QueryResultBatch( entity_result_type=query_pb2.EntityResult.FULL, end_cursor=cursor, more_results=query_pb2.QueryResultBatch.NO_MORE_RESULTS, ) ) # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.run_query(project, partition_id, read_options, query=query_pb) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "runQuery") request = _verify_protobuf_call(http, uri, datastore_pb2.RunQueryRequest()) self.assertEqual(request.partition_id, partition_id) self.assertEqual(request.query, query_pb) self.assertEqual(request.read_options, read_options) def test_run_query_wo_eventual_w_transaction(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.datastore_v1.proto import query_pb2 project = "PROJECT" kind = "Nonesuch" cursor = b"\x00" transaction = b"TRANSACTION" query_pb = self._make_query_pb(kind) partition_id = entity_pb2.PartitionId(project_id=project) read_options = datastore_pb2.ReadOptions(transaction=transaction) rsp_pb = datastore_pb2.RunQueryResponse( batch=query_pb2.QueryResultBatch( entity_result_type=query_pb2.EntityResult.FULL, end_cursor=cursor, more_results=query_pb2.QueryResultBatch.NO_MORE_RESULTS, ) ) # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.run_query(project, partition_id, read_options, query=query_pb) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "runQuery") request = _verify_protobuf_call(http, uri, datastore_pb2.RunQueryRequest()) self.assertEqual(request.partition_id, partition_id) self.assertEqual(request.query, query_pb) self.assertEqual(request.read_options, read_options) def test_run_query_wo_namespace_empty_result(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.datastore_v1.proto import query_pb2 project = "PROJECT" kind = "Nonesuch" cursor = b"\x00" query_pb = self._make_query_pb(kind) partition_id = entity_pb2.PartitionId(project_id=project) read_options = datastore_pb2.ReadOptions() rsp_pb = datastore_pb2.RunQueryResponse( batch=query_pb2.QueryResultBatch( entity_result_type=query_pb2.EntityResult.FULL, end_cursor=cursor, more_results=query_pb2.QueryResultBatch.NO_MORE_RESULTS, ) ) # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.run_query(project, partition_id, read_options, query=query_pb) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "runQuery") request = _verify_protobuf_call(http, uri, datastore_pb2.RunQueryRequest()) self.assertEqual(request.partition_id, partition_id) self.assertEqual(request.query, query_pb) self.assertEqual(request.read_options, read_options) def test_run_query_w_namespace_nonempty_result(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.datastore_v1.proto import query_pb2 project = "PROJECT" kind = "Kind" namespace = "NS" query_pb = self._make_query_pb(kind) partition_id = entity_pb2.PartitionId( project_id=project, namespace_id=namespace ) read_options = datastore_pb2.ReadOptions() rsp_pb = datastore_pb2.RunQueryResponse( batch=query_pb2.QueryResultBatch( entity_result_type=query_pb2.EntityResult.FULL, entity_results=[query_pb2.EntityResult(entity=entity_pb2.Entity())], more_results=query_pb2.QueryResultBatch.NO_MORE_RESULTS, ) ) # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.run_query(project, partition_id, read_options, query=query_pb) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "runQuery") request = _verify_protobuf_call(http, uri, datastore_pb2.RunQueryRequest()) self.assertEqual(request.partition_id, partition_id) self.assertEqual(request.query, query_pb) def test_begin_transaction(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" transaction = b"TRANSACTION" rsp_pb = datastore_pb2.BeginTransactionResponse() rsp_pb.transaction = transaction # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.begin_transaction(project) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "beginTransaction") request = _verify_protobuf_call( http, uri, datastore_pb2.BeginTransactionRequest() ) # The RPC-over-HTTP request does not set the project in the request. self.assertEqual(request.project_id, u"") def test_commit_wo_transaction(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.helpers import _new_value_pb project = "PROJECT" key_pb = _make_key_pb(project) rsp_pb = datastore_pb2.CommitResponse() req_pb = datastore_pb2.CommitRequest() mutation = req_pb.mutations.add() insert = mutation.upsert insert.key.CopyFrom(key_pb) value_pb = _new_value_pb(insert, "foo") value_pb.string_value = u"Foo" # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. rq_class = datastore_pb2.CommitRequest ds_api = self._make_one(client) mode = rq_class.NON_TRANSACTIONAL result = ds_api.commit(project, mode, [mutation]) # Check the result and verify the callers. self.assertEqual(result, rsp_pb) uri = _build_expected_url(client._base_url, project, "commit") request = _verify_protobuf_call(http, uri, rq_class()) self.assertEqual(request.transaction, b"") self.assertEqual(list(request.mutations), [mutation]) self.assertEqual(request.mode, rq_class.NON_TRANSACTIONAL) def test_commit_w_transaction(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.helpers import _new_value_pb project = "PROJECT" key_pb = _make_key_pb(project) rsp_pb = datastore_pb2.CommitResponse() req_pb = datastore_pb2.CommitRequest() mutation = req_pb.mutations.add() insert = mutation.upsert insert.key.CopyFrom(key_pb) value_pb = _new_value_pb(insert, "foo") value_pb.string_value = u"Foo" # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. rq_class = datastore_pb2.CommitRequest ds_api = self._make_one(client) mode = rq_class.TRANSACTIONAL result = ds_api.commit(project, mode, [mutation], transaction=b"xact") # Check the result and verify the callers. self.assertEqual(result, rsp_pb) uri = _build_expected_url(client._base_url, project, "commit") request = _verify_protobuf_call(http, uri, rq_class()) self.assertEqual(request.transaction, b"xact") self.assertEqual(list(request.mutations), [mutation]) self.assertEqual(request.mode, rq_class.TRANSACTIONAL) def test_rollback_ok(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" transaction = b"xact" rsp_pb = datastore_pb2.RollbackResponse() # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.rollback(project, transaction) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "rollback") request = _verify_protobuf_call(http, uri, datastore_pb2.RollbackRequest()) self.assertEqual(request.transaction, transaction) def test_allocate_ids_empty(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" rsp_pb = datastore_pb2.AllocateIdsResponse() # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.allocate_ids(project, []) # Check the result and verify the callers. self.assertEqual(response, rsp_pb) self.assertEqual(list(response.keys), []) uri = _build_expected_url(client._base_url, project, "allocateIds") request = _verify_protobuf_call(http, uri, datastore_pb2.AllocateIdsRequest()) self.assertEqual(list(request.keys), []) def test_allocate_ids_non_empty(self): from google.cloud.datastore_v1.proto import datastore_pb2 project = "PROJECT" before_key_pbs = [ _make_key_pb(project, id_=None), _make_key_pb(project, id_=None), ] after_key_pbs = [_make_key_pb(project), _make_key_pb(project, id_=2345)] rsp_pb = datastore_pb2.AllocateIdsResponse() rsp_pb.keys.add().CopyFrom(after_key_pbs[0]) rsp_pb.keys.add().CopyFrom(after_key_pbs[1]) # Create mock HTTP and client with response. http = _make_requests_session( [_make_response(content=rsp_pb.SerializeToString())] ) client = mock.Mock( _http=http, _base_url="test.invalid", spec=["_http", "_base_url"] ) # Make request. ds_api = self._make_one(client) response = ds_api.allocate_ids(project, before_key_pbs) # Check the result and verify the callers. self.assertEqual(list(response.keys), after_key_pbs) self.assertEqual(response, rsp_pb) uri = _build_expected_url(client._base_url, project, "allocateIds") request = _verify_protobuf_call(http, uri, datastore_pb2.AllocateIdsRequest()) self.assertEqual(len(request.keys), len(before_key_pbs)) for key_before, key_after in zip(before_key_pbs, request.keys): self.assertEqual(key_before, key_after) def _make_response(status=http_client.OK, content=b"", headers={}): response = requests.Response() response.status_code = status response._content = content response.headers = headers response.request = requests.Request() return response def _make_requests_session(responses): session = mock.create_autospec(requests.Session, instance=True) session.request.side_effect = responses return session def _build_expected_url(api_base_url, project, method): from google.cloud.datastore._http import API_VERSION return "/".join([api_base_url, API_VERSION, "projects", project + ":" + method]) def _make_key_pb(project, id_=1234): from google.cloud.datastore.key import Key path_args = ("Kind",) if id_ is not None: path_args += (id_,) return Key(*path_args, project=project).to_protobuf() def _verify_protobuf_call(http, expected_url, pb): from google.cloud import _http as connection_module from google.cloud.datastore._http import _CLIENT_INFO expected_headers = { "Content-Type": "application/x-protobuf", "User-Agent": connection_module.DEFAULT_USER_AGENT, connection_module.CLIENT_INFO_HEADER: _CLIENT_INFO, } http.request.assert_called_once_with( method="POST", url=expected_url, headers=expected_headers, data=mock.ANY ) data = http.request.mock_calls[0][2]["data"] pb.ParseFromString(data) return pb
{ "content_hash": "0b566b11ecc0e404f9389ac6c80707bf", "timestamp": "", "source": "github", "line_count": 765, "max_line_length": 88, "avg_line_length": 37.97516339869281, "alnum_prop": 0.624487969433066, "repo_name": "dhermes/gcloud-python", "id": "b402eafc95326949af3f885131f14fc1214ade59", "size": "29626", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "datastore/tests/unit/test__http.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3366" }, { "name": "PowerShell", "bytes": "7195" }, { "name": "Protocol Buffer", "bytes": "95635" }, { "name": "Python", "bytes": "2871895" }, { "name": "Shell", "bytes": "4683" } ], "symlink_target": "" }