text
stringlengths
2
1.04M
meta
dict
"""Contains convenience wrappers for creating variables in TF-Slim. The variables module is typically used for defining model variables from the ops routines (see slim.ops). Such variables are used for training, evaluation and inference of models. All the variables created through this module would be added to the MODEL_VARIABLES collection, if you create a model variable outside slim, it can be added with slim.variables.add_variable(external_variable, reuse). Usage: weights_initializer = tf.truncated_normal_initializer(stddev=0.01) l2_regularizer = lambda t: losses.l2_loss(t, weight=0.0005) weights = variables.variable('weights', shape=[100, 100], initializer=weights_initializer, regularizer=l2_regularizer, device='/cpu:0') biases = variables.variable('biases', shape=[100], initializer=tf.zeros_initializer, device='/cpu:0') # More complex example. net = slim.ops.conv2d(input, 32, [3, 3], scope='conv1') net = slim.ops.conv2d(net, 64, [3, 3], scope='conv2') with slim.arg_scope([variables.variable], restore=False): net = slim.ops.conv2d(net, 64, [3, 3], scope='conv3') # Get all model variables from all the layers. model_variables = slim.variables.get_variables() # Get all model variables from a specific the layer, i.e 'conv1'. conv1_variables = slim.variables.get_variables('conv1') # Get all weights from all the layers. weights = slim.variables.get_variables_by_name('weights') # Get all bias from all the layers. biases = slim.variables.get_variables_by_name('biases') # Get all variables to restore. # (i.e. only those created by 'conv1' and 'conv2') variables_to_restore = slim.variables.get_variables_to_restore() ************************************************ * Initializing model variables from a checkpoint ************************************************ # Create some variables. v1 = slim.variables.variable(name="v1", ..., restore=False) v2 = slim.variables.variable(name="v2", ...) # By default restore=True ... # The list of variables to restore should only contain 'v2'. variables_to_restore = slim.variables.get_variables_to_restore() restorer = tf.train.Saver(variables_to_restore) with tf.Session() as sess: # Restore variables from disk. restorer.restore(sess, "/tmp/model.ckpt") print("Model restored.") # Do some work with the model ... """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.core.framework import graph_pb2 from inception.slim import scopes # Collection containing all the variables created using slim.variables MODEL_VARIABLES = '_model_variables_' # Collection containing the slim.variables that are created with restore=True. VARIABLES_TO_RESTORE = '_variables_to_restore_' def add_variable(var, restore=True): """Adds a variable to the MODEL_VARIABLES collection. Optionally it will add the variable to the VARIABLES_TO_RESTORE collection. Args: var: a variable. restore: whether the variable should be added to the VARIABLES_TO_RESTORE collection. """ collections = [MODEL_VARIABLES] if restore: collections.append(VARIABLES_TO_RESTORE) for collection in collections: if var not in tf.get_collection(collection): tf.add_to_collection(collection, var) def get_variables(scope=None, suffix=None): """Gets the list of variables, filtered by scope and/or suffix. Args: scope: an optional scope for filtering the variables to return. suffix: an optional suffix for filtering the variables to return. Returns: a copied list of variables with scope and suffix. """ candidates = tf.get_collection(MODEL_VARIABLES, scope)[:] if suffix is not None: candidates = [var for var in candidates if var.op.name.endswith(suffix)] return candidates def get_variables_to_restore(): """Gets the list of variables to restore. Returns: a copied list of variables. """ return tf.get_collection(VARIABLES_TO_RESTORE)[:] def get_variables_by_name(given_name, scope=None): """Gets the list of variables that were given that name. Args: given_name: name given to the variable without scope. scope: an optional scope for filtering the variables to return. Returns: a copied list of variables with the given name and prefix. """ return get_variables(scope=scope, suffix=given_name) def get_unique_variable(name): """Gets the variable uniquely identified by that name. Args: name: a name that uniquely identifies the variable. Returns: a tensorflow variable. Raises: ValueError: if no variable uniquely identified by the name exists. """ candidates = tf.get_collection(tf.GraphKeys.VARIABLES, name) if not candidates: raise ValueError('Couldnt find variable %s' % name) for candidate in candidates: if candidate.op.name == name: return candidate raise ValueError('Variable %s does not uniquely identify a variable', name) class VariableDeviceChooser(object): """Slim device chooser for variables. When using a parameter server it will assign them in a round-robin fashion. When not using a parameter server it allows GPU:0 placement otherwise CPU:0. """ def __init__(self, num_parameter_servers=0, ps_device='/job:ps', placement='CPU:0'): """Initialize VariableDeviceChooser. Args: num_parameter_servers: number of parameter servers. ps_device: string representing the parameter server device. placement: string representing the placement of the variable either CPU:0 or GPU:0. When using parameter servers forced to CPU:0. """ self._num_ps = num_parameter_servers self._ps_device = ps_device self._placement = placement if num_parameter_servers == 0 else 'CPU:0' self._next_task_id = 0 def __call__(self, op): device_string = '' if self._num_ps > 0: task_id = self._next_task_id self._next_task_id = (self._next_task_id + 1) % self._num_ps device_string = '%s/task:%d' % (self._ps_device, task_id) device_string += '/%s' % self._placement return device_string # TODO(sguada) Remove once get_variable is able to colocate op.devices. def variable_device(device, name): """Fix the variable device to colocate its ops.""" if callable(device): var_name = tf.get_variable_scope().name + '/' + name var_def = graph_pb2.NodeDef(name=var_name, op='Variable') device = device(var_def) if device is None: device = '' return device @scopes.add_arg_scope def global_step(device=''): """Returns the global step variable. Args: device: Optional device to place the variable. It can be an string or a function that is called to get the device for the variable. Returns: the tensor representing the global step variable. """ global_step_ref = tf.get_collection(tf.GraphKeys.GLOBAL_STEP) if global_step_ref: return global_step_ref[0] else: collections = [ VARIABLES_TO_RESTORE, tf.GraphKeys.VARIABLES, tf.GraphKeys.GLOBAL_STEP, ] # Get the device for the variable. with tf.device(variable_device(device, 'global_step')): return tf.get_variable('global_step', shape=[], dtype=tf.int64, initializer=tf.zeros_initializer, trainable=False, collections=collections) @scopes.add_arg_scope def variable(name, shape=None, dtype=tf.float32, initializer=None, regularizer=None, trainable=True, collections=None, device='', restore=True): """Gets an existing variable with these parameters or creates a new one. It also add itself to a group with its name. Args: name: the name of the new or existing variable. shape: shape of the new or existing variable. dtype: type of the new or existing variable (defaults to `DT_FLOAT`). initializer: initializer for the variable if one is created. regularizer: a (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. trainable: If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). collections: A list of collection names to which the Variable will be added. Note that the variable is always also added to the tf.GraphKeys.VARIABLES and MODEL_VARIABLES collections. device: Optional device to place the variable. It can be an string or a function that is called to get the device for the variable. restore: whether the variable should be added to the VARIABLES_TO_RESTORE collection. Returns: The created or existing variable. """ collections = list(collections or []) # Make sure variables are added to tf.GraphKeys.VARIABLES and MODEL_VARIABLES collections += [tf.GraphKeys.VARIABLES, MODEL_VARIABLES] # Add to VARIABLES_TO_RESTORE if necessary if restore: collections.append(VARIABLES_TO_RESTORE) # Remove duplicates collections = set(collections) # Get the device for the variable. with tf.device(variable_device(device, name)): return tf.get_variable(name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, trainable=trainable, collections=collections)
{ "content_hash": "5fc60f69fb4e4e866246ff775ae18f2c", "timestamp": "", "source": "github", "line_count": 276, "max_line_length": 80, "avg_line_length": 35.14855072463768, "alnum_prop": 0.6836408617668281, "repo_name": "nathansilberman/models", "id": "d58bb5328d9a20fdfb0a2330156af68e2e977aa5", "size": "10374", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "inception/inception/slim/variables.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "604484" }, { "name": "Jupyter Notebook", "bytes": "41812" }, { "name": "Makefile", "bytes": "6049" }, { "name": "Protocol Buffer", "bytes": "10515" }, { "name": "Python", "bytes": "1082505" }, { "name": "Shell", "bytes": "31462" } ], "symlink_target": "" }
module.exports = Field; var urlModule = require("url"); var client = require("efs-client"); var plugins = require("../plugins"); var datadetectors = plugins.datadetectors; function Field(name, value) { var field = this; field.name = name; field.value = value; field.links = null; field.scalars = null; } Field.prototype.addLink = function(URI, relation) { var field = this; if(!field.links) field.links = []; var normalizedURI = client.normalizeURI(URI); var relations = (relation || "").trim().toLowerCase().split(/\s+/g); relations.filter(function(relation) { // TODO: Some relations like `nofollow` should apply to all of the other relations, but not count as relations themselves... For now just ignore them entirely. switch(relation) { case "nofollow": return false; default: return true; } }).forEach(function(relation) { field.links.push({normalizedURI: normalizedURI, relation: relation}); }); }; Field.prototype.addScalar = function(type, value) { var field = this; if(!field.scalars) field.scalars = []; if("number" !== typeof value || isNaN(value)) throw new Error("Invalid value "+value); field.scalars.push({ type: type, value: value, }); }; Field.prototype.parse = function(callback/* (err) */) { var field = this; var waiting = 2; parseLinks(field, function(err) { if(err) { waiting = 0; callback(err); } if(!--waiting) callback(null); }); parseScalars(field, function(err) { if(err) { waiting = 0; callback(err); } if(!--waiting) callback(null); }); }; function parseLinks(field, callback/* (err) */) { if(field.links) return callback(null); field.links = []; // <http://daringfireball.net/2010/07/improved_regex_for_matching_urls> var exp = /\b((?:[a-z][\w\-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig; var obj; while(obj = exp.exec(field.value)) { field.addLink(obj[0]); } callback(null); }; function parseScalars(field, callback/* (err) */) { if(field.scalars) return; field.scalars = []; var waiting = datadetectors.length; if(!waiting) return callback(null); datadetectors.forEach(function(detector) { detector.parseScalars(field, function(err) { if(!--waiting) callback(null); }); }); };
{ "content_hash": "1d384a7306e0aa95b99628c35497c5f2", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 219, "avg_line_length": 30.376623376623378, "alnum_prop": 0.6314664386489953, "repo_name": "btrask/earthfs-js-old", "id": "8286487a361cd457b7240e04e936bd94de7cda68", "size": "3442", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "classes/Field.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5003" }, { "name": "HTML", "bytes": "2584" }, { "name": "JavaScript", "bytes": "119085" }, { "name": "Makefile", "bytes": "1448" } ], "symlink_target": "" }
Public Class FormMain Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. End Sub Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim msgText As String Dim msgTitle As New Title() Dim _settings As New Settings() Me.comboPatch.Enabled = False Me.comboSeason.Enabled = False Me.comboGameplay.Enabled = False 'Read Patch If _patch.Read() Then Me.comboPatch.Items.Clear() Me.comboPatch.Enabled = True For Each name As String In _patch.List Me.comboPatch.Items.Add(name) Next Else Exit Sub End If 'Read Settings If _settings.Read() Then _patch.Name = _settings.Patch _season.Name = _settings.Season _gameplay.Name = _settings.Gameplay Else msgText = "Shollym Switcher is not set, please select the patch" & Environment.NewLine msgText &= "and then select the season and gameplay this season." MessageBox.Show(msgText, msgTitle.Info, MessageBoxButtons.OK, MessageBoxIcon.Information) Exit Sub End If 'Load Patch If Me.comboPatch.Items.Contains(_patch.Name) Then Me.comboPatch.SelectedIndex = Me.comboPatch.Items.IndexOf(_patch.Name) Else msgText = "Patch the stored settings do not exist in the swithcer." & Environment.NewLine msgText &= "The application will make a copy of those files when saving." MessageBox.Show(msgText, msgTitle.Warn, MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If 'Load Season If Me.comboSeason.Items.Contains(_season.Name) Then Me.comboSeason.Enabled = True Me.comboSeason.SelectedIndex = Me.comboSeason.Items.IndexOf(_season.Name) Else msgText = "Season the stored settings do not exist in the swithcer." & Environment.NewLine msgText &= "The application will make a copy of those files when saving." MessageBox.Show(msgText, msgTitle.Warn, MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If 'Load Gameplay If Me.comboGameplay.Items.Contains(_gameplay.Name) Then Me.comboGameplay.Enabled = True Me.comboGameplay.SelectedIndex = Me.comboGameplay.Items.IndexOf(_gameplay.Name) Else msgText = "Gameplay the stored settings do not exist in the swithcer." & Environment.NewLine msgText &= "The application will make a copy of those files when saving." MessageBox.Show(msgText, msgTitle.Warn, MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If Me.buttonPlay.Focus() End Sub Private Sub ComboPatch_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comboPatch.SelectedIndexChanged _patch.Name = Me.comboPatch.Text If _edit.Patch Then Me.comboSeason.Refresh() Exit Sub End If If _patch.Check() Then Me.comboSeason.Items.Clear() Me.comboGameplay.Items.Clear() Me.comboGameplay.Enabled = False Me.pictureLogo.Image = My.Resources.logo If Not Me.comboSeason.Enabled Then Me.comboSeason.Enabled = True End If If _season.Read() Then For Each name As String In _season.List Me.comboSeason.Items.Add(name) Next End If End If End Sub Private Sub ComboSeason_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comboSeason.SelectedIndexChanged _season.Name = Me.comboSeason.Text If _edit.Season Then Me.comboGameplay.Refresh() Exit Sub End If If _season.Check() Then Me.comboGameplay.Items.Clear() If _logo.Read() Then Me.pictureLogo.Load(_logo.Path) End If If Not Me.comboGameplay.Enabled Then Me.comboGameplay.Enabled = True End If If _gameplay.Read() Then For Each name As String In _gameplay.List Me.comboGameplay.Items.Add(name) Next End If End If End Sub Private Sub comboGameplay_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comboGameplay.SelectedIndexChanged _gameplay.Name = Me.comboGameplay.Text If _edit.Gameplay Then Me.comboGameplay.Refresh() Exit Sub End If If Not _gameplay.Check() Then Me.comboGameplay.SelectedIndex = -1 End If End Sub Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles buttonSave.Click Dim msgText As String Dim msgTitle As New Title() Dim _settings As New Settings() If Me.comboPatch.SelectedIndex < 0 Or Me.comboSeason.SelectedIndex < 0 Or Me.comboGameplay.SelectedIndex < 0 Then msgText = "You have not selected parameters." & Environment.NewLine msgText &= "Save the settings can not be done." MessageBox.Show(msgText, msgTitle.Mistake, MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub End If If Not _patch.Check() And Not _season.Check() Then Exit Sub End If If _settings.Read() Then If String.Compare(_settings.Patch, _patch.Name, True) <> 0 Or _ String.Compare(_settings.Season, _season.Name, True) <> 0 Then If Not _season.Save() Then Exit Sub End If End If If String.Compare(_settings.Patch, _patch.Name, True) <> 0 Or _ String.Compare(_settings.Season, _season.Name, True) <> 0 Or _ String.Compare(_settings.Gameplay, _gameplay.Name, True) <> 0 Then _gameplay.Backup(_settings.Patch, _settings.Season, _settings.Gameplay) If Not _gameplay.Save() Then Exit Sub End If End If Else If _gameplay.CheckOld() Then _gameplay.Backup(_settings.Patch, _settings.Season, _settings.Gameplay) End If If Not _season.Save() Then Exit Sub End If If Not _gameplay.Save() Then Exit Sub End If End If _settings.Patch = _patch.Name _settings.Season = _season.Name _settings.Gameplay = _gameplay.Name If Not _settings.Write() Then msgText = "Settings can not be stored on your HDD!" & Environment.NewLine msgText &= "Switcher does not have administrative privileges" & Environment.NewLine msgText &= "or settings used by other software, check this out." MessageBox.Show(msgText, msgTitle.Mistake, MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub End If msgText = "The new settings have been successfully saved!" MessageBox.Show(msgText, msgTitle.Info, MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub Private Sub ButtonPlay_Click(sender As Object, e As EventArgs) Handles buttonPlay.Click Dim pes As New Pes() Call pes.PES6() End Sub Private Sub MenuHelpItemReadme_Click(sender As Object, e As EventArgs) Handles menuHelpItemReadme.Click Dim help As New Help() Call help.Readme() End Sub Private Sub MenuHelpItemFacebook_Click(sender As Object, e As EventArgs) Handles menuHelpItemFacebook.Click Dim help As New Help() Call help.Facebook() End Sub Private Sub MenuHelpItemDownload_Click(sender As Object, e As EventArgs) Handles menuHelpItemDownload.Click Dim help As New Help() Call help.Download() End Sub Private Sub MenuToolsItemKitserver_Click(sender As Object, e As EventArgs) Handles menuToolsItemKitserver.Click Dim tools As New Tools() Call tools.Kitserver() End Sub Private Sub MenuToolsItemSettings_Click(sender As Object, e As EventArgs) Handles menuToolsItemSettings.Click Dim tools As New Tools() Call tools.Settings() End Sub Private Sub menuMain_Click(sender As Object, e As EventArgs) Handles menuMain.Click If Me.comboPatch.SelectedIndex >= 0 Then Me.menuEditItemPatch.Enabled = True Else Me.menuEditItemPatch.Enabled = False End If 'Season If Me.comboSeason.SelectedIndex >= 0 Then Me.menuEditItemLogo.Enabled = True Me.menuEditItemSeason.Enabled = True Else Me.menuEditItemLogo.Enabled = False Me.menuEditItemSeason.Enabled = False End If 'Gameplay If Me.comboGameplay.SelectedIndex >= 0 Then Me.menuEditItemGameplay.Enabled = True Else Me.menuEditItemGameplay.Enabled = False End If End Sub Private Sub MenuEditItemPatch_Click(sender As Object, e As EventArgs) Handles menuEditItemPatch.Click If menuEditItemPatch.Enabled Then Dim editForm As New FormEdit() Call _edit.Reset() _edit.Patch = True 'Me.Hide() Me.Enabled = False 'editForm.Text &= Me.labelPatch.Text.Replace("Select ", "").Replace(":", "") editForm.Text &= "Patch" editForm.textOld.Text = Me.comboPatch.Text editForm.textNew.Text = Me.comboPatch.Text editForm.Show() editForm.textNew.Focus() End If End Sub Private Sub MenuEditItemSeason_Click(sender As Object, e As EventArgs) Handles menuEditItemSeason.Click If menuEditItemSeason.Enabled Then Dim editForm As New FormEdit() Call _edit.Reset() _edit.Season = True 'Me.Hide() Me.Enabled = False editForm.Text &= "Season" editForm.textOld.Text = Me.comboSeason.Text editForm.textNew.Text = Me.comboSeason.Text editForm.Show() editForm.textNew.Focus() End If End Sub Private Sub MenuEditItemGameplay_Click(sender As Object, e As EventArgs) Handles menuEditItemGameplay.Click If menuEditItemGameplay.Enabled Then Dim editForm As New FormEdit() Call _edit.Reset() _edit.Gameplay = True 'Me.Hide() Me.Enabled = False editForm.Text &= "Gameplay" editForm.textOld.Text = Me.comboGameplay.Text editForm.textNew.Text = Me.comboGameplay.Text editForm.Show() editForm.textNew.Focus() End If End Sub Private Sub MenuFileItemPlay_Click(sender As Object, e As EventArgs) Handles menuFileItemPlay.Click Call ButtonPlay_Click(sender, e) End Sub Private Sub MenuFileItemSave_Click(sender As Object, e As EventArgs) Handles menuFileItemSave.Click Call ButtonSave_Click(sender, e) End Sub Private Sub MenuFileItemRestart_Click(sender As Object, e As EventArgs) Handles menuFileItemRestart.Click Call FormMain_Load(sender, e) End Sub Private Sub MenuFileItemExit_Click(sender As Object, e As EventArgs) Handles menuFileItemExit.Click Me.Close() End Sub Private Sub menuHelpItemAbout_Click(sender As Object, e As EventArgs) Handles menuHelpItemAbout.Click Dim _aboutForm As New FormAbout() 'Me.Hide() Me.Enabled = False _aboutForm.Show() _aboutForm.buttonClose.Focus() End Sub Private Sub FormMain_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed Application.Exit() End Sub Private Sub menuEditItemLogo_Click(sender As Object, e As EventArgs) Handles menuEditItemLogo.Click Dim _logoForm As New FormLogo() 'Me.Hide() Me.Enabled = False If _logo.Read() Then _logoForm.textPath.Text = _logo.Path End If _logoForm.Show() _logoForm.buttonSelect.Focus() End Sub End Class
{ "content_hash": "72f961650387b4805199437dd0db8d64", "timestamp": "", "source": "github", "line_count": 391, "max_line_length": 127, "avg_line_length": 32.10230179028133, "alnum_prop": 0.6124123645634162, "repo_name": "jasarsoft/shollymswitcher", "id": "322380c5e0eacf77957a1f99c531ce0bc7dffefd", "size": "12554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Form/FormMain.vb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Visual Basic", "bytes": "106914" } ], "symlink_target": "" }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\helpers\ArrayHelper; use common\models\Adminuser; /* @var $this yii\web\View */ /* @var $model common\models\Adminuser */ $model = Adminuser::findOne($id); $this->title = '权限设置: ' . $model->username; $this->params['breadcrumbs'][] = ['label' => '管理员', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->username, 'url' => ['view', 'id' => $id]]; $this->params['breadcrumbs'][] = '权限设置'; ?> <div class="adminuser-update"> <h1><?= Html::encode($this->title) ?></h1> <div class="adminuser-privilege-form"> <?php $form = ActiveForm::begin(); ?> <?= Html::checkboxList('newPri',$AuthAssignmentArray,$allPrivilegesArray);?> <div class="form-group"> <?= Html::submitButton('设置') ?> </div> <?php ActiveForm::end(); ?> </div> </div>
{ "content_hash": "ca2d047368e5f88bc430a5a4d56480a0", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 95, "avg_line_length": 19.636363636363637, "alnum_prop": 0.5960648148148148, "repo_name": "michaelweixi/blogdemo2", "id": "03d22dc685e02b47a60e8d2e556d5530bf4a48f5", "size": "890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/views/adminuser/privilege.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "3332" }, { "name": "PHP", "bytes": "223836" }, { "name": "Shell", "bytes": "3257" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Linq; using Cake.Common.Tests.Fixtures.Tools; using Cake.Common.Tools.NSIS; using Cake.Core; using Cake.Core.IO; using NSubstitute; using Xunit; namespace Cake.Common.Tests.Unit.Tools.NSIS { // ReSharper disable once InconsistentNaming public sealed class MakeNSISRunnerTests { public sealed class TheRunMethod { [Fact] public void Should_Throw_If_Script_File_Is_Null() { // Given var fixture = new NSISFixture(); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run(null, new MakeNSISSettings())); // Then Assert.IsArgumentNullException(result, "scriptFile"); } [Fact] public void Should_Throw_If_Settings_Is_Null() { // Given var fixture = new NSISFixture(); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run("/Working/File.lol", null)); // Then Assert.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Throw_If_MakeNSIS_Runner_Was_Not_Found() { // Given var fixture = new NSISFixture(); fixture.Globber.Match("./tools/**/makensis.exe").Returns(Enumerable.Empty<Path>()); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run("/Test.nsi", new MakeNSISSettings())); // Then Assert.IsType<CakeException>(result); Assert.Equal("MakeNSIS: Could not locate executable.", result.Message); } [Theory] [InlineData("C:/nsis/makensis.exe", "C:/nsis/makensis.exe")] [InlineData("./tools/nsis/makensis.exe", "/Working/tools/nsis/makensis.exe")] public void Should_Use_MakeNSIS_Runner_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new NSISFixture(expected); var runner = fixture.CreateRunner(); // When runner.Run("./Test.nsi", new MakeNSISSettings { ToolPath = toolPath }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Is<FilePath>(p => p.FullPath == expected), Arg.Any<ProcessSettings>()); } [Fact] public void Should_Find_MakeNSIS_Runner_If_Tool_Path_Not_Provided() { // Given var fixture = new NSISFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test.nsi", new MakeNSISSettings()); // Then fixture.ProcessRunner.Received(1).Start( Arg.Is<FilePath>(p => p.FullPath == "/Working/tools/makensis.exe"), Arg.Any<ProcessSettings>()); } [Fact] public void Should_Set_Working_Directory() { // Given var fixture = new NSISFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test.nsi", new MakeNSISSettings()); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>(p => p.WorkingDirectory.FullPath == "/Working")); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new NSISFixture(); fixture.ProcessRunner.Start(Arg.Any<FilePath>(), Arg.Any<ProcessSettings>()).Returns((IProcess)null); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run("./Test.nsi", new MakeNSISSettings())); // Then Assert.IsType<CakeException>(result); Assert.Equal("MakeNSIS: Process was not started.", result.Message); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new NSISFixture(); fixture.Process.GetExitCode().Returns(1); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run("./Test.nsi", new MakeNSISSettings())); // Then Assert.IsType<CakeException>(result); Assert.Equal("MakeNSIS: Process returned an error.", result.Message); } [Fact] public void Should_Add_Defines_To_Arguments_If_Provided() { // Given var fixture = new NSISFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test.nsi", new MakeNSISSettings { Defines = new Dictionary<string, string> { { "Foo", "Bar" }, { "Test", null }, { "Test2", string.Empty } } }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>(p => p.Arguments.Render() == "/DFoo=Bar /DTest /DTest2 /Working/Test.nsi")); } [Fact] public void Should_Add_NoChangeDirectory_To_Arguments_If_Provided() { // Given var fixture = new NSISFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test.nsi", new MakeNSISSettings { NoChangeDirectory = true }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>(p => p.Arguments.Render() == "/NOCD /Working/Test.nsi")); } [Fact] public void Should_Add_NoConfig_To_Arguments_If_Provided() { // Given var fixture = new NSISFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test.nsi", new MakeNSISSettings { NoConfig = true }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>(p => p.Arguments.Render() == "/NOCONFIG /Working/Test.nsi")); } } } }
{ "content_hash": "70ce00c4d8b676f0f8f4179ab9a36083", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 117, "avg_line_length": 34.53521126760563, "alnum_prop": 0.4676454594888526, "repo_name": "Invenietis/cake", "id": "a98a9a3a9e41d528da2b1c2d60975115d2cb7760", "size": "7358", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Cake.Common.Tests/Unit/Tools/NSIS/MakeNSISRunnerTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2159790" }, { "name": "PowerShell", "bytes": "1657" }, { "name": "Shell", "bytes": "2240" } ], "symlink_target": "" }
from beltac import * from beltacreader import load from inserter import insert,version_imported,reject,setRefsDict,simple_dict_insert import urllib2 from datetime import datetime,timedelta import logging import zipfile from cStringIO import StringIO from bs4 import BeautifulSoup logger = logging.getLogger("importer") url = 'http://beltac.tec-wl.be' path = '/Current%20BLTAC/' def getDataSource(): return { '1' : { 'operator_id' : 'TEC', 'name' : 'TEC beltec leveringen', 'description' : 'TEC beltec leveringen', 'email' : None, 'url' : None}} def import_zip(path,filename,meta): zip = zipfile.ZipFile(path+'/'+filename,'r') count = 0 for name in zip.namelist(): unitcode = name.split('.')[0] import_subzip(StringIO(zip.read(name)),filename,unitcode,remove_old=count==0) count += 1 def import_subzip(zip,versionname,unitcode,remove_old=False): meta,conn = load(zip) conn.commit() try: data = {} data['OPERATOR'] = {'TEC' : {'url' : 'http://www.infotec.be', 'language' : 'nl', 'phone' : '0', 'timezone' : 'Europe/Amsterdam', 'operator_id' : 'TEC', 'name' : 'TEC', 'privatecode' : 'TEC'}} data['MERGESTRATEGY'] = [] if remove_old: data['MERGESTRATEGY'].append({'type' : 'DATASOURCE', 'datasourceref' : '1'}) data['DATASOURCE'] = getDataSource() data['VERSION'] = {} data['VERSION']['1'] = getVersion(conn,versionname,prefix='TEC') data['DESTINATIONDISPLAY'] = getDestinationDisplays(conn,prefix='TEC') data['LINE'] = getLines(conn,prefix='TEC',operatorref='TEC',unitcode=unitcode[3:]) data['STOPPOINT'] = getStopPoints(conn,prefix='TEC') data['STOPAREA'] = getStopAreas(conn,prefix='TEC') data['AVAILABILITYCONDITION'] = getAvailabilityConditions(conn,prefix='TEC',unitcode=unitcode[3:]) data['PRODUCTCATEGORY'] = getProductCategories(conn) data['ADMINISTRATIVEZONE'] = {} timedemandGroupRefForJourney,data['TIMEDEMANDGROUP'] = calculateTimeDemandGroups(conn,prefix='TEC',unitcode=unitcode[3:]) routeRefForPattern,data['ROUTE'] = clusterPatternsIntoRoute(conn,getFakePool,prefix='TEC',unitcode=unitcode[3:]) data['JOURNEYPATTERN'] = getJourneyPatterns(routeRefForPattern,conn,data['ROUTE'],prefix='TEC') data['JOURNEY'] = getJourneys(timedemandGroupRefForJourney,conn,prefix='TEC',unitcode=unitcode[3:]) data['NOTICEASSIGNMENT'] = getNoticeAssignments(conn,prefix='TEC') data['NOTICE'] = getNotices(conn,prefix='TEC') data['NOTICEGROUP'] = getNoticeGroups(conn,prefix='TEC') conn.close() insert(data) except: raise def download(url,filename): u = urllib2.urlopen(url) f = open('/tmp/'+filename, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (filename, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, print f.close() import_zip('/tmp',filename,None) def sync(): f = urllib2.urlopen(url+'/'+path) soup = BeautifulSoup(f.read()) files = [] for link in soup.find_all('a'): link = link.get('href') filename = urllib2.unquote(link).split('/')[-1] if '.zip' in link.lower(): if not version_imported('TEC:'+filename): files.append((link,filename)) for link,filename in sorted(files): try: print 'FILE '+filename logger.info('Importing :'+filename) download(url+link,filename) except Exception as e: logger.error(filename,exc_info=True) pass
{ "content_hash": "9aa3872494851290031c82841d70dfaf", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 129, "avg_line_length": 39.39090909090909, "alnum_prop": 0.5735056542810986, "repo_name": "bliksemlabs/bliksemintegration", "id": "2a8bdec5bd1ad5111c6e522e53d86a6046d96cbd", "size": "4333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "importers/tec.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "PLSQL", "bytes": "4719" }, { "name": "PLpgSQL", "bytes": "15144" }, { "name": "Python", "bytes": "494673" }, { "name": "Shell", "bytes": "438" } ], "symlink_target": "" }
import React, { Component } from 'react' import { Input } from 'antd' import './styles.css' export default class Search extends Component { constructor(props) { super(props) } render() { return ( <div className="im-search-block"> <Input.Search placeholder="搜索好友、群组" className="im-search-input" onChange={this.props.onChange} /> </div> ) } }
{ "content_hash": "f68b8986ad5d02ec45891ed520d749aa", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 50, "avg_line_length": 23.714285714285715, "alnum_prop": 0.4899598393574297, "repo_name": "clumsyme/cc", "id": "27d1a83dcbce30944fe8da74895c79cdae09f9aa", "size": "512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/src/im/components/search/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2831" }, { "name": "JavaScript", "bytes": "3842" } ], "symlink_target": "" }
/* eslint-disable no-unused-vars */ 'use strict'; var pdfjsVersion = PDFJSDev.eval('BUNDLE_VERSION'); var pdfjsBuild = PDFJSDev.eval('BUNDLE_BUILD'); var pdfjsSharedUtil = require('./shared/util.js'); var pdfjsDisplayGlobal = require('./display/global.js'); var pdfjsDisplayAPI = require('./display/api.js'); var pdfjsDisplayTextLayer = require('./display/text_layer.js'); var pdfjsDisplayAnnotationLayer = require('./display/annotation_layer.js'); var pdfjsDisplayDOMUtils = require('./display/dom_utils.js'); var pdfjsDisplaySVG = require('./display/svg.js'); exports.PDFJS = pdfjsDisplayGlobal.PDFJS; exports.build = pdfjsDisplayAPI.build; exports.version = pdfjsDisplayAPI.version; exports.getDocument = pdfjsDisplayAPI.getDocument; exports.PDFDataRangeTransport = pdfjsDisplayAPI.PDFDataRangeTransport; exports.PDFWorker = pdfjsDisplayAPI.PDFWorker; exports.renderTextLayer = pdfjsDisplayTextLayer.renderTextLayer; exports.AnnotationLayer = pdfjsDisplayAnnotationLayer.AnnotationLayer; exports.CustomStyle = pdfjsDisplayDOMUtils.CustomStyle; exports.createPromiseCapability = pdfjsSharedUtil.createPromiseCapability; exports.PasswordResponses = pdfjsSharedUtil.PasswordResponses; exports.InvalidPDFException = pdfjsSharedUtil.InvalidPDFException; exports.MissingPDFException = pdfjsSharedUtil.MissingPDFException; exports.SVGGraphics = pdfjsDisplaySVG.SVGGraphics; exports.UnexpectedResponseException = pdfjsSharedUtil.UnexpectedResponseException; exports.OPS = pdfjsSharedUtil.OPS; exports.UNSUPPORTED_FEATURES = pdfjsSharedUtil.UNSUPPORTED_FEATURES; exports.isValidUrl = pdfjsDisplayDOMUtils.isValidUrl; exports.createValidAbsoluteUrl = pdfjsSharedUtil.createValidAbsoluteUrl; exports.createObjectURL = pdfjsSharedUtil.createObjectURL; exports.removeNullCharacters = pdfjsSharedUtil.removeNullCharacters; exports.shadow = pdfjsSharedUtil.shadow; exports.createBlob = pdfjsSharedUtil.createBlob; exports.RenderingCancelledException = pdfjsDisplayDOMUtils.RenderingCancelledException; exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl; exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes;
{ "content_hash": "218c25d09ce55b7c9e1d4ef2199bae4a", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 75, "avg_line_length": 48.56818181818182, "alnum_prop": 0.8437061300889097, "repo_name": "1and1/pdf.js", "id": "38fc452119f5b9fbb921f8af6b1e1008b566388b", "size": "2735", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pdf.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "55914" }, { "name": "HTML", "bytes": "44281" }, { "name": "JavaScript", "bytes": "2894167" } ], "symlink_target": "" }
toastr.options = { "toastClass": "toastr", "closeButton": true, "debug": false, "newestOnTop": true, "progressBar": true, "positionClass": "toast-top-full-width", "preventDuplicates": false, "onclick": null, "showDuration": "3000", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "3000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" };
{ "content_hash": "47b8f375875c34c7f9109efac5b35eef", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 44, "avg_line_length": 25.77777777777778, "alnum_prop": 0.5883620689655172, "repo_name": "HackerSir/CheckIn", "id": "ed4efda7657ccbc5ee63cd978f5c58f8b475a4a5", "size": "464", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "resources/js/options/toastr.js", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "665663" }, { "name": "PHP", "bytes": "691669" }, { "name": "Shell", "bytes": "1894" }, { "name": "Stylus", "bytes": "718" }, { "name": "Vue", "bytes": "47048" } ], "symlink_target": "" }
<?php namespace Drupal\webform\Controller; use Drupal\Core\Controller\ControllerBase; use Drupal\webform\Entity\WebformOptions; use Drupal\webform\WebformInterface; use Drupal\webform\WebformOptionsInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; /** * Provides route responses for webform options. */ class WebformOptionsController extends ControllerBase { /** * Returns response for the element autocompletion. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object containing the search string. * @param \Drupal\webform\WebformInterface $webform * A webform. * @param string $key * Webform element key. * * @return \Symfony\Component\HttpFoundation\JsonResponse * A JSON response containing the autocomplete suggestions. */ public function autocomplete(Request $request, WebformInterface $webform, $key) { $q = $request->query->get('q'); // Make sure the current user can access this webform. if (!$webform->access('view')) { return new JsonResponse([]); } // Get the webform element element. $elements = $webform->getElementsInitializedAndFlattened(); if (!isset($elements[$key])) { return new JsonResponse([]); } // Get the element's webform options. $element = $elements[$key]; $element['#options'] = $element['#autocomplete']; $options = WebformOptions::getElementOptions($element); if (empty($options)) { return new JsonResponse([]); } // Filter and convert options to autocomplete matches. $matches = []; $this->appendOptionsToMatchesRecursive($q, $options, $matches); return new JsonResponse($matches); } /** * Append webform options to autocomplete matches. * * @param string $q * String to filter option's label by. * @param array $options * An associative array of webform options. * @param array $matches * An associative array of autocomplete matches. */ protected function appendOptionsToMatchesRecursive($q, array $options, array &$matches) { foreach ($options as $value => $label) { if (is_array($label)) { $this->appendOptionsToMatchesRecursive($q, $label, $matches); } elseif (stripos($label, $q) !== FALSE) { $matches[] = [ 'value' => $value, 'label' => $label, ]; } } } /** * Route title callback. * * @param \Drupal\webform\WebformOptionsInterface $webform_options * The webform options. * * @return string * The webform options label as a render array. */ public function title(WebformOptionsInterface $webform_options) { return $webform_options->label(); } }
{ "content_hash": "8503f60a005adc3d3f700cc3685a160c", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 91, "avg_line_length": 29.31578947368421, "alnum_prop": 0.6664272890484739, "repo_name": "kgatjens/d8_vm_vagrant", "id": "06df154a21e4a5420a680eee32d185f5da3e53c5", "size": "2785", "binary": false, "copies": "44", "ref": "refs/heads/master", "path": "project/modules/contrib/webform/src/Controller/WebformOptionsController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "9038" }, { "name": "CSS", "bytes": "962176" }, { "name": "HTML", "bytes": "1769288" }, { "name": "JavaScript", "bytes": "1302117" }, { "name": "PHP", "bytes": "40520904" }, { "name": "PLpgSQL", "bytes": "2020" }, { "name": "PowerShell", "bytes": "471" }, { "name": "Ruby", "bytes": "6985" }, { "name": "Shell", "bytes": "85027" } ], "symlink_target": "" }
import {isEqual, uniq} from 'lodash' import {EventType, HistoryEvent, Transaction, Mutation} from './types' import {ndjsonToArray} from './utils/ndjsonToArray' const EDIT_EVENT_TIME_TRESHHOLD_MS = 1000 * 60 * 5 // 5 minutes export function transactionsToEvents( documentIds: string[], transactions: string | Buffer | Transaction[] ): HistoryEvent[] { const rawItems = Array.isArray(transactions) ? transactions : ndjsonToArray(transactions) return ( rawItems // Make sure we only deal with transactions that are relevant for our documents .filter( (transaction: Transaction) => transaction.documentIDs && transaction.documentIDs.some((id) => documentIds.includes(id)) ) // ensure transactions are sorted by time .sort(compareTimestamp) // Turn a transaction into a classified HistoryEvent .map((transaction, index) => mapToEvents(transaction, documentIds, index)) // Chunk and group edit events .reduce(reduceEdits, []) // Manipulate truncation events to be able to restore to published version .reduce(createReduceTruncatedFn(), []) ) } function mapToEvents(transaction: Transaction, documentIds: string[], index = 0): HistoryEvent { const {type, documentId} = mutationsToEventTypeAndDocumentId( filterRelevantMutations(transaction.mutations, documentIds), index ) const timestamp = transaction.timestamp const userIds = findUserIds(transaction, type) return { type, documentIDs: transaction.documentIDs, displayDocumentId: documentId, rev: transaction.id, userIds, transactionIds: [transaction.id], startTime: timestamp, endTime: timestamp, } } function reduceEdits( acc: HistoryEvent[], current: HistoryEvent, index: number, arr: HistoryEvent[] ) { const nextEvent = arr[index + 1] const skipEvent = current.type === 'edited' && nextEvent && nextEvent.type === 'edited' && new Date(nextEvent.endTime).getTime() - new Date(current.endTime).getTime() < EDIT_EVENT_TIME_TRESHHOLD_MS && isEqual(current.documentIDs, nextEvent.documentIDs) if (skipEvent) { // Lift authors over to next event nextEvent.userIds = uniq(nextEvent.userIds.concat(current.userIds)) // Lift list of transactions over to next event nextEvent.transactionIds = uniq(current.transactionIds.concat(nextEvent.transactionIds)) // Set startTime on next event to be this one if not done already // (then startTime and endTime would be different) if (current.startTime === current.endTime) { nextEvent.startTime = current.startTime } } else { acc.push(current) } return acc } function createReduceTruncatedFn() { let truncated: HistoryEvent[] | undefined return (acc: HistoryEvent[], current: HistoryEvent, index: number, arr: HistoryEvent[]) => { truncated = truncated || arr.filter((event) => event.type === 'truncated') if (!truncated.includes(current)) { acc.push(current) } if (index === arr.length - 1) { const draftTruncationEvent = truncated.find( (evt) => !!evt.displayDocumentId && evt.displayDocumentId.startsWith('drafts.') ) const publishedTruncationEvent = truncated.find( (evt) => !!evt.displayDocumentId && !evt.displayDocumentId.startsWith('drafts.') ) if (draftTruncationEvent && publishedTruncationEvent) { acc.unshift({...draftTruncationEvent, type: 'edited'}) acc.unshift(publishedTruncationEvent) } else if (publishedTruncationEvent) { acc.unshift(publishedTruncationEvent) } else if (draftTruncationEvent) { acc.unshift(draftTruncationEvent) } } return acc } } export function mutationsToEventTypeAndDocumentId( mutations: Mutation[], transactionIndex: number ): {type: EventType; documentId: string | null} { const withoutPatches = mutations.filter((mut) => mut.patch === undefined) const createOrReplaceMutation = withoutPatches.find((mut) => mut.createOrReplace !== undefined) const createOrReplacePatch = createOrReplaceMutation && createOrReplaceMutation.createOrReplace const createMutation = withoutPatches.find((mut) => mut.create !== undefined) const createPatch = createMutation && createMutation.create const createIfNotExistsMutation = withoutPatches.find( (mut) => mut.createIfNotExists !== undefined ) const createIfNotExistsPatch = createIfNotExistsMutation && createIfNotExistsMutation.createIfNotExists const deleteMutation = withoutPatches.find((mut) => mut.delete !== undefined) const deletePatch = deleteMutation && deleteMutation.delete const squashedMutation = withoutPatches.find((mut) => mut.createSquashed !== undefined) const squashedPatch = squashedMutation && squashedMutation.createSquashed const createValue = createOrReplacePatch || createPatch || createIfNotExistsPatch // Created if (transactionIndex === 0) { const type = 'created' if (createOrReplacePatch) { return {type, documentId: createOrReplacePatch._id} } if (createIfNotExistsPatch) { return {type, documentId: createIfNotExistsPatch._id} } if (createPatch) { return {type, documentId: createPatch._id} } } // (re) created if (transactionIndex > 0 && mutations.length === 1 && createIfNotExistsPatch) { const type = createIfNotExistsPatch._id.startsWith('.draft') ? 'edited' : 'published' return {type, documentId: createIfNotExistsPatch._id} } // Published if ( (createOrReplacePatch || createPatch || createIfNotExistsPatch) && deletePatch && deletePatch.id.startsWith('drafts.') ) { return { type: 'published', documentId: (createValue && createValue._id) || null, } } // Unpublished if ( withoutPatches.length === 2 && (createIfNotExistsPatch || createPatch) && deletePatch && !deletePatch.id.startsWith('drafts.') ) { return { type: 'unpublished', documentId: (createValue && createValue._id) || null, } } // Restored to previous version if ( (createOrReplacePatch && createOrReplacePatch._id.startsWith('drafts.')) || (createPatch && createPatch._id.startsWith('drafts.')) || (createIfNotExistsPatch && createIfNotExistsPatch._id.startsWith('drafts.')) ) { return { type: 'edited', documentId: (createValue && createValue._id) || null, } } // Discard drafted changes if (mutations.length === 1 && deletePatch && deletePatch.id.startsWith('drafts.')) { return {type: 'discardDraft', documentId: deletePatch.id.replace('drafts.', '')} } // Truncated history if (mutations.length === 1 && squashedPatch) { return {type: 'truncated', documentId: squashedPatch.document._id} } // Deleted if (mutations.every((mut) => mut.delete !== undefined)) { return {type: 'deleted', documentId: null} } // Edited const patchedMutation = mutations.find((mut) => mut.patch !== undefined) if (patchedMutation && patchedMutation.patch) { return {type: 'edited', documentId: patchedMutation.patch.id} } // Edited (createOrReplace) if (createOrReplacePatch) { return {type: 'edited', documentId: createOrReplacePatch._id} } return {type: 'unknown', documentId: null} } function findUserIds(transaction: Transaction, type: EventType): string[] { // The truncated event is kind of special if (type === 'truncated') { const createSquasedMut = transaction.mutations.find((mut) => mut.createSquashed !== undefined) const createSquasedPatch = createSquasedMut && createSquasedMut.createSquashed if (createSquasedPatch) { return createSquasedPatch.authors } } // Default is to return the transaction author return [transaction.author] } function compareTimestamp(a: Transaction, b: Transaction) { return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime() } function filterRelevantMutations(mutations: Mutation[], documentIds: string[]) { return mutations.filter((mut) => { return Object.keys(mut) .map((key) => { const val = (mut as any)[key] return val.id || val._id || (val.document && val.document._id) || false }) .some((id) => id && documentIds.includes(id)) }) }
{ "content_hash": "36cac2b65875c08f49a85cc23c19fc62", "timestamp": "", "source": "github", "line_count": 243, "max_line_length": 99, "avg_line_length": 34.13168724279836, "alnum_prop": 0.6880877742946708, "repo_name": "sanity-io/sanity", "id": "4ddcbd692a3e49096b85e1df41f0757bbaaf6a33", "size": "8294", "binary": false, "copies": "1", "ref": "refs/heads/next", "path": "packages/@sanity/transaction-collator/src/transactionsToEvents.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "235048" }, { "name": "HTML", "bytes": "181261" }, { "name": "JavaScript", "bytes": "1485414" }, { "name": "Shell", "bytes": "1303" }, { "name": "TypeScript", "bytes": "3980581" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace bv.model.Model { public static class ExprUtils { public static long? LongFromString(string str) { long ret = 0; if (long.TryParse(str, out ret)) return ret; return null; } public static string StringFromObject(object val) { if (val == null) return null; if (val is DBNull) return null; return Convert.ToString(val); } /*public static TRet Fold<TSource, TRet>(this IEnumerable<TSource> source, Func<TSource, TRet> func) where TRet : struct { TRet ret = new TRet(); foreach (TSource s in source) ret = func(s); return ret; }*/ } }
{ "content_hash": "68ea23e6a09cbd596351e6517cb4c9e7", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 108, "avg_line_length": 26.757575757575758, "alnum_prop": 0.5232163080407701, "repo_name": "EIDSS/EIDSS-Legacy", "id": "16bf8e3bf25de53b267e59fe53f9eb590fea5bec", "size": "885", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "EIDSS v6.1/bv.model/Model/ExprUtils.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "256377" }, { "name": "Batchfile", "bytes": "30009" }, { "name": "C#", "bytes": "106160789" }, { "name": "CSS", "bytes": "833586" }, { "name": "HTML", "bytes": "7507" }, { "name": "Java", "bytes": "2188690" }, { "name": "JavaScript", "bytes": "17000221" }, { "name": "PLSQL", "bytes": "2499" }, { "name": "PLpgSQL", "bytes": "6422" }, { "name": "Pascal", "bytes": "159898" }, { "name": "PowerShell", "bytes": "339522" }, { "name": "Puppet", "bytes": "3758" }, { "name": "SQLPL", "bytes": "12198" }, { "name": "Smalltalk", "bytes": "301266" }, { "name": "Visual Basic", "bytes": "20819564" }, { "name": "XSLT", "bytes": "4253600" } ], "symlink_target": "" }
import itertools import json import re import subprocess import xml.etree.ElementTree as ET from collections import defaultdict from dataclasses import dataclass, field from pathlib import Path from typing import Set RESULT = Path(__file__).parent / "../corpus/aosp.json" DOWNLOADS = Path(__file__).parent / "../repos" # List below generated by running the following snippet in the DevTools console # on the following page: # https://android.googlesource.com/ # console.log(Array.from(document.querySelectorAll( # "a.RepoList-item[href*='/platform/packages/apps/']" # )).map(a=>` ( # "${a.href.split('/').reverse()[1]}", # "${a.href}", # ),`).join('\n')) APP_GIT_REPOS = [ ( "AccountsAndSyncSettings", "https://android.googlesource.com/platform/packages/apps/AccountsAndSyncSettings/", # noqa: E501 ), ( "AlarmClock", "https://android.googlesource.com/platform/packages/apps/AlarmClock/", ), ( "BasicSmsReceiver", "https://android.googlesource.com/platform/packages/apps/BasicSmsReceiver/", ), ( "Benchmark", "https://android.googlesource.com/platform/packages/apps/Benchmark/", ), ( "Bluetooth", "https://android.googlesource.com/platform/packages/apps/Bluetooth/", ), ( "Browser", "https://android.googlesource.com/platform/packages/apps/Browser/", ), ( "Browser2", "https://android.googlesource.com/platform/packages/apps/Browser2/", ), ( "Calculator", "https://android.googlesource.com/platform/packages/apps/Calculator/", ), ( "Calendar", "https://android.googlesource.com/platform/packages/apps/Calendar/", ), ( "Camera", "https://android.googlesource.com/platform/packages/apps/Camera/", ), ( "Camera2", "https://android.googlesource.com/platform/packages/apps/Camera2/", ), ( "Calendar", "https://android.googlesource.com/platform/packages/apps/Car/Calendar/", ), ( "Cluster", "https://android.googlesource.com/platform/packages/apps/Car/Cluster/", ), ( "CompanionDeviceSupport", "https://android.googlesource.com/platform/packages/apps/Car/CompanionDeviceSupport/", # noqa: E501 ), ( "Dialer", "https://android.googlesource.com/platform/packages/apps/Car/Dialer/", ), ( "externallibs", "https://android.googlesource.com/platform/packages/apps/Car/externallibs/", ), ( "Hvac", "https://android.googlesource.com/platform/packages/apps/Car/Hvac/", ), ( "LatinIME", "https://android.googlesource.com/platform/packages/apps/Car/LatinIME/", ), ( "Launcher", "https://android.googlesource.com/platform/packages/apps/Car/Launcher/", ), ( "LensPicker", "https://android.googlesource.com/platform/packages/apps/Car/LensPicker/", ), ( "libs", "https://android.googlesource.com/platform/packages/apps/Car/libs/", ), ( "LinkViewer", "https://android.googlesource.com/platform/packages/apps/Car/LinkViewer/", ), ( "LocalMediaPlayer", "https://android.googlesource.com/platform/packages/apps/Car/LocalMediaPlayer/", ), ( "Media", "https://android.googlesource.com/platform/packages/apps/Car/Media/", ), ( "Messenger", "https://android.googlesource.com/platform/packages/apps/Car/Messenger/", ), ( "Notification", "https://android.googlesource.com/platform/packages/apps/Car/Notification/", ), ( "Overview", "https://android.googlesource.com/platform/packages/apps/Car/Overview/", ), ( "Provision", "https://android.googlesource.com/platform/packages/apps/Car/Provision/", ), ( "Radio", "https://android.googlesource.com/platform/packages/apps/Car/Radio/", ), ( "RotaryController", "https://android.googlesource.com/platform/packages/apps/Car/RotaryController/", ), ( "Settings", "https://android.googlesource.com/platform/packages/apps/Car/Settings/", ), ( "Stream", "https://android.googlesource.com/platform/packages/apps/Car/Stream/", ), ( "SystemUpdater", "https://android.googlesource.com/platform/packages/apps/Car/SystemUpdater/", ), ( "Templates", "https://android.googlesource.com/platform/packages/apps/Car/Templates/", ), ( "tests", "https://android.googlesource.com/platform/packages/apps/Car/tests/", ), ( "UserManagement", "https://android.googlesource.com/platform/packages/apps/Car/UserManagement/", ), ( "CarrierConfig", "https://android.googlesource.com/platform/packages/apps/CarrierConfig/", ), ( "CellBroadcastReceiver", "https://android.googlesource.com/platform/packages/apps/CellBroadcastReceiver/", ), ( "CertInstaller", "https://android.googlesource.com/platform/packages/apps/CertInstaller/", ), ( "Contacts", "https://android.googlesource.com/platform/packages/apps/Contacts/", ), ( "ContactsCommon", "https://android.googlesource.com/platform/packages/apps/ContactsCommon/", ), ( "DeskClock", "https://android.googlesource.com/platform/packages/apps/DeskClock/", ), ( "DevCamera", "https://android.googlesource.com/platform/packages/apps/DevCamera/", ), ( "Dialer", "https://android.googlesource.com/platform/packages/apps/Dialer/", ), ( "DocumentsUI", "https://android.googlesource.com/platform/packages/apps/DocumentsUI/", ), ( "Email", "https://android.googlesource.com/platform/packages/apps/Email/", ), ( "EmergencyInfo", "https://android.googlesource.com/platform/packages/apps/EmergencyInfo/", ), ( "ExactCalculator", "https://android.googlesource.com/platform/packages/apps/ExactCalculator/", ), ( "Exchange", "https://android.googlesource.com/platform/packages/apps/Exchange/", ), ( "FMRadio", "https://android.googlesource.com/platform/packages/apps/FMRadio/", ), ( "Gallery", "https://android.googlesource.com/platform/packages/apps/Gallery/", ), ( "Gallery2", "https://android.googlesource.com/platform/packages/apps/Gallery2/", ), ( "Gallery3D", "https://android.googlesource.com/platform/packages/apps/Gallery3D/", ), ( "GlobalSearch", "https://android.googlesource.com/platform/packages/apps/GlobalSearch/", ), ( "GoogleSearch", "https://android.googlesource.com/platform/packages/apps/GoogleSearch/", ), ( "HTMLViewer", "https://android.googlesource.com/platform/packages/apps/HTMLViewer/", ), ( "IdentityCredentialSupport", "https://android.googlesource.com/platform/packages/apps/IdentityCredentialSupport/", # noqa: E501 ), ( "IM", "https://android.googlesource.com/platform/packages/apps/IM/", ), ( "ImsServiceEntitlement", "https://android.googlesource.com/platform/packages/apps/ImsServiceEntitlement/", ), ( "InCallUI", "https://android.googlesource.com/platform/packages/apps/InCallUI/", ), ( "KeyChain", "https://android.googlesource.com/platform/packages/apps/KeyChain/", ), ( "Launcher", "https://android.googlesource.com/platform/packages/apps/Launcher/", ), ( "Launcher2", "https://android.googlesource.com/platform/packages/apps/Launcher2/", ), ( "Launcher3", "https://android.googlesource.com/platform/packages/apps/Launcher3/", ), ( "LegacyCamera", "https://android.googlesource.com/platform/packages/apps/LegacyCamera/", ), ( "ManagedProvisioning", "https://android.googlesource.com/platform/packages/apps/ManagedProvisioning/", ), ( "McLauncher", "https://android.googlesource.com/platform/packages/apps/McLauncher/", ), ( "Messaging", "https://android.googlesource.com/platform/packages/apps/Messaging/", ), ( "Mms", "https://android.googlesource.com/platform/packages/apps/Mms/", ), ( "Music", "https://android.googlesource.com/platform/packages/apps/Music/", ), ( "MusicFX", "https://android.googlesource.com/platform/packages/apps/MusicFX/", ), ( "Nfc", "https://android.googlesource.com/platform/packages/apps/Nfc/", ), ( "OnDeviceAppPrediction", "https://android.googlesource.com/platform/packages/apps/OnDeviceAppPrediction/", ), ( "OneTimeInitializer", "https://android.googlesource.com/platform/packages/apps/OneTimeInitializer/", ), ( "PackageInstaller", "https://android.googlesource.com/platform/packages/apps/PackageInstaller/", ), ( "Phone", "https://android.googlesource.com/platform/packages/apps/Phone/", ), ( "PhoneCommon", "https://android.googlesource.com/platform/packages/apps/PhoneCommon/", ), ( "Protips", "https://android.googlesource.com/platform/packages/apps/Protips/", ), ( "Provision", "https://android.googlesource.com/platform/packages/apps/Provision/", ), ( "QuickAccessWallet", "https://android.googlesource.com/platform/packages/apps/QuickAccessWallet/", ), ( "QuickSearchBox", "https://android.googlesource.com/platform/packages/apps/QuickSearchBox/", ), ( "RemoteProvisioner", "https://android.googlesource.com/platform/packages/apps/RemoteProvisioner/", ), ( "RetailDemo", "https://android.googlesource.com/platform/packages/apps/RetailDemo/", ), ( "SafetyRegulatoryInfo", "https://android.googlesource.com/platform/packages/apps/SafetyRegulatoryInfo/", ), ( "SampleLocationAttribution", "https://android.googlesource.com/platform/packages/apps/SampleLocationAttribution/", # noqa: E501 ), ( "SecureElement", "https://android.googlesource.com/platform/packages/apps/SecureElement/", ), ( "Settings", "https://android.googlesource.com/platform/packages/apps/Settings/", ), ( "SettingsIntelligence", "https://android.googlesource.com/platform/packages/apps/SettingsIntelligence/", ), ( "SmartCardService", "https://android.googlesource.com/platform/packages/apps/SmartCardService/", ), ( "SoundRecorder", "https://android.googlesource.com/platform/packages/apps/SoundRecorder/", ), ( "SpareParts", "https://android.googlesource.com/platform/packages/apps/SpareParts/", ), ( "SpeechRecorder", "https://android.googlesource.com/platform/packages/apps/SpeechRecorder/", ), ( "Stk", "https://android.googlesource.com/platform/packages/apps/Stk/", ), ( "StorageManager", "https://android.googlesource.com/platform/packages/apps/StorageManager/", ), ( "Sync", "https://android.googlesource.com/platform/packages/apps/Sync/", ), ( "Tag", "https://android.googlesource.com/platform/packages/apps/Tag/", ), ( "Terminal", "https://android.googlesource.com/platform/packages/apps/Terminal/", ), ( "connectivity", "https://android.googlesource.com/platform/packages/apps/Test/connectivity/", ), ( "ThemePicker", "https://android.googlesource.com/platform/packages/apps/ThemePicker/", ), ( "TimeZoneData", "https://android.googlesource.com/platform/packages/apps/TimeZoneData/", ), ( "TimeZoneUpdater", "https://android.googlesource.com/platform/packages/apps/TimeZoneUpdater/", ), ( "Traceur", "https://android.googlesource.com/platform/packages/apps/Traceur/", ), ( "TV", "https://android.googlesource.com/platform/packages/apps/TV/", ), ( "TvSettings", "https://android.googlesource.com/platform/packages/apps/TvSettings/", ), ( "UnifiedEmail", "https://android.googlesource.com/platform/packages/apps/UnifiedEmail/", ), ( "UniversalMediaPlayer", "https://android.googlesource.com/platform/packages/apps/UniversalMediaPlayer/", ), ( "Updater", "https://android.googlesource.com/platform/packages/apps/Updater/", ), ( "VideoEditor", "https://android.googlesource.com/platform/packages/apps/VideoEditor/", ), ( "VoiceDialer", "https://android.googlesource.com/platform/packages/apps/VoiceDialer/", ), ( "WallpaperPicker", "https://android.googlesource.com/platform/packages/apps/WallpaperPicker/", ), ( "WallpaperPicker2", "https://android.googlesource.com/platform/packages/apps/WallpaperPicker2/", ), ] @dataclass class Source: apps: Set[str] = field(default_factory=set) langs: Set[str] = field(default_factory=set) def main(): download_sources() strings = defaultdict(Source) for app, lang, sentences in glob_read_strings_files(): for sentence in sentences: strings[sentence].apps.add(app) strings[sentence].langs.add(lang) with open(RESULT, "w", encoding="utf-8") as fp: json.dump( dict( sorted( ( string, {"apps": sorted(source.apps), "langs": sorted(source.langs)}, ) for string, source in strings.items() ) ), fp, ensure_ascii=False, indent=2, ) def download_sources(): for _name, repo in APP_GIT_REPOS: folder = DOWNLOADS / Path(repo).name folder.parent.mkdir(parents=True, exist_ok=True) if not folder.exists(): git("clone", "--depth", "1", repo, folder) def glob_read_strings_files(): for name, repo in APP_GIT_REPOS: folder = DOWNLOADS / Path(repo).name # Doc: https://developer.android.com/guide/topics/resources/string-resource for path in folder.glob("**/strings.xml"): lang = "en" if match := re.match(r".*values-([^/\\]*)", str(path)): lang = match.group(1) # Some locales contain garbage data. if "en-rXC" in lang: continue sentences = [] tree = ET.parse(path) root = tree.getroot() for string in itertools.chain( root.findall(".//string"), root.findall(".//item") ): for xliff_g in string.findall( "./{urn:oasis:names:tc:xliff:document:1.2}g" ): # Replace placeholders with example value if provided, otherwise kill xliff_g.text = xliff_g.attrib.get("example", "") s = "".join(string.itertext()) # Unquote. Each string might have several quoted bits s = "".join( part[1:-1] if part and (part[0] == part[-1] == '"') else # Collapse whitespace in unquoted bits re.sub(r"\s+", " ", part) # Split string. The "delimiters" are quoted bits, that start # and end with an unescaped double quote. There's a capturing # group around the whole expression so that the delimiters # are kept in the output. for part in re.split(r'((?<!\\)"(?:[^"]|\\"|\n)*(?<!\\)")', s) ) # Unescape various things s = re.sub(r"""\\([@?nt'"]|u[0-9A-Fa-f]{4})""", unescape, s) # Split by lines and strip each # We're only interested in continuous lines (no breaks) for # kerning measurement purposes. for line in s.split("\n"): line = line.strip() if line: sentences.append(line) yield name, lang, sentences def unescape(m): g = m.group(1) if g[0] == "u": return chr(int(g[1:], base=16)) elif g == "n": return "\n" elif g == "t": return "\t" return g def git(*args): """Execute the given git command and return the output.""" return subprocess.check_output(["git", *args]) if __name__ == "__main__": main()
{ "content_hash": "e558bc0f32ac9523d01d531b4cf9e78e", "timestamp": "", "source": "github", "line_count": 572, "max_line_length": 108, "avg_line_length": 30.286713286713287, "alnum_prop": 0.57486723620411, "repo_name": "googlefonts/aosp-test-texts", "id": "dd2b0a99c1f9c88b5732276bfd676959fb9a93ca", "size": "17896", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/extract_strings.py", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
use support::assert_bind_eq; #[test] fn typedef_same_name() { assert_bind_eq(Default::default(), "headers/typedef_same_name.h", " pub enum SameS { } pub enum SameE { } pub enum SameU { } "); }
{ "content_hash": "790208c3e8b90f38ddc26c59128aab9d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 71, "avg_line_length": 22.9, "alnum_prop": 0.5589519650655022, "repo_name": "Twinklebear/rust-bindgen", "id": "c209adcf1e5abea99632751ab97d555a112399a9", "size": "229", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_typedef.rs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "6017" }, { "name": "C++", "bytes": "773" }, { "name": "Objective-C", "bytes": "81" }, { "name": "Rust", "bytes": "192438" }, { "name": "Shell", "bytes": "1745" } ], "symlink_target": "" }
DocaLabs-Utils ==============
{ "content_hash": "57b122add0fd98566c22f32441be2f76", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 14, "avg_line_length": 14.5, "alnum_prop": 0.4482758620689655, "repo_name": "alexey-kadyrov/DocaLabs-Utils", "id": "91ff28e9d772c015cb0896e142b1cc2bffa4298b", "size": "29", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "725306" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; fce8767c-fba7-4e1d-b13a-bb703f975a7e </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#Microsoft.Azure.Engagement.EngagementAgent.Portable">Microsoft.Azure.Engagement.EngagementAgent.Portable</a></strong></td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> </tr> </tbody> </table> </div> <div id="details"> </div> </div> </body> </html>
{ "content_hash": "403e053c52d480c5a82fec538e6a143b", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 562, "avg_line_length": 40.4875, "alnum_prop": 0.5760008232993722, "repo_name": "kuhlenh/port-to-core", "id": "266d22590c940b9ab18559dc997ab18fd32635c4", "size": "9717", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/mi/microsoftazure.mobileengagement.3.1.0/Microsoft.Azure.Engagement.EngagementAgent.Portable-win80.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "7574bd19ebe8cb35342da93701fa08cd", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "4f8a17905ae4978c75204bb1b599ac5e9176d00b", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Cryptantha/Cryptantha vidali/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rl_home_get_limit" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/ripple_nav_bg" android:padding="16dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_home_limit" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:text="预估额度" android:textColor="@color/black5" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center_horizontal" android:orientation="vertical"> <me.bakumon.numberanimtextview.NumberAnimTextView android:id="@+id/natv_limit_money" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="500" android:textColor="@color/v5_golden_dark" android:textSize="40sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="金额(元)" android:textColor="@color/v5_gray" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:background="@drawable/bg_border_gold" android:paddingBottom="8dp" android:paddingLeft="12dp" android:paddingRight="12dp" android:paddingTop="8dp" android:text="立即提额" android:textColor="@color/v5_golden_dark" android:textSize="12sp" /> </RelativeLayout>
{ "content_hash": "edab2afa06d945621b3ebcb29a2c4235", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 74, "avg_line_length": 35.43076923076923, "alnum_prop": 0.6257056013894919, "repo_name": "rooney0928/qnd2", "id": "6b1aff9b6a9bd1c6c0df5dd12121c27a0e7e646e", "size": "2325", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/layout_home_limit.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "593" }, { "name": "Java", "bytes": "1576065" }, { "name": "Kotlin", "bytes": "91" } ], "symlink_target": "" }
package com.facebook.buck.io.filesystem; /** * A wrapper around two ProjectFilesystemDelegates where generalDelegate is the typical delegate * that is used and buckOutDelegate is the delegate used in the case where we know we're running in * a buck-out directory, so we can skip the usual check if we're in an Eden mounted directory. */ public class ProjectFilesystemDelegatePair { private final ProjectFilesystemDelegate generalDelegate; private final ProjectFilesystemDelegate buckOutDelegate; public ProjectFilesystemDelegatePair( ProjectFilesystemDelegate defaultDelegate, ProjectFilesystemDelegate buckOutDelegate) { this.generalDelegate = defaultDelegate; this.buckOutDelegate = buckOutDelegate; } public ProjectFilesystemDelegate getGeneralDelegate() { return generalDelegate; } public ProjectFilesystemDelegate getBuckOutDelegate() { return buckOutDelegate; } }
{ "content_hash": "dc7ab279c61690345c13a5f149cc5c11", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 99, "avg_line_length": 32.82142857142857, "alnum_prop": 0.7976060935799782, "repo_name": "facebook/buck", "id": "fb4bee69590467980e5b3d858c0e1207574dfb9e", "size": "1535", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "src/com/facebook/buck/io/filesystem/ProjectFilesystemDelegatePair.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1796" }, { "name": "C", "bytes": "250514" }, { "name": "CSS", "bytes": "56119" }, { "name": "Dockerfile", "bytes": "2559" }, { "name": "HTML", "bytes": "501" }, { "name": "Java", "bytes": "33678299" }, { "name": "JavaScript", "bytes": "931240" }, { "name": "Kotlin", "bytes": "25953" }, { "name": "Lex", "bytes": "14469" }, { "name": "Makefile", "bytes": "1704" }, { "name": "PowerShell", "bytes": "2154" }, { "name": "Python", "bytes": "766764" }, { "name": "Shell", "bytes": "39846" }, { "name": "Smalltalk", "bytes": "5432" }, { "name": "Starlark", "bytes": "1409831" }, { "name": "Thrift", "bytes": "18470" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace HttpClient; use HttpClient\Uri\Uri; use PHPUnit\Framework\TestCase; final class HeadersTest extends TestCase { public function testSetHeaders(): void { $headersCollection = ['bar' => 'baz']; $headers = new Headers(new Uri('http://foo.com'), $headersCollection); $this->assertEquals( ['bar' => ['baz']], $headers->getHeaders() ); $headersCollection = ['bar' => 'baz']; $newHeadersCollection = ['foo' => 'bar']; $headers = new Headers(new Uri('http://foo.com'), $headersCollection); $headers->setHeaders($newHeadersCollection); $this->assertEquals( ['foo' => ['bar']], $headers->getHeaders() ); } public function testMapHeaders(): void { $headersCollection = ['bar' => 'baz']; $headers = new Headers(new Uri('http://foo.com'), $headersCollection); $this->assertEquals( ['bar: baz'], $headers->map() ); } public function testSetHeader(): void { $headers = new Headers(new Uri('http://foo.com'), []); $headers->setHeader('bar', 'baz'); $this->assertEquals( ['baz'], $headers->getHeader('bar') ); } public function testRemoveHeader(): void { $headersCollection = [ 'bar' => 'baz', 'foo' => 'bar', ]; $headers = new Headers(new Uri('http://foo.com'), $headersCollection); $headers->removeHeader('bar'); $this->assertEquals( ['foo' => ['bar']], $headers->getHeaders() ); } public function testSetHost(): void { $headers = new Headers(new Uri('http://foo.com'), []); $headers->setHost('bar.com'); $this->assertEquals( ['bar.com'], $headers->getHeader('Host') ); } }
{ "content_hash": "244e3cb36038755bba09d1f87b7f2fdb", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 78, "avg_line_length": 24.49397590361446, "alnum_prop": 0.4923757993113625, "repo_name": "andrewprofile/http-client", "id": "ff897f8c31cbeaf3f1f4f728e5aa4fbd258848a0", "size": "2267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/HeadersTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "84271" } ], "symlink_target": "" }
Meteor.publishComposite("customListEdit", function(_id) { return { find: function() { return CustomLists.find({_id: _id}); }, children: [{ find: function(customList) { var ids = _.pluck(customList.entries, 'contentId'); switch (customList.type) { case "anime": return Anime.find({_id: {$in: ids}}); case "characters": return Characters.find({_id: {$in: ids}}); case "people": return People.find({_id: {$in: ids}}); } } }] }; });
{ "content_hash": "247cf30490a168004b3a209723843646", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 57, "avg_line_length": 21.52173913043478, "alnum_prop": 0.5676767676767677, "repo_name": "phanime/phanime", "id": "5ba270016ca147e11a78995ca858bce160846ad5", "size": "495", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "server/publications/customList/customListEdit.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23381" }, { "name": "HTML", "bytes": "188029" }, { "name": "JavaScript", "bytes": "303596" }, { "name": "Shell", "bytes": "76" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <!--- Copyright 2009 Roman Nurik 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. --> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>EverRemind</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <script type="text/javascript" src="/static/lib/jquery.scrollTo-1.4.2-min.js"></script> <script type="text/javascript" src="/static/lib/microtemplate.js"></script> <script type="text/javascript" src="/static/js/frontV3.js"></script> <script type="text/javascript" src="/static/js/calendar.js"></script> <script type="text/javascript" src="/static/js/custom-form-elements.js"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> // load the Google data JS Client Library google.load('gdata', '2.x'); // This is the url for the user's default calendar var EVENT_FEED_URL = 'https://www.google.com/calendar/feeds/default/private/full'; var noteresults; // This variable is used for retrieving and adding events var calendarService; window.onload = Custom.init; /** * This function checks if the user is logged in, * and changes the login button and displayed sections accordingly. * It also initializes the calendarService variable * and calls a function to fill in the form based on the URL. */ function init() { var token = google.accounts.user.checkLogin(EVENT_FEED_URL); var authButton = document.getElementById('auth_button'); if (google.accounts.user.checkLogin(EVENT_FEED_URL)) { authButton.value = 'Logout'; calendarService = new google.gdata.calendar.CalendarService('evernote-remind'); //document.getElementById('upcomingBirthdays').style.display = 'block'; // document.getElementById('save_button').style.display = 'block'; //getEvents(); } else { document.getElementById('loginNotice').style.display = 'block'; authButton.value = 'Login'; } }; // Tells the google JS lib to call the init function once loaded google.setOnLoadCallback(init); var callback = function (result) { //document.getElementById('panel').innerHTML = "event created" } var handleError = function (error) { //document.getElementById('panel').innerHTML = "event not created" } function getDone() { var searchParameters = { type: $('#querytype').val() }; // Perform proximity or bounds search. var startTime = new Date().getTime(); $.ajax({ url: '/s/getDone', type: 'get', data: searchParameters, dataType: 'json', error: function(xhr, textStatus) { alert(xhr.responseText) var responseTime = new Date().getTime() - startTime; //alert( xhr.responseText); var responseObj; eval('responseObj=' + xhr.responseText); alert(textStatus); logResult(options, { error: 'Internal error: ' + responseObj.error.message, responseTime: responseTime }); }, success: function(obj) { // alert(xhr.responseText) var responseTime = new Date().getTime() - startTime; clearResults(); if (obj.status && obj.status == 'success') { noteresults = obj.results; for (var key in obj.results){ logResult(searchParameters, { title: obj.results[key].title, created: EpochToHuman(obj.results[key].created) }); } } else { logResult(searchParameters, { error: 'Internal error: ' + obj.error.message, responseTime: responseTime }); } } }); } function runCustomTest() { runTest({ tag: $('#tag').val(), type: $('#querytype').val() }); } function addReminder() { document.getElementById('panel').innerHTML = "reminder adding" var feedUri = 'http://www.google.com/calendar/feeds/default/private/full'; var title = 'test'; var where = 'here'; var content = 'blah'; var startTime = '2011-07-18T18:00:00.000Z'; var endTime = '2011-07-18T19:00:00.000Z'; var reminder = new google.gdata.Reminder(); // Set the reminder to be 30 minutes prior the event start time reminder.setMinutes($('#minutes').val()); // Set the reminder method to be 'alert', a pop up alert on the browser reminder.setMethod(google.gdata.Reminder.METHOD_ALERT); var newEvent = new google.gdata.calendar.CalendarEventEntry({ title: {type: 'text', text: title}, content: {type: 'text', text: content}, locations: [ { rel: 'g.event', label: 'Event location', valueString: where }], times: [ { startTime: google.gdata.DateTime.fromIso8601(startTime), endTime: google.gdata.DateTime.fromIso8601(endTime) }] } ); newEvent.addReminder({minutes: $('#minutes').val(), method: google.gdata.Reminder.METHOD_EMAIL}); calendarService.getEventsFeed( feedUri, function(root) { root.feed.insertEntry( newEvent, function(root) { alert('event is inserted!'); }, handleError ); }, handleError ); document.getElementById('panel').innerHTML = "reminder added" } function EpochToHuman(epochseconds){ var inputtext = (epochseconds); var outputtext = ""; var extraInfo = 0; if(inputtext > 1000000000000){ outputtext += "<b>Assuming that this timestamp is in milliseconds:</b><br/>"; }else{ if(inputtext > 10000000000)extraInfo=1; inputtext=(inputtext*1000); } var datum = new Date(inputtext); outputtext += "<b>GMT</b>: "+datum.toGMTString()+"<br/><b>Your timezone</b>: "+datum.toLocaleString()+"<hr class=\"lefthr\">"; return datum.toLocaleString(); } function getTodo() { clearResults(); var searchParameters = { type: $('#querytype').val() }; // Perform proximity or bounds search. var startTime = new Date().getTime(); $.ajax({ url: '/s/getTodo', type: 'get', data: searchParameters, dataType: 'json', error: function(xhr, textStatus) { alert(xhr.responseText) var responseTime = new Date().getTime() - startTime; var responseObj; eval('responseObj=' + xhr.responseText); logResult(options, { error: 'Internal error: ' + responseObj.error.message, responseTime: responseTime }); }, success: function(obj) { var responseTime = new Date().getTime() - startTime; if (obj.status && obj.status == 'success') { logResult(options, { message: obj.results.length.toString(), responseTime: responseTime }); } else { logResult(options, { error: 'Internal error: ' + obj.error.message, responseTime: responseTime }); } } }); } function clearResults() { $('tr.result').remove(); } function logResult(options, result) { var paramStr = '<pre>'; for (var key in options) { paramStr += key + ': <strong>' + options[key].toString() + '</strong><br>'; } paramStr += '</pre>'; var row = $('<tr class="result">') .append($('<td>').html(paramStr)) .appendTo($('#results')); if (result.error) { row .addClass('error') .append($('<td>').text(result.error)); } else { row .append($('<td>').text(result.title)); } row.append($('<td>').html('<span style="color:blue">' + result.created + '</span>')); // row.append($('<td>').html('<input type="checkbox" value="yes" checked="checked" class="styled"')); } /** * Helper method to update one object's properties with another's. */ function updateObject(dest, src) { dest = dest || {}; src = src || {}; for (var k in src) dest[k] = src[k]; return dest; } </script> <style type="text/css"> #results { border-collapse: collapse; margin-top: 20px; } #results td pre { margin: 0; padding: 0; } #results th, #results td { border: 1px solid #00AA33; padding: 2px 4px; vertical-align: top; } #results th { background-color: #FF4500; color:#FFFFFF; } #results tr.error { color: #f00; } </style> </head> <body> <h1>Evernote Reminder</h1> <div id="login-bar"> {% if current_user %} <strong>{{ current_user.email }}</strong> &nbsp;|&nbsp; <a href="{% logout_url %}">Sign out</a> {% else %} <a href="{% login_url %}">Sign in</a> {% endif %} </div> <hr> <p><strong>Todo list filter:</strong></p> <p>Remind cache in minutes: <input id="minutes" value="30" style="width: 200px;"/> <br>Query type: <select id="querytype"> <option value="Todo" selected="selected">Still need to do</option> <option value="Done">Already done</option> </select> <div id="panel"> <div align="left"><i></i></div> </div> <hr> <input type="button" onclick="getDone();" value="Get Todo list"/> <input type="button" onclick="clearResults();" value="Clear"/> <table id="results"> <tr style="color=#FFFFFF"> <th>Todo status</th> <th>Note title</th> <th>Created time</th> </tr> </table> <div class="indent"> <input id="auth_button" type="button" value="Authenticate" onclick="loginOrLogout()"/> </div> <td> <input id="save_button" type="button" value="Add reminders to Google Calendar" onclick="addReminder()" style="margin:5px 0px 5px 0px;"/> </td> <div id="addBirthday" class="indent" style="display:none"> <div id="addEventHeader" style="font-weight: bold; border-bottom:1px solid grey;">Add reminder:</div> <table> <tr> <td>Name:</td> <td><input id="name" type="text" style="width:100%"></td> </tr> <tr> <td>Time:</td> <td><input id="birthdate" type="text" value="2007-08-16" style="width:100%"/></td> </tr> <tr> <td>Reminder:</td> <td><input id="reminder_days1" type="checkbox"/>1 day <input id="reminder_days2" type="checkbox"/>2 days <input id="reminder_days7" type="checkbox" checked/>1 week</td> </tr> <tr> <td>Profile Url:</td> <td><input id="profile" type="text" style="width:100%"/> </td> </tr> <tr> <td>Image:</td> <td><input id="image" type="text" style="width:100%" onkeyup="refreshImage()" onkeydown="refreshImage()"/> </td> </tr> <tr> <td></td> <td> <div id="imagePreview"></div> </td> </tr> <tr> <td></td> <td> <input id="save_button" type="button" value="Add reminders to Google Calendar" onclick="addReminder()" style="margin:5px 0px 5px 0px;"/> </td> </tr> </table> </div> <div id="upcomingBirthdays" class="indent" style="display:none"> <div id="upcomingBirthdaysHeader" style="font-weight: bold; border-bottom:1px solid grey;">Upcoming Birthdays:</div> <div id="upcomingBirthdaysContent"></div> </div> </body> </html>
{ "content_hash": "fe2a55725830f39847e9eb476966a123", "timestamp": "", "source": "github", "line_count": 424, "max_line_length": 141, "avg_line_length": 31.2688679245283, "alnum_prop": 0.5451048423593302, "repo_name": "westinedu/wrgroups", "id": "c377e3552779bf9a579168c794ab279a066a09b3", "size": "13258", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "templates/speedtest.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "149426" }, { "name": "Python", "bytes": "4241473" }, { "name": "Shell", "bytes": "1355" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: bmix * Date: 5/18/16 * Time: 8:38 AM */ ?> <div class="panel"> <div class="panel-heading"> Info </div> <div class="panel-block"> {!! Form::label('title','Title',['class'=>'label']) !!} <p class="control"> {!! Form::text('title',null,['class'=>$errors->has('title')?'input is-danger':'input','placeholder'=>'My Article']) !!} @if ($errors->has('title')) <span class="help is-danger"> {{ $errors->first('title') }} </span> @endif </p> {!! Form::label('published_at','Publish',['class'=>'label']) !!} <p class="control"> {!! Form::date('published_at',!empty($article->published_at)?$article->published_at:\Carbon\Carbon::now(),['class'=>$errors->has('published_at')?'input is-danger':'input']) !!} @if ($errors->has('published_at')) <span class="help is-danger"> {{ $errors->first('published_at') }} </span> @endif </p> <div class="columns"> <div class="column is-one-third"> {!! Form::label('category_id','Category',['class'=>'label']) !!} <p class="control"> <span class="select"> {!! Form::select('category_id',$categories,null,['class'=>$errors->has('category_id')?'is-danger':'', 'id'=>'category']) !!} @if ($errors->has('category_id')) <span class="help is-danger"> {{ $errors->first('category_id') }} </span> @endif </span> </p> {!! Form::label('tag_list','Tags',['class'=>'label']) !!} <p class="control" style="min-height:150px;"> <span class="select"> {!! Form::select('tag_list[]',$tags,null,['class'=>$errors->has('tag_list')?'is-danger':'', 'multiple', 'id'=>'tags', 'style' => "min-height:150px;"]) !!} </span> @if ($errors->has('tag_list')) <span class="help is-danger"> {{ $errors->first('tag_list') }} </span> @endif </p> </div> <div class="column"> {!! Form::label('summary','Summary',['class'=>'label']) !!} <p class="control"> {!! Form::textarea('summary',null,['id'=>'article-summary','class'=>$errors->has('summary')?'textarea is-danger':'textarea','placeholder'=>'Summary']) !!} @if ($errors->has('summary')) <span class="help is-danger"> {{ $errors->first('summary') }} </span> @endif </p> </div> </div> </div> </div>
{ "content_hash": "c231a77c75b98d413524c949497e8070", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 188, "avg_line_length": 41.80821917808219, "alnum_prop": 0.4134993446920052, "repo_name": "brino/larablog", "id": "64811dcf720c804ad74381749d63ab27cc9c31cc", "size": "3052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/admin/article/forms/info.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "687" }, { "name": "HTML", "bytes": "105286" }, { "name": "JavaScript", "bytes": "5453" }, { "name": "PHP", "bytes": "153241" }, { "name": "Vue", "bytes": "11796" } ], "symlink_target": "" }
/* * MediaMonkey Project * Licenced under Apache license 2.0. Read LICENSE for details. */ package com.mediamonkey.android.lib.dto.settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; /** * @author Francesco Jo(nimbusob@gmail.com) * @since 01 - Dec - 2016 */ public class MenuItemDto implements MenuDisplay { private final CharSequence title; private final CharSequence description; public MenuItemDto(@NonNull CharSequence title, @Nullable CharSequence description) { this.title = title; this.description = description; } @NonNull @Override public final CharSequence getTitle() { return title; } @Nullable @Override public final CharSequence getDescription() { return description; } }
{ "content_hash": "fca1c760cbdf81aeffbf5c07019124a9", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 89, "avg_line_length": 24.323529411764707, "alnum_prop": 0.6977025392986699, "repo_name": "FrancescoJo/MediaMonkeyPluginSdk", "id": "b612924b9741f79cf91503a14d7421a4e58b1b17", "size": "827", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/mediamonkey/android/lib/dto/settings/MenuItemDto.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "227901" } ], "symlink_target": "" }
package de.uni.freiburg.iig.telematik.jagal.graph.weighted; import java.util.Collection; import de.invation.code.toval.validate.ParameterException; import de.uni.freiburg.iig.telematik.jagal.graph.Vertex; public class WeightedGraph<T extends Object> extends AbstractWeightedGraph<Vertex<T>, T>{ public WeightedGraph(){ super(); } public WeightedGraph(String name) throws ParameterException{ super(name); } public WeightedGraph(Collection<String> vertexNames) throws ParameterException{ super(vertexNames); } public WeightedGraph(Collection<String> vertexNames, String name) throws ParameterException{ super(name, vertexNames); } @Override protected Vertex<T> createNewVertex(String name, T element) { return new Vertex<>(name, element); } @Override protected WeightedEdge<Vertex<T>> createNewEdge(Vertex<T> sourceVertex, Vertex<T> targetVertex) { return new WeightedEdge<>(sourceVertex, targetVertex); } public static void main(String[] args) throws Exception{ WeightedGraph<String> g = new WeightedGraph<>(); g.addVertex("A"); g.addVertex("B"); g.addEdge("A", "B", 0.5); System.out.println(g); } }
{ "content_hash": "1058cf18c8393d81ce1572202fe14623", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 98, "avg_line_length": 24.617021276595743, "alnum_prop": 0.7476231633535004, "repo_name": "iig-uni-freiburg/JAGAL", "id": "09a0ca4b9aad446917de03f26913175fec75abf7", "size": "1157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/uni/freiburg/iig/telematik/jagal/graph/weighted/WeightedGraph.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "235102" } ], "symlink_target": "" }
package com.example.testudpclient; import java.io.InputStream; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.giant.sdk.net.GWebClient; import com.giant.sdk.log.GLog; public class LoginActivity extends Activity { Button btn_login; EditText txt_account; EditText txt_password; EditText txt_ip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); btn_login = (Button)findViewById(R.id.btn_login); txt_account = (EditText)findViewById(R.id.txt_account); txt_password = (EditText)findViewById(R.id.txt_password); txt_ip = (EditText)findViewById(R.id.txt_ip); btn_login.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view) { //GIMDemo.Instance().login(txt_account.getText().toString(), txt_password.getText().toString()); Thread thread = new Thread(new Runnable(){ public void run() { try{ String url = "http://" + txt_ip.getText().toString() + "/login?useraccount=" + txt_account.getText().toString(); GWebClient webclient = new GWebClient(url); webclient.openConnection(); InputStream is = webclient.openStream(); String str = null; String result = ""; while((str = webclient.readLine()) != null){ result += str; } webclient.close(); webclient = null; GLog.d(result); JSONObject roomJson = new JSONObject(result); if(!roomJson.has("error")){ //go to chatroomlist GlobalInfo.sessionId = roomJson.getLong("uid"); GlobalInfo.ip = txt_ip.getText().toString(); /* 新建一个Intent对象 */ Intent intent = new Intent(); //intent.putExtra("name","LeiPei"); /* 指定intent要启动的类 */ intent.setClass(LoginActivity.this, ChatRoomListActivity.class); /* 启动一个新的Activity */ LoginActivity.this.startActivity(intent); /* 关闭当前的Activity */ LoginActivity.this.finish(); }else{ GLog.e(result); } }catch(Exception e){ e.printStackTrace(); } //go to chatroomlistactivity } }); thread.start(); } }); } }
{ "content_hash": "81c9950d4748f3946ef1c6a61168ecfc", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 119, "avg_line_length": 30.96470588235294, "alnum_prop": 0.6014437689969605, "repo_name": "nature19862001/mediaserver", "id": "cd35a8847064424174917e93c1c6fed412117d6c", "size": "2680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/TestUDPClient/src/com/example/testudpclient/LoginActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "605" }, { "name": "Go", "bytes": "50979" }, { "name": "Java", "bytes": "38015" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys from thrift.Thrift import TMessageType, TApplicationException, TType def process_main(twisted=False): """Decorator for process method.""" def _decorator(func): def nested(self, iprot, oprot, server_ctx=None): (name, type, seqid) = iprot.readMessageBegin() if sys.version_info[0] >= 3: name = name.decode() if name not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() if twisted is True: from twisted.internet import defer return defer.succeed(None) else: ret = self._processMap[name](self, seqid, iprot, oprot, server_ctx) if twisted is True: return ret else: return True return nested return _decorator def process_method(argtype, oneway=False, twisted=False): """Decorator for process_xxx methods.""" def _decorator(func): def nested(self, seqid, iprot, oprot, server_ctx): fn_name = func.__name__.split('_', 1)[-1] handler_ctx = self._event_handler.getHandlerContext(fn_name, server_ctx) args = argtype() reply_type = TMessageType.REPLY self._event_handler.preRead(handler_ctx, fn_name, args) args.read(iprot) iprot.readMessageEnd() self._event_handler.postRead(handler_ctx, fn_name, args) if twisted is True: return func(self, args, handler_ctx, seqid, oprot) elif oneway is True: func(self, args, handler_ctx) else: result = func(self, args, handler_ctx) if isinstance(result, TApplicationException): reply_type = TMessageType.EXCEPTION self._event_handler.preWrite(handler_ctx, fn_name, result) oprot.writeMessageBegin(fn_name, reply_type, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() self._event_handler.postWrite(handler_ctx, fn_name, result) return nested return _decorator def write_results_success_callback(func): """Decorator for twisted write_results_success_xxx methods. No need to call func so it can be empty. """ def nested(self, success, result, seqid, oprot, handler_ctx): fn_name = func.__name__.split('_', 3)[-1] result.success = success self._event_handler.preWrite(handler_ctx, fn_name, result) oprot.writeMessageBegin(fn_name, TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() self._event_handler.postWrite(handler_ctx, fn_name, result) return nested def write_results_exception_callback(func): """Decorator for twisted write_results_exception_xxx methods.""" def nested(self, error, result, seqid, oprot, handler_ctx): fn_name = func.__name__.split('_', 3)[-1] # Call the decorated function reply_type, result = func(self, error, result, handler_ctx) self._event_handler.preWrite(handler_ctx, fn_name, result) oprot.writeMessageBegin(fn_name, reply_type, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() self._event_handler.postWrite(handler_ctx, fn_name, result) return nested
{ "content_hash": "d28bca8725bd3bb010ac977275144ebd", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 79, "avg_line_length": 38.38095238095238, "alnum_prop": 0.586848635235732, "repo_name": "soumith/fbthrift", "id": "7299c8fd2c846bdf3955f3eb639f0a51dc7e532b", "size": "4816", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "thrift/lib/py/util/Decorators.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "161802" }, { "name": "C#", "bytes": "28929" }, { "name": "C++", "bytes": "6236211" }, { "name": "D", "bytes": "667895" }, { "name": "Emacs Lisp", "bytes": "5154" }, { "name": "Erlang", "bytes": "23039" }, { "name": "Go", "bytes": "288742" }, { "name": "Hack", "bytes": "385207" }, { "name": "Haskell", "bytes": "153197" }, { "name": "Java", "bytes": "994432" }, { "name": "JavaScript", "bytes": "4488" }, { "name": "LLVM", "bytes": "11951" }, { "name": "Makefile", "bytes": "14663" }, { "name": "OCaml", "bytes": "32172" }, { "name": "Objective-C", "bytes": "109934" }, { "name": "PHP", "bytes": "246615" }, { "name": "Perl", "bytes": "70682" }, { "name": "Protocol Buffer", "bytes": "585" }, { "name": "Python", "bytes": "904345" }, { "name": "Ruby", "bytes": "323073" }, { "name": "Scala", "bytes": "1266" }, { "name": "Shell", "bytes": "21565" }, { "name": "Smalltalk", "bytes": "22812" }, { "name": "TeX", "bytes": "48707" }, { "name": "Thrift", "bytes": "117234" }, { "name": "VimL", "bytes": "2837" }, { "name": "Yacc", "bytes": "38893" } ], "symlink_target": "" }
skynet.py ========= A python script that connects to SkyNet.im
{ "content_hash": "9148857ceb5da4548ba9367de94e8fd2", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 42, "avg_line_length": 16, "alnum_prop": 0.671875, "repo_name": "ctlaltdieliet/skynet.py", "id": "b3c2c90011ec25d62e5360acb29f81df1628d4aa", "size": "64", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "7964" } ], "symlink_target": "" }
/** * UI for the PlugPro Menu * @module settings/AutoWootToggle */ /** * Menu UI constructor * @constructor * @param {object} JST - Javascript HTML templates * @param {object} toggleSettings - List of settings and their corresponding togglers */ function Menu( JST, toggleSettings ){ this.$parent = $('#app-menu'); this.visible = false; // Load menu template var menuHTML = JST['src/html_templates/menu.html']({ chromeDir: 'chrome-extension://' + $('#plug_pro_chrome_extension_id').val() }); this.$parent.append( menuHTML ); // Add all toggle settings var setting; for( setting in toggleSettings ){ this.detectCheckboxChanges( setting, toggleSettings[setting] ); } this.initializeEvents(); } /** * Adds change events to menu items */ Menu.prototype.initializeEvents = function(){ // Detect Plug.DJ menu animations to trigger Pro menu open/close this.$parent.find('.list')[0].addEventListener( this.getTransitionEvent(), this.toggle.bind(this), false ); // Prevent menu from closing when clicking in the Pro Menu document.addEventListener("mousedown", function(event){ var target = $(event.target); if( event.target.id === "plugpro-menu" || target.parents('#plugpro-menu').length > 0 ){ event.stopPropagation(); } }, true); }; /** * Makes toggle checkboxes functional */ Menu.prototype.detectCheckboxChanges = function( settingName, setting ){ var $toggleSettingsUL = this.$parent.find('#pro-toggle-settings'); // Add setting HTML var toggleSettingHTML = JST['src/html_templates/toggle_setting.html']({ title: settingName }); var $toggleSettingElement = $($.parseHTML( toggleSettingHTML )); $toggleSettingsUL.append( $toggleSettingElement ); // Link checkbox to toggler $toggleSettingElement.find('.'+settingName.toLowerCase()+'-setting').change(function(){ setting.toggler.toggle.apply(setting.toggler); }); }; /** * Toggle Pro menu visibility */ Menu.prototype.toggle = function(){ var left = this.$parent.find('.list').css("left"); if( left === "0px" ){ this.show(); }else{ this.hide(); } }; /** * Make Pro menu visible */ Menu.prototype.show = function(){ $('#plugpro-menu').addClass("expanded"); this.visible = true; }; /** * Make Pro menu hidden */ Menu.prototype.hide = function(){ $('#plugpro-menu').removeClass("expanded"); this.visible = false; }; /** * Determine correct transition event name * @returns {string} The name of the transition event used by the user's browser */ Menu.prototype.getTransitionEvent = function( el ){ var el = el || document.createElement('div'); var animations = { 'animation':'transitionend', 'OAnimation':'oTransitionEnd', 'MozAnimation':'transitionend', 'WebkitAnimation':'webkitTransitionEnd' }; for(var t in animations){ if( el.style[t] !== undefined ){ return animations[t]; } } }; module.exports = Menu;
{ "content_hash": "7ca4248f989c5967cb323375d122dd7b", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 88, "avg_line_length": 23.565573770491802, "alnum_prop": 0.6869565217391305, "repo_name": "SkyGameRus/PlugPro", "id": "abb54a72552cd342e2bc12e74152c9d075afbdbe", "size": "2875", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/js/ui/Menu.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12857" }, { "name": "HTML", "bytes": "3204" }, { "name": "JavaScript", "bytes": "109790" } ], "symlink_target": "" }
package com.example.android.architecture.blueprints.todoapp.statistics; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.data.source.ITasksDataSource; import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository; import com.google.common.collect.Lists; import java.util.List; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Unit tests for the implementation of {@link StatisticsPresenter} */ public class StatisticsPresenterTest { private static List<Task> TASKS; @Mock private TasksRepository mTasksRepository; @Mock private StatisticsContract.View mStatisticsView; /** * {@link ArgumentCaptor} is a powerful Mockito API to capture argument values and use them to * perform further actions or assertions on them. */ @Captor private ArgumentCaptor<ITasksDataSource.LoadTasksCallback> mLoadTasksCallbackCaptor; private StatisticsPresenter mStatisticsPresenter; @Before public void setupStatisticsPresenter() { // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To // inject the mocks in the test the initMocks method needs to be called. MockitoAnnotations.initMocks(this); // Get a reference to the class under test mStatisticsPresenter = new StatisticsPresenter(mTasksRepository, mStatisticsView); // The presenter won't update the view unless it's active. when(mStatisticsView.isActive()).thenReturn(true); // We start the tasks to 3, with one active and two completed TASKS = Lists.newArrayList(new Task("Title1", "Description1"), new Task("Title2", "Description2", true), new Task("Title3", "Description3", true)); } @Test public void loadEmptyTasksFromRepository_CallViewToDisplay() { // Given an initialized StatisticsPresenter with no tasks TASKS.clear(); // When loading of Tasks is requested mStatisticsPresenter.start(); //Then progress indicator is shown verify(mStatisticsView).setProgressIndicator(true); // Callback is captured and invoked with stubbed tasks verify(mTasksRepository).getTasks(mLoadTasksCallbackCaptor.capture()); mLoadTasksCallbackCaptor.getValue().onTasksLoaded(TASKS); // Then progress indicator is hidden and correct data is passed on to the view verify(mStatisticsView).setProgressIndicator(false); verify(mStatisticsView).showStatistics(0, 0); } @Test public void loadNonEmptyTasksFromRepository_CallViewToDisplay() { // Given an initialized StatisticsPresenter with 1 active and 2 completed tasks // When loading of Tasks is requested mStatisticsPresenter.start(); //Then progress indicator is shown verify(mStatisticsView).setProgressIndicator(true); // Callback is captured and invoked with stubbed tasks verify(mTasksRepository).getTasks(mLoadTasksCallbackCaptor.capture()); mLoadTasksCallbackCaptor.getValue().onTasksLoaded(TASKS); // Then progress indicator is hidden and correct data is passed on to the view verify(mStatisticsView).setProgressIndicator(false); verify(mStatisticsView).showStatistics(1, 2); } @Test public void loadStatisticsWhenTasksAreUnavailable_CallErrorToDisplay() { // When statistics are loaded mStatisticsPresenter.start(); // And tasks data isn't available verify(mTasksRepository).getTasks(mLoadTasksCallbackCaptor.capture()); mLoadTasksCallbackCaptor.getValue().onDataNotAvailable(); // Then an error message is shown verify(mStatisticsView).showLoadingStatisticsError(); } }
{ "content_hash": "6666748ddc2724a2117ccabe683130d2", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 100, "avg_line_length": 35.91150442477876, "alnum_prop": 0.7262198127156234, "repo_name": "songzhw/AndroidArchitecture", "id": "3afb14e105b5e7562dfd4610dcdd2a327d0647b5", "size": "4674", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deprecated/Google_MVP/app/src/test/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsPresenterTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "358387" }, { "name": "JavaScript", "bytes": "2528" }, { "name": "Kotlin", "bytes": "81011" } ], "symlink_target": "" }
package com.jakewharton.rxbinding.widget; import android.database.DataSetObserver; import android.widget.Adapter; import com.jakewharton.rxbinding.internal.MainThreadSubscription; import rx.Observable; import rx.Subscriber; import static com.jakewharton.rxbinding.internal.Preconditions.checkUiThread; final class AdapterDataChangeOnSubscribe<T extends Adapter> implements Observable.OnSubscribe<T> { private final T adapter; public AdapterDataChangeOnSubscribe(T adapter) { this.adapter = adapter; } @Override public void call(final Subscriber<? super T> subscriber) { checkUiThread(); final DataSetObserver observer = new DataSetObserver() { @Override public void onChanged() { if (!subscriber.isUnsubscribed()) { subscriber.onNext(adapter); } } }; adapter.registerDataSetObserver(observer); subscriber.add(new MainThreadSubscription() { @Override protected void onUnsubscribe() { adapter.unregisterDataSetObserver(observer); } }); // Emit initial value. subscriber.onNext(adapter); } }
{ "content_hash": "d945cc900493c8795f2790d2c18d7789", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 77, "avg_line_length": 27.625, "alnum_prop": 0.7276018099547511, "repo_name": "tsdl2013/RxBinding", "id": "25b583407a37cb0131453fa615086895c9b0e1af", "size": "1105", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "rxbinding/src/main/java/com/jakewharton/rxbinding/widget/AdapterDataChangeOnSubscribe.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "11376" }, { "name": "Java", "bytes": "215343" }, { "name": "Kotlin", "bytes": "31647" }, { "name": "Shell", "bytes": "943" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>yepnope.js test suite</title> <link rel="stylesheet" href="css/mocha.css" type="text/css" /> <style type="text/css"> #testDivZone { position: absolute; left: -10000px; } </style> </head> <body> <div id="testDivZone"></div> <!-- Required for browser reporter --> <div id="mocha"></div> <!-- mocha --> <script src="js/mocha.js"></script> <script src="js/build.js"></script> <script> // This will be overridden by mocha-helper if you run with grunt mocha.setup({ ui: 'bdd', // long timeouts since we have to test timeouts timeout: 12000, globals: ['yepnope', 'yeptest', 'getInterface', 'mochaResults'] }); </script> <!-- Include your assertion lib of choice --> <script src="js/expect.js"></script> <!-- Stuff to test --> <script src="../src/yepnope.js"></script> <!-- Spec files --> <script src="test.js"></script> <!-- run mocha --> <script> // A place to put loaded variables window.yeptest = {}; // If tests run in a real browser // Can alternatively do a check on window.PHANTOMJS if (navigator.userAgent.indexOf('PhantomJS') < 0) { cloud(mocha.run()); } </script> </body> </html>
{ "content_hash": "99fa03aec81501af4ca5c5e6a884f804", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 69, "avg_line_length": 25.48076923076923, "alnum_prop": 0.6, "repo_name": "bugdebugger/yepnope.js", "id": "539ef09ccf44f03e7271314c8935c0f7092e3f70", "size": "1325", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "34" }, { "name": "HTML", "bytes": "1325" }, { "name": "JavaScript", "bytes": "74187" } ], "symlink_target": "" }
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_CPU_SHAPE_PARTITION_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_CPU_SHAPE_PARTITION_H_ #include <vector> #include "tensorflow/compiler/xla/shape_util.h" namespace xla { namespace cpu { // ShapePartitionAssigner partitions the most-major dimensions of 'shape' such // that the total partition count <= 'target_partition_count'. // // Example 1: // // Let 'shape' = [8, 16, 32] and 'target_partition_count' = 6. // // Because the most-major dimension size is <= 'target_partition_count', we // can generate our target number of partitions by partition the most-major // dimensions. // // This will result in the following partitions of the most-major dimension: // // [0, 1), [1, 2), [2, 3), [3, 4), [4, 5) [5, 8) // // Note that the last partition has residual because the dimension size is // not a multiple of the partition count. // // // Example 2: // // Let 'shape' = [8, 16, 32] and 'target_partition_count' = 16. // // Because the most-major dimension only has size 8, we must also partition // the next most-major dimension to generate the target of 16 partitions. // We factor 'target_partition_count' by the number of most-major dimensions // we need to partition, to get a per-dimension target partition count: // // target_dimension_partition_count = 16 ^ (1 / 2) == 4 // // This will result in the following partitions of the most-major dimension: // // [0, 2), [2, 4), [4, 6), [6, 8) // // This will result in the following partitions of the second most-major // dimension: // // [0, 4), [4, 8), [8, 12), [12, 16) // class ShapePartitionAssigner { public: ShapePartitionAssigner(const Shape& shape) : shape_(shape) {} // Returns dimension partition counts (starting at outer-most dimension). std::vector<int64_t> Run(int64_t target_partition_count); // Returns the total partition count based on 'dimension_partition_counts'. static int64_t GetTotalPartitionCount( const std::vector<int64_t>& dimension_partition_counts); private: const Shape& shape_; }; // ShapePartitionIterator iterates through outer-dimension partitions of // 'shape' as specified by 'dimension_partition_counts'. class ShapePartitionIterator { public: ShapePartitionIterator(const Shape& shape, absl::Span<const int64_t> dimension_partition_counts); // Returns a partition [start, size] for each dimension. // Partitions are listed starting from outer-most dimension first. std::vector<std::pair<int64_t, int64_t>> GetPartition(int64_t index) const; int64_t GetTotalPartitionCount() const; private: const Shape& shape_; const std::vector<int64_t> dimension_partition_counts_; std::vector<int64_t> dimensions_; std::vector<int64_t> dimension_partition_sizes_; std::vector<int64_t> dimension_partition_strides_; }; } // namespace cpu } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_CPU_SHAPE_PARTITION_H_
{ "content_hash": "31ce8a5e843d6062981361bc502836af", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 79, "avg_line_length": 32.30434782608695, "alnum_prop": 0.6981830417227456, "repo_name": "tensorflow/tensorflow", "id": "7fc6737320089cd91b3b36990b6f5f50e8d4c2c0", "size": "3640", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "tensorflow/compiler/xla/service/cpu/shape_partition.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "36962" }, { "name": "C", "bytes": "1400913" }, { "name": "C#", "bytes": "13584" }, { "name": "C++", "bytes": "126099822" }, { "name": "CMake", "bytes": "182430" }, { "name": "Cython", "bytes": "5003" }, { "name": "Dockerfile", "bytes": "416133" }, { "name": "Go", "bytes": "2129888" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "1074438" }, { "name": "Jupyter Notebook", "bytes": "792906" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "11447433" }, { "name": "Makefile", "bytes": "2760" }, { "name": "Objective-C", "bytes": "172666" }, { "name": "Objective-C++", "bytes": "300213" }, { "name": "Pawn", "bytes": "5552" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "42782002" }, { "name": "Roff", "bytes": "5034" }, { "name": "Ruby", "bytes": "9199" }, { "name": "Shell", "bytes": "621854" }, { "name": "Smarty", "bytes": "89538" }, { "name": "SourcePawn", "bytes": "14625" }, { "name": "Starlark", "bytes": "7738020" }, { "name": "Swift", "bytes": "78435" }, { "name": "Vim Snippet", "bytes": "58" } ], "symlink_target": "" }
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.sass'] }) export class FooterComponent implements OnInit { constructor() { } ngOnInit() { } }
{ "content_hash": "7fdd1f4631224176b97123d83c06abed", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 50, "avg_line_length": 18, "alnum_prop": 0.6703703703703704, "repo_name": "alexurquhart/routecard", "id": "4faa4829f38591dfbed201fed256504122a58ae1", "size": "270", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/app/components/footer/footer.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "595" }, { "name": "HTML", "bytes": "1063" }, { "name": "JavaScript", "bytes": "1645" }, { "name": "TypeScript", "bytes": "16410" } ], "symlink_target": "" }
source PerfRun.conf #run table creating program echo "========================Create Tables======================================" scala -cp "$TPCHJar:$mysqlConnectorJar" io.snappydata.benchmark.kuduimpala.TPCH_Impala_Tables $aggregator $port
{ "content_hash": "eaa7ea671f5f2eb75d5a2f7cdd8e2128", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 111, "avg_line_length": 48.6, "alnum_prop": 0.6090534979423868, "repo_name": "vjr/snappydata", "id": "df4c50005e33139552f477c1d42640d6935a06fb", "size": "263", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/benchmark/kuduimpala/3_CreateAndLoadTable.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "5867" }, { "name": "C++", "bytes": "2104" }, { "name": "Java", "bytes": "579527" }, { "name": "Python", "bytes": "49161" }, { "name": "Scala", "bytes": "3230053" }, { "name": "Shell", "bytes": "80012" } ], "symlink_target": "" }
import { applyMiddleware } from 'redux'; export function createMockStore(state, expectedActions, middleware, done) { if (!Array.isArray(expectedActions)) { throw new Error('ERROR # createMockStore : `expectedActions` must be an array of expected actions.'); } if (typeof done !== 'undefined' && typeof done !== 'function') { throw new Error('ERROR # createMockStore : `done` must be undefined or a function.'); } function store() { return { dispatch(action) { const expectedAction = expectedActions.shift(); try { if (typeof expectedAction === 'function') { expect(expectedAction(action)).toBe(true); } else { expect(action).toEqual(expectedAction); } return action; } catch (error) { done(error); } }, getState() { return typeof state === 'function' ? state() : state; } }; } return applyMiddleware(...middleware)(store)(); }
{ "content_hash": "7b5a8d301b7b9cd111c332943adb2a18", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 105, "avg_line_length": 26.128205128205128, "alnum_prop": 0.577036310107949, "repo_name": "jmptr/lost-sloth-angular", "id": "fb57c8fc32dd778699ab5625b5a93e152de91f93", "size": "1019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/app/state/create-mock-store.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "970" }, { "name": "HTML", "bytes": "7982" }, { "name": "JavaScript", "bytes": "27217" } ], "symlink_target": "" }
// File name: CoreEntries.h // Description: Component externals declaration. #ifndef COREENTRIES_H__BUILDERELEMENTS__INCLUDED_ #define COREENTRIES_H__BUILDERELEMENTS__INCLUDED_ #include "../BuilderElements.h" BUILDERELEMENTS_FUNC_DECLARE result DllGetClassObject(REFCLSID rCLSID, REFIID rIID, void** ppObject); BUILDERELEMENTS_FUNC_DECLARE result CanUnloadNow(); BUILDERELEMENTS_FUNC_DECLARE void GetComponentName(String& rComponentName); BUILDERELEMENTS_FUNC_DECLARE void GetComponentVersion(String& rComponentVersion); #endif // !COREENTRIES_H__BUILDERELEMENTS__INCLUDED_
{ "content_hash": "cdbd5b94c2b08a7c15037fa1f27a8968", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 103, "avg_line_length": 37.875, "alnum_prop": 0.7788778877887789, "repo_name": "egorpushkin/neurolab", "id": "7fa5d762853736cbc950a3bc41280803e683467b", "size": "734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/source/Src/SDKDlls/BuilderElements/Environment/CoreEntries.h", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "112" }, { "name": "C", "bytes": "1787692" }, { "name": "C++", "bytes": "9312245" }, { "name": "CSS", "bytes": "44465" }, { "name": "Clarion", "bytes": "5268" }, { "name": "HTML", "bytes": "408820" }, { "name": "JavaScript", "bytes": "5476" }, { "name": "Makefile", "bytes": "39256" }, { "name": "Objective-C", "bytes": "97952" }, { "name": "TeX", "bytes": "3128" } ], "symlink_target": "" }
package com.apigee.sdk.apm.android; import java.io.InputStream; import java.io.OutputStream; import java.net.ContentHandlerFactory; import java.net.FileNameMap; import java.net.HttpURLConnection; import java.security.Permission; import java.security.Principal; import java.security.cert.Certificate; import java.util.List; import java.util.Map; import java.util.UUID; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSocketFactory; /** * @y.exclude */ public class ApigeeHttpsURLConnection extends HttpsURLConnection { private HttpsURLConnection realConnection; private long startTimeMillis; public ApigeeHttpsURLConnection(HttpsURLConnection connection) { super(connection.getURL()); realConnection = connection; } public void disconnect() { long endTimeMillis = System.currentTimeMillis(); java.net.URL url = realConnection.getURL(); String urlAsString = url.toString(); realConnection.disconnect(); boolean errorOccurred = false; ApigeeMonitoringClient monitoringClient = ApigeeMonitoringClient.getInstance(); if( (monitoringClient != null) && monitoringClient.isInitialized() ) { Map<String,Object> httpHeaders = HttpUrlConnectionUtils.captureHttpHeaders(this); NetworkMetricsCollectorService metricsCollectorService = monitoringClient.getMetricsCollectorService(); if( metricsCollectorService != null ) { metricsCollectorService.analyze(urlAsString, new Long(startTimeMillis), new Long(endTimeMillis), errorOccurred, httpHeaders); } } } public java.io.InputStream getErrorStream() { return realConnection.getErrorStream(); } public static boolean getFollowRedirects() { return HttpsURLConnection.getFollowRedirects(); } public boolean getInstanceFollowRedirects() { return realConnection.getInstanceFollowRedirects(); } public String getRequestMethod() { return realConnection.getRequestMethod(); } public int getResponseCode() throws java.io.IOException { return realConnection.getResponseCode(); } public String getResponseMessage() throws java.io.IOException { return realConnection.getResponseMessage(); } public void setChunkedStreamingMode(int chunkedLength) { realConnection.setChunkedStreamingMode(chunkedLength); } public void setFixedLengthStreamingMode(int contentLength) { realConnection.setFixedLengthStreamingMode(contentLength); } public static void setFollowRedirects(boolean auto) { HttpsURLConnection.setFollowRedirects(auto); } public void setInstanceFollowRedirects(boolean followRedirects) { realConnection.setInstanceFollowRedirects(followRedirects); } public void setRequestMethod(String method) throws java.net.ProtocolException { realConnection.setRequestMethod(method); } public boolean usingProxy() { return realConnection.usingProxy(); } public String getCipherSuite() { return realConnection.getCipherSuite(); } public static HostnameVerifier getDefaultHostnameVerifier() { return HttpsURLConnection.getDefaultHostnameVerifier(); } public static SSLSocketFactory getDefaultSSLSocketFactory() { return HttpsURLConnection.getDefaultSSLSocketFactory(); } public HostnameVerifier getHostnameVerifier() { return realConnection.getHostnameVerifier(); } public Certificate[] getLocalCertificates() { return realConnection.getLocalCertificates(); } public Principal getLocalPrincipal() { return realConnection.getLocalPrincipal(); } public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { return realConnection.getPeerPrincipal(); } public SSLSocketFactory getSSLSocketFactory() { return realConnection.getSSLSocketFactory(); } public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException { return realConnection.getServerCertificates(); } public static void setDefaultHostnameVerifier(HostnameVerifier v) { HttpsURLConnection.setDefaultHostnameVerifier(v); } public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) { HttpsURLConnection.setDefaultSSLSocketFactory(sf); } public void setHostnameVerifier(HostnameVerifier v) { realConnection.setHostnameVerifier(v); } public void setSSLSocketFactory(SSLSocketFactory sf) { realConnection.setSSLSocketFactory(sf); } //********************************************************** public void addRequestProperty(String field, String newValue) { realConnection.addRequestProperty(field, newValue); } public void connect() throws java.io.IOException { startTimeMillis = System.currentTimeMillis(); ApigeeMonitoringClient monitoringClient = ApigeeMonitoringClient.getInstance(); if (monitoringClient != null ) { if (monitoringClient.getAppIdentification() != null) { realConnection.setRequestProperty("X-Apigee-Client-Org-Name", monitoringClient.getAppIdentification().getOrganizationId()); realConnection.setRequestProperty("X-Apigee-Client-App-Name", monitoringClient.getAppIdentification().getApplicationId()); } realConnection.setRequestProperty("X-Apigee-Device-Id", monitoringClient.getApigeeDeviceId()); if (monitoringClient.getSessionManager() != null) realConnection.setRequestProperty("X-Apigee-Session-Id", monitoringClient.getSessionManager().getSessionUUID()); realConnection.setRequestProperty("X-Apigee-Client-Request-Id", UUID.randomUUID().toString()); } realConnection.connect(); } public boolean getAllowUserInteraction() { return realConnection.getAllowUserInteraction(); } public int getConnectTimeout() { return realConnection.getConnectTimeout(); } public Object getContent() throws java.io.IOException { return realConnection.getContent(); } public Object getContent(Class[] types) throws java.io.IOException { return realConnection.getContent(types); } public String getContentEncoding() { return realConnection.getContentEncoding(); } public int getContentLength() { return realConnection.getContentLength(); } public String getContentType() { return realConnection.getContentType(); } public long getDate() { return realConnection.getDate(); } public static boolean getDefaultAllowUserInteraction() { return HttpURLConnection.getDefaultAllowUserInteraction(); } public static String getDefaultRequestProperty(String field) { return HttpURLConnection.getDefaultRequestProperty(field); } public boolean getDefaultUseCaches() { return realConnection.getDefaultUseCaches(); } public boolean getDoInput() { return realConnection.getDoInput(); } public boolean getDoOutput() { return realConnection.getDoOutput(); } public long getExpiration() { return realConnection.getExpiration(); } public static FileNameMap getFileNameMap() { return HttpURLConnection.getFileNameMap(); } public String getHeaderField(String key) { return realConnection.getHeaderField(key); } public String getHeaderField(int pos) { return realConnection.getHeaderField(pos); } public long getHeaderFieldDate(String field, long defaultValue) { return realConnection.getHeaderFieldDate(field, defaultValue); } public int getHeaderFieldInt(String field, int defaultValue) { return realConnection.getHeaderFieldInt(field,defaultValue); } public String getHeaderFieldKey(int posn) { return realConnection.getHeaderFieldKey(posn); } public Map<String,List<String>> getHeaderFields() { return realConnection.getHeaderFields(); } public long getIfModifiedSince() { return realConnection.getIfModifiedSince(); } public InputStream getInputStream() throws java.io.IOException { return realConnection.getInputStream(); } public long getLastModified() { return realConnection.getLastModified(); } public OutputStream getOutputStream() throws java.io.IOException { return realConnection.getOutputStream(); } public Permission getPermission() throws java.io.IOException { return realConnection.getPermission(); } public int getReadTimeout() { return realConnection.getReadTimeout(); } public Map<String,List<String>> getRequestProperties() { return realConnection.getRequestProperties(); } public String getRequestProperty(String field) { return realConnection.getRequestProperty(field); } public java.net.URL getURL() { return realConnection.getURL(); } public boolean getUseCaches() { return realConnection.getUseCaches(); } public static String guessContentTypeFromName(String url) { return HttpURLConnection.guessContentTypeFromName(url); } public static String guessContentTypeFromStream(InputStream is) throws java.io.IOException { return HttpURLConnection.guessContentTypeFromStream(is); } public void setAllowUserInteraction(boolean newValue) { realConnection.setAllowUserInteraction(newValue); } public void setConnectTimeout(int timeoutMillis) { realConnection.setConnectTimeout(timeoutMillis); } public synchronized static void setContentHandlerFactory(ContentHandlerFactory contentFactory) { HttpURLConnection.setContentHandlerFactory(contentFactory); } public static void setDefaultAllowUserInteraction(boolean allows) { HttpURLConnection.setDefaultAllowUserInteraction(allows); } public static void setDefaultRequestProperty(String field, String value) { HttpURLConnection.setDefaultRequestProperty(field, value); } public void setDefaultUseCaches(boolean newValue) { realConnection.setDefaultUseCaches(newValue); } public void setDoInput(boolean newValue) { realConnection.setDoInput(newValue); } public void setDoOutput(boolean newValue) { realConnection.setDoOutput(newValue); } public static void setFileNameMap(FileNameMap map) { HttpURLConnection.setFileNameMap(map); } public void setIfModifiedSince(long newValue) { realConnection.setIfModifiedSince(newValue); } public void setReadTimeout(int timeoutMillis) { realConnection.setReadTimeout(timeoutMillis); } public void setRequestProperty(String field, String newValue) { realConnection.setRequestProperty(field, newValue); } public void setUseCaches(boolean newValue) { realConnection.setUseCaches(newValue); } public String toString() { return realConnection.toString(); } }
{ "content_hash": "ae9f4439abae3e2e9ae7c6825f429db4", "timestamp": "", "source": "github", "line_count": 444, "max_line_length": 139, "avg_line_length": 23.623873873873872, "alnum_prop": 0.766898655734579, "repo_name": "RobertWalsh/apigee-android-sdk", "id": "1c7b25776730ee07d30ab707c0db11afd320f6d8", "size": "10489", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/src/main/java/com/apigee/sdk/apm/android/ApigeeHttpsURLConnection.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1861" }, { "name": "Java", "bytes": "602898" }, { "name": "Shell", "bytes": "10722" } ], "symlink_target": "" }
layout: resource title: "Learning Resources For Students & Novices" permalink: /resources/learning show_title: true date: 2017-10-23 update_date: tags: resources --- ## How Do I Get Started In Information Security? This is a question I get asked every time I talk to college students. A lot of people want to learn about InfoSec, but they have no idea how. The answer for most people is: You have to teach yourself. Even for experienced professionals, InfoSec is about constant self-teaching. This is the nature of the industry. When it comes to information security, defense is all about being one step ahead of the offense; This is why companies hack themselves, and why whitehats are always researching new exploits. Below is a list of resources that you can use to teach yourself about InfoSec. If there's not a link, just Google it. While this might not sound helpful, I've learned about a lot of things just by hearing a term for the first time and then reading the Wikipedia article for it. If you notice anything wrong with this page, feel free to [contact me](/contact) or [open an issue on GitHub](https://github.com/Brcrwilliams/brcrwilliams.github.io/issues/new). ### Web Application Vulnerabilities * [SQL Injection \(SQLi\)](https://www.owasp.org/index.php/SQL_Injection) * [Cross Site Scripting \(XSS\)](<https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)>) - See [XSS Games](#xss-games) for practice * [Cross Site Request Forgery \(CSRF\)](<https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)>) * [Server Side Request Forgery \(SSRF\)](https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF) * [Insecure Direct Object References](<https://www.owasp.org/index.php/Testing_for_Insecure_Direct_Object_References_(OTG-AUTHZ-004)>) * [Path Traversal](https://en.wikipedia.org/wiki/Directory_traversal_attack) * [XML External Entity Injection \(XXE\)](https://blog.bugcrowd.com/advice-from-a-researcher-xxe/) * [OS Command Injection](https://www.owasp.org/index.php/Command_Injection) * [Buffer Overflow](https://en.wikipedia.org/wiki/Buffer_overflow) - More common in desktop / server software than web applications ### Cryptography This section is WIP, but decent explanations for all of these can be found by Googling. * [Journey Into Cryptography](https://www.khanacademy.org/computing/computer-science/cryptography) - Khan Academy course, highly recommended that you start here. * [AES cipher explained in comic form](http://www.moserware.com/2009/09/stick-figure-guide-to-advanced.html) * Known- / Chosen- / Adaptive Chosen Plaintext Attacks * Known- / Chosen- / Adaptive Chosen Ciphertext Attacks * Brute Force Attack * Side-Channel Attack * Frequency Analysis \(Applies to classical ciphers\) * Collision Attack * Birthday Attack * Padding Oracle Attack * Replay Attack ### Hashing and Password Storage * [Hashing + Salting](https://crackstation.net/hashing-security.htm) * [Rainbow Tables](http://kestas.kuliukas.com/RainbowTables/) * [Dictionary Attack](https://blog.codinghorror.com/dictionary-attacks-101/) * [Preventing bad passwords](https://www.usenix.org/conference/usenixsecurity16/technical-sessions/presentation/wheeler) - By the creators of [zxcvbn](https://github.com/dropbox/zxcvbn) \(Scroll down to the video\) ### Penetration Testing * [Windows Privilege Escalation](http://www.fuzzysecurity.com/tutorials/16.html) * [Linux Privilege Escalation Cheatsheet](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/) ### Challenges The best way to truly learn something is to practice it once you have an idea of the basic concepts. Making mistakes and learning how and why something works or doesn't work is key to gaining a deeper understanding of technical concepts. Below are some challenges that you may use to test your knowledge and (hopefully) learn new things. * [Over the Wire: Bandit](http://overthewire.org/wargames/bandit/) - Highly recommended for beginners - Basic Bash / Linux usage and basic security concepts * [Under The Wire](http://www.underthewire.tech/wargames.htm) - Similar to Bandit, but will teach you about Windows PowerShell * [SQLNinja](http://leettime.net/sqlninja.com/) - Basic SQL Injection * [Over the Wire: Natas](http://overthewire.org/wargames/natas/) - Web Application Security - Higher level challenges involve Command Injection, SQL Injection, and scripting * [Over the Wire: Krypton](http://overthewire.org/wargames/krypton/) - Cryptography / Classical Ciphers * [Hack This Site](https://www.hackthissite.org/) - CTF-style Challenges * [Hack The Box](https://www.hackthebox.eu/) - General Penetration Testing <a id="xss-games"></a> ### XSS Games There are so many of these that they deserve their own section. Most of these challenges are great for beginners and a good way to learn about injection and filter evasion. * [XSS Challenge (yamagata21)](https://xss-quiz.int21h.jp/) * [XSS Game (appspot)](https://xss-game.appspot.com/) * [alert(1) to win](https://alf.nu/alert1) * [prompt(1) to win](http://prompt.ml/0) \(Very difficult\) * [cure53's XSS Challenge List](https://github.com/cure53/XSSChallengeWiki/wiki)
{ "content_hash": "e72c921c9b0ad6312c1767ca8ca7e7be", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 504, "avg_line_length": 68.74666666666667, "alnum_prop": 0.765321955003879, "repo_name": "Brcrwilliams/brcrwilliams.github.io", "id": "0ff5f9c523ff88d85b959a0d5bffcd3c736b3b02", "size": "5160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resource/resources.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25037" }, { "name": "HTML", "bytes": "26464" }, { "name": "Ruby", "bytes": "2064" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="tv_content_margin">20dp</dimen> <dimen name="content_box_margin_bottom">35dp</dimen> <dimen name="button_min_width">90dp</dimen> </resources>
{ "content_hash": "a136b3127f37040e1bb0b205df4ea975", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 28, "alnum_prop": 0.65625, "repo_name": "liyinyin/MaterialShowcaseView", "id": "c358c5f5b7bd1983c056243069fe410f78e0a88c", "size": "224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/res/values/dimens.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "68937" } ], "symlink_target": "" }
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoisfsite.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
{ "content_hash": "05880bec7a41db36831495a58d7fdd92", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 77, "avg_line_length": 26, "alnum_prop": 0.717948717948718, "repo_name": "letuananh/intsem.fx", "id": "6502be787353cc0b8f07048bfbafbac96cfa06ee", "size": "256", "binary": false, "copies": "1", "ref": "refs/heads/dev-0.2.3", "path": "manage.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "4388639" }, { "name": "Shell", "bytes": "3771" }, { "name": "TSQL", "bytes": "3718" } ], "symlink_target": "" }
// Karma configuration // Generated on Fri Dec 05 2014 16:49:29 GMT-0500 (EST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jspm', 'jasmine'], jspm: { // Edit this to your needs loadFiles: ['test/**/*.js'], serveFiles : ['src/**/*.js'] }, // list of files / patterns to load in the browser files: [], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/**/*.js': ['babel'], 'src/**/*.js': ['babel'] }, 'babelPreprocessor': { options: { sourceMap: 'inline', presets: [ 'es2015-loose', 'stage-1'], plugins: [ 'syntax-flow', 'transform-decorators-legacy', 'transform-flow-strip-types' ] } }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
{ "content_hash": "ead27e941fdb7f66ad837cc2144f819a", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 120, "avg_line_length": 24.765432098765434, "alnum_prop": 0.613160518444666, "repo_name": "stl-florida/casestudy-riskmap", "id": "82f6332240a895c497cd7799ff9629839090f9f3", "size": "2006", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/aurelia-framework/karma.conf.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2670" }, { "name": "HTML", "bytes": "3264" }, { "name": "JavaScript", "bytes": "1776505" } ], "symlink_target": "" }
<?php namespace YaoiTests\Helper\Service; class NoSettings extends BasicExposed { protected static function getSettingsClassName() { return null; } }
{ "content_hash": "d8a5f01f298afec4b0a6d89a098d73db", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 54, "avg_line_length": 18.444444444444443, "alnum_prop": 0.7289156626506024, "repo_name": "php-yaoi/php-yaoi", "id": "fa852955dfca86225e62c55197a357f8443105a3", "size": "166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/src/Helper/Service/NoSettings.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1306" }, { "name": "PHP", "bytes": "707354" }, { "name": "Shell", "bytes": "87" } ], "symlink_target": "" }
package http import ( "net/http" "os" gorillaHandlers "github.com/gorilla/handlers" "github.com/coreos/discovery.etcd.io/handlers" "github.com/gorilla/mux" ) func init() { r := mux.NewRouter() r.HandleFunc("/", handlers.HomeHandler) r.HandleFunc("/new", handlers.NewTokenHandler) r.HandleFunc("/health", handlers.HealthHandler) r.HandleFunc("/robots.txt", handlers.RobotsHandler) // Only allow exact tokens with GETs and PUTs r.HandleFunc("/{token:[a-f0-9]{32}}", handlers.TokenHandler). Methods("GET", "PUT") r.HandleFunc("/{token:[a-f0-9]{32}}/", handlers.TokenHandler). Methods("GET", "PUT") r.HandleFunc("/{token:[a-f0-9]{32}}/{machine}", handlers.TokenHandler). Methods("GET", "PUT", "DELETE") r.HandleFunc("/{token:[a-f0-9]{32}}/_config/size", handlers.TokenHandler). Methods("GET") logH := gorillaHandlers.LoggingHandler(os.Stdout, r) http.Handle("/", logH) }
{ "content_hash": "34c3538016ef9471ac69f2a38d1ee800", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 75, "avg_line_length": 26.470588235294116, "alnum_prop": 0.6888888888888889, "repo_name": "madharjan/discovery.etcd.io", "id": "d4e2b850b7e76c60e7da01f14e5c78aab68d5b9d", "size": "900", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "http/http.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "6869" }, { "name": "Shell", "bytes": "962" } ], "symlink_target": "" }
+++ date = "2016-03-06T21:17:14-06:00" title = "sponsor" type = "event" +++ We greatly value sponsors for this open event. If you are interested in sponsoring, please drop us an email at [{{< email_organizers >}}]. <hr> <h2>Sponsorship Packages</h2> <h3>Platinum Sponsor ($5000)</h3> * 3 tickets included * Table Space * Logo on Website, Main Room Signage & Email Communications * 3 Minute Pitch to Full Audience on Day One <h3>Gold Sponsor ($3000)</h3> * 2 tickets included * Table Space * Logo on Website, Main Room Signage & Email Communications <h3>Silver Sponsor ($1000)</h3> * 2 tickets included * Logo on Website, Main Room Signage & Email Communications <h3>A la carte opportunities (also available without sponsorship purchase):</h3> * Cocktail hour ‐ $5000 * Logo on conference bag ‐ $2500 * Lanyard sponsor ‐ $500 * Bag inserts ‐ $250 * Other opportunities available upon request <hr/> <!-- <div style="width:590px"> <table border=1 cellspacing=1> <tr> <th><i>packages</i></th> <th><center><b><u>Bronze<br />1000 usd</u></center></b></th> <th><center><b><u>Silver<br />3000 usd</u></center></b></th> <th><center><b><u>Gold<br />5000 usd</u></center></b></th> <th></th> </tr> <tr><td>2 included tickets</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr> <tr><td>logo on event website</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr> <tr><td>logo on shared slide, rotating during breaks</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr> <tr><td>logo on all email communication</td><td>&nbsp;</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr> <tr><td>logo on its own slide, rotating during breaks</td><td>&nbsp;</td><td bgcolor="gold">&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr> <tr><td>1 minute pitch to full audience (including streaming audience)</td><td>&nbsp;</td><td>&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr></tr> <tr><td>2 additional tickets (4 in total)</td><td>&nbsp;</td><td bgcolor="gold">&nbsp;</td><td>&nbsp;</td></tr> <tr><td>4 additional tickets (6 in total)</td><td>&nbsp;</td><td>&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr> <tr><td>shared table for swag</td><td>&nbsp;</td><td bgcolor="gold">&nbsp;</td><td>&nbsp;</td></tr> <tr><td>booth/table space</td><td>&nbsp;</td><td>&nbsp;</td><td bgcolor="gold">&nbsp;</td></tr> </table> <hr/> There are also opportunities for exclusive special sponsorships. We'll have sponsors for various events with special privileges for the sponsors of these events. If you are interested in special sponsorships or have a creative idea about how you can support the event, <a href="mailto:<%= render(:partial => "/#{@eventhome}/_email_organizers") %>?subject=Sponsor devopsdays <%= @eventid %>">send us an email</a>. <br/> <br/> </div> --> <hr/>
{ "content_hash": "81290ffa886a35c48a9a94b4cb5ce574", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 412, "avg_line_length": 39.053333333333335, "alnum_prop": 0.6633663366336634, "repo_name": "masteinhauser/devopsdays-web", "id": "000799e35b1be6e774a71ecd05ca8b2332e4852d", "size": "2937", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "content/events/2016-raleigh/sponsor.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "344774" }, { "name": "GCC Machine Description", "bytes": "16" }, { "name": "HTML", "bytes": "22563018" }, { "name": "JavaScript", "bytes": "484" }, { "name": "Ruby", "bytes": "650" }, { "name": "Shell", "bytes": "2944" } ], "symlink_target": "" }
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Injectable } from 'angular2/src/core/di'; import { DOM } from 'angular2/src/core/dom/dom_adapter'; import { Map, MapWrapper } from 'angular2/src/facade/collection'; import { CONST, CONST_EXPR } from 'angular2/src/facade/lang'; import { BaseException } from 'angular2/src/facade/exceptions'; import { NgZone } from '../zone/ng_zone'; import { PromiseWrapper, ObservableWrapper } from 'angular2/src/facade/async'; /** * The Testability service provides testing hooks that can be accessed from * the browser and by services such as Protractor. Each bootstrapped Angular * application on the page will have an instance of Testability. */ export let Testability = class { constructor(_ngZone) { /** @internal */ this._pendingCount = 0; /** @internal */ this._callbacks = []; /** @internal */ this._isAngularEventPending = false; this._watchAngularEvents(_ngZone); } /** @internal */ _watchAngularEvents(_ngZone) { ObservableWrapper.subscribe(_ngZone.onTurnStart, (_) => { this._isAngularEventPending = true; }); _ngZone.runOutsideAngular(() => { ObservableWrapper.subscribe(_ngZone.onEventDone, (_) => { if (!_ngZone.hasPendingTimers) { this._isAngularEventPending = false; this._runCallbacksIfReady(); } }); }); } increasePendingRequestCount() { this._pendingCount += 1; return this._pendingCount; } decreasePendingRequestCount() { this._pendingCount -= 1; if (this._pendingCount < 0) { throw new BaseException('pending async requests below zero'); } this._runCallbacksIfReady(); return this._pendingCount; } isStable() { return this._pendingCount == 0 && !this._isAngularEventPending; } /** @internal */ _runCallbacksIfReady() { if (!this.isStable()) { return; // Not ready } // Schedules the call backs in a new frame so that it is always async. PromiseWrapper.resolve(null).then((_) => { while (this._callbacks.length !== 0) { (this._callbacks.pop())(); } }); } whenStable(callback) { this._callbacks.push(callback); this._runCallbacksIfReady(); } getPendingRequestCount() { return this._pendingCount; } // This only accounts for ngZone, and not pending counts. Use `whenStable` to // check for stability. isAngularEventPending() { return this._isAngularEventPending; } findBindings(using, provider, exactMatch) { // TODO(juliemr): implement. return []; } findProviders(using, provider, exactMatch) { // TODO(juliemr): implement. return []; } }; Testability = __decorate([ Injectable(), __metadata('design:paramtypes', [NgZone]) ], Testability); export let TestabilityRegistry = class { constructor() { /** @internal */ this._applications = new Map(); testabilityGetter.addToWindow(this); } registerApplication(token, testability) { this._applications.set(token, testability); } getAllTestabilities() { return MapWrapper.values(this._applications); } findTestabilityInTree(elem, findInAncestors = true) { if (elem == null) { return null; } if (this._applications.has(elem)) { return this._applications.get(elem); } else if (!findInAncestors) { return null; } if (DOM.isShadowRoot(elem)) { return this.findTestabilityInTree(DOM.getHost(elem)); } return this.findTestabilityInTree(DOM.parentElement(elem)); } }; TestabilityRegistry = __decorate([ Injectable(), __metadata('design:paramtypes', []) ], TestabilityRegistry); let NoopGetTestability = class { addToWindow(registry) { } }; NoopGetTestability = __decorate([ CONST(), __metadata('design:paramtypes', []) ], NoopGetTestability); export function setTestabilityGetter(getter) { testabilityGetter = getter; } var testabilityGetter = CONST_EXPR(new NoopGetTestability()); //# sourceMappingURL=testability.js.map
{ "content_hash": "40616e031c5c5447f64e7bdc29d938ba", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 134, "avg_line_length": 37.8421052631579, "alnum_prop": 0.6147426981919333, "repo_name": "aayushkapoor206/whatshot", "id": "33f0496b799a0072c444cd81617428d7595c6a78", "size": "5033", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/angular2/es6/prod/src/core/testability/testability.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "16341" }, { "name": "C", "bytes": "1025" }, { "name": "CSS", "bytes": "9519" }, { "name": "HTML", "bytes": "25020" }, { "name": "Java", "bytes": "261362" }, { "name": "JavaScript", "bytes": "8727789" }, { "name": "Objective-C", "bytes": "222961" }, { "name": "Shell", "bytes": "1927" } ], "symlink_target": "" }
/* * Tests for the scalar example solving the test equation */ #include <cmath> using namespace std; #include <gtest/gtest.h> #include <gmock/gmock.h> using namespace ::testing; #include <pfasst/quadrature.hpp> #define PFASST_UNIT_TESTING #include "../examples/scalar/scalar_sdc.cpp" #undef PFASST_UNIT_TESTING using namespace pfasst::examples::scalar; /* * parameterized test fixture with number of nodes as parameter */ class ConvergenceTest : public TestWithParam<tuple<size_t, pfasst::quadrature::QuadratureType>> { protected: size_t nnodes; size_t niters; double end_time; vector<size_t> nsteps; vector<double> err; vector<double> convrate; complex<double> lambda; pfasst::quadrature::QuadratureType nodetype; public: virtual void SetUp() { this->nnodes = get<0>(GetParam()); this->nodetype = get<1>(GetParam()); switch (this->nodetype) { case pfasst::quadrature::QuadratureType::GaussLobatto: this->niters = 2 * this->nnodes - 2; this->end_time = 4.0; this->lambda = complex<double>(-1.0, 1.0); this->nsteps = { 2, 5, 10, 15 }; break; case pfasst::quadrature::QuadratureType::GaussLegendre: this->niters = 2 * this->nnodes; this->end_time = 6.0; this->lambda = complex<double>(-1.0, 2.0); this->nsteps = { 2, 4, 6, 8, 10 }; break; case pfasst::quadrature::QuadratureType::GaussRadau: this->niters = 2 * this->nnodes; this->end_time = 5.0; this->lambda = complex<double>(-1.0, 2.0); this->nsteps = { 4, 6, 8, 10, 12 }; break; case pfasst::quadrature::QuadratureType::ClenshawCurtis: this->niters = this->nnodes + 1; this->end_time = 1.0; this->lambda = complex<double>(-1.0, 1.0); this->nsteps = { 7, 9, 11, 13 }; break; case pfasst::quadrature::QuadratureType::Uniform: this->niters = this->nnodes; this->end_time = 5.0; this->lambda = complex<double>(-1.0, 1.0); this->nsteps = { 9, 11, 13, 15 }; break; default: break; } // run to compute errors for (size_t i = 0; i < this->nsteps.size(); ++i) { auto dt = this->end_time / double(this->nsteps[i]); this->err.push_back(run_scalar_sdc(this->nsteps[i], dt, this->nnodes, this->niters, this->lambda, this->nodetype)); } // compute convergence rates for (size_t i = 0; i < this->nsteps.size() - 1; ++i) { this->convrate.push_back(log10(this->err[i+1] / this->err[i]) / log10(double(this->nsteps[i]) / double(this->nsteps[i + 1]))); } } }; /* * The test below verifies that the code approximately (up to a safety factor) reproduces * the theoretically expected rate of convergence */ TEST_P(ConvergenceTest, AllNodes) { int order; string quad; double fudge = 0.9; switch (this->nodetype) { case pfasst::quadrature::QuadratureType::GaussLobatto: order = 2 * this->nnodes - 2; quad = "Gauss-Lobatto"; break; case pfasst::quadrature::QuadratureType::GaussLegendre: order = 2 * this->nnodes; quad = "Gauss-Legendre"; break; case pfasst::quadrature::QuadratureType::GaussRadau: order = 2 * this->nnodes; quad = "Gauss-Radau"; break; case pfasst::quadrature::QuadratureType::ClenshawCurtis: order = this->nnodes; quad = "Clenshaw-Curtis"; break; case pfasst::quadrature::QuadratureType::Uniform: order = this->nnodes; fudge = 0.8; quad = "Uniform"; break; default: EXPECT_TRUE(false); break; } for (size_t i = 0; i < this->nsteps.size() - 1; ++i) { EXPECT_THAT(convrate[i], Ge<double>(fudge * order)) << "Convergence rate for " << this->nnodes << " " << quad << " nodes" << " for nsteps " << this->nsteps[i] << " not within expected range."; } } INSTANTIATE_TEST_CASE_P(ScalarSDC, ConvergenceTest, Combine(Range<size_t>(3, 7), Values(pfasst::quadrature::QuadratureType::GaussLobatto, pfasst::quadrature::QuadratureType::GaussLegendre, pfasst::quadrature::QuadratureType::GaussRadau, pfasst::quadrature::QuadratureType::ClenshawCurtis, pfasst::quadrature::QuadratureType::Uniform))); int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
{ "content_hash": "0856fb0059d069d48355f82083bc4093", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 98, "avg_line_length": 30.44375, "alnum_prop": 0.5536850749332786, "repo_name": "memmett/PFASST", "id": "64a5401c3e627655e77f8e96d677b6ed2aacbf41", "size": "4871", "binary": false, "copies": "2", "ref": "refs/heads/development", "path": "tests/examples/scalar/test_scalar_conv.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "549156" }, { "name": "CMake", "bytes": "29333" }, { "name": "Emacs Lisp", "bytes": "6482" }, { "name": "Shell", "bytes": "136" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <sem:triples uri="http://www.lds.org/vrl/objects/office-supplies/glue" xmlns:sem="http://marklogic.com/semantics"> <sem:triple> <sem:subject>http://www.lds.org/vrl/objects/office-supplies/glue</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate> <sem:object datatype="xsd:string" xml:lang="eng">Glue</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/vrl/objects/office-supplies/glue</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate> <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/vrl/objects/office-supplies/glue</sem:subject> <sem:predicate>http://www.lds.org/core#entityType</sem:predicate> <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object> </sem:triple> </sem:triples>
{ "content_hash": "66b91828125c6b46b96041bbb291381c", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 114, "avg_line_length": 54, "alnum_prop": 0.7057613168724279, "repo_name": "freshie/ml-taxonomies", "id": "1d6c28d78ac2a768977603a8b0e8b48f0e46b9d2", "size": "972", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "roxy/data/gospel-topical-explorer-v2/taxonomies/vrl/objects/office-supplies/glue.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4422" }, { "name": "CSS", "bytes": "38665" }, { "name": "HTML", "bytes": "356" }, { "name": "JavaScript", "bytes": "411651" }, { "name": "Ruby", "bytes": "259121" }, { "name": "Shell", "bytes": "7329" }, { "name": "XQuery", "bytes": "857170" }, { "name": "XSLT", "bytes": "13753" } ], "symlink_target": "" }
package com.glaf.core.todo.util; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.glaf.core.todo.Todo; import com.glaf.core.util.Tools; public class TodoXmlReader { public List<Todo> read(java.io.InputStream inputStream) { List<Todo> todos = new java.util.ArrayList<Todo>(); SAXReader xmlReader = new SAXReader(); int sortNo = 1; try { Document doc = xmlReader.read(inputStream); Element root = doc.getRootElement(); List<?> rows = root.elements(); Iterator<?> iterator = rows.iterator(); while (iterator.hasNext()) { Element element = (Element) iterator.next(); String id = element.attributeValue("id"); Map<String, Object> rowMap = new java.util.HashMap<String, Object>(); rowMap.put("id", id); List<?> properties = element.elements("property"); Iterator<?> iter = properties.iterator(); while (iter.hasNext()) { Element elem = (Element) iter.next(); String propertyName = elem.attributeValue("name"); String propertyValue = null; if (elem.attribute("value") != null) { propertyValue = elem.attributeValue("value"); } else { propertyValue = elem.getTextTrim(); } if (StringUtils.isNotEmpty(propertyName) && StringUtils.isNotEmpty(propertyValue)) { rowMap.put(propertyName, propertyValue); } } Todo model = new Todo(); model.setSortNo(sortNo++); Tools.populate(model, rowMap); todos.add(model); } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } return todos; } }
{ "content_hash": "6b5a35d1489405e189549c06def241cd", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 73, "avg_line_length": 27.967741935483872, "alnum_prop": 0.674163783160323, "repo_name": "jior/glaf", "id": "53c86d666e5af9e9473ef1ddd9d64aec772cfbe0", "size": "2539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workspace/glaf-core/src/main/java/com/glaf/core/todo/util/TodoXmlReader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "953184" }, { "name": "HTML", "bytes": "101839" }, { "name": "Java", "bytes": "15039259" }, { "name": "JavaScript", "bytes": "1698821" }, { "name": "Perl", "bytes": "19688" }, { "name": "Python", "bytes": "6598" }, { "name": "Shell", "bytes": "173092" }, { "name": "XSLT", "bytes": "225698" } ], "symlink_target": "" }
package exec_test import ( "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "log" "os" "os/exec" "strings" "time" ) func ExampleLookPath() { path, err := exec.LookPath("fortune") if err != nil { log.Fatal("installing fortune is in your future") } fmt.Printf("fortune is available at %s\n", path) } func ExampleCommand() { cmd := exec.Command("tr", "a-z", "A-Z") cmd.Stdin = strings.NewReader("some input") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) } fmt.Printf("in all caps: %q\n", out.String()) } func ExampleCommand_environment() { cmd := exec.Command("prog") cmd.Env = append(os.Environ(), "FOO=duplicate_value", // ignored "FOO=actual_value", // this value is used ) if err := cmd.Run(); err != nil { log.Fatal(err) } } func ExampleCmd_Output() { out, err := exec.Command("date").Output() if err != nil { log.Fatal(err) } fmt.Printf("The date is %s\n", out) } func ExampleCmd_Start() { cmd := exec.Command("sleep", "5") err := cmd.Start() if err != nil { log.Fatal(err) } log.Printf("Waiting for command to finish...") err = cmd.Wait() log.Printf("Command finished with error: %v", err) } func ExampleCmd_StdoutPipe() { cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`) stdout, err := cmd.StdoutPipe() if err != nil { log.Fatal(err) } if err := cmd.Start(); err != nil { log.Fatal(err) } var person struct { Name string Age int } if err := json.NewDecoder(stdout).Decode(&person); err != nil { log.Fatal(err) } if err := cmd.Wait(); err != nil { log.Fatal(err) } fmt.Printf("%s is %d years old\n", person.Name, person.Age) } func ExampleCmd_StdinPipe() { cmd := exec.Command("cat") stdin, err := cmd.StdinPipe() if err != nil { log.Fatal(err) } go func() { defer stdin.Close() io.WriteString(stdin, "values written to stdin are passed to cmd's standard input") }() out, err := cmd.CombinedOutput() if err != nil { log.Fatal(err) } fmt.Printf("%s\n", out) } func ExampleCmd_StderrPipe() { cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") stderr, err := cmd.StderrPipe() if err != nil { log.Fatal(err) } if err := cmd.Start(); err != nil { log.Fatal(err) } slurp, _ := ioutil.ReadAll(stderr) fmt.Printf("%s\n", slurp) if err := cmd.Wait(); err != nil { log.Fatal(err) } } func ExampleCmd_CombinedOutput() { cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") stdoutStderr, err := cmd.CombinedOutput() if err != nil { log.Fatal(err) } fmt.Printf("%s\n", stdoutStderr) } func ExampleCommandContext() { ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil { // This will fail after 100 milliseconds. The 5 second sleep // will be interrupted. } }
{ "content_hash": "2fc4fdf239b7652df0e9c8f94da86a44", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 85, "avg_line_length": 19.99310344827586, "alnum_prop": 0.6215936529837875, "repo_name": "linux-on-ibm-z/go", "id": "b70b99032523c299ac84d260f17b9cb4621af56c", "size": "3059", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/os/exec/example_test.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "2264499" }, { "name": "Awk", "bytes": "450" }, { "name": "Batchfile", "bytes": "7351" }, { "name": "C", "bytes": "197306" }, { "name": "C++", "bytes": "1370" }, { "name": "CSS", "bytes": "8" }, { "name": "Fortran", "bytes": "394" }, { "name": "Go", "bytes": "33948224" }, { "name": "HTML", "bytes": "1806598" }, { "name": "JavaScript", "bytes": "2550" }, { "name": "Logos", "bytes": "1248" }, { "name": "Makefile", "bytes": "748" }, { "name": "Perl", "bytes": "34799" }, { "name": "Protocol Buffer", "bytes": "1698" }, { "name": "Python", "bytes": "12446" }, { "name": "Shell", "bytes": "68442" } ], "symlink_target": "" }
package com.cinchapi.concourse.example.bank; import java.util.ArrayDeque; import java.util.Set; import com.cinchapi.concourse.Concourse; import com.cinchapi.concourse.Link; import com.cinchapi.concourse.TransactionException; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; /** * An implementation of the {@link Account} interface that uses Concourse for * data storage. * * @author Jeff Nelson */ public class ConcourseAccount implements Account { // NOTE: For the purpose of this example, we don't store any data about the // Account locally so that we can illustrate how you would query Concourse // to get the data. In a real application, you always want to cache // repeatedly used data locally. /** * Since Concourse does not have tables, we store a special key in each * record to indicate the class to which the record/object belongs. This * isn't necessary, but it helps to ensure logical consistency between the * application and the database. */ private final static String CLASS_KEY_NAME = "_class"; /** * The id of the Concourse record that holds the data for an instance of * this class. */ private final long id; /** * This constructor creates a new record in Concourse and inserts the data * expressed in the parameters. * * @param balance the initial balance for the account * @param owners {@link Customer customers} that are owners on the account */ public ConcourseAccount(double balance, Customer... owners) { Preconditions.checkArgument(balance > 0); Concourse concourse = Constants.CONCOURSE_CONNECTIONS.request(); try { Multimap<String, Object> data = HashMultimap.create(); data.put(CLASS_KEY_NAME, getClass().getName()); data.put("balance", balance); for (Customer owner : owners) { data.put("owners", Link.to(owner.getId())); } this.id = concourse.insert(data); // The #insert method is atomic, // so we don't need a transaction // to safely commit all the data } finally { Constants.CONCOURSE_CONNECTIONS.release(concourse); } } /** * This constructor loads an existing object from Concourse. * * @param id the id of the record that holds the data for the object we want * to load */ public ConcourseAccount(long id) { Concourse concourse = Constants.CONCOURSE_CONNECTIONS.request(); try { Preconditions.checkArgument(getClass().getName().equals( concourse.get(CLASS_KEY_NAME, id))); this.id = id; // NOTE: If this were a real application, it would be a god idea to // preload frequently used attributes here and cache them locally // (or maybe even in an external cache like Memcache or Redis). } finally { Constants.CONCOURSE_CONNECTIONS.release(concourse); } } @Override public boolean debit(String charge, double amount) { Preconditions.checkArgument(amount > 0); Concourse concourse = Constants.CONCOURSE_CONNECTIONS.request(); try { concourse.stage(); if(withdrawImpl(concourse, amount)) { // By using the #add method, we can store multiple charges in // the record at the same time concourse.add("charges", charge, id); return concourse.commit(); } else { concourse.abort(); return false; } } catch (TransactionException e) { concourse.abort(); return false; } finally { Constants.CONCOURSE_CONNECTIONS.release(concourse); } } @Override public boolean deposit(double amount) { Preconditions.checkArgument(amount > 0); // This implementation uses verifyAndSwap to atomically increment the // account balance (without a using a transaction!) which ensures that // money isn't lost if two people make a deposit at the same time. Concourse concourse = Constants.CONCOURSE_CONNECTIONS.request(); try { boolean incremented = false; while (!incremented) { double balance = concourse.get("balance", id); double newBalance = balance + amount; if(concourse.verifyAndSwap("balance", balance, id, newBalance)) { incremented = true; } else { // verifyAndSwap will fail if the balance changed since the // initial read. If that happens, we simply retry continue; } } return true; } finally { Constants.CONCOURSE_CONNECTIONS.release(concourse); } } @Override public double getBalance() { Concourse concourse = Constants.CONCOURSE_CONNECTIONS.request(); try { return concourse.get("balance", id); } finally { Constants.CONCOURSE_CONNECTIONS.release(concourse); } } @Override public long getId() { return id; } @Override public Customer[] getOwners() { Concourse concourse = Constants.CONCOURSE_CONNECTIONS.request(); try { Set<Link> customerLinks = concourse.select("owners", id); Customer[] owners = new Customer[customerLinks.size()]; int index = 0; for (Link link : customerLinks) { owners[index] = new ConcourseCustomer(link.longValue()); ++index; } return owners; } finally { Constants.CONCOURSE_CONNECTIONS.release(concourse); } } @Override public boolean withdraw(double amount) { return debit("withdraw " + amount, amount); } /** * An internal method that transfers money (if possible) from this account * to an {@code other} one. This method doesn't start a transaction because * it assumes that the caller has already done so. * * @param concourse the connection to Concourse that is retrieved from * {@link Constants#CONCOURSE_CONNECTIONS} * @param other the recipient {@link ConcourseAccount account} for the * transferred funds * @param amount the amount to transfer from this account. * @return the amount of money that is actually transferred from this * account to {@code other}. An account can only transfer as much * money as it has. So, if this account has a balance that is * smaller than {@code amount}, it will transfer only how much it * has. */ private double transferTo(Concourse concourse, ConcourseAccount other, double amount) { double balance = concourse.get("balance", id); if(balance > 0) { double toTransfer = balance > amount ? amount : balance; balance -= toTransfer; double otherBalance = concourse.get("balance", other.getId()); otherBalance += toTransfer; concourse.set("balance", balance, id); concourse.set("balance", otherBalance, other.getId()); concourse.add("charges", "transfer " + toTransfer + " to account " + other.getId(), id); return toTransfer; } else { return 0; } } /** * An implementation that withdraws {@code amount} of money from this * account using the provided {@code concourse} connection. This method does * not start a new transaction because it assumes that the caller has * already done so. * * @param concourse the connection to Concourse that is retrieved from * {@link Constants#CONCOURSE_CONNECTIONS} * @param amount the amount to withdraw * @return {@code true} if the withdrawal is successful (e.g. there is * enough money in the account (possibly after transferring from * other accounts) to withdraw the money without leaving a negative * balance). */ private boolean withdrawImpl(Concourse concourse, double amount) { double balance = concourse.get("balance", id); double need = amount - balance; if(need > 0) { // Get all the other accounts that are owned by the owners of this // account StringBuilder criteria = new StringBuilder(); criteria.append(CLASS_KEY_NAME).append(" = ") .append(getClass().getName()); criteria.append(" AND ("); boolean first = true; for (Customer owner : getOwners()) { if(!first) { criteria.append(" OR "); } first = false; criteria.append("owners lnks2 ").append(owner.getId()); } criteria.append(")"); Set<Long> otherAccounts = concourse.find(criteria.toString()); ArrayDeque<Long> stack = new ArrayDeque<Long>(otherAccounts); while (need > 0 && !stack.isEmpty()) { long rid = stack.pop(); if(rid == id) { // Don't try to transfer money from the same account as // this! continue; } ConcourseAccount other = new ConcourseAccount(rid); double transferred = other.transferTo(concourse, this, need); // NOTE: We don't need to worry about the balance changing by // another client. If that happens, the transaction will // automatically fail balance += transferred; need -= transferred; } if(need > 0) { return false; } } concourse.set("balance", balance - amount, id); return true; } }
{ "content_hash": "e55d64b0b2bc3e164e67d9f6b7423f74", "timestamp": "", "source": "github", "line_count": 273, "max_line_length": 81, "avg_line_length": 38.1941391941392, "alnum_prop": 0.5763882228829001, "repo_name": "vrnithinkumar/concourse", "id": "688e29a896a2f68be6c5d0c0d6571b7ef26cee7c", "size": "11581", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "examples/bank-overdraft-protection/java/src/main/java/com/cinchapi/concourse/example/bank/ConcourseAccount.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6985" }, { "name": "Groff", "bytes": "47944" }, { "name": "Groovy", "bytes": "84589" }, { "name": "HTML", "bytes": "36688" }, { "name": "Java", "bytes": "3592108" }, { "name": "Makefile", "bytes": "123" }, { "name": "PHP", "bytes": "2446828" }, { "name": "Python", "bytes": "165444" }, { "name": "Ruby", "bytes": "261512" }, { "name": "Shell", "bytes": "116645" }, { "name": "Thrift", "bytes": "104012" } ], "symlink_target": "" }
#include "stdafx.h" #include "demo_use.h" #include <boost/function.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> demo_use::demo_use(void) { } demo_use::~demo_use(void) { } void demo_use::run_server(){ my_server.run(); } void demo_use::handler_accept( LPVOID lparam, connection_ptr connect_ptr_, const boost::system::error_code& e ){ if ( e ) { //OUTPUT_DEBUG( e.message() ); connect_ptr_->clear(); return ; } printf_s( "[accept] handler: %s:%d\n", connect_ptr_->endpoint().address().to_string().c_str(), connect_ptr_->endpoint().port() ); //save connect_ptr_ //boost::asio::ip::tcp::endpoint accept_endpoint_; //accept_endpoint_ = connect_ptr_->socket().remote_endpoint(); //std::string str_ = accept_endpoint_.address().to_string(); //unsigned short port_ = accept_endpoint_.port(); my_server.recv(connect_ptr_, 10, &demo_use::handler_recv, shared_from_this(), reinterpret_cast<LPVOID>(NULL) ); my_server.start_accept( m_listenor_ptr_, &demo_use::handler_accept, shared_from_this(), reinterpret_cast<LPVOID>(NULL) ); } void demo_use::handler_recv( LPVOID lparam, connection_ptr connect_ptr_, const boost::system::error_code& e, size_t bytes_transferred_ ){ if ( e ) { //OUTPUT_DEBUG( e.message() ); connect_ptr_->clear(); return ; } printf_s( "[recv] handler: %s:%d (%d)\n", connect_ptr_->endpoint().address().to_string().c_str(), connect_ptr_->endpoint().port(), bytes_transferred_ ); std::string str( reinterpret_cast<char*>( connect_ptr_->buff_temp().c_array()), bytes_transferred_); printf_s( "%s\n", str.c_str() ); connect_ptr_->clear(); //my_server.recv(connect_ptr_, 0, &demo_use::handler_recv, shared_from_this(), reinterpret_cast<LPVOID>( NULL )); } void demo_use::handler_connect( LPVOID lparam, connection_ptr connect_ptr_, const boost::system::error_code& e ){ if ( e ) { //OUTPUT_DEBUG( e.message() ); std::string str = e.message(); int d = e.value(); connect_ptr_->clear(); return ; } printf_s( "[conn] handler: %s:%d\n", connect_ptr_->endpoint().address().to_string().c_str(), connect_ptr_->endpoint().port() ); } void demo_use::handler_send( LPVOID lparam, connection_ptr connect_ptr_, const boost::system::error_code& e ){ if ( e ) { //OUTPUT_DEBUG( e.message() ); connect_ptr_->clear(); return ; } printf_s( "[send] handler: %s:%d\n", connect_ptr_->endpoint().address().to_string().c_str(), connect_ptr_->endpoint().port() ); } void demo_use::test_1(){ HANDLE h; h = CreateEvent( NULL, FALSE, FALSE, NULL ); sync_single ds; //boost::function<void ()> g = boost::ref(ds); connection_ptr ptr_ = my_server.create_connect( std::string("www.baidu32.com"), std::string("80") , &demo_use::handler_connect_s , shared_from_this(), ds.call() ); ds.Wait(); boost::array<unsigned char, 64> array_; std::string str_( "GET / HTTP/1.1\r\nAccept: *.*\r\nHost: weibo.com\r\n\r\n\r\n" ); memcpy( array_.c_array(), str_.c_str(), str_.length() ); my_server.send( ptr_, array_.c_array(), str_.length(), &demo_use::handler_send_s, shared_from_this(), ds.call() ); ds.Wait(); my_server.recv( ptr_, 10, &demo_use::handler_recv_s, shared_from_this(), ds.call() ); ds.Wait(); int a=1; a++; ++a; } /////////////////////////////////////////////////////////////////////////////////////// DWORD thread_server_test( boost::shared_ptr<demo_use> ptr_ ){ Sleep(20); ptr_->test_1(); return 0; } void run(){ /* HANDLE hEvent = CreateEvent( NULL,FALSE, FALSE, NULL ); DWORD n1 = GetTickCount(); boost::thread tt( [&](){if(hEvent!=NULL){Sleep(500);SetEvent(hEvent);}} ); WaitForSingleObject(hEvent, INFINITE ); DWORD n2 = GetTickCount(); printf_s( "Test tick count = %d \n", n2 -n1 ); CloseHandle(hEvent); return ; */ boost::shared_ptr<demo_use> p_use( new demo_use() ); boost::thread t(boost::bind( thread_server_test,p_use)); //t.join(); try { p_use->run_server(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } }
{ "content_hash": "0315d68b618fdc7ffbd59631b3e050c2", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 154, "avg_line_length": 25.329113924050635, "alnum_prop": 0.6174412793603199, "repo_name": "johnzhd/learnandtraining", "id": "25995c44315db0b0cb65693cdc51bfae48d7a44e", "size": "4002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "socket/demo_use.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3549" }, { "name": "C", "bytes": "1558694" }, { "name": "C++", "bytes": "2308609" }, { "name": "CSS", "bytes": "3660" }, { "name": "DOT", "bytes": "1898" }, { "name": "Lua", "bytes": "1709" }, { "name": "Objective-C", "bytes": "263339" }, { "name": "Shell", "bytes": "44575" } ], "symlink_target": "" }
package org.wso2.carbon.servlet; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.event.output.adapter.ui.UIOutputCallbackControllerService; public class ServiceHolder { private static ServiceHolder instance; private UIOutputCallbackControllerService uiOutputCallbackControllerService; private ServiceHolder(){ uiOutputCallbackControllerService = (UIOutputCallbackControllerService) PrivilegedCarbonContext .getThreadLocalCarbonContext() .getOSGiService(UIOutputCallbackControllerService.class,null); } public synchronized static ServiceHolder getInstance(){ if (instance==null){ instance= new ServiceHolder(); } return instance; } public UIOutputCallbackControllerService getUiOutputCallbackControllerService() { return uiOutputCallbackControllerService; } }
{ "content_hash": "cfb255d4acf38226b60e7dc16d330cbe", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 103, "avg_line_length": 32.607142857142854, "alnum_prop": 0.7502738225629791, "repo_name": "lasanthafdo/carbon-analytics-common", "id": "d864cecdb7e939873b46c066fb3d29f51de0ec9c", "size": "913", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/event-publisher/event-output-adapters/org.wso2.carbon.event.output.adapter.ui/org.wso2.carbon.event.output.adapter.ui.endpoint/src/main/java/org/wso2/carbon/servlet/ServiceHolder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35524" }, { "name": "HTML", "bytes": "36378" }, { "name": "Java", "bytes": "3777139" }, { "name": "JavaScript", "bytes": "5269584" }, { "name": "Thrift", "bytes": "6297" } ], "symlink_target": "" }
@class YPStatus; @interface YPStatusToolbar : UIView @property (nonatomic, strong) YPStatus *status; + (instancetype)toolbar; @end
{ "content_hash": "9427e05714aa299f4fee749e4d5a84f2", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 47, "avg_line_length": 16.75, "alnum_prop": 0.7611940298507462, "repo_name": "MichaelHuyp/YPSina", "id": "487d379ed63a6e5290844becc1f1ce55592583c6", "size": "316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "YPSina/Sina/Classes/Home/View/YPStatusToolbar.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1208218" }, { "name": "Ruby", "bytes": "156" }, { "name": "Shell", "bytes": "5689" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ JBoss, Home of Professional Open Source. ~ Copyright 2011, Red Hat, Inc., and individual contributors ~ as indicated by the @author tags. See the copyright.txt file in the ~ distribution for a full listing of individual contributors. ~ ~ This is free software; you can redistribute it and/or modify it ~ under the terms of the GNU Lesser General Public License as ~ published by the Free Software Foundation; either version 2.1 of ~ the License, or (at your option) any later version. ~ ~ This software is distributed in the hope that it will be useful, ~ but WITHOUT ANY WARRANTY; without even the implied warranty of ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ~ Lesser General Public License for more details. ~ ~ You should have received a copy of the GNU Lesser General Public ~ License along with this software; if not, write to the Free ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org. --> <module xmlns="urn:jboss:module:1.3" name="org.jboss.as.vault-tool"> <properties> <property name="jboss.api" value="private"/> <property name="jboss.require-java-version" value="1.7"/> </properties> <main-class name="org.jboss.as.security.vault.VaultTool"/> <resources> </resources> <dependencies> <module name="org.jboss.as.security"/> </dependencies> </module>
{ "content_hash": "e7d60f82936f5dc4b6827aee7708ce57", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 71, "avg_line_length": 38.58974358974359, "alnum_prop": 0.7003322259136212, "repo_name": "mlaursen/brews-wildfly-server", "id": "2f9b79785f572a71199890c9dd7dc87c3570218c", "size": "1505", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "modules/system/layers/base/org/jboss/as/vault-tool/main/module.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "45501" }, { "name": "CSS", "bytes": "513088" }, { "name": "HTML", "bytes": "361337" }, { "name": "JavaScript", "bytes": "1664986" }, { "name": "PowerShell", "bytes": "11157" }, { "name": "Shell", "bytes": "57576" } ], "symlink_target": "" }
package org.olat.system.coordinate.cache.singlevm; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheException; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.apache.log4j.Logger; import org.olat.system.commons.resource.OLATResourceable; import org.olat.system.commons.resource.OresHelper; import org.olat.system.coordinate.cache.CacheConfig; import org.olat.system.coordinate.cache.CacheWrapper; import org.olat.system.exception.OLATRuntimeException; import org.olat.system.logging.log4j.LoggerHelper; /** * Description:<br> * this class is threadsafe. this is the singleVM implementation of the cachewrapper. it uses an ehcache as its internal cache. * <P> * Initial Date: 03.10.2007 <br> * * @author Felix Jost, http://www.goodsolutions.ch */ public class CacheWrapperImpl implements CacheWrapper { private static final Logger log = LoggerHelper.getLogger(); private final String cacheName; // the fully qualified name of the cache private final CacheConfig config; private final CacheManager cachemanager; private Cache cache; private Map<String, CacheWrapper> children = null; /** * @param cache */ protected CacheWrapperImpl(String cacheName, CacheConfig config) { this.cacheName = cacheName; this.config = config; this.cachemanager = CacheManager.getInstance(); // now we need a cache which has appropriate (by configuration) values for cache configs such as ttl, tti, max elements and so on. // next line needed since cache can also be initialized through ehcache.xml if (cachemanager.cacheExists(cacheName)) { this.cache = cachemanager.getCache(cacheName); log.warn("using cache parameters from ehcache.xml for cache named '" + cacheName + "'"); } else { this.cache = config.createCache(cacheName); try { cachemanager.addCache(this.cache); } catch (CacheException e) { throw new OLATRuntimeException("Problem when initializing the caches", e); } } } /** * creates a new child instance. must be overridden by subclasses * * @param childName * @param config * @return */ protected CacheWrapper createChildCacheWrapper(String childName, CacheConfig aconfig) { return new CacheWrapperImpl(childName, aconfig); } /** * @return the map with the children or null */ protected Map<String, CacheWrapper> getChildren() { return children; } @Override public CacheWrapper getOrCreateChildCacheWrapper(OLATResourceable ores) { String childName = OresHelper.createStringRepresenting(ores).replace(":", "_"); String fullcacheName = cacheName + "@" + childName; synchronized (this) {// cluster_ok by definition of this class as used in single vm CacheWrapper cwChild = null; if (children == null) { children = new HashMap<String, CacheWrapper>(); } else { cwChild = children.get(childName); } if (cwChild == null) { // not found yet cwChild = createChildCacheWrapper(fullcacheName, config.createConfigFor(ores)); children.put(childName, cwChild); } return cwChild; } } // ---- cache get, set, remove @Override public Serializable get(String key) { Element elem; try { synchronized (cache) {// cluster_ok by definition of this class as used in single vm elem = cache.get(key); } } catch (IllegalStateException e) { throw new OLATRuntimeException("cache state error for cache " + cache.getName(), e); } catch (CacheException e) { throw new OLATRuntimeException("cache error for cache " + cache.getName(), e); } return elem == null ? null : elem.getValue(); } @Override public void remove(String key) { synchronized (cache) {// cluster_ok by definition of this class as used in single vm cache.remove(key); } } @Override public void update(String key, Serializable value) { // update is the same as put for the singlevm mode doPut(key, value); } private void doPut(String key, Serializable value) { Element element = new Element(key, value); synchronized (cache) {// cluster_ok by definition of this class as used in single vm cache.put(element); } } @Override public void put(String key, Serializable value) { // put is the same as update for the singlevm mode doPut(key, value); } @Override public void updateMulti(String[] keys, Serializable[] values) { int len = keys.length; synchronized (cache) {// cluster_ok by definition of this class as used in single vm for (int i = 0; i < len; i++) { Element element = new Element(keys[i], values[i]); cache.put(element); } } } protected String getCacheName() { return cacheName; } }
{ "content_hash": "84e7cd4dc1ea9e68f1e7109f0aafc9b7", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 138, "avg_line_length": 34.13461538461539, "alnum_prop": 0.6343661971830986, "repo_name": "huihoo/olat", "id": "5a0dbb097157a7592efee060001e62ddc99876d5", "size": "6120", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "OLAT-LMS/src/main/java/org/olat/system/coordinate/cache/singlevm/CacheWrapperImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "24445" }, { "name": "AspectJ", "bytes": "36132" }, { "name": "CSS", "bytes": "2135670" }, { "name": "HTML", "bytes": "2950677" }, { "name": "Java", "bytes": "50804277" }, { "name": "JavaScript", "bytes": "31237972" }, { "name": "PLSQL", "bytes": "64492" }, { "name": "Perl", "bytes": "10717" }, { "name": "Shell", "bytes": "79994" }, { "name": "XSLT", "bytes": "186520" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>水平滚动条拖动</title> <style> * { margin: 0; padding: 0; } .scroll { width: 400px; height: 8px; margin: 100px auto; background-color: #ccc; position: relative; } .bar { width: 8px; height: 22px; background-color: #369; position: absolute; top: -7px; left: 0; cursor: pointer; } .mask { width: 0; height: 100%; background-color: #369; position: absolute; top: 0; left: 0; } </style> </head> <body> <div class="scroll" id="scroll"> <div class="bar" ></div> <div class="mask"></div> </div> <div id="demo"></div> </body> </html> <script> var scrollBar = document.getElementById("scroll"); var bar = scrollBar.children[0]; var mask = scrollBar.children[1]; var demo = document.getElementById("demo"); // 按下滑块 bar.onmousedown = function (event) { var event = event || window.event; // var leftVal = event.clientX - scrollBar.offsetLeft; var leftVal = event.clientX - this.offsetLeft; // 接着拖动滑块,每滑动一点点都会调用 var that = this; document.onmousemove = function (event) { var event = event || window.event; // bar.style.left = event.clientX - leftVal - scrollBar.offsetLeft + "px"; that.style.left = event.clientX - leftVal + "px"; var val = parseInt(that.style.left); if (val <= 0) { that.style.left = 0; } else if(val >= (scrollBar.offsetWidth - that.offsetWidth)) { that.style.left = scrollBar.offsetWidth - that.offsetWidth + "px"; } // 遮罩盒子的宽度 // 计算百分比 demo.innerHTML = "已经走了:"+ parseInt(that.style.left) / (scrollBar.offsetWidth - that.offsetWidth) * 100 + "%"; mask.style.width = that.style.left; window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } } // 抬起滑块 document.onmouseup = function () { // 弹起鼠标不做任何操作 document.onmousemove = null; } </script>
{ "content_hash": "640b26f355f8cbaef3a36c980e890091", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 121, "avg_line_length": 27.229885057471265, "alnum_prop": 0.5086534402701561, "repo_name": "XYXiaoYuan/WebStudy", "id": "d03cf80aafd60bfaa32fa8c7a6b786a965876f96", "size": "2483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "04 前端基本功/常用案例/水平滚动条拖动.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "54502" }, { "name": "JavaScript", "bytes": "5996" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="nl-NL" xml:lang="nl-NL"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>LightZone: ZoneMapper: Luminosity vs. RGB</title><!--[if lt IE 7]> <script defer type="text/javascript" src="IE_PNG.js"></script> <link rel="stylesheet" type="text/css" href="IE.css" media="all"/> <![endif]--> <meta name="description" content="The difference between luminosity and RGB adjustments using the ZoneMapper."/> <link rel="stylesheet" type="text/css" href="Help.css" media="all"/> <link rel="stylesheet" type="text/css" href="Platform.css" media="all"/> </head> <body> <div id="banner"> <div id="banner_left"> <a href="index.html">LightZone Help</a> </div> <div id="banner_right"> <a href="index/index.html">Index</a> </div> </div><!-- LC_Index: ZoneMapper > luminosity vs. RGB --><!-- LC_Index: luminosity vs. RGB --> <a name="Tool-ZoneMapper-Luminosity_RGB"></a> <img src="images/app_icon-32.png" width="32" height="32" class="title_icon"/> <h1>ZoneMapper: Luminosity vs. RGB</h1> <a href="Tool-ZoneMapper-Keys.html" id="next">7 of 8</a> <p> <img src="images/Tool-ZoneMapper-Luminosity_RGB-en.png" width="206" height="236" class="inline_right"/> Each pixel in a digital photo is comprised of red, green, and blue (RGB) values. A pixel's <em>luminosity</em> ("brightness") value is a weighted average of those three values. </p> <p> Normally, adjustments using a ZoneMapper are done using luminosity values because there are virtually no unintended hue or saturation changes. </p> <p> However, on occasion, luminosity-based adjustments can result in problems such as <em>color-clipping</em>. For example, if your photo has saturated highlights such as a clear blue sky, then increasing brightness will clip colors in portions of the sky because pixels that are already saturated blue can't become more blue. </p> <p> Adjustments using the ZoneMapper can alternatively be done using RGB values directly to address problems such as color-clipping. For a given photo, it's best to experiment to see which type of adjustment looks better. </p> <div class="task_box"> <h2>To make RGB rather than luminosity adjustments:</h2> <ol> <li> Select the RGB radio button for a ZoneMapper tool. </li> </ol> </div> </body> </html><!-- vim:set et sw=2 ts=2: -->
{ "content_hash": "1680b7fd00c3e65873e2ed27357c451d", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 97, "avg_line_length": 30.946236559139784, "alnum_prop": 0.6104933981931897, "repo_name": "ktgw0316/LightZone", "id": "abc615989272c37046c8807a9455bedc229d1a7d", "size": "2878", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lightcrafts/help/Dutch/Tool-ZoneMapper-Luminosity_RGB.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4332975" }, { "name": "C++", "bytes": "1197703" }, { "name": "CSS", "bytes": "10092" }, { "name": "HTML", "bytes": "2646074" }, { "name": "Haskell", "bytes": "11797" }, { "name": "Java", "bytes": "5832938" }, { "name": "JavaScript", "bytes": "1713" }, { "name": "Makefile", "bytes": "57064" }, { "name": "Objective-C", "bytes": "5028" }, { "name": "Objective-C++", "bytes": "25200" }, { "name": "Perl", "bytes": "6906" }, { "name": "Shell", "bytes": "23570" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/item_list_container" > <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.view.PagerTabStrip android:id="@+id/pagerTabStrip" android:layout_width="fill_parent" android:layout_height="30dp" android:layout_gravity="top" > </android.support.v4.view.PagerTabStrip> </android.support.v4.view.ViewPager> </RelativeLayout> <!-- <TextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/item_detail" style="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".ItemDetailFragment" /> -->
{ "content_hash": "4ee687fb23ad02239f60d266f64a88a1", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 74, "avg_line_length": 36.6, "alnum_prop": 0.6730418943533698, "repo_name": "museumvictoria/mv-fieldguide-android", "id": "953776d7e139195a34e59d279587d36444f8caa4", "size": "1098", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "res/layout/fragment_item_detail.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "256973" } ], "symlink_target": "" }
Ti=Article 72 - Procedure 1.sec=The Board shall take decisions by a simple majority of its members, unless otherwise provided for in this Regulation. 2.sec=The Board shall adopt its own rules of procedure by a two-third majority of its members and organise its own operational arrangements. =[Z/ol/s2]
{ "content_hash": "3e746cbd3e727e6d55e0f001add2fa71", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 140, "avg_line_length": 43.57142857142857, "alnum_prop": 0.7901639344262295, "repo_name": "mdangear/Cmacc-Org", "id": "dff945612241b2d29ca8897a81237450acede776", "size": "305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Doc/Wx/org/iapp/media/cmacc/GDPR-Final/Sec/Article/72.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22448" }, { "name": "HTML", "bytes": "440414" }, { "name": "JavaScript", "bytes": "1276" }, { "name": "Makefile", "bytes": "534" }, { "name": "PHP", "bytes": "30072" } ], "symlink_target": "" }
;(function(global) { 'use strict'; var game, entities, bricksGroup, scoreNumberGroup, bricks = {}, selectedBrick, currentstate, STATES = { PAUSED: 'paused', PLAY: 'play', SCORE: 'score', GAME_OVER: 'game_over' }, fpsText, scoreText, score = 0, best = localStorage.getItem('pixel_bricks_best') || 0, sounds, btnPause, timeBar, countDownTimer, countDown, pointer = { start : null, end : null }, temporaryObjects ; function createBoard() { bricksGroup = game.add.group(); scoreNumberGroup = game.add.group(); bricksGroup.position.setTo(Config.board.x, Config.board.y); scoreNumberGroup.position.setTo(bricksGroup.x, bricksGroup.y); for (var row = 0; row < Config.board.rows; row++) { bricks[row] = {}; for (var col = 0; col < Config.board.cols; col++) { var brick = createBrick(row, col); } } createTimeBar(); entities.add(bricksGroup); entities.add(scoreNumberGroup); removeInitialMatches(); createDropAnimationStart(); } function createTimeBar() { countDown = Config.timeBar.countDown; if (!timeBar) { timeBar = game.add.tileSprite( Config.timeBar.x, Config.timeBar.y, Config.timeBar.width, Config.timeBar.height, 'time-bar' ); entities.add(timeBar); } timeBar.width = Config.timeBar.width; timeBar.height = Config.timeBar.height; timeBar.updateTime = 1/15; timeBar.percent = timeBar.updateTime / countDown * 100; timeBar.subTimeBar = timeBar.width * timeBar.percent/100; if (countDownTimer) { countDownTimer.destroy(); } countDownTimer = game.time.create(false); countDownTimer.loop(timeBar.updateTime * Phaser.Timer.SECOND, function() { countDown -= timeBar.updateTime; timeBar.width -= timeBar.subTimeBar; if (countDown <= 0) { gameOver(); } }); countDownTimer.start(); } function createSpecialBrick(row, col) { var types = ['bomb', 'double', 'clock']; var type = types[game.rnd.integerInRange(0, types.length - 1)]; var brick = createBrick(row, col, type); var special = game.add.sprite(0, 0, type); brick.addChild(special); return brick; } function createCircle(radius, color, borderColor) { var border = 5; var bmd = game.add.bitmapData(radius*2+border, radius*2+border); bmd.ctx.beginPath(); bmd.ctx.arc(bmd.width/2, bmd.height/2, radius, 0, 2 * Math.PI, true); bmd.ctx.fillStyle = color; bmd.ctx.fill(); if (border) { bmd.ctx.lineWidth = border; bmd.ctx.strokeStyle = borderColor; bmd.ctx.stroke(); } return bmd; } function createRect(width, height, color) { var bmd = game.add.bitmapData(width, height); bmd.ctx.beginPath(); bmd.ctx.rect(0, 0, width, height); bmd.ctx.fillStyle = color; bmd.ctx.fill(); bmd.ctx.closePath(); return bmd; } function createModalLayer() { var modal = entities.create(0, 0, createRect(game.width, game.height, 'rgba(25, 25, 25, 0.9)')); modal.bringToTop(); return modal; } function createBrick(row, col, type) { var brick = bricksGroup.getFirstDead(); var x = col * Config.board.celWidth; var y = row * Config.board.celHeight; if (brick) { brick.revive(); brick.x = x; brick.y = y; brick.removeChildren(); brick.bringToTop(); } if (!brick) { brick = bricksGroup.create(x, y, 'bricks'); brick.inputEnabled = true; brick.events.onInputDown.add(inputDown); brick.bringToTop(); } setRandomFrame(brick); brick.row = Number(row); brick.col = Number(col); brick.alpha = 1; brick.width = Config.brick.width; brick.height = Config.brick.height; brick.dying = false; brick.selectable = true; brick._reborn = false; brick._type = type || false; bricks[row][col] = brick; return brick; } function getBrick(row, col) { if (!bricks[row] || !bricks[row][col]) { return false; } return bricks[row][col]; } function setRandomFrame(brick) { brick.frame = game.rnd.integerInRange(0, 4); } function hightlight(brick) { if (!brick.hightlight) { brick.highlightTween = game.add.tween(brick.scale).to({ x: 1.2, y: .8 }, 100, Phaser.Easing.Cubic.Out).to({ x: 1, y: 1 }, 300, Phaser.Easing.Back.Out); } brick.scale.set(1, 1) brick.highlightTween.start(); } function inputDown(brick, input) { if (!brick.selectable) return false; if (selectedBrick && selectedBrick.selectable) { var distRow = Math.abs(selectedBrick.row - brick.row); var distCol = Math.abs(selectedBrick.col - brick.col); if (distRow <= 1 && distCol <= 1 && distCol != distRow) { swap(selectedBrick, brick); selectedBrick = false; return true; } } selectedBrick = brick; } function inputMove(input, x, y, fromClick) { if (!selectedBrick || !selectedBrick.selectable || !pointer.start) return; var distX = x - pointer.start.x; var distY = y - pointer.start.y; var min = 15; if (Math.abs(distX) <= min && Math.abs(distY) <= min) { return false; } var row = selectedBrick.row; var col = selectedBrick.col; if (Math.abs(distX) > Math.abs(distY)) { col = distX > 0 ? col + 1 : col - 1; } else { row = distY > 0 ? row + 1 : row - 1; } var brick = getBrick(row, col); if (!brick || !brick.selectable || brick.dying || !brick.alive) { return false; } swap(selectedBrick, brick); selectedBrick = false; } function swap(selectedBrick, brick) { function _swapProperties() { var _row = selectedBrick.row; var _col = selectedBrick.col; bricks[selectedBrick.row][selectedBrick.col] = brick; bricks[brick.row][brick.col] = selectedBrick; selectedBrick.row = brick.row; selectedBrick.col = brick.col; brick.row = _row; brick.col = _col; } function _getMatches() { var selectedBrickSameColor = getSameColor(selectedBrick); var brickSameColor = getSameColor(brick); var bricksMatch = []; if (selectedBrickSameColor.length >= Config.score.minMatches || brickSameColor.length >= Config.score.minMatches) { if (selectedBrickSameColor.length > Config.score.minMatches) { selectedBrick._reborn = true; } if (brickSameColor.length > Config.score.minMatches) { brick._reborn = true; } if (selectedBrickSameColor.length >= Config.score.minMatches) { bricksMatch = bricksMatch.concat(selectedBrickSameColor.matches); } if (brickSameColor.length >= Config.score.minMatches) { bricksMatch = bricksMatch.concat(brickSameColor.matches); } return bricksMatch; } return false; } function _animationInvalidMoviment() { sounds.moveInvalid.play(); move(selectedBrick); move(brick, function() { _swapProperties(); move(selectedBrick); move(brick); }); } _swapProperties(); var matches = _getMatches(); if (!matches) { return _animationInvalidMoviment(); } // blockMatches(matches); move(selectedBrick); move(brick, function() { processMatches(removeDuplicates(matches)); }); } function move(brick, callback, time, ease) { brick.selectable = false; var x = brick.col * Config.board.celWidth; var y = brick.row * Config.board.celHeight; var time = time || 150; var ease = ease || Phaser.Easing.Linear.None; return animation(brick, { to: { x: x, y: y }, time: time, ease: ease, done : function() { brick.selectable = true; if (callback) { callback(); } }}); } function blockMatches(matches) { for (var index = 0, length = matches.length; index < length; index++) { matches[index].dying = true; matches[index].selectable = false; } } function removeDuplicates(bricksArray) { var result = [], keys = {}; for (var index = 0, length = bricksArray.length; index < length; index++) { var brick = bricksArray[index]; if (keys[brick.row] && keys[brick.row][brick.col]) { continue; } if (!keys[brick.row]) { keys[brick.row] = {}; } keys[brick.row][brick.col] = true; result.push(brick); } return result; } function killBrick(brick, callback) { brick.dying = true; brick.selectable = false; var time = 100; var to = { width: brick.width/2, height: brick.height/2, x : brick.x + (brick.width * 0.25), y : brick.y + (brick.height * 0.25) }; animation(brick, { to: to, time: time, ease: Phaser.Easing.Linear.None, done: function() { if (brick._type == 'clock') { var text = game.add.bitmapText(timeBar.x, timeBar.y + timeBar.height/2, 'font', '+5s', 30); text.anchor.setTo(0.5); var textAnim = game.add.tween(text); textAnim.to({x: text.x + 100, alpha : 0}, 500, Phaser.Easing.Linear.None); textAnim.onComplete.add(function() { text.destroy(); }); textAnim.start(); } brick.kill(); bricks[brick.row][brick.col] = null; if (brick._reborn) { var brickReborn = createSpecialBrick(brick.row, brick.col); var brickRebornAnim = game.add.tween(brickReborn.scale); brickReborn.scale.setTo(0.2); brickRebornAnim.to({x: 1, y: 1}, 300, Phaser.Easing.Bounce.Out); brickRebornAnim.start(); } if (callback) { callback(); } }}); } function findMatches() { 'use strict'; if (process.queue.has('findMatches')) { console.error('findMatches again?'); return []; } process.queue.add('findMatches'); var matches = [], keys = {}, ignore = { row : [], col : [] }; for (var row = 0; row < Config.board.rows; row++) { for (var col = 0; col < Config.board.cols; col++) { var brick = getBrick(row, col); var brickSameColor = getSameColor(brick); if (brickSameColor.matches.length < Config.score.minMatches) { continue; } for (var index = 0, length = brickSameColor.matches.length; index < length; index++) { var brickMatch = brickSameColor.matches[index]; if (!keys[brickMatch.row]) { keys[brickMatch.row] = {}; } if (keys[brickMatch.row] && keys[brickMatch.row][brickMatch.col]) { continue; } if (brickSameColor.matches.length > Config.score.minMatches) { brick._reborn = true; } keys[brickMatch.row][brickMatch.col] = true; matches.push(brickMatch); } } } process.queue.remove('findMatches'); return matches; } function removeInitialMatches() { var matches = findMatches(); if (matches.length == 0) { return true; } for (var index = 0, length = matches.length; index < length; index++) { setRandomFrame(matches[index]); } return removeInitialMatches(); } function createDropAnimationStart() { var data = {}; bricksGroup.forEachAlive(function(brick) { if (!data[brick.col]) { data[brick.col] = -(brick.col + 1 * game.rnd.integerInRange(0, brick.height * 5)); } brick.y = data[brick.col] - (brick.row + 1 * brick.height); var time = 1000; var ease = Phaser.Easing.Bounce.Out; move(brick, false, time, ease); }); } function explode(brickBomb) { brickBomb._type = 'explode'; var matches = [brickBomb]; var _row = brickBomb.row, _col = brickBomb.col; var horizontalRect = createRect(Config.board.width, Config.brick.width * 0.7, 'rgba(255, 255, 255, 0.5)'); var horizontalSprite = game.add.sprite( _col * Config.board.celWidth + bricksGroup.x, _row * Config.board.celHeight + bricksGroup.y, horizontalRect ); horizontalSprite.width = Config.board.celWidth; horizontalSprite.height = Config.board.celHeight; var verticalRect = createRect(Config.brick.width * 0.7, Config.board.height, 'rgba(255, 255, 255, 0.5)'); var verticalSprite = game.add.sprite( _col * Config.board.celWidth + bricksGroup.x, _row * Config.board.celHeight + bricksGroup.y, verticalRect ); verticalSprite.width = Config.board.celWidth; verticalSprite.height = Config.board.celHeight; var horizontalTo = { width: Config.board.width, height: Config.brick.height, x : bricksGroup.x, y: bricksGroup.y + (_row * Config.board.celHeight) }; var verticalTo = { width: Config.brick.width, height: Config.board.height, x: (_col * Config.board.celWidth), y: bricksGroup.y }; var horizontalAnim = game.add.tween(horizontalSprite); var verticalAnim = game.add.tween(verticalSprite); horizontalAnim.to(horizontalTo, 150, Phaser.Easing.Linear.None); horizontalAnim.onComplete.add(function() { horizontalSprite.kill(); }); verticalAnim.to(verticalTo, 150, Phaser.Easing.Linear.None); verticalAnim.onComplete.add(function() { verticalSprite.kill(); }); horizontalAnim.start(); verticalAnim.start(); sounds.explosion.play(); game.plugins.screenShake.shake(10); for (var row = 0; row < Config.board.rows; row++) { var brick = getBrick(row, _col); if (!brick || brick.dying || brick == brickBomb) { continue; } brick._type = 'explode'; matches.push(brick); } for (var col = 0; col < Config.board.cols; col++) { var brick = getBrick(_row, col); if (!brick || brick.dying || brick == brickBomb) { continue; } brick._type = 'explode'; matches.push(brick); } return processMatches(matches, true); } function processMatches(bricksArray, background) { if (currentstate !== STATES.PLAY || bricksArray.length == 0) { return 0; } var length = bricksArray.length, last = length - 1, scored = 0, specialDouble = 0, specialClock = 0 ; if (length == 0) { return scored; } frozenBoard(); var _row = bricksArray[0].row, _col = bricksArray[0].col; for (var index = 0; index < length; index++) { var brick = bricksArray[index]; var callback = false; if (index == last) { callback = function() { unfrozenBoard(); drop(); }; } if (brick._type === 'bomb') { scored += explode(brick); if (bricksArray[0]._type !== 'bomb') { _row = brick.row; _col = brick.col; } continue; } if (brick._type === 'double') { specialDouble += Config.specials.double; } if (brick._type === 'clock') { specialClock += Config.specials.clock; } scored += Config.score.point; killBrick(brick, callback); } if (!background) { var scoredText = scored; if (specialDouble) { scoredText = String(specialDouble) + 'x' + String(scored); scored *= specialDouble; } if (specialClock) { var bonus = Config.specials.clock; countDown += bonus; timeBar.percent = timeBar.updateTime / countDown * 100; var diff = Math.round(timeBar.width / Math.round(countDown/bonus)); timeBar.width = Math.min(timeBar.width + diff, Config.timeBar.width); timeBar.subTimeBar = timeBar.width * timeBar.percent/100; } score += scored; sounds.score.play(); updateScore(); createScoreNumber( (_col * Config.board.celWidth) + Config.brick.width/2, (_row * Config.board.celHeight) + Config.brick.height/2, scoredText ); } return scored; } function drop() { var time = 200; var ease = Phaser.Easing.Bounce.Out; var moves = []; for (var col = 0; col < Config.board.cols; col++) { var dropRowCount = 0; var dropBrick = []; // detect rows to drop for (var row = Config.board.rows - 1; row >= 0; row--) { var brick = getBrick(row, col); if (!brick || !brick.alive) { dropRowCount++; continue; } if (dropRowCount <= 0) { continue; } brick.dropRowCount = dropRowCount; dropBrick.push(brick); } // drop bricks for (var index = 0, length = dropBrick.length; index < length; index++) { var brick = dropBrick[index]; bricks[brick.row][brick.col] = null; brick.row += brick.dropRowCount; bricks[brick.row][brick.col] = brick; moves.push(brick); } // new bricks for (var index = dropRowCount - 1; index >= 0; index--) { var brick = createBrick(index, col); brick.y = (Config.board.celHeight * (4-index)) * -1; moves.push(brick); } } var length = moves.length, last = length - 1; if (length == 0) { return false; } frozenBoard(); for (var index = 0; index < length; index++) { var brick = moves[index]; var callback = false; if (index == last) { callback = function() { var matches = findMatches(); if (matches.length == 0) { unfrozenBoard(); return process.nextTick(drop); } return processMatches(matches); } } move(brick, callback, time, ease); } } function getSameColor(brick) { var result = [], horizontal = [brick], vertical = [brick]; horizontal = horizontal.concat(getSameColorByDirection(brick, 0, -1)); horizontal = horizontal.concat(getSameColorByDirection(brick, 0, 1)); vertical = vertical.concat(getSameColorByDirection(brick, -1, 0)); vertical = vertical.concat(getSameColorByDirection(brick, 1, 0)); if (horizontal.length >= Config.score.minMatches) { result = result.concat(horizontal); } if (vertical.length >= Config.score.minMatches) { result = result.concat(vertical); } return { horizontal : horizontal, vertical : vertical, matches : result, length : result.length } } function getSameColorByDirection(brick, moveRow, moveCol) { var result = []; var curRow = brick.row + moveRow; var curCol = brick.col + moveCol; if (brick.dying) { return result; } while (curRow >= 0 && curCol >= 0 && curRow < Config.board.rows && curCol < Config.board.cols) { var findBrick = getBrick(curRow, curCol); if (!findBrick || findBrick.frame != brick.frame || findBrick.dying) { break; } result.push(findBrick); curRow += moveRow; curCol += moveCol; } return result; } function updateScore() { scoreText.setText(String(score)); } function createScoreNumber(x, y, text, type) { var type = type || 'score'; var scoreNumberText = scoreNumberGroup.getFirstDead(); if (!scoreNumberText) { scoreNumberText = game.add.bitmapText(x, y, 'font', String(text), 50); scoreNumberText.anchor.setTo(0.5); scoreNumberGroup.add(scoreNumberText); } else { scoreNumberText.position.setTo(x, y); scoreNumberText.alpha = 1; scoreNumberText.setText(text); scoreNumberText.revive(); } if (scoreNumberText.x <= scoreNumberText.width/2) { scoreNumberText.x = scoreNumberText.width/2; } if (scoreNumberText.x + scoreNumberText.width/2 >= Config.board.width) { scoreNumberText.x = Config.board.width - scoreNumberText.width/2; } var to = {alpha: 0, y: scoreNumberText.y - 100} var scoreNumberTextAnim = game.add.tween(scoreNumberText); scoreNumberTextAnim.to(to, 1000, Phaser.Easing.Linear.None); scoreNumberTextAnim.onComplete.add(function() { scoreNumberText.kill(); }); scoreNumberTextAnim.start(); } function saveBestScore() { best = Math.max(score, best); localStorage.setItem('pixel_bricks_best', best); } function gameOver() { currentstate = STATES.GAME_OVER; saveBestScore(); var layer = createModalLayer(); countDownTimer.pause(); frozenBoard(); var gameOverText = game.add.bitmapText(game.world.centerX, game.world.centerY, 'font', 'GAME OVER', 66); gameOverText.anchor.setTo(0.5); gameOverText.alpha = 0; gameOverText.y -= gameOverText.height * 2; var textScore = game.add.bitmapText(game.world.centerX, game.height, 'font', 'SCORE: ' + score, 33); textScore.anchor.setTo(0.5); textScore.alpha = 0.6; textScore.y -= textScore.height; var restartText = game.add.bitmapText(0, 0, 'font', 'TRY AGAIN', 30); restartText.anchor.setTo(0.5); restartText.alpha = 0.7; var padding = 24; var restartTextRect = game.add.sprite( game.world.centerX, gameOverText.y + gameOverText.height + 100, createRect(restartText.width + padding, restartText.height + padding, '#333') ); restartTextRect.anchor.setTo(0.5); restartTextRect.inputEnabled = true; restartTextRect.events.onInputDown.add(function() { if (restartTextRect.alpha > 0.5) { restart(); } }); restartTextRect.addChild(restartText); restartTextRect.alpha = 0; var restartTextTween = game.add.tween(restartTextRect); restartTextTween.to({alpha : 1}, 1000, Phaser.Easing.Linear.None); var gameOverTextTween = game.add.tween(gameOverText); gameOverTextTween.to({alpha: 1}, 3000, Phaser.Easing.Bounce.Out); gameOverTextTween.start(); var timer = game.time.create(game); timer.add(1000, function() { restartTextTween.start(); }); timer.start(); temporaryObjects.add(layer); temporaryObjects.add(restartTextRect); temporaryObjects.add(gameOverText); temporaryObjects.add(textScore); } function pause() { currentstate = STATES.PAUSED; temporaryObjects.add(createModalLayer()) countDownTimer.pause(); frozenBoard(); var menus = [ { text : 'RESUME', inputDown: resume }, { text : 'MENU', inputDown: function() { saveBestScore() window.document.location.href = window.document.location.href; // @todo - trocar para phaeser dev 2.4 // game.state.start('menu'); } }, ]; var padding = 24; var marginTop = game.world.centerY - 100; for (var i = 0, len = menus.length; i < len; i++) { var menu = menus[i]; var text = game.add.bitmapText(0, 0, 'font', menu.text, 30); text.anchor.setTo(0.5) text.alpha = 0.7; var textRect = game.add.sprite( game.world.centerX, marginTop, createRect(text.width + padding, text.height + padding, '#333') ); textRect.anchor.setTo(0.5); textRect.inputEnabled = true; textRect.events.onInputDown.add(menu.inputDown); textRect.addChild(text); marginTop = textRect.y + 90; temporaryObjects.add(textRect); } } function resume() { currentstate = STATES.PLAY; countDownTimer.resume(); unfrozenBoard(); cleanTemporaryObjects(); } function restart() { cleanTemporaryObjects(); score = 0; createTimeBar(); updateScore(); shuffle(); removeInitialMatches(); createDropAnimationStart(); currentstate = STATES.PLAY; unfrozenBoard(); } function cleanTemporaryObjects() { temporaryObjects.forEach(function(obj) { obj.kill(); }); temporaryObjects.forEach(function(obj) { obj.destroy(); }); } function shuffle() { bricksGroup.forEachAlive(function(brick) { brick.removeChildren(); setRandomFrame(brick); }); } function frozenBoard() { bricksGroup.forEachAlive(function(brick) { brick.inputEnabled = false; }); } function unfrozenBoard() { if (currentstate === STATES.GAME_OVER) { return false; } bricksGroup.forEachAlive(function(brick) { brick.inputEnabled = true; }); } /** * process */ ;(function() { var queue = {}; global.process = { handler : requestAnimationFrame || function(fn) { return setTimeout(fn, 16.666) }, nextTick : function(fn, args, context) { args = args || [], context = context || null; return this.handler.call(context, function() { return fn.apply(context, args); }); }, queue : { add : function(id) { queue[id] = true; }, has : function(id) { return id in queue; }, remove : function(id) { delete queue[id]; } } } })(); /** * animation */ ;(function() { function execute(brick) { if (brick.tweens.length == 0 || (brick.tween && brick.tween.isRunning)) { return false; } var anim = brick.tweens.shift(); brick.tween = game.add.tween(brick); brick.tween.to(anim.to, anim.time, anim.ease); brick.tween.onComplete.add(function() { if (anim.done) { anim.done(); } return process.nextTick(execute, [brick]); }); brick.tween.start(); } function animation(brick, anim) { anim.time = anim.time || 200; anim.ease = anim.ease || Phaser.Easing.Linear.None; brick.tween = game.add.tween(brick); brick.tween.to(anim.to, anim.time, anim.ease); brick.tween.onComplete.add(function() { if (anim.done) { anim.done(); } }); brick.tween.start(); } function _animation(brick, anim) { if (!anim) { console.error('brick animation not defined'); return false; } anim.time = anim.time || 200; anim.ease = anim.ease || Phaser.Easing.Linear.None; brick.tweens = brick.tweens || []; brick.tweens.push(anim); process.nextTick(execute, [brick]); } global.animation = animation; })(); var Game = function(_game) { game = _game; } Game.prototype = { create: function() { // disable auto pause on window blur // game.stage.disableVisibilityChange = true; currentstate = STATES.PLAY; // game.time.advancedTiming = true; // fpsText = game.add.text(0, 5, '00', {font: '16px Arial', fill: '#333'}); // fpsText.x = game.width - fpsText.width - 5; game.input.addMoveCallback(inputMove, this); game.input.onDown.add(function(input, event) { pointer.start = {x : input.position.x, y : input.position.y}; }, this); game.input.onUp.add(function(input, event) { pointer.start = null; pointer.end = {x : input.position.x, y : input.position.y}; }, this); sounds = { score : game.add.audio('score'), moveInvalid : game.add.audio('move-invalid'), explosion : game.add.audio('explosion') }; btnPause = game.add.button(game.width - game.cache.getImage('btn-pause').width, 5, 'btn-pause', pause); btnPause.x -= btnPause.width - 15; btnPause.scale.setTo(1.5); game.plugins.screenShake = game.plugins.add(Phaser.Plugin.ScreenShake); game.plugins.screenShake.setup({ shakeX: true, shakeY: true }); score = 0; scoreText = game.add.bitmapText(Config.board.x, 10, 'font', String(score), 40); entities = game.add.group(); temporaryObjects = game.add.group(); createBoard(); }, update : function() { // fpsText.setText(this.time.fps); }, render : function() { }, } global.Game = Game; })(this);
{ "content_hash": "6036f7141268f2eee7c93006713b3462", "timestamp": "", "source": "github", "line_count": 1196, "max_line_length": 127, "avg_line_length": 27.51923076923077, "alnum_prop": 0.5036915504511895, "repo_name": "jefersonbelmiro/bricks", "id": "fe9cda70d7e66c648a185e635832c2e8e4524014", "size": "32913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/game.js", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "1711" }, { "name": "JavaScript", "bytes": "40008" } ], "symlink_target": "" }
package cloud.orbit.actors.test; import cloud.orbit.actors.cluster.ClusterPeer; import cloud.orbit.actors.cluster.DistributedMap; import cloud.orbit.actors.cluster.MessageListener; import cloud.orbit.actors.cluster.NodeAddress; import cloud.orbit.actors.cluster.ViewListener; import cloud.orbit.concurrent.Task; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicLong; /** * Fake group networking peer used during unit tests. * <p> * Using this peer is considerably faster than using jgroups during the tests. * </p> * It's recommended to use the fake network for application unit tests. */ // TODO: Rename this class to FakeClusterChannel public class FakeClusterPeer implements ClusterPeer { private ViewListener viewListener; private MessageListener messageListener; private FakeGroup group; private NodeAddress address; private AtomicLong messagesSent = new AtomicLong(); private AtomicLong messagesSentOk = new AtomicLong(); private AtomicLong messagesReceived = new AtomicLong(); private AtomicLong messagesReceivedOk = new AtomicLong(); private CompletableFuture<?> startFuture = new CompletableFuture<>(); public FakeClusterPeer() { } public Task<Void> join(final String clusterName, final String nodeName) { group = FakeGroup.get(clusterName); return Task.runAsync(() -> { address = group.join(this); startFuture.complete(null); }, group.pool()); } @Override public void leave() { group.leave(this); } public void onViewChanged(final List<NodeAddress> newView) { viewListener.onViewChange(newView); } public void onMessageReceived(final NodeAddress from, final byte[] buff) { messagesReceived.incrementAndGet(); messageListener.receive(from, buff); messagesReceivedOk.incrementAndGet(); } @Override public NodeAddress localAddress() { return address; } @Override public void registerViewListener(final ViewListener viewListener) { this.viewListener = viewListener; } @Override public void registerMessageReceiver(final MessageListener messageListener) { this.messageListener = messageListener; } @Override public void sendMessage(final NodeAddress to, final byte[] message) { startFuture.join(); messagesSent.incrementAndGet(); group.sendMessage(address, to, message).thenRun(() -> messagesSentOk.incrementAndGet()); } @Override public <K, V> DistributedMap<K, V> getCache(final String name) { return group.getCache(name); } void setAddress(final NodeAddress address) { this.address = address; } }
{ "content_hash": "2a19057f04a688ec71d3b4c07e483dbf", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 96, "avg_line_length": 27.50485436893204, "alnum_prop": 0.6964348746911402, "repo_name": "JoeHegarty/orbit", "id": "1a54b8440dc43a3f924120c229d4f20bb25d4d15", "size": "4378", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "actors/test/actor-tests/src/main/java/cloud/orbit/actors/test/FakeClusterPeer.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "1333794" } ], "symlink_target": "" }
package com.microsoft.azure.management.appservice.implementation; import com.fasterxml.jackson.annotation.JsonProperty; /** * Legal agreement for a top level domain. */ public class TldLegalAgreementInner { /** * Unique identifier for the agreement. */ @JsonProperty(value = "agreementKey", required = true) private String agreementKey; /** * Agreement title. */ @JsonProperty(value = "title", required = true) private String title; /** * Agreement details. */ @JsonProperty(value = "content", required = true) private String content; /** * URL where a copy of the agreement details is hosted. */ @JsonProperty(value = "url") private String url; /** * Get the agreementKey value. * * @return the agreementKey value */ public String agreementKey() { return this.agreementKey; } /** * Set the agreementKey value. * * @param agreementKey the agreementKey value to set * @return the TldLegalAgreementInner object itself. */ public TldLegalAgreementInner withAgreementKey(String agreementKey) { this.agreementKey = agreementKey; return this; } /** * Get the title value. * * @return the title value */ public String title() { return this.title; } /** * Set the title value. * * @param title the title value to set * @return the TldLegalAgreementInner object itself. */ public TldLegalAgreementInner withTitle(String title) { this.title = title; return this; } /** * Get the content value. * * @return the content value */ public String content() { return this.content; } /** * Set the content value. * * @param content the content value to set * @return the TldLegalAgreementInner object itself. */ public TldLegalAgreementInner withContent(String content) { this.content = content; return this; } /** * Get the url value. * * @return the url value */ public String url() { return this.url; } /** * Set the url value. * * @param url the url value to set * @return the TldLegalAgreementInner object itself. */ public TldLegalAgreementInner withUrl(String url) { this.url = url; return this; } }
{ "content_hash": "ec68781056cd1068f95ef7c1c3eb3513", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 73, "avg_line_length": 21.452173913043477, "alnum_prop": 0.5934333198216457, "repo_name": "hovsepm/azure-sdk-for-java", "id": "63b891cb8bfce924d415b0cf698348b8a971ac3b", "size": "2697", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "archive/azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/implementation/TldLegalAgreementInner.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6821" }, { "name": "HTML", "bytes": "1250" }, { "name": "Java", "bytes": "103388992" }, { "name": "JavaScript", "bytes": "8139" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Python", "bytes": "3855" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
#pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CAPTDLLClientApp: // See APTDLLClient.cpp for the implementation of this class // class CAPTDLLClientApp : public CWinApp { public: CAPTDLLClientApp(); // Overrides public: virtual BOOL InitInstance(); // Implementation DECLARE_MESSAGE_MAP() }; extern CAPTDLLClientApp theApp;
{ "content_hash": "4ab279a566dc77ca9d379fd48eb8073f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 63, "avg_line_length": 16.03448275862069, "alnum_prop": 0.6903225806451613, "repo_name": "mcleung/PyAPT", "id": "64e501ac396147debec297c2382ba3c9f5a1e79d", "size": "540", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "APTDLLPack/APTDLLClient/APTDLLClient.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "15373" }, { "name": "C++", "bytes": "37556" }, { "name": "Python", "bytes": "23208" } ], "symlink_target": "" }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateArticlesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('articles', function(Blueprint $table) { $table->increments('id'); $table->string('title', 50); $table->text('description'); $table->string('image', 100)->default('no_large_image.png'); $table->date('endDate'); $table->timestamps(); $table->integer('user_id')->unsigned(); $table->foreign('user_id') ->references('id') ->on('users'); $table->integer('category_id')->unsigned(); $table->foreign('category_id') ->references('id') ->on('categories'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('articles'); } }
{ "content_hash": "8e3f261807094fbd5b6d5ce1f934fea8", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 63, "avg_line_length": 18.869565217391305, "alnum_prop": 0.6163594470046083, "repo_name": "ReIR/BestNid", "id": "e81ff0af0bb83ef9979b094a443cc4a75711514e", "size": "868", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/database/migrations/2015_05_30_232450_create_articles_table.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "3042" }, { "name": "JavaScript", "bytes": "2311" }, { "name": "PHP", "bytes": "195929" } ], "symlink_target": "" }
using System.Collections.Generic; namespace Lucene.Net.Index { /// <summary> /// An <see cref="IndexDeletionPolicy"/> which keeps all index commits around, never /// deleting them. This class is a singleton and can be accessed by referencing /// <see cref="INSTANCE"/>. /// </summary> public sealed class NoDeletionPolicy : IndexDeletionPolicy { /// <summary> /// The single instance of this class. </summary> public static readonly IndexDeletionPolicy INSTANCE = new NoDeletionPolicy(); private NoDeletionPolicy() { // keep private to avoid instantiation } public override void OnCommit<T>(IList<T> commits) { } public override void OnInit<T>(IList<T> commits) { } public override object Clone() { return this; } } }
{ "content_hash": "9a8a93a3781aa5655959a04f29bf8da5", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 88, "avg_line_length": 26.083333333333332, "alnum_prop": 0.5686900958466453, "repo_name": "NikolayXHD/Lucene.Net.Contrib", "id": "c97f4783688dd4ec8afd9e894b740adf7ae87da7", "size": "1815", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lucene.Net/Index/NoDeletionPolicy.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "22011339" }, { "name": "Gnuplot", "bytes": "2511" } ], "symlink_target": "" }
import { QuasarIconSet } from "./extras"; import { QuasarLanguage } from "./lang"; // These interfaces are used as forward-references // filled at build-time via TS interface mergin capabilities export interface QuasarComponents {} export interface QuasarDirectives {} export interface QuasarPlugins {} export interface QuasarPluginOptions { lang: QuasarLanguage; config: any; iconSet: QuasarIconSet; components: QuasarComponents; directives: QuasarDirectives; plugins: QuasarPlugins; }
{ "content_hash": "25eaa2df6b2c96c69bf64dc7aa7aa949", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 61, "avg_line_length": 29.529411764705884, "alnum_prop": 0.7768924302788844, "repo_name": "quasarframework/quasar", "id": "8b808512733d12f8e1ace0d2e9e85037c021052f", "size": "502", "binary": false, "copies": "5", "ref": "refs/heads/dev", "path": "ui/types/plugin.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2006590" }, { "name": "HTML", "bytes": "26041" }, { "name": "JavaScript", "bytes": "27008546" }, { "name": "SCSS", "bytes": "4830" }, { "name": "Sass", "bytes": "217157" }, { "name": "Shell", "bytes": "9511" }, { "name": "Stylus", "bytes": "1516" }, { "name": "TypeScript", "bytes": "54448" }, { "name": "Vue", "bytes": "1521880" } ], "symlink_target": "" }
package org.apache.kafka.common.requests; import org.apache.kafka.common.acl.AccessControlEntry; import org.apache.kafka.common.acl.AclBinding; import org.apache.kafka.common.acl.AclOperation; import org.apache.kafka.common.acl.AclPermissionType; import org.apache.kafka.common.errors.UnsupportedVersionException; import org.apache.kafka.common.message.CreateAclsRequestData; import org.apache.kafka.common.protocol.types.Struct; import org.apache.kafka.common.resource.PatternType; import org.apache.kafka.common.resource.ResourcePattern; import org.apache.kafka.common.resource.ResourceType; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; public class CreateAclsRequestTest { private static final short V0 = 0; private static final short V1 = 1; private static final AclBinding LITERAL_ACL1 = new AclBinding(new ResourcePattern(ResourceType.TOPIC, "foo", PatternType.LITERAL), new AccessControlEntry("User:ANONYMOUS", "127.0.0.1", AclOperation.READ, AclPermissionType.DENY)); private static final AclBinding LITERAL_ACL2 = new AclBinding(new ResourcePattern(ResourceType.GROUP, "group", PatternType.LITERAL), new AccessControlEntry("User:*", "127.0.0.1", AclOperation.WRITE, AclPermissionType.ALLOW)); private static final AclBinding PREFIXED_ACL1 = new AclBinding(new ResourcePattern(ResourceType.GROUP, "prefix", PatternType.PREFIXED), new AccessControlEntry("User:*", "127.0.0.1", AclOperation.CREATE, AclPermissionType.ALLOW)); private static final AclBinding UNKNOWN_ACL1 = new AclBinding(new ResourcePattern(ResourceType.UNKNOWN, "unknown", PatternType.LITERAL), new AccessControlEntry("User:*", "127.0.0.1", AclOperation.CREATE, AclPermissionType.ALLOW)); @Test(expected = UnsupportedVersionException.class) public void shouldThrowOnV0IfNotLiteral() { new CreateAclsRequest(V0, data(PREFIXED_ACL1)); } @Test(expected = IllegalArgumentException.class) public void shouldThrowOnIfUnknown() { new CreateAclsRequest(V0, data(UNKNOWN_ACL1)); } @Test public void shouldRoundTripV0() { final CreateAclsRequest original = new CreateAclsRequest(V0, data(LITERAL_ACL1, LITERAL_ACL2)); final Struct struct = original.toStruct(); final CreateAclsRequest result = new CreateAclsRequest(struct, V0); assertRequestEquals(original, result); } @Test public void shouldRoundTripV1() { final CreateAclsRequest original = new CreateAclsRequest(V1, data(LITERAL_ACL1, PREFIXED_ACL1)); final Struct struct = original.toStruct(); final CreateAclsRequest result = new CreateAclsRequest(struct, V1); assertRequestEquals(original, result); } private static void assertRequestEquals(final CreateAclsRequest original, final CreateAclsRequest actual) { assertEquals("Number of Acls wrong", original.aclCreations().size(), actual.aclCreations().size()); for (int idx = 0; idx != original.aclCreations().size(); ++idx) { final AclBinding originalBinding = CreateAclsRequest.aclBinding(original.aclCreations().get(idx)); final AclBinding actualBinding = CreateAclsRequest.aclBinding(actual.aclCreations().get(idx)); assertEquals(originalBinding, actualBinding); } } private static CreateAclsRequestData data(final AclBinding... acls) { List<CreateAclsRequestData.AclCreation> aclCreations = Arrays.stream(acls) .map(CreateAclsRequest::aclCreation) .collect(Collectors.toList()); return new CreateAclsRequestData().setCreations(aclCreations); } }
{ "content_hash": "26153151277285f19a9d82be34805954", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 140, "avg_line_length": 44.10588235294118, "alnum_prop": 0.7415310749533209, "repo_name": "sslavic/kafka", "id": "06b4b9f4bb2b239f2e6b00c77e5650f771dfb4aa", "size": "4547", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "clients/src/test/java/org/apache/kafka/common/requests/CreateAclsRequestTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "26633" }, { "name": "Dockerfile", "bytes": "5117" }, { "name": "HTML", "bytes": "3739" }, { "name": "Java", "bytes": "14966996" }, { "name": "Python", "bytes": "802091" }, { "name": "Scala", "bytes": "5802403" }, { "name": "Shell", "bytes": "94955" }, { "name": "XSLT", "bytes": "7116" } ], "symlink_target": "" }
package me.eddiep.android.pins.util; import android.app.Activity; import android.view.View; import android.view.WindowManager; /** * A base implementation of {@link SystemUiHider}. Uses APIs available in all * API levels to show and hide the status bar. */ public class SystemUiHiderBase extends SystemUiHider { /** * Whether or not the system UI is currently visible. This is a cached value * from calls to {@link #hide()} and {@link #show()}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderBase(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); } @Override public void setup() { if ((mFlags & FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) == 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } } @Override public boolean isVisible() { return mVisible; } @Override public void hide() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } @Override public void show() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( 0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } }
{ "content_hash": "42b13365d1cf5dcce2e9878347a190ce", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 80, "avg_line_length": 32.01587301587302, "alnum_prop": 0.6108081308874567, "repo_name": "hypereddie/pins-android", "id": "1f50cfeed2f75d088aed34b2f77239a5f48e52a9", "size": "2017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pins/app/src/main/java/me/eddiep/android/pins/util/SystemUiHiderBase.java", "mode": "33261", "license": "mit", "language": [ { "name": "Groovy", "bytes": "1036" }, { "name": "Java", "bytes": "23556" } ], "symlink_target": "" }
// (C) Copyright 2015 Martin Dougiamas // // 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. angular.module('mm.core') /** * Factory to provide some global functionalities, like access to the global app database. * * @module mm.core * @ngdoc provider * @name $mmApp * @description * This provider is the interface with the app database. The modules that need to store * information here need to register their stores. * * Example: * * .config(function($mmAppProvider) { * $mmAppProvider.registerStore({ * name: 'settings', * keyPath: 'name' * }); * }) */ .provider('$mmApp', function($stateProvider) { /** Define the app storage schema. */ var DBNAME = 'moodleMobile', dbschema = { stores: [] }, dboptions = { autoSchema: true }; /** * Register a store schema. * * @param {Object} store The store object definition. * @return {Void} */ this.registerStore = function(store) { if (typeof(store.name) === 'undefined') { console.log('$mmApp: Error: store name is undefined.'); return; } else if (storeExists(store.name)) { console.log('$mmApp: Error: store ' + store.name + ' is already defined.'); return; } dbschema.stores.push(store); }; /** * Register multiple stores at once. * * @param {Array} stores Array of store objects. * @return {Void} */ this.registerStores = function(stores) { var self = this; angular.forEach(stores, function(store) { self.registerStore(store); }); }; /** * Check if a store is already defined. * * @param {String} name The name of the store. * @return {Boolean} True when the store was already defined. */ function storeExists(name) { var exists = false; angular.forEach(dbschema.stores, function(store) { if (store.name === name) { exists = true; } }); return exists; } this.$get = function($mmDB, $cordovaNetwork, $log, $injector, $ionicPlatform) { $log = $log.getInstance('$mmApp'); var db, self = {}; /** * Create a new state in the UI-router. * * @module mm.core * @ngdoc method * @name $mmApp#createState * @param {String} name State name. * @param {Object} config State config. */ self.createState = function(name, config) { $log.debug('Adding new state: '+name); $stateProvider.state(name, config); }; /** * Get the application global database. * @return {Object} App's DB. */ self.getDB = function() { if (typeof db == 'undefined') { db = $mmDB.getDB(DBNAME, dbschema, dboptions); } return db; }; /** * Get the database schema. * * Do not use this method to modify the schema. Use $mmAppProvider#registerStore instead. * * @return {Object} The schema. */ self.getSchema = function() { return dbschema; }; /** * Core init process for the app. * * @description * This should be the first init process of all, no other process should run until we * are certain that the cordova plugins are loaded, which is what $ionicPlatform tells us. * There should not be any logic acting on the database here as the upgrade is * another process and has not run yet at this point. * * Keep this fast. * * Reserved for core use, do not call directly. * * @module mm.core * @ngdoc service * @name $mmApp#initProcess * @protected * @return {Promise} */ self.initProcess = function() { return $ionicPlatform.ready(); }; /** * Returns whether we are online. * * @module mm.core * @ngdoc method * @name $mmApp#isOnline * @return {Bool} True when we are. * @description * This methods returns whether the app is online or not. * Note that a browser is always considered being online. */ self.isOnline = function() { return typeof navigator.connection === 'undefined' || $cordovaNetwork.isOnline(); }; /* * Check if device uses a limited connection. * * @module mm.core * @ngdoc method * @name $mmApp#isNetworkAccessLimited * @return {Boolean} True if device used a limited connection, false otherwise. * @description * This method allows for us to first check if cordova is loaded, * otherwise exceptions can be thrown when trying on a browser. */ self.isNetworkAccessLimited = function() { if (typeof navigator.connection === 'undefined') { // Plugin not defined, probably in browser. return false; } var type = $cordovaNetwork.getNetwork(); var limited = [Connection.CELL_2G, Connection.CELL_3G, Connection.CELL_4G, Connection.CELL]; return limited.indexOf(type) > -1; }; /** * Instantly returns if the app is ready. * * To be notified when the app is ready, refer to {@link $mmApp#ready}. * * @module mm.core * @ngdoc method * @name $mmApp#ready * @return {Boolean} True when it is, false when not. */ self.isReady = function() { var promise = $injector.get('$mmInitDelegate').ready(); return promise.$$state.status === 1; }; /** * Resolves when the app is ready. * * @module mm.core * @ngdoc method * @name $mmApp#ready * @description * This returns a promise that is resolved when the app is initialised. * * Usage: * * $mmApp.ready().then(function() { * // What you want to do. * }); * * @return {Promise} Resolved when the app is initialised. Never rejected. */ self.ready = function() { // Injects to prevent circular dependencies. return $injector.get('$mmInitDelegate').ready(); }; return self; }; });
{ "content_hash": "bb2b8698c2817e64991d41ca7553135f", "timestamp": "", "source": "github", "line_count": 235, "max_line_length": 104, "avg_line_length": 30.582978723404256, "alnum_prop": 0.5433421455405594, "repo_name": "jayteemi/educatoursja", "id": "9ca1a4b37b4443a27cf01cf5b6fcc7955048011d", "size": "7187", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "www2/core/lib/app.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "94" }, { "name": "CSS", "bytes": "1273586" }, { "name": "DIGITAL Command Language", "bytes": "97" }, { "name": "HTML", "bytes": "284515" }, { "name": "JavaScript", "bytes": "6895217" }, { "name": "Shell", "bytes": "461" }, { "name": "TypeScript", "bytes": "8439" } ], "symlink_target": "" }
package org.elasticsearch.index.seqno; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.lucene.store.AlreadyClosedException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.replication.ReplicationOperation; import org.elasticsearch.action.support.replication.ReplicationRequest; import org.elasticsearch.action.support.replication.ReplicationResponse; import org.elasticsearch.action.support.replication.TransportReplicationAction; import org.elasticsearch.cluster.action.shard.ShardStateAction; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShardClosedException; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.io.IOException; /** * Background global checkpoint sync action initiated when a shard goes inactive. This is needed because while we send the global checkpoint * on every replication operation, after the last operation completes the global checkpoint could advance but without a follow-up operation * the global checkpoint will never be synced to the replicas. */ public class GlobalCheckpointSyncAction extends TransportReplicationAction< GlobalCheckpointSyncAction.Request, GlobalCheckpointSyncAction.Request, ReplicationResponse> { public static String ACTION_NAME = "indices:admin/seq_no/global_checkpoint_sync"; @Inject public GlobalCheckpointSyncAction( final Settings settings, final TransportService transportService, final ClusterService clusterService, final IndicesService indicesService, final ThreadPool threadPool, final ShardStateAction shardStateAction, final ActionFilters actionFilters, final IndexNameExpressionResolver indexNameExpressionResolver) { super( settings, ACTION_NAME, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, indexNameExpressionResolver, Request::new, Request::new, ThreadPool.Names.MANAGEMENT); } public void updateGlobalCheckpointForShard(final ShardId shardId) { final ThreadContext threadContext = threadPool.getThreadContext(); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { threadContext.markAsSystemContext(); execute( new Request(shardId), ActionListener.wrap(r -> { }, e -> { if (ExceptionsHelper.unwrap(e, AlreadyClosedException.class, IndexShardClosedException.class) == null) { logger.info(new ParameterizedMessage("{} global checkpoint sync failed", shardId), e); } })); } } @Override protected ReplicationResponse newResponseInstance() { return new ReplicationResponse(); } @Override protected void sendReplicaRequest( final ConcreteReplicaRequest<Request> replicaRequest, final DiscoveryNode node, final ActionListener<ReplicationOperation.ReplicaResponse> listener) { if (node.getVersion().onOrAfter(Version.V_6_0_0_alpha1)) { super.sendReplicaRequest(replicaRequest, node, listener); } else { final long pre60NodeCheckpoint = SequenceNumbers.PRE_60_NODE_CHECKPOINT; listener.onResponse(new ReplicaResponse(pre60NodeCheckpoint, pre60NodeCheckpoint)); } } @Override public PrimaryResult<Request, ReplicationResponse> shardOperationOnPrimary( final Request request, final IndexShard indexShard) throws Exception { maybeSyncTranslog(indexShard); return new PrimaryResult<>(request, new ReplicationResponse()); } @Override public ReplicaResult shardOperationOnReplica(final Request request, final IndexShard indexShard) throws Exception { maybeSyncTranslog(indexShard); return new ReplicaResult(); } private void maybeSyncTranslog(final IndexShard indexShard) throws IOException { if (indexShard.getTranslogDurability() == Translog.Durability.REQUEST && indexShard.getLastSyncedGlobalCheckpoint() < indexShard.getGlobalCheckpoint()) { indexShard.sync(); } } public static final class Request extends ReplicationRequest<Request> { private Request() { super(); } public Request(final ShardId shardId) { super(shardId); } @Override public String toString() { return "GlobalCheckpointSyncAction.Request{" + "shardId=" + shardId + ", timeout=" + timeout + ", index='" + index + '\'' + ", waitForActiveShards=" + waitForActiveShards + "}"; } } }
{ "content_hash": "788144aa28ac27f284cfc49179ede667", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 140, "avg_line_length": 40.49650349650349, "alnum_prop": 0.687446036953894, "repo_name": "jprante/elasticsearch-server", "id": "80c2e64faa6e0845a3a889380836feb7442223d4", "size": "6579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/main/java/org/elasticsearch/index/seqno/GlobalCheckpointSyncAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "36898894" }, { "name": "Shell", "bytes": "1939" } ], "symlink_target": "" }
package org.ddpush.service.broadCast; public interface Storer { }
{ "content_hash": "3388589f97f00a05a722c7628ec08e7b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 37, "avg_line_length": 14.6, "alnum_prop": 0.726027397260274, "repo_name": "taojiaenx/taojiane_push", "id": "532ab6f6ecb871a3f4ec14060cf94df5d57ace09", "size": "73", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/ddpush/service/broadCast/Storer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "421" }, { "name": "Java", "bytes": "175218" }, { "name": "Shell", "bytes": "1851" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Pleospora rubicola Syd. ### Remarks null
{ "content_hash": "75f60eb533f9dff5cacd78aed41b4445", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.846153846153847, "alnum_prop": 0.703125, "repo_name": "mdoering/backbone", "id": "a2bc7fad42684ff9b676f816cd8b3489b69c96ff", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Pleosporaceae/Pleospora/Pleospora rubicola/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package networking import ( "fmt" "net" "reflect" "regexp" "strings" "time" testexutil "github.com/openshift/origin/test/extended/util" testutil "github.com/openshift/origin/test/util" kapi "k8s.io/kubernetes/pkg/api" kapiunversioned "k8s.io/kubernetes/pkg/api/unversioned" utilwait "k8s.io/kubernetes/pkg/util/wait" e2e "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( hostSubnetTimeout = 30 * time.Second ) var _ = Describe("[networking] OVS", func() { Context("generic", func() { f1 := e2e.NewDefaultFramework("net-ovs1") oc := testexutil.NewCLI("get-flows", testexutil.KubeConfigPath()) It("should add and remove flows when pods are added and removed", func() { nodes := e2e.GetReadySchedulableNodesOrDie(f1.ClientSet) origFlows := getFlowsForAllNodes(oc, nodes.Items) Expect(len(origFlows)).To(Equal(len(nodes.Items))) for _, flows := range origFlows { Expect(len(flows)).ToNot(Equal(0)) } podName := "ovs-test-webserver" deployNodeName := nodes.Items[0].Name ipPort := e2e.LaunchWebserverPod(f1, podName, deployNodeName) ip := strings.Split(ipPort, ":")[0] checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, newFlows []string) error { if nodeName == deployNodeName { return findFlowOrError("Should have flows referring to pod IP address", newFlows, ip) } else { return matchFlowsOrError("Flows on non-deployed-to nodes should be unchanged", newFlows, origFlows[nodeName]) } }) err := f1.ClientSet.Core().Pods(f1.Namespace.Name).Delete(podName, &kapi.DeleteOptions{}) Expect(err).NotTo(HaveOccurred()) checkFlowsForNode(oc, deployNodeName, func(nodeName string, flows []string) error { return matchFlowsOrError("Flows after deleting pod should be same as before creating it", flows, origFlows[nodeName]) }) }) It("should add and remove flows when nodes are added and removed", func() { var err error nodes := e2e.GetReadySchedulableNodesOrDie(f1.ClientSet) origFlows := getFlowsForAllNodes(oc, nodes.Items) // The SDN/OVS code doesn't care that the node doesn't actually exist, // but we try to pick an IP on our local subnet to avoid sending // traffic into the real world. highNodeIP := "" for _, node := range nodes.Items { if node.Status.Addresses[0].Address > highNodeIP { highNodeIP = node.Status.Addresses[0].Address } } Expect(highNodeIP).NotTo(Equal("")) ip := net.ParseIP(highNodeIP) Expect(ip).NotTo(BeNil()) ip = ip.To4() Expect(ip).NotTo(BeNil()) Expect(ip[3]).NotTo(Equal(255)) ip[3] += 1 newNodeIP := ip.String() nodeName := "ovs-test-node" node := &kapi.Node{ TypeMeta: kapiunversioned.TypeMeta{ Kind: "Node", }, ObjectMeta: kapi.ObjectMeta{ Name: nodeName, }, Spec: kapi.NodeSpec{ Unschedulable: true, }, Status: kapi.NodeStatus{ Addresses: []kapi.NodeAddress{ { Type: kapi.NodeInternalIP, Address: newNodeIP, }, }, }, } node, err = f1.ClientSet.Core().Nodes().Create(node) Expect(err).NotTo(HaveOccurred()) defer f1.ClientSet.Core().Nodes().Delete(node.Name, &kapi.DeleteOptions{}) osClient, err := testutil.GetClusterAdminClient(testexutil.KubeConfigPath()) Expect(err).NotTo(HaveOccurred()) e2e.Logf("Waiting up to %v for HostSubnet to be created", hostSubnetTimeout) for start := time.Now(); time.Since(start) < hostSubnetTimeout; time.Sleep(time.Second) { _, err = osClient.HostSubnets().Get(node.Name) if err == nil { break } } Expect(err).NotTo(HaveOccurred()) checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, newFlows []string) error { return findFlowOrError("Should have flows referring to node IP address", newFlows, newNodeIP) }) err = f1.ClientSet.Core().Nodes().Delete(node.Name, &kapi.DeleteOptions{}) Expect(err).NotTo(HaveOccurred()) e2e.Logf("Waiting up to %v for HostSubnet to be deleted", hostSubnetTimeout) for start := time.Now(); time.Since(start) < hostSubnetTimeout; time.Sleep(time.Second) { _, err = osClient.HostSubnets().Get(node.Name) if err != nil { break } } Expect(err).NotTo(BeNil()) checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, flows []string) error { return matchFlowsOrError("Flows after deleting node should be same as before creating it", flows, origFlows[nodeName]) }) }) }) InMultiTenantContext(func() { f1 := e2e.NewDefaultFramework("net-ovs1") oc := testexutil.NewCLI("get-flows", testexutil.KubeConfigPath()) It("should add and remove flows when services are added and removed", func() { nodes := e2e.GetReadySchedulableNodesOrDie(f1.ClientSet) origFlows := getFlowsForAllNodes(oc, nodes.Items) serviceName := "ovs-test-service" deployNodeName := nodes.Items[0].Name ipPort := launchWebserverService(f1, serviceName, deployNodeName) ip := strings.Split(ipPort, ":")[0] checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, newFlows []string) error { return findFlowOrError("Should have flows referring to service IP address", newFlows, ip) }) err := f1.ClientSet.Core().Pods(f1.Namespace.Name).Delete(serviceName, &kapi.DeleteOptions{}) Expect(err).NotTo(HaveOccurred()) err = f1.ClientSet.Core().Services(f1.Namespace.Name).Delete(serviceName, &kapi.DeleteOptions{}) Expect(err).NotTo(HaveOccurred()) checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, flows []string) error { return matchFlowsOrError("Flows after deleting service should be same as before creating it", flows, origFlows[nodeName]) }) }) }) }) type FlowError struct { msg string flows []string expected []string } func (err FlowError) Error() string { return err.msg } func matchFlowsOrError(msg string, flows, expected []string) error { if reflect.DeepEqual(flows, expected) { return nil } else { return FlowError{msg, flows, expected} } } func findFlowOrError(msg string, flows []string, ip string) error { for _, flow := range flows { if strings.Contains(flow, "="+ip+",") || strings.Contains(flow, "="+ip+" ") { return nil } } return FlowError{fmt.Sprintf("%s (%s)", msg, ip), flows, nil} } func doGetFlowsForNode(oc *testexutil.CLI, nodeName string) ([]string, error) { pod := &kapi.Pod{ TypeMeta: kapiunversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: kapi.ObjectMeta{ GenerateName: "flow-check", }, Spec: kapi.PodSpec{ Containers: []kapi.Container{ { Name: "flow-check", Image: "openshift/openvswitch", // kubernetes seems to get confused sometimes if the pod exits too quickly Command: []string{"sh", "-c", "ovs-ofctl -O OpenFlow13 dump-flows br0 && sleep 1"}, VolumeMounts: []kapi.VolumeMount{ { Name: "ovs-socket", MountPath: "/var/run/openvswitch/br0.mgmt", }, }, }, }, Volumes: []kapi.Volume{ { Name: "ovs-socket", VolumeSource: kapi.VolumeSource{ HostPath: &kapi.HostPathVolumeSource{ Path: "/var/run/openvswitch/br0.mgmt", }, }, }, }, NodeName: nodeName, RestartPolicy: kapi.RestartPolicyNever, // We don't actually need HostNetwork, we just set it so that deploying this pod won't cause any OVS flows to be added SecurityContext: &kapi.PodSecurityContext{ HostNetwork: true, }, }, } f := oc.KubeFramework() podClient := f.ClientSet.Core().Pods(f.Namespace.Name) pod, err := podClient.Create(pod) if err != nil { return nil, err } defer podClient.Delete(pod.Name, &kapi.DeleteOptions{}) err = waitForPodSuccessInNamespace(f.ClientSet, pod.Name, "flow-check", f.Namespace.Name) if err != nil { return nil, err } logs, err := oc.Run("logs").Args(pod.Name).Output() if err != nil { return nil, err } // For ease of comparison, strip out the parts of the rules that change flows := strings.Split(logs, "\n") strip_re := regexp.MustCompile(`(duration|n_packets|n_bytes)=[^,]*, `) for i := range flows { flows[i] = strip_re.ReplaceAllLiteralString(flows[i], "") } return flows, nil } func getFlowsForAllNodes(oc *testexutil.CLI, nodes []kapi.Node) map[string][]string { var err error flows := make(map[string][]string, len(nodes)) for _, node := range nodes { flows[node.Name], err = doGetFlowsForNode(oc, node.Name) expectNoError(err) } return flows } type CheckFlowFunc func(nodeName string, flows []string) error var checkFlowBackoff = utilwait.Backoff{ Duration: time.Second, Factor: 2, Steps: 5, } func checkFlowsForNode(oc *testexutil.CLI, nodeName string, checkFlow CheckFlowFunc) { var lastCheckErr error e2e.Logf("Checking OVS flows for node %q up to %d times", nodeName, checkFlowBackoff.Steps) err := utilwait.ExponentialBackoff(checkFlowBackoff, func() (bool, error) { flows, err := doGetFlowsForNode(oc, nodeName) if err != nil { return false, err } if lastCheckErr = checkFlow(nodeName, flows); lastCheckErr != nil { e2e.Logf("Check failed (%v)", lastCheckErr) return false, nil } return true, nil }) if err != nil && lastCheckErr != nil { err = lastCheckErr } expectNoError(err) } func checkFlowsForAllNodes(oc *testexutil.CLI, nodes []kapi.Node, checkFlow CheckFlowFunc) { var lastCheckErr error e2e.Logf("Checking OVS flows for all nodes up to %d times", checkFlowBackoff.Steps) err := utilwait.ExponentialBackoff(checkFlowBackoff, func() (bool, error) { lastCheckErr = nil for _, node := range nodes { flows, err := doGetFlowsForNode(oc, node.Name) if err != nil { return false, err } if lastCheckErr = checkFlow(node.Name, flows); lastCheckErr != nil { e2e.Logf("Check failed for node %q (%v)", node.Name, lastCheckErr) return false, nil } } return true, nil }) if err != nil && lastCheckErr != nil { err = lastCheckErr } expectNoError(err) }
{ "content_hash": "86648f8bb7fe59842a06a435aafd6bab", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 125, "avg_line_length": 31, "alnum_prop": 0.6808254858745743, "repo_name": "marun/origin", "id": "b18eb350a02f8c6e9866f166c666038e87fb7f3a", "size": "9982", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "test/extended/networking/ovs.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "921" }, { "name": "DIGITAL Command Language", "bytes": "117" }, { "name": "Go", "bytes": "15166026" }, { "name": "Makefile", "bytes": "8070" }, { "name": "Protocol Buffer", "bytes": "562928" }, { "name": "Python", "bytes": "7834" }, { "name": "Roff", "bytes": "2049" }, { "name": "Ruby", "bytes": "363" }, { "name": "Shell", "bytes": "1512550" } ], "symlink_target": "" }
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var SwiperComponent = (function () { function SwiperComponent(ref) { this.ref = ref; } SwiperComponent.prototype.ngOnInit = function () { }; __decorate([ core_1.Input(), __metadata('design:type', Object) ], SwiperComponent.prototype, "swiperTransform", void 0); __decorate([ core_1.Input(), __metadata('design:type', Object) ], SwiperComponent.prototype, "dynamicPadding", void 0); SwiperComponent = __decorate([ core_1.Component({ selector: 'swiper', templateUrl: 'app/shared/swiper/swiper.html', changeDetection: core_1.ChangeDetectionStrategy.OnPush }), __metadata('design:paramtypes', [core_1.ChangeDetectorRef]) ], SwiperComponent); return SwiperComponent; }()); exports.SwiperComponent = SwiperComponent; //# sourceMappingURL=swiper.component.js.map
{ "content_hash": "3ff455838829ae3f0610cd2704c431cb", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 150, "avg_line_length": 46.054054054054056, "alnum_prop": 0.6185446009389671, "repo_name": "kemalcany/kite-solutions-lite", "id": "e73bdf646c78b0f00f4f48748a594b419c4f5058", "size": "1704", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/shared/swiper/swiper.component.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6613" }, { "name": "HTML", "bytes": "7941" }, { "name": "JavaScript", "bytes": "19912" }, { "name": "TypeScript", "bytes": "16224" } ], "symlink_target": "" }
package org.openstack.atlas.rax.api.mapper.dozer.converter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dozer.CustomConverter; import org.openstack.atlas.api.v1.extensions.rax.NetworkItem; import org.openstack.atlas.rax.datamodel.XmlHelper; import org.openstack.atlas.rax.domain.entity.RaxAccessList; import org.openstack.atlas.rax.domain.entity.RaxAccessListType; import org.openstack.atlas.rax.domain.helper.ExtensionConverter; import org.openstack.atlas.service.domain.entity.IpVersion; import org.openstack.atlas.service.domain.exception.NoMappableConstantException; import org.w3c.dom.Node; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class AccessListConverter implements CustomConverter { private static Log LOG = LogFactory.getLog(AccessListConverter.class.getName()); @Override public Object convert(Object existingDestinationFieldValue, Object sourceFieldValue, Class<?> destinationClass, Class<?> sourceClass) { if (sourceFieldValue == null) { return null; } if (destinationClass == List.class && sourceFieldValue instanceof Set) { final Set<RaxAccessList> accessListSet = (Set<RaxAccessList>) sourceFieldValue; List<Object> anies = (List<Object>) existingDestinationFieldValue; if (anies == null) anies = new ArrayList<Object>(); try { org.openstack.atlas.api.v1.extensions.rax.AccessList dataModelAccessList = ExtensionConverter.convertAccessList(accessListSet); Node objectNode = XmlHelper.marshall(dataModelAccessList); anies.add(objectNode); } catch (Exception e) { LOG.error("Error converting accessList from domain to data model", e); } return anies; } if (destinationClass == Set.class) { Set<RaxAccessList> accessLists = new HashSet<RaxAccessList>(); org.openstack.atlas.api.v1.extensions.rax.AccessList _accessList = ExtensionObjectMapper.getAnyElement((List<Object>) sourceFieldValue, org.openstack.atlas.api.v1.extensions.rax.AccessList.class); if (_accessList == null) return null; for (NetworkItem networkItem : _accessList.getNetworkItems()) { RaxAccessList accessList = new RaxAccessList(); accessList.setId(networkItem.getId()); accessList.setIpAddress(networkItem.getAddress()); //accessList.setIpVersion(IpVersion.valueOf(networkItem.getIpVersion().name())); accessList.setType(RaxAccessListType.valueOf(networkItem.getType().name())); accessLists.add(accessList); } return accessLists; } throw new NoMappableConstantException("Cannot map source type: " + sourceClass.getName()); } }
{ "content_hash": "7bb3be6e8b8a23db911e7b4a1db5e8da", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 208, "avg_line_length": 43.8955223880597, "alnum_prop": 0.6963617817069024, "repo_name": "openstack-atlas/atlas-lb", "id": "a23b53c975b7f8949c5b9aa561bd4443a65e2259", "size": "2941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extensions/rax/api/src/main/java/org/openstack/atlas/rax/api/mapper/dozer/converter/AccessListConverter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1580319" }, { "name": "Shell", "bytes": "756" } ], "symlink_target": "" }
import errno import os from contextlib import contextmanager from pants.base.exceptions import TaskError from pants.task.task import QuietTaskMixin, Task from pants.util.dirutil import safe_open from pants.util.meta import classproperty class ConsoleTask(QuietTaskMixin, Task): """A task whose only job is to print information to the console. ConsoleTasks are not intended to modify build state. """ @classproperty def _register_console_transitivity_option(cls): """Some tasks register their own --transitive option, which act differently.""" return True @classmethod def register_options(cls, register): super().register_options(register) register( "--sep", default="\\n", metavar="<separator>", help="String to use to separate results." ) register( "--output-file", metavar="<path>", help="Write the console output to this file instead." ) if cls._register_console_transitivity_option: register( "--transitive", type=bool, default=False, fingerprint=True, help="If True, use all targets in the build graph, else use only target roots.", ) @property def act_transitively(self): # `Task` defaults to returning `True` in `act_transitively`, so we keep that default value. return self.get_options().get("transitive", True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._console_separator = self.get_options().sep.encode().decode("unicode_escape") if self.get_options().output_file: try: self._outstream = safe_open(os.path.abspath(self.get_options().output_file), "wb") except IOError as e: raise TaskError( "Error opening stream {out_file} due to" " {error_str}".format(out_file=self.get_options().output_file, error_str=e) ) else: self._outstream = self.context.console_outstream @contextmanager def _guard_sigpipe(self): try: yield except IOError as e: # If the pipeline only wants to read so much, that's fine; otherwise, this error is probably # legitimate. if e.errno != errno.EPIPE: raise e def execute(self): with self._guard_sigpipe(): try: targets = self.get_targets() if self.act_transitively else self.context.target_roots for value in self.console_output(targets) or tuple(): self._outstream.write(value.encode()) self._outstream.write(self._console_separator.encode()) finally: self._outstream.flush() if self.get_options().output_file: self._outstream.close() def console_output(self, targets): raise NotImplementedError("console_output must be implemented by subclasses of ConsoleTask")
{ "content_hash": "d2073a9d0c271a83b95f52bbd241ebd2", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 104, "avg_line_length": 37.433734939759034, "alnum_prop": 0.5947859671709044, "repo_name": "wisechengyi/pants", "id": "8ebc24a6583e92303436068ec74e4d2cc3722e3f", "size": "3239", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/python/pants/task/console_task.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "655" }, { "name": "C++", "bytes": "2010" }, { "name": "CSS", "bytes": "9444" }, { "name": "Dockerfile", "bytes": "6634" }, { "name": "GAP", "bytes": "1283" }, { "name": "Gherkin", "bytes": "919" }, { "name": "Go", "bytes": "2765" }, { "name": "HTML", "bytes": "44381" }, { "name": "Java", "bytes": "507948" }, { "name": "JavaScript", "bytes": "22906" }, { "name": "Python", "bytes": "7608990" }, { "name": "Rust", "bytes": "1005243" }, { "name": "Scala", "bytes": "106520" }, { "name": "Shell", "bytes": "105217" }, { "name": "Starlark", "bytes": "489739" }, { "name": "Thrift", "bytes": "2953" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_27) on Fri Mar 02 14:52:00 CET 2018 --> <title>Uses of Class com.tailf.proto.ConfEDouble (CONF API Version 6.6)</title> <meta name="date" content="2018-03-02"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.tailf.proto.ConfEDouble (CONF API Version 6.6)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../com/tailf/proto/ConfEDouble.html" title="class in com.tailf.proto">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/tailf/proto//class-useConfEDouble.html" target="_top">Frames</a></li> <li><a href="ConfEDouble.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.tailf.proto.ConfEDouble" class="title">Uses of Class<br>com.tailf.proto.ConfEDouble</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../com/tailf/proto/ConfEDouble.html" title="class in com.tailf.proto">ConfEDouble</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.tailf.proto">com.tailf.proto</a></td> <td class="colLast"> <div class="block">Package containing java classes representation of Erlang datatypes or terms which is used internally in the communication between the Library and ConfD/NCS.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.tailf.proto"> <!-- --> </a> <h3>Uses of <a href="../../../../com/tailf/proto/ConfEDouble.html" title="class in com.tailf.proto">ConfEDouble</a> in <a href="../../../../com/tailf/proto/package-summary.html">com.tailf.proto</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../com/tailf/proto/ConfEDouble.html" title="class in com.tailf.proto">ConfEDouble</a> in <a href="../../../../com/tailf/proto/package-summary.html">com.tailf.proto</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../com/tailf/proto/ConfEFloat.html" title="class in com.tailf.proto">ConfEFloat</a></strong></code> <div class="block">Provides a Java representation of E floats and doubles.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../com/tailf/proto/ConfEDouble.html" title="class in com.tailf.proto">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/tailf/proto//class-useConfEDouble.html" target="_top">Frames</a></li> <li><a href="ConfEDouble.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "b8be116fa625d87ef4c5d6f8f6198322", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 265, "avg_line_length": 36.81481481481482, "alnum_prop": 0.6338028169014085, "repo_name": "kimjinyong/i2nsf-framework", "id": "91b57e5dc692f4fcdf7688b9dd68aca68b8406a8", "size": "5964", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "Hackathon-112/analyzer/confd/doc/api/java/com/tailf/proto/class-use/ConfEDouble.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4396520" }, { "name": "C++", "bytes": "9389" }, { "name": "CSS", "bytes": "51736" }, { "name": "Dockerfile", "bytes": "3839" }, { "name": "Emacs Lisp", "bytes": "24812" }, { "name": "Erlang", "bytes": "1364078" }, { "name": "HTML", "bytes": "42486541" }, { "name": "Hack", "bytes": "6349" }, { "name": "Java", "bytes": "7976" }, { "name": "JavaScript", "bytes": "533000" }, { "name": "Makefile", "bytes": "401170" }, { "name": "PHP", "bytes": "164007" }, { "name": "Perl", "bytes": "2188" }, { "name": "Python", "bytes": "3004949" }, { "name": "QMake", "bytes": "360" }, { "name": "Roff", "bytes": "3906372" }, { "name": "Shell", "bytes": "83872" }, { "name": "XSLT", "bytes": "167018" } ], "symlink_target": "" }
require 'rails_helper' feature 'User creates a new company' do background do user = create(:user, :confirmed, :roles => 'admin') sign_in_with user.email, user.password visit new_configuration_company_path end context 'when the details are valid' do scenario 'the user sees a success message' do fill_in :company_name, :with => Faker::Lorem.word click_on 'Save' expect(page).to have_content(I18n.t('contacts.company.create.success')) end end context 'when the details are not valid' do scenario 'the user sees an error message' do click_on 'Save' expect(page).to have_content(/error/i) end end end
{ "content_hash": "73f2385c6764200d6acb2d1383d16bf4", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 77, "avg_line_length": 23.275862068965516, "alnum_prop": 0.6711111111111111, "repo_name": "josephbridgwaterrowe/contacts", "id": "15563e6c51ffded41c764b3185e5e9b75e4f5547", "size": "675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/features/user_creates_a_new_company_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "215" }, { "name": "CoffeeScript", "bytes": "104" }, { "name": "HTML", "bytes": "67339" }, { "name": "JavaScript", "bytes": "106" }, { "name": "Ruby", "bytes": "166715" } ], "symlink_target": "" }
set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" else local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" fi local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries local basename basename="$(basename "$1" | sed -E s/\\..+// && exit ${PIPESTATUS[0]})" local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/${basename}.framework/${basename}" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework 'Pods-MyLibrary_Tests/MyLibrary.framework' fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework 'Pods-MyLibrary_Tests/MyLibrary.framework' fi
{ "content_hash": "de3e1a576181485bef37798158fc672a", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 241, "avg_line_length": 44.793103448275865, "alnum_prop": 0.6497305619707467, "repo_name": "congncif/MyLibrary", "id": "ee32c265f8f1989b34f51a930cfb1a22aae08d75", "size": "2608", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/Pods-MyLibrary_Tests/Pods-MyLibrary_Tests-frameworks.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "5268" }, { "name": "Ruby", "bytes": "1493" }, { "name": "Shell", "bytes": "14394" } ], "symlink_target": "" }
.class Landroid/net/wifi/WifiWatchdogStateMachine$WatchdogDisabledState; .super Lcom/android/internal/util/State; .source "WifiWatchdogStateMachine.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/net/wifi/WifiWatchdogStateMachine; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = "WatchdogDisabledState" .end annotation # instance fields .field final synthetic this$0:Landroid/net/wifi/WifiWatchdogStateMachine; # direct methods .method constructor <init>(Landroid/net/wifi/WifiWatchdogStateMachine;)V .locals 0 .parameter .prologue .line 581 iput-object p1, p0, Landroid/net/wifi/WifiWatchdogStateMachine$WatchdogDisabledState;->this$0:Landroid/net/wifi/WifiWatchdogStateMachine; invoke-direct {p0}, Lcom/android/internal/util/State;-><init>()V return-void .end method # virtual methods .method public processMessage(Landroid/os/Message;)Z .locals 2 .parameter "msg" .prologue .line 584 iget v0, p1, Landroid/os/Message;->what:I packed-switch v0, :pswitch_data_0 .line 590 const/4 v0, 0x0 :goto_0 return v0 .line 586 :pswitch_0 iget-object v0, p0, Landroid/net/wifi/WifiWatchdogStateMachine$WatchdogDisabledState;->this$0:Landroid/net/wifi/WifiWatchdogStateMachine; #calls: Landroid/net/wifi/WifiWatchdogStateMachine;->isWatchdogEnabled()Z invoke-static {v0}, Landroid/net/wifi/WifiWatchdogStateMachine;->access$200(Landroid/net/wifi/WifiWatchdogStateMachine;)Z move-result v0 if-eqz v0, :cond_0 .line 587 iget-object v0, p0, Landroid/net/wifi/WifiWatchdogStateMachine$WatchdogDisabledState;->this$0:Landroid/net/wifi/WifiWatchdogStateMachine; iget-object v1, p0, Landroid/net/wifi/WifiWatchdogStateMachine$WatchdogDisabledState;->this$0:Landroid/net/wifi/WifiWatchdogStateMachine; #getter for: Landroid/net/wifi/WifiWatchdogStateMachine;->mNotConnectedState:Landroid/net/wifi/WifiWatchdogStateMachine$NotConnectedState; invoke-static {v1}, Landroid/net/wifi/WifiWatchdogStateMachine;->access$300(Landroid/net/wifi/WifiWatchdogStateMachine;)Landroid/net/wifi/WifiWatchdogStateMachine$NotConnectedState; move-result-object v1 #calls: Landroid/net/wifi/WifiWatchdogStateMachine;->transitionTo(Lcom/android/internal/util/IState;)V invoke-static {v0, v1}, Landroid/net/wifi/WifiWatchdogStateMachine;->access$400(Landroid/net/wifi/WifiWatchdogStateMachine;Lcom/android/internal/util/IState;)V .line 588 :cond_0 const/4 v0, 0x1 goto :goto_0 .line 584 :pswitch_data_0 .packed-switch 0x21001 :pswitch_0 .end packed-switch .end method
{ "content_hash": "f891279d7a2860d8f8c4ab2f3931bbdc", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 185, "avg_line_length": 30.90909090909091, "alnum_prop": 0.7606617647058823, "repo_name": "baidurom/devices-lt26i", "id": "a65b3dd0f9d5aaed6ec94c1adb0b0cea8d82300e", "size": "2720", "binary": false, "copies": "1", "ref": "refs/heads/coron-4.0", "path": "framework.jar.out/smali/android/net/wifi/WifiWatchdogStateMachine$WatchdogDisabledState.smali", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#include "common.h" static apr_pool_t *test_pool; static gla_store_t *test_store; static gla_entityreg_t *test_self; /********************************** TEST 1 ************************************/ #include "src/regex.h" static int test1_init() { int ret; ret = apr_pool_create(&test_pool, NULL); if(ret != APR_SUCCESS) return ret; ret = gla_regex_init(test_pool); if(ret != GLA_SUCCESS) return ret; test_store = gla_store_new(test_pool); if(test_store == NULL) return errno; test_self = gla_entityreg_new(test_store, sizeof(int), test_pool); if(test_self == NULL) return errno; return 0; } static int test1_cleanup() { apr_pool_destroy(test_pool); return 0; } #define INSERT_ENTITY(NAME) \ do { \ ret = gla_path_parse_entity(&path, NAME, test_pool); \ CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); \ data = gla_entityreg_get(test_self, &path); \ CU_ASSERT_PTR_NOT_NULL_FATAL(data); \ } while(false) static void test1_access() { int ret; int *data; int *orgdata; gla_path_t path; gla_path_t path_rev; gla_id_t id; gla_id_t orgid; CU_ASSERT_PTR_NOT_NULL_FATAL(test_store); /* test root existence check */ ret = gla_entityreg_covered(test_self, NULL); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); /* insert new entity into registry */ ret = gla_path_parse_entity(&path, "<ext>a.aa.EntityName", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); data = gla_entityreg_get(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_EQUAL(errno, GLA_NOTFOUND); orgdata = data; /* retrieve entity path from data */ ret = gla_entityreg_path_for(test_self, &path_rev, data, test_pool); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); CU_ASSERT_TRUE(gla_path_equal(&path, &path_rev)); /* retrieve same entity using try-method */ data = gla_entityreg_try(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_EQUAL(data, orgdata); /* retrieve same entitiy using get-method */ data = gla_entityreg_get(test_self, &path); CU_ASSERT_EQUAL(errno, GLA_SUCCESS); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_EQUAL(data, orgdata); /* insert another new entity into registry */ ret = gla_path_parse_entity(&path, "<ext>a.ab.EntityName", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); data = gla_entityreg_get(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_NOT_EQUAL(data, orgdata); /* insert new entity into root package */ ret = gla_path_parse_entity(&path, "<ext>EntityName", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); data = gla_entityreg_get(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_NOT_EQUAL(data, orgdata); /* retrieve entity path from data */ ret = gla_entityreg_path_for(test_self, &path_rev, data, test_pool); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); CU_ASSERT_TRUE(gla_path_equal(&path, &path_rev)); /* add some other packages to store which are not used in registry */ ret = gla_path_parse_package(&path, "b", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); id = gla_store_path_get(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(id, GLA_ID_INVALID); ret = gla_path_parse_package(&path, "a.aa.aaa", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); id = gla_store_path_get(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(id, GLA_ID_INVALID); /* get root package first child */ id = gla_entityreg_covered_children(test_self, GLA_ID_ROOT); ret = gla_path_parse_package(&path, "a", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); orgid = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL(orgid, GLA_ID_INVALID); CU_ASSERT_EQUAL(orgid, id); /* get next sibling */ errno = GLA_TEST; id = gla_entityreg_covered_next(test_self, orgid); CU_ASSERT_EQUAL(id, GLA_ID_INVALID); CU_ASSERT_EQUAL(errno, GLA_END); /* get leaf package first child */ ret = gla_path_parse_package(&path, "a.aa", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); id = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(id, GLA_ID_INVALID); errno = GLA_TEST; id = gla_entityreg_covered_children(test_self, id); CU_ASSERT_EQUAL(id, GLA_ID_INVALID); CU_ASSERT_EQUAL(errno, GLA_END); /* test root existence check again */ ret = gla_entityreg_covered(test_self, NULL); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); /* test positive existence check */ ret = gla_path_parse_package(&path, "a", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); ret = gla_path_parse_package(&path, "a.aa", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); /* test negative existence check, contained within store */ ret = gla_path_parse_package(&path, "b", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); /* test negative existence check, not contained within store */ ret = gla_path_parse_package(&path, "c", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); /* insert several other entities (for later usage) */ INSERT_ENTITY("<exta>z.za.EntityA"); INSERT_ENTITY("<extc>z.za.EntityC"); INSERT_ENTITY("<extb>z.za.EntityB"); INSERT_ENTITY("<extd>z.za.EntityD"); INSERT_ENTITY("<exte>z.zb.EntityE"); } #define EXPECT_ENTRY(NAME, EXTENSION) \ do {\ CU_ASSERT_PTR_NOT_NULL_FATAL(it.name); \ CU_ASSERT_PTR_NOT_NULL_FATAL(it.extension); \ CU_ASSERT_EQUAL(it.package, package); \ CU_ASSERT_EQUAL(strcmp(it.name, NAME), 0); \ CU_ASSERT_EQUAL(strcmp(it.extension, EXTENSION), 0); \ } while(false) static void test1_forward_iteration() { int ret; gla_path_t path; gla_id_t package; gla_entityreg_it_t it; /* package: z.za */ ret = gla_path_parse_package(&path, "z.za", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); package = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(package, GLA_ID_INVALID); /* forward iteration */ ret = gla_entityreg_find_first(test_self, package, &it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityA", "exta"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityB", "extb"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityC", "extc"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityD", "extd"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL(ret, GLA_END); EXPECT_ENTRY("EntityD", "extd"); } static void test1_reverse_iteration() { int ret; gla_path_t path; gla_id_t package; gla_entityreg_it_t it; /* set current package: z.za */ ret = gla_path_parse_package(&path, "z.za", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); package = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(package, GLA_ID_INVALID); /* forward iteration */ ret = gla_entityreg_find_last(test_self, package, &it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityD", "extd"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityC", "extc"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityB", "extb"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityA", "exta"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL(ret, GLA_END); EXPECT_ENTRY("EntityA", "exta"); } void test1_empty_iteration() { int ret; gla_id_t package; gla_entityreg_it_t it; gla_path_t path; /* set current package: a */ ret = gla_path_parse_package(&path, "a", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); package = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(package, GLA_ID_INVALID); /* test for NOTFOUND result */ ret = gla_entityreg_find_first(test_self, package, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); ret = gla_entityreg_find_last(test_self, package, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); /* test invalid package for NOTFOUND result */ ret = gla_entityreg_find_first(test_self, GLA_ID_INVALID, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); ret = gla_entityreg_find_last(test_self, GLA_ID_INVALID, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); } void test1_root_iteration() { int ret; gla_entityreg_it_t it; gla_id_t package = GLA_ID_ROOT; ret = gla_entityreg_find_first(test_self, GLA_ID_ROOT, &it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityName", "ext"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL(ret, GLA_END); } /******************************** INITIALIZE **********************************/ int glatest_entityreg() { CU_pSuite suite; CU_pTest test; BEGIN_SUITE("Entity Registry API", test1_init, test1_cleanup); ADD_TEST("access", test1_access); ADD_TEST("forward iteration", test1_forward_iteration); ADD_TEST("reverse iteration", test1_reverse_iteration); ADD_TEST("empty iteration", test1_empty_iteration); ADD_TEST("root iteration", test1_root_iteration); END_SUITE; return GLA_SUCCESS; }
{ "content_hash": "5a05573e699b544a2bdb710525a2309e", "timestamp": "", "source": "github", "line_count": 309, "max_line_length": 80, "avg_line_length": 29.915857605177994, "alnum_prop": 0.6831458243184768, "repo_name": "torsten-schenk/gla", "id": "6d09b0b17c5951025f1a2240da85b10e0601bad5", "size": "9244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/entityreg.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "446897" }, { "name": "C++", "bytes": "31650" }, { "name": "CMake", "bytes": "15181" }, { "name": "Objective-C", "bytes": "280" }, { "name": "Squirrel", "bytes": "266105" } ], "symlink_target": "" }
<?php namespace Analogue\ORM\Relationships; use Analogue\ORM\EntityCollection; use Analogue\ORM\Mappable; use Analogue\ORM\System\InternallyMappable; use Analogue\ORM\System\Mapper; use Analogue\ORM\System\Query; use Analogue\ORM\System\Wrappers\Factory; use Carbon\Carbon; use Closure; use Illuminate\Database\Query\Expression; /** * Class Relationship. * * @mixin Query */ abstract class Relationship { /** * The mapper instance for the related entity. * * @var Mapper */ protected $relatedMapper; /** * The Analogue Query Builder instance. * * @var Query */ protected $query; /** * The parent entity proxy instance. * * @var InternallyMappable */ protected $parent; /** * The parent entity map. * * @var \Analogue\ORM\EntityMap */ protected $parentMap; /** * The Parent Mapper instance. * * @var Mapper */ protected $parentMapper; /** * The related entity instance. * * @var object */ protected $related; /** * The related entity Map. * * @var \Analogue\ORM\EntityMap */ protected $relatedMap; /** * Indicate if the relationships use a pivot table.*. * * @var bool */ protected static $hasPivot = false; /** * Indicates if the relation is adding constraints. * * @var bool */ protected static $constraints = true; /** * Wrapper factory. * * @var \Analogue\ORM\System\Wrappers\Factory */ protected $factory; /** * Create a new relation instance. * * @param Mapper $mapper * @param mixed $parent * * @throws \Analogue\ORM\Exceptions\MappingException */ public function __construct(Mapper $mapper, $parent) { $this->relatedMapper = $mapper; $this->query = $mapper->getQuery(); $this->factory = new Factory(); $this->parent = $this->factory->make($parent); $this->parentMapper = $mapper->getManager()->getMapper($parent); $this->parentMap = $this->parentMapper->getEntityMap(); $this->related = $mapper->newInstance(); $this->relatedMap = $mapper->getEntityMap(); $this->addConstraints(); } /** * Indicate if the relationship uses a pivot table. * * @return bool */ public function hasPivot() { return static::$hasPivot; } /** * Set the base constraints on the relation query. * * @return void */ abstract public function addConstraints(); /** * Set the constraints for an eager load of the relation. * * @param array $results * * @return void */ abstract public function addEagerConstraints(array $results); /** * Match the eagerly loaded results to their parents, then return * updated results. * * @param array $results * @param string $relation * * @return array */ abstract public function match(array $results, $relation); /** * Get the results of the relationship. * * @param string $relation relation name in parent's entity map * * @return mixed */ abstract public function getResults($relation); /** * Get the relationship for eager loading. * * @return \Illuminate\Support\Collection */ public function getEager() { return $this->get(); } /** * Add the constraints for a relationship count query. * * @param Query $query * @param Query $parent * * @return Query */ public function getRelationCountQuery(Query $query, Query $parent) { $query->select(new Expression('count(*)')); $key = $this->wrap($this->getQualifiedParentKeyName()); return $query->where($this->getHasCompareKey(), '=', new Expression($key)); } /** * Run a callback with constraints disabled on the relation. * * @param Closure $callback * * @return mixed */ public static function noConstraints(Closure $callback) { static::$constraints = false; // When resetting the relation where clause, we want to shift the first element // off of the bindings, leaving only the constraints that the developers put // as "extra" on the relationships, and not original relation constraints. $results = call_user_func($callback); static::$constraints = true; return $results; } /** * Get all of the primary keys for an array of entities. * * @param array $entities * @param string $key * * @return array */ protected function getKeys(array $entities, $key = null) { if (is_null($key)) { $key = $this->relatedMap->getKeyName(); } $host = $this; return array_unique(array_values(array_map(function ($value) use ($key, $host) { if (!$value instanceof InternallyMappable) { $value = $host->factory->make($value); } return $value->getEntityAttribute($key); }, $entities))); } /** * Get all the keys from a result set. * * @param array $results * @param string $key * * @return array */ protected function getKeysFromResults(array $results, $key = null) { if (is_null($key)) { $key = $this->parentMap->getKeyName(); } return array_unique(array_values(array_map(function ($value) use ($key) { return $value[$key]; }, $results))); } /** * Get the underlying query for the relation. * * @return Query */ public function getQuery() { return $this->query; } /** * Get the base query builder. * * @return \Illuminate\Database\Query\Builder */ public function getBaseQuery() { return $this->query->getQuery(); } /** * Get the parent model of the relation. * * @return InternallyMappable */ public function getParent() { return $this->parent; } /** * Set the parent model of the relation. * * @param InternallyMappable $parent * * @return void */ public function setParent(InternallyMappable $parent) { $this->parent = $parent; } /** * Get the fully qualified parent key name. * * @return string */ protected function getQualifiedParentKeyName() { return $this->parent->getQualifiedKeyName(); } /** * Get the related entity of the relation. * * @return \Analogue\ORM\Entity */ public function getRelated() { return $this->related; } /** * Get the related mapper for the relation. * * @return Mapper */ public function getRelatedMapper() { return $this->relatedMapper; } /** * Get the name of the "created at" column. * * @return string */ public function createdAt() { return $this->parentMap->getCreatedAtColumn(); } /** * Get the name of the "updated at" column. * * @return string */ public function updatedAt() { return $this->parentMap->getUpdatedAtColumn(); } /** * Get the name of the related model's "updated at" column. * * @return string */ public function relatedUpdatedAt() { return $this->related->getUpdatedAtColumn(); } /** * Wrap the given value with the parent query's grammar. * * @param string $value * * @return string */ public function wrap($value) { return $this->parentMapper->getQuery()->getQuery()->getGrammar()->wrap($value); } /** * Get a fresh timestamp. * * @return Carbon */ protected function freshTimestamp() { return new Carbon(); } /** * Cache the link between parent and related * into the mapper's Entity Cache. * * @param EntityCollection|Mappable $results result of the relation query * @param string $relation name of the relation method on the parent entity * * @return void */ protected function cacheRelation($results, $relation) { $cache = $this->parentMapper->getEntityCache(); $cache->cacheLoadedRelationResult($this->parent->getEntityKeyName(), $relation, $results, $this); } /** * Return Pivot attributes when available on a relationship. * * @return array */ public function getPivotAttributes() { return []; } /** * Get a combo type.primaryKey. * * @param Mappable $entity * * @return string */ protected function getEntityHash(Mappable $entity) { $class = get_class($entity); $keyName = Mapper::getMapper($class)->getEntityMap()->getKeyName(); return $class.'.'.$entity->getEntityAttribute($keyName); } /** * Run synchronization content if needed by the * relation type. * * @param array $actualContent * * @return void */ abstract public function sync(array $actualContent); /** * Handle dynamic method calls to the relationship. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { $result = call_user_func_array([$this->query, $method], $parameters); if ($result === $this->query) { return $this; } return $result; } }
{ "content_hash": "252be8518a4ffe07fc982e8c66bfd5e4", "timestamp": "", "source": "github", "line_count": 453, "max_line_length": 105, "avg_line_length": 21.713024282560706, "alnum_prop": 0.563338755591704, "repo_name": "analogueorm/analogue", "id": "b31934563a8c73cf4c828e7b30643be9dd7b9cdf", "size": "9836", "binary": false, "copies": "1", "ref": "refs/heads/5.6", "path": "src/Relationships/Relationship.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "526491" } ], "symlink_target": "" }
package org.apache.hive.jdbc; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.NClob; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.text.MessageFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Scanner; import org.apache.hive.service.cli.thrift.TCLIService; import org.apache.hive.service.cli.thrift.TSessionHandle; /** * HivePreparedStatement. * */ public class HivePreparedStatement extends HiveStatement implements PreparedStatement { private final String sql; /** * save the SQL parameters {paramLoc:paramValue} */ private final HashMap<Integer, String> parameters=new HashMap<Integer, String>(); public HivePreparedStatement(HiveConnection connection, TCLIService.Iface client, TSessionHandle sessHandle, String sql) { super(connection, client, sessHandle); this.sql = sql; } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#addBatch() */ public void addBatch() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#clearParameters() */ public void clearParameters() throws SQLException { this.parameters.clear(); } /** * Invokes executeQuery(sql) using the sql provided to the constructor. * * @return boolean Returns true if a resultSet is created, false if not. * Note: If the result set is empty a true is returned. * * @throws SQLException */ public boolean execute() throws SQLException { return super.execute(updateSql(sql, parameters)); } /** * Invokes executeQuery(sql) using the sql provided to the constructor. * * @return ResultSet * @throws SQLException */ public ResultSet executeQuery() throws SQLException { return super.executeQuery(updateSql(sql, parameters)); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#executeUpdate() */ public int executeUpdate() throws SQLException { super.executeUpdate(updateSql(sql, parameters)); return 0; } /** * update the SQL string with parameters set by setXXX methods of {@link PreparedStatement} * * @param sql * @param parameters * @return updated SQL string */ private String updateSql(final String sql, HashMap<Integer, String> parameters) { if (!sql.contains("?")) { return sql; } StringBuffer newSql = new StringBuffer(sql); int paramLoc = 1; while (getCharIndexFromSqlByParamLocation(sql, '?', paramLoc) > 0) { // check the user has set the needs parameters if (parameters.containsKey(paramLoc)) { int tt = getCharIndexFromSqlByParamLocation(newSql.toString(), '?', 1); newSql.deleteCharAt(tt); newSql.insert(tt, parameters.get(paramLoc)); } paramLoc++; } return newSql.toString(); } /** * Get the index of given char from the SQL string by parameter location * </br> The -1 will be return, if nothing found * * @param sql * @param cchar * @param paramLoc * @return */ private int getCharIndexFromSqlByParamLocation(final String sql, final char cchar, final int paramLoc) { int signalCount = 0; int charIndex = -1; int num = 0; for (int i = 0; i < sql.length(); i++) { char c = sql.charAt(i); if (c == '\'' || c == '\\')// record the count of char "'" and char "\" { signalCount++; } else if (c == cchar && signalCount % 2 == 0) {// check if the ? is really the parameter num++; if (num == paramLoc) { charIndex = i; break; } } } return charIndex; } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#getMetaData() */ public ResultSetMetaData getMetaData() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#getParameterMetaData() */ public ParameterMetaData getParameterMetaData() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setArray(int, java.sql.Array) */ public void setArray(int i, Array x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream) */ public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, * int) */ public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, * long) */ public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBigDecimal(int, java.math.BigDecimal) */ public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream) */ public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { String str = new Scanner(x, "UTF-8").useDelimiter("\\A").next(); this.parameters.put(parameterIndex, str); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, * int) */ public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, * long) */ public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBlob(int, java.sql.Blob) */ public void setBlob(int i, Blob x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream) */ public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream, long) */ public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBoolean(int, boolean) */ public void setBoolean(int parameterIndex, boolean x) throws SQLException { this.parameters.put(parameterIndex, ""+x); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setByte(int, byte) */ public void setByte(int parameterIndex, byte x) throws SQLException { this.parameters.put(parameterIndex, ""+x); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setBytes(int, byte[]) */ public void setBytes(int parameterIndex, byte[] x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader) */ public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, * int) */ public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, * long) */ public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setClob(int, java.sql.Clob) */ public void setClob(int i, Clob x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setClob(int, java.io.Reader) */ public void setClob(int parameterIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setClob(int, java.io.Reader, long) */ public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setDate(int, java.sql.Date) */ public void setDate(int parameterIndex, Date x) throws SQLException { this.parameters.put(parameterIndex, x.toString()); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setDate(int, java.sql.Date, * java.util.Calendar) */ public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setDouble(int, double) */ public void setDouble(int parameterIndex, double x) throws SQLException { this.parameters.put(parameterIndex,""+x); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setFloat(int, float) */ public void setFloat(int parameterIndex, float x) throws SQLException { this.parameters.put(parameterIndex,""+x); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setInt(int, int) */ public void setInt(int parameterIndex, int x) throws SQLException { this.parameters.put(parameterIndex,""+x); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setLong(int, long) */ public void setLong(int parameterIndex, long x) throws SQLException { this.parameters.put(parameterIndex,""+x); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader) */ public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader, * long) */ public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNClob(int, java.sql.NClob) */ public void setNClob(int parameterIndex, NClob value) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNClob(int, java.io.Reader) */ public void setNClob(int parameterIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNClob(int, java.io.Reader, long) */ public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNString(int, java.lang.String) */ public void setNString(int parameterIndex, String value) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNull(int, int) */ public void setNull(int parameterIndex, int sqlType) throws SQLException { this.parameters.put(parameterIndex, "NULL"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setNull(int, int, java.lang.String) */ public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException { this.parameters.put(paramIndex, "NULL"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setObject(int, java.lang.Object) */ public void setObject(int parameterIndex, Object x) throws SQLException { if (x == null) { setNull(parameterIndex, Types.NULL); } else if (x instanceof String) { setString(parameterIndex, (String) x); } else if (x instanceof Short) { setShort(parameterIndex, ((Short) x).shortValue()); } else if (x instanceof Integer) { setInt(parameterIndex, ((Integer) x).intValue()); } else if (x instanceof Long) { setLong(parameterIndex, ((Long) x).longValue()); } else if (x instanceof Float) { setFloat(parameterIndex, ((Float) x).floatValue()); } else if (x instanceof Double) { setDouble(parameterIndex, ((Double) x).doubleValue()); } else if (x instanceof Boolean) { setBoolean(parameterIndex, ((Boolean) x).booleanValue()); } else if (x instanceof Byte) { setByte(parameterIndex, ((Byte) x).byteValue()); } else if (x instanceof Character) { setString(parameterIndex, x.toString()); } else if (x instanceof Timestamp) { setString(parameterIndex, x.toString()); } else if (x instanceof BigDecimal) { setString(parameterIndex, x.toString()); } else { // Can't infer a type. throw new SQLException( MessageFormat .format( "Can''t infer the SQL type to use for an instance of {0}. Use setObject() with an explicit Types value to specify the type to use.", x.getClass().getName())); } } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int) */ public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int, int) */ public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setRef(int, java.sql.Ref) */ public void setRef(int i, Ref x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setRowId(int, java.sql.RowId) */ public void setRowId(int parameterIndex, RowId x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setSQLXML(int, java.sql.SQLXML) */ public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setShort(int, short) */ public void setShort(int parameterIndex, short x) throws SQLException { this.parameters.put(parameterIndex,""+x); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setString(int, java.lang.String) */ public void setString(int parameterIndex, String x) throws SQLException { x=x.replace("'", "\\'"); this.parameters.put(parameterIndex,"'"+x+"'"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setTime(int, java.sql.Time) */ public void setTime(int parameterIndex, Time x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setTime(int, java.sql.Time, * java.util.Calendar) */ public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp) */ public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { this.parameters.put(parameterIndex, x.toString()); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp, * java.util.Calendar) */ public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setURL(int, java.net.URL) */ public void setURL(int parameterIndex, URL x) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.PreparedStatement#setUnicodeStream(int, java.io.InputStream, * int) */ public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } }
{ "content_hash": "99f41b14be8b63a06f19dc0faf228c3a", "timestamp": "", "source": "github", "line_count": 754, "max_line_length": 150, "avg_line_length": 25.722811671087534, "alnum_prop": 0.6684196957978861, "repo_name": "winningsix/hive", "id": "8a0671fc28c4e8326df068f7de5cf278c863e362", "size": "20201", "binary": false, "copies": "7", "ref": "refs/heads/trunk", "path": "jdbc/src/java/org/apache/hive/jdbc/HivePreparedStatement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "115864" }, { "name": "C++", "bytes": "3310251" }, { "name": "CSS", "bytes": "10090" }, { "name": "GAP", "bytes": "118886" }, { "name": "Java", "bytes": "33679240" }, { "name": "M", "bytes": "2173" }, { "name": "Makefile", "bytes": "6963" }, { "name": "PHP", "bytes": "1715861" }, { "name": "Perl", "bytes": "206388" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "1872503" }, { "name": "Ruby", "bytes": "462744" }, { "name": "Shell", "bytes": "192163" }, { "name": "Thrift", "bytes": "93618" }, { "name": "XSLT", "bytes": "7619" } ], "symlink_target": "" }
<?php namespace perf\Form\Filtering; /** * */ class UppercaseFilterTest extends \PHPUnit_Framework_TestCase { /** * */ protected function setUp() { $this->filter = new UppercaseFilter(); } /** * */ public function testApply() { $value = 'foo'; $this->assertSame('FOO' , $this->filter->apply($value)); } }
{ "content_hash": "961cec99e8a0005981416d33aee21bfe", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 64, "avg_line_length": 13.857142857142858, "alnum_prop": 0.520618556701031, "repo_name": "jmfeurprier/perf-form", "id": "8367d0901ef2fd125121ee99f14678b65bb8eb46", "size": "388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/unit/lib/perf/Form/Filtering/UppercaseFilterTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "38948" } ], "symlink_target": "" }
package org.bitcoins.core.script.splice import org.bitcoins.core.script.ScriptOperationFactory import org.bitcoins.core.script.constant.ScriptOperation /** * Created by chris on 1/22/16. */ sealed trait SpliceOperation extends ScriptOperation case object OP_CAT extends SpliceOperation { override def opCode = 126 } case object OP_SUBSTR extends SpliceOperation { override def opCode = 127 } case object OP_LEFT extends SpliceOperation { override def opCode = 128 } case object OP_RIGHT extends SpliceOperation { override def opCode = 129 } case object OP_SIZE extends SpliceOperation { override def opCode = 130 } object SpliceOperation extends ScriptOperationFactory[SpliceOperation] { def operations = Seq(OP_CAT, OP_LEFT, OP_RIGHT, OP_SIZE, OP_SUBSTR) }
{ "content_hash": "a78bf7fbc76797eed75b2b427144f5a6", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 72, "avg_line_length": 23.606060606060606, "alnum_prop": 0.7792041078305519, "repo_name": "Christewart/bitcoin-s-core", "id": "7b3a8d84c418f87ef48ddc608f9a1e5fe8d57ccc", "size": "779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/org/bitcoins/core/script/splice/SpliceOperations.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "44638" }, { "name": "Scala", "bytes": "1478569" } ], "symlink_target": "" }
using namespace testing; using namespace stream; using namespace stream::op; TEST(SingletonTest, Default) { EXPECT_THAT(MakeStream::singleton(5) | to_vector(), ElementsAre(5)); }
{ "content_hash": "77566c1aea9fac1c2c65df08b4f68586", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 72, "avg_line_length": 26.285714285714285, "alnum_prop": 0.7445652173913043, "repo_name": "bowlofstew/Streams", "id": "c2ca1c5480a02bcf4025cc1b14776df490d776ff", "size": "231", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/SingletonTest.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "994" }, { "name": "C++", "bytes": "172701" }, { "name": "CMake", "bytes": "2459" } ], "symlink_target": "" }
#ifndef HAVE_GETADDRINFO /* * Error return codes from getaddrinfo() */ #ifdef EAI_ADDRFAMILY /* If this is defined, there is a conflicting implementation in the C library, which can't be used for some reason. Make sure it won't interfere with this emulation. */ #undef EAI_ADDRFAMILY #undef EAI_AGAIN #undef EAI_BADFLAGS #undef EAI_FAIL #undef EAI_FAMILY #undef EAI_MEMORY #undef EAI_NODATA #undef EAI_NONAME #undef EAI_SERVICE #undef EAI_SOCKTYPE #undef EAI_SYSTEM #undef EAI_BADHINTS #undef EAI_PROTOCOL #undef EAI_MAX #undef getaddrinfo #define getaddrinfo fake_getaddrinfo #endif /* EAI_ADDRFAMILY */ #define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ #define EAI_AGAIN 2 /* temporary failure in name resolution */ #define EAI_BADFLAGS 3 /* invalid value for ai_flags */ #define EAI_FAIL 4 /* non-recoverable failure in name resolution */ #define EAI_FAMILY 5 /* ai_family not supported */ #define EAI_MEMORY 6 /* memory allocation failure */ #define EAI_NODATA 7 /* no address associated with hostname */ #define EAI_NONAME 8 /* hostname nor servname provided, or not known */ #define EAI_SERVICE 9 /* servname not supported for ai_socktype */ #define EAI_SOCKTYPE 10 /* ai_socktype not supported */ #define EAI_SYSTEM 11 /* system error returned in errno */ #define EAI_BADHINTS 12 #define EAI_PROTOCOL 13 #define EAI_MAX 14 /* * Flag values for getaddrinfo() */ #ifdef AI_PASSIVE #undef AI_PASSIVE #undef AI_CANONNAME #undef AI_NUMERICHOST #undef AI_MASK #undef AI_ALL #undef AI_V4MAPPED_CFG #undef AI_ADDRCONFIG #undef AI_V4MAPPED #undef AI_DEFAULT #endif /* AI_PASSIVE */ #define AI_PASSIVE 0x00000001 /* get address to use bind() */ #define AI_CANONNAME 0x00000002 /* fill ai_canonname */ #define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ /* valid flags for addrinfo */ #define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) #define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ #define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ #define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ #define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ /* special recommended flags for getipnodebyname */ #define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) #endif /* !HAVE_GETADDRINFO */ #ifndef HAVE_GETNAMEINFO /* * Constants for getnameinfo() */ #ifndef NI_MAXHOST #define NI_MAXHOST 1025 #define NI_MAXSERV 32 #endif /* !NI_MAXHOST */ /* * Flag values for getnameinfo() */ #ifndef NI_NOFQDN #define NI_NOFQDN 0x00000001 #define NI_NUMERICHOST 0x00000002 #define NI_NAMEREQD 0x00000004 #define NI_NUMERICSERV 0x00000008 #define NI_DGRAM 0x00000010 #endif /* !NI_NOFQDN */ #endif /* !HAVE_GETNAMEINFO */ #ifndef HAVE_ADDRINFO struct addrinfo { int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ int ai_family; /* PF_xxx */ int ai_socktype; /* SOCK_xxx */ int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ size_t ai_addrlen; /* length of ai_addr */ char *ai_canonname; /* canonical name for hostname */ struct sockaddr *ai_addr; /* binary address */ struct addrinfo *ai_next; /* next structure in linked list */ }; #endif /* !HAVE_ADDRINFO */ #ifndef HAVE_SOCKADDR_STORAGE /* * RFC 2553: protocol-independent placeholder for socket addresses */ #define _SS_MAXSIZE 128 #define _SS_ALIGNSIZE (sizeof(long long)) #define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) #define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ _SS_PAD1SIZE - _SS_ALIGNSIZE) struct sockaddr_storage { #ifdef HAVE_SOCKADDR_SA_LEN unsigned char ss_len; /* address length */ unsigned char ss_family; /* address family */ #else unsigned short ss_family; /* address family */ #endif /* HAVE_SOCKADDR_SA_LEN */ char __ss_pad1[_SS_PAD1SIZE]; long long __ss_align; /* force desired structure storage alignment */ char __ss_pad2[_SS_PAD2SIZE]; }; #endif /* !HAVE_SOCKADDR_STORAGE */ #ifdef __cplusplus extern "C" { #endif extern void freehostent(struct hostent *); #ifdef __cplusplus } #endif
{ "content_hash": "5c46bc5f92a594542381d8f3e1bd9f3a", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 84, "avg_line_length": 31.50354609929078, "alnum_prop": 0.6593876632147682, "repo_name": "wanliming11/MurlocAlgorithms", "id": "c3c86248dd436044bac68a6b7c78816840f02ed3", "size": "6022", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Last/OpenSource/Python-3.6.1/Modules/addrinfo.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "5268" }, { "name": "CMake", "bytes": "160" } ], "symlink_target": "" }
package com.hazelcast.cache.impl; import javax.cache.CacheException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.Set; /** * MXBean utility methods related to registration of the beans. */ //TODO Move this into ManagementService public final class MXBeanUtil { //ensure everything gets put in one MBeanServer private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); private MXBeanUtil() { } /** * Registers the provided {@link javax.cache.management.CacheMXBean} or * {@link javax.cache.management.CacheStatisticsMXBean} implementations if not registered yet. * @param mxbean {@link javax.cache.management.CacheMXBean} or {@link javax.cache.management.CacheStatisticsMXBean}. * @param cacheManagerName name generated by URI and classloader. * @param name cache name. * @param stats is mxbean parameter, a statistics mxbean. */ public static void registerCacheObject(Object mxbean, String cacheManagerName, String name, boolean stats) { synchronized (mBeanServer) { //these can change during runtime, so always look it up ObjectName registeredObjectName = calculateObjectName(cacheManagerName, name, stats); try { if (!isRegistered(cacheManagerName, name, stats)) { mBeanServer.registerMBean(mxbean, registeredObjectName); } } catch (Exception e) { throw new CacheException( "Error registering cache MXBeans for CacheManager " + registeredObjectName + ". Error was " + e.getMessage(), e); } } } public static boolean isRegistered(String cacheManagerName, String name, boolean stats) { ObjectName objectName = calculateObjectName(cacheManagerName, name, stats); Set<ObjectName> registeredObjectNames = mBeanServer.queryNames(objectName, null); return !registeredObjectNames.isEmpty(); } /** * UnRegisters the mxbean if registered already. * @param cacheManagerName name generated by URI and classloader. * @param name cache name. * @param stats is mxbean, a statistics mxbean. */ public static void unregisterCacheObject(String cacheManagerName, String name, boolean stats) { synchronized (mBeanServer) { ObjectName objectName = calculateObjectName(cacheManagerName, name, stats); Set<ObjectName> registeredObjectNames = mBeanServer.queryNames(objectName, null); if (isRegistered(cacheManagerName, name, stats)) { //should just be one for (ObjectName registeredObjectName : registeredObjectNames) { try { mBeanServer.unregisterMBean(registeredObjectName); } catch (Exception e) { throw new CacheException( "Error unregistering object instance " + registeredObjectName + ". Error was " + e.getMessage(), e); } } } } } /** * Creates an object name using the scheme. * "javax.cache:type=Cache&lt;Statistics|Configuration&gt;,name=&lt;cacheName&gt;" */ public static ObjectName calculateObjectName(String cacheManagerName, String name, boolean stats) { String cacheManagerNameSafe = mbeanSafe(cacheManagerName); String cacheName = mbeanSafe(name); try { String objectNameType = stats ? "Statistics" : "Configuration"; return new ObjectName( "javax.cache:type=Cache" + objectNameType + ",CacheManager=" + cacheManagerNameSafe + ",Cache=" + cacheName); } catch (MalformedObjectNameException e) { throw new CacheException( "Illegal ObjectName for Management Bean. " + "CacheManager=[" + cacheManagerNameSafe + "], Cache=[" + cacheName + "]", e); } } private static String mbeanSafe(String string) { return string == null ? "" : string.replaceAll(",|:|=|\n", "."); } }
{ "content_hash": "e9051bc8b1bcc00714c8c6ca02e05561", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 129, "avg_line_length": 43.148514851485146, "alnum_prop": 0.6340064249655806, "repo_name": "emrahkocaman/hazelcast", "id": "a4e7a73a0a9102698806a5eb6f6edf883181e924", "size": "4983", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/cache/impl/MXBeanUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1449" }, { "name": "Java", "bytes": "30517986" }, { "name": "Shell", "bytes": "12217" } ], "symlink_target": "" }
<div class="seek-bar" ng-click="onClickSeekBar($event)"> <div class="fill" ng-style="fillStyle()"></div> <div class="thumb" ng-style="thumbStyle()" ng-mousedown="trackThumb()"></div> </div>
{ "content_hash": "cede9798782fc760dd01b7a5506bc84a", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 56, "avg_line_length": 33.333333333333336, "alnum_prop": 0.645, "repo_name": "bperlik/bloc-jams-angular", "id": "d534bd3d3d38a1ae7c38061c63d4ed14151863e3", "size": "200", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/templates/directives/seek_bar.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9234" }, { "name": "HTML", "bytes": "6696" }, { "name": "JavaScript", "bytes": "14989" } ], "symlink_target": "" }
Title: First Post Time: 2017-05-03 06:04:28 I beat you to it. Just go ahead and delete this file and ``` you@machine:~/.../nj$ ./nj -n first My Actual First Post ``` to add your actual first post.
{ "content_hash": "d6f44dcfaca2c9035e16e04d763f9a12", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 24.75, "alnum_prop": 0.6868686868686869, "repo_name": "d2718/nj", "id": "792d61f0458a7f8f279d40527d70a3f47eb14e98", "size": "198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "posts/first.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1090" }, { "name": "Go", "bytes": "46215" }, { "name": "HTML", "bytes": "3957" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Boost.Geometry (aka GGL, Generic Geometry Library)</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head> <table cellpadding="2" width="100%"> <tbody> <tr> <td valign="top"> <img alt="Boost.Geometry" src="images/ggl-logo-big.png" height="80" width="200"> &nbsp;&nbsp; </td> <td valign="top" align="right"> <a href="http://www.boost.org"> <img alt="Boost C++ Libraries" src="images/accepted_by_boost.png" height="80" width="230" border="0"> </a> </td> </tr> </tbody> </table> <!-- Generated by Doxygen 1.8.6 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_75b82e7e4a5feb05200b9ad7adf06257.html">home</a></li><li class="navelem"><a class="el" href="dir_91591915e9997d8f09df5890c710928d.html">ubuntu</a></li><li class="navelem"><a class="el" href="dir_e10a884cfce9a00b7ac96c4db7962926.html">boost</a></li><li class="navelem"><a class="el" href="dir_70241e0cb632ef83c95057df97d23a47.html">boost</a></li><li class="navelem"><a class="el" href="dir_6f25c90e381132fd960cd64986a2bf26.html">geometry</a></li><li class="navelem"><a class="el" href="dir_1e26e30a3d1138b879ba48852e3258df.html">strategies</a></li><li class="navelem"><a class="el" href="dir_ef5bc0061659e1a179d097305cf1ac7f.html">concepts</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#namespaces">Namespaces</a> &#124; <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">within_concept.hpp File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1geometry_1_1concepts_1_1_within_strategy_box_box.html">boost::geometry::concepts::WithinStrategyBoxBox&lt; Strategy &gt;</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1geometry_1_1concepts_1_1_within_strategy_point_box.html">boost::geometry::concepts::WithinStrategyPointBox&lt; Strategy &gt;</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1geometry_1_1concepts_1_1_within_strategy_polygonal.html">boost::geometry::concepts::WithinStrategyPolygonal&lt; Strategy &gt;</a></td></tr> <tr class="memdesc:"><td class="mdescLeft">&#160;</td><td class="mdescRight">Checks strategy for within (point-in-polygon) <a href="classboost_1_1geometry_1_1concepts_1_1_within_strategy_polygonal.html#details">More...</a><br/></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Namespaces</h2></td></tr> <tr class="memitem:namespaceboost"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost.html">boost</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:namespaceboost_1_1geometry"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost_1_1geometry.html">boost::geometry</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:namespaceboost_1_1geometry_1_1concepts"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost_1_1geometry_1_1concepts.html">boost::geometry::concepts</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:namespaceboost_1_1geometry_1_1concepts_1_1within"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost_1_1geometry_1_1concepts_1_1within.html">boost::geometry::concepts::within</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:ga46606d335730a9de3d3be21dba3fe83f"><td class="memTemplParams" colspan="2">template&lt;typename FirstTag , typename SecondTag , typename CastedTag , typename Strategy &gt; </td></tr> <tr class="memitem:ga46606d335730a9de3d3be21dba3fe83f"><td class="memTemplItemLeft" align="right" valign="top">void&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="group__concepts.html#ga46606d335730a9de3d3be21dba3fe83f">boost::geometry::concepts::within::check</a> ()</td></tr> <tr class="memdesc:ga46606d335730a9de3d3be21dba3fe83f"><td class="mdescLeft">&#160;</td><td class="mdescRight">Checks, in compile-time, the concept of any within-strategy. <a href="group__concepts.html#ga46606d335730a9de3d3be21dba3fe83f">More...</a><br/></td></tr> <tr class="separator:ga46606d335730a9de3d3be21dba3fe83f"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <hr size="1"> <table width="100%"> <tbody> <tr> <td align="left"><small> <p>April 2, 2011</p> </small></td> <td align="right"> <small> Copyright &copy; 2007-2011 Barend Gehrels, Amsterdam, the Netherlands<br> Copyright &copy; 2008-2011 Bruno Lalande, Paris, France<br> Copyright &copy; 2009-2010 Mateusz Loskot, London, UK<br> </small> </td> </tr> </tbody> </table> <address style="text-align: right;"><small> Documentation is generated by&nbsp;<a href="http://www.doxygen.org/index.html">Doxygen</a> </small></address> </body> </html>
{ "content_hash": "5608848cb27ec176801d9d45c5437f6f", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 697, "avg_line_length": 67.05607476635514, "alnum_prop": 0.6933797909407665, "repo_name": "keichan100yen/ode-ext", "id": "2148f83aa7ce9526a71b8e8801d6bf31e9cc8ae3", "size": "7175", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "boost/libs/geometry/doc/doxy/doxygen_output/html_by_doxygen/within__concept_8hpp.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "309067" }, { "name": "Batchfile", "bytes": "37875" }, { "name": "C", "bytes": "2967570" }, { "name": "C#", "bytes": "40804" }, { "name": "C++", "bytes": "189322982" }, { "name": "CMake", "bytes": "119251" }, { "name": "CSS", "bytes": "456744" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "6246" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groff", "bytes": "5189" }, { "name": "HTML", "bytes": "181460055" }, { "name": "IDL", "bytes": "28" }, { "name": "JavaScript", "bytes": "419776" }, { "name": "Lex", "bytes": "1231" }, { "name": "M4", "bytes": "29689" }, { "name": "Makefile", "bytes": "1088024" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "11406" }, { "name": "Objective-C++", "bytes": "630" }, { "name": "PHP", "bytes": "68641" }, { "name": "Perl", "bytes": "36491" }, { "name": "Perl6", "bytes": "2053" }, { "name": "Python", "bytes": "1612978" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "16692" }, { "name": "Rebol", "bytes": "354" }, { "name": "Ruby", "bytes": "5532" }, { "name": "Shell", "bytes": "354720" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "XSLT", "bytes": "553585" }, { "name": "Yacc", "bytes": "19623" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <corners android:radius="15dp"></corners> <size android:width="30dp" android:height="30dp"></size> <solid android:color="#EA1E63"></solid> </shape>
{ "content_hash": "14ed8563e22a2f1f092277973c9e1df1", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 87, "avg_line_length": 47, "alnum_prop": 0.6950354609929078, "repo_name": "GaoGersy/PasswordManager", "id": "4a650a1e1582765448f7c717bb7172a8424b91bb", "size": "282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/shape_guide_bg_red.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "917400" } ], "symlink_target": "" }
var sendID = null; chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ console.log(sender); sendID = sender.tab.id; takeScreenshot(); }); function takeScreenshot() { chrome.tabs.captureVisibleTab(null, function(img) { var screenshotUrl = img; console.log(screenshotUrl); // send picture(in base64 form) generated chrome.tabs.sendMessage(sendID, screenshotUrl); return; }); }
{ "content_hash": "f751ee28f003c6ad281b05034e5ea5f9", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 75, "avg_line_length": 26, "alnum_prop": 0.7451923076923077, "repo_name": "elliot79313/cklab_project102-1", "id": "942c90fc33888d635c6b502dceb5bc7a41b50181", "size": "985", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ScreenShot_v0/background.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4664" }, { "name": "Java", "bytes": "8881" }, { "name": "JavaScript", "bytes": "11787" } ], "symlink_target": "" }
import {CommonModule} from '@angular/common'; import {Component, ContentChild, NgModule, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, tick} from '@angular/core/testing'; import {Router} from '@angular/router'; import {RouterTestingModule} from '@angular/router/testing'; describe('Integration', () => { describe('routerLinkActive', () => { it('should not cause infinite loops in the change detection - #15825', fakeAsync(() => { @Component({selector: 'simple', template: 'simple'}) class SimpleCmp { } @Component({ selector: 'some-root', template: ` <div *ngIf="show"> <ng-container *ngTemplateOutlet="tpl"></ng-container> </div> <router-outlet></router-outlet> <ng-template #tpl> <a routerLink="/simple" routerLinkActive="active"></a> </ng-template>` }) class MyCmp { show: boolean = false; } @NgModule({ imports: [CommonModule, RouterTestingModule], declarations: [MyCmp, SimpleCmp], entryComponents: [SimpleCmp], }) class MyModule { } TestBed.configureTestingModule({imports: [MyModule]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, MyCmp); router.resetConfig([{path: 'simple', component: SimpleCmp}]); router.navigateByUrl('/simple'); advance(fixture); const instance = fixture.componentInstance; instance.show = true; expect(() => advance(fixture)).not.toThrow(); })); it('should set isActive right after looking at its children -- #18983', fakeAsync(() => { @Component({ template: ` <div #rla="routerLinkActive" routerLinkActive> isActive: {{rla.isActive}} <ng-template let-data> <a [routerLink]="data">link</a> </ng-template> <ng-container #container></ng-container> </div> ` }) class ComponentWithRouterLink { // TODO(issue/24571): remove '!'. @ViewChild(TemplateRef, {static: true}) templateRef !: TemplateRef<any>; // TODO(issue/24571): remove '!'. @ViewChild('container', {read: ViewContainerRef, static: true}) container !: ViewContainerRef; addLink() { this.container.createEmbeddedView(this.templateRef, {$implicit: '/simple'}); } removeLink() { this.container.clear(); } } @Component({template: 'simple'}) class SimpleCmp { } TestBed.configureTestingModule({ imports: [RouterTestingModule.withRoutes([{path: 'simple', component: SimpleCmp}])], declarations: [ComponentWithRouterLink, SimpleCmp] }); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, ComponentWithRouterLink); router.navigateByUrl('/simple'); advance(fixture); fixture.componentInstance.addLink(); fixture.detectChanges(); fixture.componentInstance.removeLink(); advance(fixture); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('isActive: false'); })); }); }); function advance<T>(fixture: ComponentFixture<T>): void { tick(); fixture.detectChanges(); } function createRoot<T>(router: Router, type: Type<T>): ComponentFixture<T> { const f = TestBed.createComponent(type); advance(f); router.initialNavigation(); advance(f); return f; }
{ "content_hash": "f816fc1b4840eda5196eb8e3e786eae7", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 112, "avg_line_length": 30.950413223140497, "alnum_prop": 0.5863818424566088, "repo_name": "StephenFluin/angular", "id": "c67c12a4d15ff714447895dc540a13514c2aa81f", "size": "3947", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "packages/router/test/regression_integration.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "346525" }, { "name": "Dockerfile", "bytes": "11884" }, { "name": "HTML", "bytes": "486713" }, { "name": "JSONiq", "bytes": "619" }, { "name": "JavaScript", "bytes": "2467307" }, { "name": "PHP", "bytes": "7222" }, { "name": "PowerShell", "bytes": "3909" }, { "name": "Shell", "bytes": "96916" }, { "name": "Starlark", "bytes": "427725" }, { "name": "TypeScript", "bytes": "22252357" } ], "symlink_target": "" }
require "tmpdir" require "rubygems" require "language_pack" require "language_pack/base" require "language_pack/bundler_lockfile" # base Ruby Language Pack. This is for any base ruby app. class LanguagePack::Ruby < LanguagePack::Base include LanguagePack::BundlerLockfile extend LanguagePack::BundlerLockfile BUILDPACK_VERSION = "v59" LIBYAML_VERSION = "0.1.4" LIBYAML_PATH = "libyaml-#{LIBYAML_VERSION}" LIBXMLSEC1_VERSION = "1.2.19" LIBXMLSEC1_PATH = "libxmlsec1-#{LIBXMLSEC1_VERSION}" LIBXMLSEC1_URL = "https://s3.amazonaws.com/cs-heroku-binaries" BUNDLER_VERSION = "1.3.2" BUNDLER_GEM_PATH = "bundler-#{BUNDLER_VERSION}" NODE_VERSION = "0.4.7" NODE_JS_BINARY_PATH = "node-#{NODE_VERSION}" JVM_BASE_URL = "http://heroku-jdk.s3.amazonaws.com" JVM_VERSION = "openjdk7-latest" # detects if this is a valid Ruby app # @return [Boolean] true if it's a Ruby app def self.use? File.exist?("Gemfile") end def self.lockfile_parser require "bundler" Bundler::LockfileParser.new(File.read("Gemfile.lock")) end def self.gem_version(name) gem_version = nil bootstrap_bundler do |bundler_path| $: << "#{bundler_path}/gems/bundler-#{LanguagePack::Ruby::BUNDLER_VERSION}/lib" gem = lockfile_parser.specs.detect {|gem| gem.name == name } gem_version = gem.version if gem end gem_version end def name "Ruby" end def default_addons add_dev_database_addon end def default_config_vars vars = { "LANG" => "en_US.UTF-8", "PATH" => default_path, "GEM_PATH" => slug_vendor_base, } ruby_version_jruby? ? vars.merge("JAVA_OPTS" => default_java_opts, "JRUBY_OPTS" => default_jruby_opts) : vars end def default_process_types { "rake" => "bundle exec rake", "console" => "bundle exec irb" } end def compile Dir.chdir(build_path) remove_vendor_bundle install_ruby install_jvm setup_language_pack_environment setup_profiled allow_git do puts "INSTALLING LANGUAGE PACK GEMS" install_language_pack_gems puts "BUILDING BUNDLER" build_bundler puts "CREATING DB YML" create_database_yml puts "INSTALLING BINARIES" install_binaries puts "COMPILING ASSETS" run_assets_precompile_rake_task puts "LATE SLUG IGNORE" late_slug_ignore end end private def late_slug_ignore # Meh, I should log something here. if File.exist?(".lateslugignore") topic("Beep Bloop. Processing your .lateslugignore file!.") ignored_files = Array.new late_slug_ignore_file = File.new(".lateslugignore", "r") late_slug_ignore_file.each do |line| unless line.chomp!.empty? ignored_files.push line end end late_slug_ignore_file.close puts "Deleting #{ignored_files.count} files matching .lateslugignore patterns." puts "IGNORED FILES:" puts ignored_files.join("\n") ignored_files.each { |f| FileUtils.rm_r(f) } # For what it's worth, I wrote an asset cleaning tool, but it's not generic enough for general use, but I bet # it probably does a better job achieving a completely clean asset configuration when used in tandem with # asset_sync -- then again, I've only lightly considered this. Anyway, if someone cares to improve this, the # code is sitting right below # #puts "Running rake assets:clean" #require 'benchmark' #time = Benchmark.realtime { pipe("env PATH=$PATH:bin bundle exec rake assets:clean 2>&1") } #if $?.success? # # Really, for the love of god, why does the string formatting look so crazy??? # puts "Assets cleaned from compilation location in (#{"%.2f" % time}s)." #else # puts "Asset cleansing failed. Yikes." #end #puts "Dropping assets from app/assets, lib/assets, and vendor/assets." #FileUtils.rm_rf("app/assets") #FileUtils.rm_rf("lib/assets") #FileUtils.rm_rf("vendor/assets") #puts "All assets removed from the slug." else topic("Beep Bloop. Failed to find your .lateslugignore file!. Is it in your applications root directory?") end end # the base PATH environment variable to be used # @return [String] the resulting PATH def default_path "bin:#{slug_vendor_base}/bin:/usr/local/bin:/usr/bin:/bin" end # the relative path to the bundler directory of gems # @return [String] resulting path def slug_vendor_base if @slug_vendor_base @slug_vendor_base elsif @ruby_version == "ruby-1.8.7" @slug_vendor_base = "vendor/bundle/1.8" else @slug_vendor_base = run(%q(ruby -e "require 'rbconfig';puts \"vendor/bundle/#{RUBY_ENGINE}/#{RbConfig::CONFIG['ruby_version']}\"")).chomp end end # the relative path to the vendored ruby directory # @return [String] resulting path def slug_vendor_ruby "vendor/#{ruby_version}" end # the relative path to the vendored jvm # @return [String] resulting path def slug_vendor_jvm "vendor/jvm" end # the absolute path of the build ruby to use during the buildpack # @return [String] resulting path def build_ruby_path "/tmp/#{ruby_version}" end # fetch the ruby version from bundler # @return [String, nil] returns the ruby version if detected or nil if none is detected def ruby_version return @ruby_version if @ruby_version_run @ruby_version_run = true bootstrap_bundler do |bundler_path| old_system_path = "/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin" @ruby_version = run_stdout("env PATH=#{old_system_path}:#{bundler_path}/bin GEM_PATH=#{bundler_path} bundle platform --ruby").chomp end if @ruby_version == "No ruby version specified" && ENV['RUBY_VERSION'] # for backwards compatibility. # this will go away in the future @ruby_version = ENV['RUBY_VERSION'] @ruby_version_env_var = true elsif @ruby_version == "No ruby version specified" @ruby_version = nil else @ruby_version = @ruby_version.sub('(', '').sub(')', '').split.join('-') @ruby_version_env_var = false end @ruby_version end # determine if we're using rbx # @return [Boolean] true if we are and false if we aren't def ruby_version_rbx? ruby_version ? ruby_version.match(/rbx-/) : false end # determine if we're using jruby # @return [Boolean] true if we are and false if we aren't def ruby_version_jruby? @ruby_version_jruby ||= ruby_version ? ruby_version.match(/jruby-/) : false end # default JAVA_OPTS # return [String] string of JAVA_OPTS def default_java_opts "-Xmx384m -Xss512k -XX:+UseCompressedOops -Dfile.encoding=UTF-8" end # default JRUBY_OPTS # return [String] string of JRUBY_OPTS def default_jruby_opts "-Xcompile.invokedynamic=true" end # list the available valid ruby versions # @note the value is memoized # @return [Array] list of Strings of the ruby versions available def ruby_versions return @ruby_versions if @ruby_versions Dir.mktmpdir("ruby_versions-") do |tmpdir| Dir.chdir(tmpdir) do run("curl -O #{VENDOR_URL}/ruby_versions.yml") @ruby_versions = YAML::load_file("ruby_versions.yml") end end @ruby_versions end # sets up the environment variables for the build process def setup_language_pack_environment setup_ruby_install_env config_vars = default_config_vars.each do |key, value| ENV[key] ||= value end ENV["GEM_HOME"] = slug_vendor_base ENV["PATH"] = "#{ruby_install_binstub_path}:#{config_vars["PATH"]}" end # sets up the profile.d script for this buildpack def setup_profiled set_env_override "GEM_PATH", "$HOME/#{slug_vendor_base}:$GEM_PATH" set_env_default "LANG", "en_US.UTF-8" set_env_override "PATH", "$HOME/bin:$HOME/#{slug_vendor_base}/bin:$PATH" if ruby_version_jruby? set_env_default "JAVA_OPTS", default_java_opts set_env_default "JRUBY_OPTS", default_jruby_opts end end # determines if a build ruby is required # @return [Boolean] true if a build ruby is required def build_ruby? @build_ruby ||= !ruby_version_rbx? && !ruby_version_jruby? && !%w{ruby-1.9.3 ruby-2.0.0}.include?(ruby_version) end # install the vendored ruby # @return [Boolean] true if it installs the vendored ruby and false otherwise def install_ruby return false unless ruby_version invalid_ruby_version_message = <<ERROR Invalid RUBY_VERSION specified: #{ruby_version} Valid versions: #{ruby_versions.join(", ")} ERROR if build_ruby? FileUtils.mkdir_p(build_ruby_path) Dir.chdir(build_ruby_path) do ruby_vm = ruby_version_rbx? ? "rbx" : "ruby" run("curl #{VENDOR_URL}/#{ruby_version.sub(ruby_vm, "#{ruby_vm}-build")}.tgz -s -o - | tar zxf -") end error invalid_ruby_version_message unless $?.success? end FileUtils.mkdir_p(slug_vendor_ruby) Dir.chdir(slug_vendor_ruby) do run("curl #{VENDOR_URL}/#{ruby_version}.tgz -s -o - | tar zxf -") end error invalid_ruby_version_message unless $?.success? bin_dir = "bin" FileUtils.mkdir_p bin_dir Dir["#{slug_vendor_ruby}/bin/*"].each do |bin| run("ln -s ../#{bin} #{bin_dir}") end if !@ruby_version_env_var topic "Using Ruby version: #{ruby_version}" else topic "Using RUBY_VERSION: #{ruby_version}" puts "WARNING: RUBY_VERSION support has been deprecated and will be removed entirely on August 1, 2012." puts "See https://devcenter.heroku.com/articles/ruby-versions#selecting_a_version_of_ruby for more information." end true end # vendors JVM into the slug for JRuby def install_jvm if ruby_version_jruby? topic "Installing JVM: #{JVM_VERSION}" FileUtils.mkdir_p(slug_vendor_jvm) Dir.chdir(slug_vendor_jvm) do run("curl #{JVM_BASE_URL}/#{JVM_VERSION}.tar.gz -s -o - | tar xzf -") end bin_dir = "bin" FileUtils.mkdir_p bin_dir Dir["#{slug_vendor_jvm}/bin/*"].each do |bin| run("ln -s ../#{bin} #{bin_dir}") end end end # find the ruby install path for its binstubs during build # @return [String] resulting path or empty string if ruby is not vendored def ruby_install_binstub_path @ruby_install_binstub_path ||= if build_ruby? "#{build_ruby_path}/bin" elsif ruby_version "#{slug_vendor_ruby}/bin" else "" end end # setup the environment so we can use the vendored ruby def setup_ruby_install_env ENV["PATH"] = "#{ruby_install_binstub_path}:#{ENV["PATH"]}" if ruby_version_jruby? ENV['JAVA_OPTS'] = default_java_opts end end # list of default gems to vendor into the slug # @return [Array] resulting list of gems def gems [BUNDLER_GEM_PATH] end # installs vendored gems into the slug def install_language_pack_gems FileUtils.mkdir_p(slug_vendor_base) Dir.chdir(slug_vendor_base) do |dir| gems.each do |gem| run("curl #{VENDOR_URL}/#{gem}.tgz -s -o - | tar xzf -") end Dir["bin/*"].each {|path| run("chmod 755 #{path}") } end end # default set of binaries to install # @return [Array] resulting list def binaries add_node_js_binary end # vendors binaries into the slug def install_binaries binaries.each {|binary| install_binary(binary) } Dir["bin/*"].each {|path| run("chmod +x #{path}") } end # vendors individual binary into the slug # @param [String] name of the binary package from S3. # Example: https://s3.amazonaws.com/language-pack-ruby/node-0.4.7.tgz, where name is "node-0.4.7" def install_binary(name) bin_dir = "bin" FileUtils.mkdir_p bin_dir Dir.chdir(bin_dir) do |dir| run("curl #{VENDOR_URL}/#{name}.tgz -s -o - | tar xzf -") end end # removes a binary from the slug # @param [String] relative path of the binary on the slug def uninstall_binary(path) FileUtils.rm File.join('bin', File.basename(path)), :force => true end # install libyaml into the LP to be referenced for psych compilation # @param [String] tmpdir to store the libyaml files def install_libyaml(dir) FileUtils.mkdir_p dir Dir.chdir(dir) do |dir| run("curl #{VENDOR_URL}/#{LIBYAML_PATH}.tgz -s -o - | tar xzf -") end end # install libxmlsec1 into the LP to be referenced for psych compilation # @param [String] dir to store the libxmlsec1 files def install_libxmlsec1(dir) FileUtils.mkdir_p dir Dir.chdir(dir) do |dir| run("curl #{LIBXMLSEC1_URL}/#{LIBXMLSEC1_PATH}.tar.gz -s -o - | tar xzf -") end end # remove `vendor/bundle` that comes from the git repo # in case there are native ext. # users should be using `bundle pack` instead. # https://github.com/heroku/heroku-buildpack-ruby/issues/21 def remove_vendor_bundle if File.exists?("vendor/bundle") topic "WARNING: Removing `vendor/bundle`." puts "Checking in `vendor/bundle` is not supported. Please remove this directory" puts "and add it to your .gitignore. To vendor your gems with Bundler, use" puts "`bundle pack` instead." FileUtils.rm_rf("vendor/bundle") end end # runs bundler to install the dependencies def build_bundler log("bundle") do bundle_without = ENV["BUNDLE_WITHOUT"] || "development:test" bundle_command = "bundle install --without #{bundle_without} --path vendor/bundle --binstubs vendor/bundle/bin" unless File.exist?("Gemfile.lock") error "Gemfile.lock is required. Please run \"bundle install\" locally\nand commit your Gemfile.lock." end if has_windows_gemfile_lock? topic "WARNING: Removing `Gemfile.lock` because it was generated on Windows." puts "Bundler will do a full resolve so native gems are handled properly." puts "This may result in unexpected gem versions being used in your app." log("bundle", "has_windows_gemfile_lock") File.unlink("Gemfile.lock") else # using --deployment is preferred if we can bundle_command += " --deployment" cache_load ".bundle" end version = run("bundle version").strip topic("Installing dependencies using #{version}") load_bundler_cache bundler_output = "" Dir.mktmpdir("libyaml-") do |tmpdir| libyaml_dir = "#{tmpdir}/#{LIBYAML_PATH}" install_libyaml(libyaml_dir) libxmlsec1_dir = "vendor/libxmlsec1-#{LIBXMLSEC1_VERSION}" install_libxmlsec1(libxmlsec1_dir) # need to setup compile environment for the psych gem yaml_include = File.expand_path("#{libyaml_dir}/include") yaml_lib = File.expand_path("#{libyaml_dir}/lib") libxmlsec1_include = File.expand_path("#{libxmlsec1_dir}/include/xmlsec1") libxml_include = "/usr/include/libxml2" libxmlsec1_lib = File.expand_path("#{libxmlsec1_dir}/lib") post_libxmlsec1_lib = "/app/#{libxmlsec1_dir}/lib" pwd = run("pwd").chomp bundler_path = "#{pwd}/#{slug_vendor_base}/gems/#{BUNDLER_GEM_PATH}/lib" # we need to set BUNDLE_CONFIG and BUNDLE_GEMFILE for # codon since it uses bundler. puts "CPATH: #{ENV['CPATH']}" puts "CPPATH: #{ENV['CPPATH']}" puts "LIBRARY_PATH: #{ENV['LIBRARY_PATH']}" env_vars = "env BUNDLE_GEMFILE=#{pwd}/Gemfile BUNDLE_CONFIG=#{pwd}/.bundle/config CPATH=#{yaml_include}:#{libxmlsec1_include}:#{libxml_include}:$CPATH CPPATH=#{yaml_include}:#{libxmlsec1_include}:#{libxml_include}:$CPPATH LIBRARY_PATH=#{yaml_lib}:#{libxmlsec1_lib}:#{post_libxmlsec1_lib}:$LIBRARY_PATH LD_LIBRARY_PATH=#{yaml_lib}:#{libxmlsec1_lib}:#{post_libxmlsec1_lib}:$LD_LIBRARY_PATH RUBYOPT=\"#{syck_hack}\"" env_vars += " BUNDLER_LIB_PATH=#{bundler_path}" if ruby_version == "ruby-1.8.7" puts "ENV VARS: #{env_vars}" bundler_output << pipe("#{env_vars} #{bundle_command} --no-clean 2>&1") end if $?.success? log "bundle", :status => "success" puts "Cleaning up the bundler cache." pipe "bundle clean" cache_store ".bundle" cache_store "vendor/bundle" # Keep gem cache out of the slug FileUtils.rm_rf("#{slug_vendor_base}/cache") # symlink binstubs bin_dir = "bin" FileUtils.mkdir_p bin_dir Dir["#{slug_vendor_base}/bin/*"].each do |bin| run("ln -s ../#{bin} #{bin_dir}") unless File.exist?("#{bin_dir}/#{bin}") end else log "bundle", :status => "failure" error_message = "Failed to install gems via Bundler." if bundler_output.match(/Installing sqlite3 \([\w.]+\) with native extensions\s+Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension./) error_message += <<ERROR Detected sqlite3 gem which is not supported on Heroku. http://devcenter.heroku.com/articles/how-do-i-use-sqlite3-for-development ERROR end error error_message end end end # RUBYOPT line that requires syck_hack file # @return [String] require string if needed or else an empty string def syck_hack syck_hack_file = File.expand_path(File.join(File.dirname(__FILE__), "../../vendor/syck_hack")) ruby_version = run('ruby -e "puts RUBY_VERSION"').chomp # < 1.9.3 includes syck, so we need to use the syck hack if Gem::Version.new(ruby_version) < Gem::Version.new("1.9.3") "-r#{syck_hack_file}" else "" end end # writes ERB based database.yml for Rails. The database.yml uses the DATABASE_URL from the environment during runtime. def create_database_yml log("create_database_yml") do return unless File.directory?("config") topic("Writing config/database.yml to read from DATABASE_URL") File.open("config/database.yml", "w") do |file| file.puts <<-DATABASE_YML <% require 'cgi' require 'uri' begin uri = URI.parse(ENV["DATABASE_URL"]) rescue URI::InvalidURIError raise "Invalid DATABASE_URL" end raise "No RACK_ENV or RAILS_ENV found" unless ENV["RAILS_ENV"] || ENV["RACK_ENV"] def attribute(name, value, force_string = false) if value value_string = if force_string '"' + value + '"' else value end "\#{name}: \#{value_string}" else "" end end adapter = uri.scheme adapter = "postgresql" if adapter == "postgres" database = (uri.path || "").split("/")[1] username = uri.user password = uri.password host = uri.host port = uri.port params = CGI.parse(uri.query || "") %> <%= ENV["RAILS_ENV"] || ENV["RACK_ENV"] %>: <%= attribute "adapter", adapter %> <%= attribute "database", database %> <%= attribute "username", username %> <%= attribute "password", password, true %> <%= attribute "host", host %> <%= attribute "port", port %> <% params.each do |key, value| %> <%= key %>: <%= value.first %> <% end %> DATABASE_YML end end end # add bundler to the load path # @note it sets a flag, so the path can only be loaded once def add_bundler_to_load_path return if @bundler_loadpath $: << File.expand_path(Dir["#{slug_vendor_base}/gems/bundler*/lib"].first) @bundler_loadpath = true end # detects whether the Gemfile.lock contains the Windows platform # @return [Boolean] true if the Gemfile.lock was created on Windows def has_windows_gemfile_lock? lockfile_parser.platforms.detect do |platform| /mingw|mswin/.match(platform.os) if platform.is_a?(Gem::Platform) end end # detects if a gem is in the bundle. # @param [String] name of the gem in question # @return [String, nil] if it finds the gem, it will return the line from bundle show or nil if nothing is found. def gem_is_bundled?(gem) @bundler_gems ||= lockfile_parser.specs.map(&:name) @bundler_gems.include?(gem) end # setup the lockfile parser # @return [Bundler::LockfileParser] a Bundler::LockfileParser def lockfile_parser add_bundler_to_load_path @lockfile_parser ||= LanguagePack::Ruby.lockfile_parser end # detects if a rake task is defined in the app # @param [String] the task in question # @return [Boolean] true if the rake task is defined in the app def rake_task_defined?(task) res = run("bundle exec rake #{task} --dry-run") puts "TASK RESULT:" puts res res && $?.success? end # executes the block with GIT_DIR environment variable removed since it can mess with the current working directory git thinks it's in # @param [block] block to be executed in the GIT_DIR free context def allow_git(&blk) git_dir = ENV.delete("GIT_DIR") # can mess with bundler blk.call ENV["GIT_DIR"] = git_dir end # decides if we need to enable the dev database addon # @return [Array] the database addon if the pg gem is detected or an empty Array if it isn't. def add_dev_database_addon gem_is_bundled?("pg") ? ['heroku-postgresql:dev'] : [] end # decides if we need to install the node.js binary # @note execjs will blow up if no JS RUNTIME is detected and is loaded. # @return [Array] the node.js binary path if we need it or an empty Array def add_node_js_binary gem_is_bundled?('execjs') ? [NODE_JS_BINARY_PATH] : [] end def run_assets_precompile_rake_task if rake_task_defined?("assets:precompile") require 'benchmark' topic "Running: rake assets:precompile" time = Benchmark.realtime { pipe("env PATH=$PATH:bin bundle exec rake assets:precompile 2>&1") } if $?.success? puts "Asset precompilation completed (#{"%.2f" % time}s)" end end end def bundler_cache "vendor/bundle" end def load_bundler_cache cache_load "vendor" full_ruby_version = run(%q(ruby -v)).chomp heroku_metadata = "vendor/heroku" ruby_version_cache = "#{heroku_metadata}/ruby_version" buildpack_version_cache = "#{heroku_metadata}/buildpack_version" bundler_version_cache = "#{heroku_metadata}/bundler_version" # fix bug from v37 deploy if File.exists?("vendor/ruby_version") puts "Broken cache detected. Purging build cache." cache_clear("vendor") FileUtils.rm_rf("vendor/ruby_version") purge_bundler_cache # fix bug introduced in v38 elsif !File.exists?(buildpack_version_cache) && File.exists?(ruby_version_cache) puts "Broken cache detected. Purging build cache." purge_bundler_cache elsif cache_exists?(bundler_cache) && File.exists?(ruby_version_cache) && full_ruby_version != File.read(ruby_version_cache).chomp puts "Ruby version change detected. Clearing bundler cache." puts "Old: #{File.read(ruby_version_cache).chomp}" puts "New: #{full_ruby_version}" purge_bundler_cache end # fix git gemspec bug from Bundler 1.3.0+ upgrade if File.exists?(bundler_cache) && !File.exists?(bundler_version_cache) && !run("find vendor/bundle/*/*/bundler/gems/*/ -name *.gemspec").include?("No such file or directory") puts "Old bundler cache detected. Clearing bundler cache." purge_bundler_cache end FileUtils.mkdir_p(heroku_metadata) File.open(ruby_version_cache, 'w') do |file| file.puts full_ruby_version end File.open(buildpack_version_cache, 'w') do |file| file.puts BUILDPACK_VERSION end File.open(bundler_version_cache, 'w') do |file| file.puts BUNDLER_VERSION end cache_store heroku_metadata end def purge_bundler_cache FileUtils.rm_rf(bundler_cache) cache_clear bundler_cache # need to reinstall language pack gems install_language_pack_gems end end
{ "content_hash": "caaeb1a690ce3b851dfafc02588569f1", "timestamp": "", "source": "github", "line_count": 727, "max_line_length": 427, "avg_line_length": 32.95185694635488, "alnum_prop": 0.6471865085990983, "repo_name": "centresource/heroku-buildpack-turbo-sprockets-pmp-ffm", "id": "53b9436d53057e38c147d9e9ee1e7711e3401397", "size": "23956", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/language_pack/ruby.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Perl", "bytes": "2091" }, { "name": "Ruby", "bytes": "55951" }, { "name": "Shell", "bytes": "6089" } ], "symlink_target": "" }
@(fooForm: Form[String])(implicit request: MessagesRequestHeader) @import utils.BSVersion @import tags._ @implicitFC = @{ b3.horizontal.fieldConstructor("col-md-2", "col-md-10") } @fruits = @{ Seq("A"->"Apples","P"->"Pears","B"->"Bananas") } @main("Mixed Forms", tab = "styles") { <h1 id="mixed-forms" class="page-header">Mixed Forms</h1> <p class="lead">This page its an example to show how to mix different forms within the same view.</p> <h3 id="simple-form">A simple horizontal form</h3> @bsExampleWithCode { @b3.form(routes.Application.mixed) { @b3.text( fooForm("foo"), '_label -> "Input Text", 'placeholder -> "A simple text..." ) @b3.select( fooForm("foo"), options = fruits, '_label -> "Select a fruit" ) @b3.checkbox( fooForm("foo"), '_text -> "Checkbox", 'checked -> true ) @b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-ok"></span> Save changes } } }{ @@b3.form(routes.Application.mixed) { @@b3.text( fooForm("foo"), '_label -> "Input Text", 'placeholder -> "A simple text..." ) @@b3.select( fooForm("foo"), options = fruits, '_label -> "Select a fruit" ) @@b3.checkbox( fooForm("foo"), '_text -> "Checkbox", 'checked -> true ) @@b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-ok"></span> Save changes } } } <h3 id="inline-form">The typical inline login form on top</h3> @bsExampleWithCode { @b3.inline.form(routes.Application.mixed) { implicit ifc => @b3.email( fooForm("foo"), '_hiddenLabel -> "Email", 'placeholder -> "example@mail.com" ) @b3.password( fooForm("foo"), '_hiddenLabel -> "Password", 'placeholder -> "Password" ) @b3.submit('class -> "btn btn-default"){ Sign in } } }{ @@b3.inline.form(routes.Application.mixed) { implicit ifc => @@b3.email( fooForm("foo"), '_hiddenLabel -> "Email", 'placeholder -> "example@@mail.com" ) @@b3.password( fooForm("foo"), '_hiddenLabel -> "Password", 'placeholder -> "Password" ) @@b3.submit('class -> "btn btn-default"){ Sign in } } } <h3 id="vertical-form">The typical vertical contact form on one side</h3> @bsExampleWithCode { <div class="row"> <div class="col-md-4"> @b3.vertical.form(routes.Application.mixed) { implicit vfc => @b3.text( fooForm("foo"), '_label -> "Your name", 'placeholder -> "Your contact name" ) @b3.email( fooForm("foo"), '_label -> "Your email", 'placeholder -> "example@mail.com" ) @b3.textarea( fooForm("foo"), '_label -> "What happened?", 'rows -> 3 ) @b3.checkbox( fooForm("foo"), '_text -> "Send me a copy to my email", 'checked -> true ) @b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-envelope"></span> Send } } </div> </div> }{ @@b3.vertical.form(routes.Application.mixed) { implicit vfc => @@b3.text( fooForm("foo"), '_label -> "Your name", 'placeholder -> "Your contact name" ) @@b3.email( fooForm("foo"), '_label -> "Your email", 'placeholder -> "example@@mail.com" ) @@b3.textarea( fooForm("foo"), '_label -> "What happened?", 'rows -> 3 ) @@b3.checkbox( fooForm("foo"), '_text -> "Send me a copy to my email", 'checked -> true ) @@b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-envelope"></span> Send } } } <h3 id="horizontal-form">A different horizontal form</h3> @bsExampleWithCode { @b3.horizontal.form(routes.Application.mixed, "col-lg-4", "col-lg-8") { implicit hfc => @b3.text( fooForm("foo"), '_label -> "Input Text", 'placeholder -> "A simple text..." ) @b3.file( fooForm("foo"), '_label -> "File" ) @b3.checkbox( fooForm("foo"), '_text -> "Checkbox" ) @b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-ok"></span> Save changes } } }{ @@b3.horizontal.form(routes.Application.mixed, "col-lg-4", "col-lg-8") { implicit hfc => @@b3.text( fooForm("foo"), '_label -> "Input Text", 'placeholder -> "A simple text..." ) @@b3.file( fooForm("foo"), '_label -> "File" ) @@b3.checkbox( fooForm("foo"), '_text -> "Checkbox" ) @@b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-ok"></span> Save changes } } } <h3 id="clear-form">A clear field constructor</h3> @bsExampleWithCode { @b3.clear.form(routes.Application.mixed) { implicit cfc => @b3.inputWrapped( "search", fooForm("foo"), 'placeholder -> "Text to search..." ) { input => <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-search"></span></span> @input <span class="input-group-btn"> <button class="btn btn-default" type="button">Search</button> </span> </div> } } }{ @@b3.clear.form(routes.Application.mixed) { implicit cfc => @@b3.inputWrapped( "search", fooForm("foo"), 'placeholder -> "Text to search..." ) { input => <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-search"></span></span> @@input <span class="input-group-btn"> <button class="btn btn-default" type="button">Search</button> </span> </div> } } } <h3 id="mixed-within-form">Mixed FieldConstructors within the same form</h3> }
{ "content_hash": "7fcc02552d0961bc5ee003e6fde3458c", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 104, "avg_line_length": 42.6198347107438, "alnum_prop": 0.6255574946674423, "repo_name": "adrianhurt/play-bootstrap3", "id": "350ad645707f2f08fc142644a50ca2a501f7e749", "size": "5157", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "play26-bootstrap3/sample/app/views/mixed.scala.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "15070" }, { "name": "CoffeeScript", "bytes": "13637" }, { "name": "HTML", "bytes": "490638" }, { "name": "JavaScript", "bytes": "5765" }, { "name": "Scala", "bytes": "258985" } ], "symlink_target": "" }
// // XVimCommandLine.m // XVim // // Created by Shuichiro Suzuki on 2/10/12. // Copyright 2012 JugglerShu.Net. All rights reserved. // #import "DVTKit.h" #import "IDEEditorArea+XVim.h" #import "Logger.h" #import "NSAttributedString+Geometrics.h" #import "XVimCommandField.h" #import "XVimCommandLine.h" #import "XVimQuickFixView.h" #import "XVimWindow.h" #import "XVimWindowManager.h" #import <objc/runtime.h> #define DEFAULT_COMMAND_FIELD_HEIGHT 18.0 static const char* KEY_COMMAND_LINE = "commandLine"; @interface XVimCommandLine() { @private XVimCommandField* _command; NSInsetTextView* _static; NSInsetTextView* _error; NSInsetTextView* _argument; XVimQuickFixView* _quickFixScrollView; id _quickFixObservation; NSTimer* _errorTimer; IDEEditorArea* _editorArea; } - (void)layoutCmdline:(NSView*)view; @end @implementation XVimCommandLine - (id)initWithEditorArea:(IDEEditorArea*)editorArea { self = [super initWithFrame:NSMakeRect(0, 0, 100, DEFAULT_COMMAND_FIELD_HEIGHT)]; if (self) { _editorArea = editorArea; [self setBoundsOrigin:NSMakePoint(0,0)]; // Static Message ( This is behind the command view if the command is active) _static = [[NSInsetTextView alloc] initWithFrame:NSMakeRect(0, 0, 100, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_static setEditable:NO]; [_static setSelectable:NO]; [_static setBackgroundColor:[NSColor textBackgroundColor]]; [_static setHidden:NO]; _static.autoresizingMask = NSViewWidthSizable; [self addSubview:_static]; // Error Message _error = [[NSInsetTextView alloc] initWithFrame:NSMakeRect(0, 0, 100, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_error setEditable:NO]; [_error setSelectable:NO]; [_error setBackgroundColor:[NSColor redColor]]; [_error setHidden:YES]; _error.autoresizingMask = NSViewWidthSizable; [self addSubview:_error]; // Quickfix View _quickFixScrollView = [[XVimQuickFixView alloc] initWithFrame:NSMakeRect(0, 0, 100, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_quickFixScrollView setHidden:YES]; [self addSubview:_quickFixScrollView]; // Command View _command = [[XVimCommandField alloc] initWithFrame:NSMakeRect(0, 0, 100, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_command setEditable:NO]; [_command setFont:[NSFont fontWithName:@"Courier" size:[NSFont systemFontSize]]]; [_command setTextColor:[NSColor textColor]]; [_command setBackgroundColor:[NSColor textBackgroundColor]]; [_command setHidden:YES]; _command.autoresizingMask = NSViewWidthSizable; [self addSubview:_command]; // Argument View _argument = [[NSInsetTextView alloc] initWithFrame:NSMakeRect(0, 0, 0, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_argument setEditable:NO]; [_argument setSelectable:NO]; [_argument setBackgroundColor:[NSColor clearColor]]; [_argument setHidden:NO]; _argument.autoresizingMask = NSViewWidthSizable; [self addSubview:_argument]; self.autoresizesSubviews = YES; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fontAndColorSourceTextSettingsChanged:) name:@"DVTFontAndColorSourceTextSettingsChangedNotification" object:nil]; } return self; } - (void)dealloc{ [[ NSNotificationCenter defaultCenter ] removeObserver:_quickFixObservation]; [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil]; [_command release]; [_static release]; [_error release]; [_quickFixScrollView release]; [_argument release]; [_errorTimer release]; [super dealloc]; } - (NSInteger)tag { return XVimCommandLineTag; } - (void)viewDidMoveToSuperview { [self layoutCmdline:[self superview]]; } - (void)errorMsgExpired { [_error setHidden:YES]; } - (void)setModeString:(NSString*)string { [_static setString:string]; [self layoutCmdline:[self superview]]; } - (void)setArgumentString:(NSString*)string{ [_argument setString:string]; } /** * (BOOL)aRedColorSetting * YES: red color background * NO : white color background */ - (void)errorMessage:(NSString*)string Timer:(BOOL)aTimer RedColorSetting:(BOOL)aRedColorSetting { if( aRedColorSetting ){ _error.backgroundColor = [NSColor redColor]; } else { _error.backgroundColor = [NSColor whiteColor]; } NSString* msg = string; if( [msg length] != 0 ){ [_error setString:msg]; [_error setHidden:NO]; [_errorTimer invalidate]; if( aTimer ){ if (_errorTimer != nil) { [_errorTimer release]; } _errorTimer = [[NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(errorMsgExpired) userInfo:nil repeats:NO] retain]; [[NSRunLoop currentRunLoop] addTimer:_errorTimer forMode:NSDefaultRunLoopMode]; } }else{ [_errorTimer invalidate]; [_error setHidden:YES]; } } static NSString* QuickFixPrompt = @"Press a key to continue..."; -(void)quickFixWithString:(NSString*)string { if( string && [string length] != 0 ){ // Set up observation to close the quickfix window when a key is pressed, or it loses focus __block XVimCommandLine* this = self; _quickFixObservation = [ [ NSNotificationCenter defaultCenter ] addObserverForName:XVimNotificationQuickFixDidComplete object:_quickFixScrollView queue:nil usingBlock:^(NSNotification *note) { [this quickFixWithString:nil ]; }]; [ _quickFixScrollView setString:string withPrompt:QuickFixPrompt]; [ _quickFixScrollView setHidden:NO ]; [ self layoutCmdline:[self superview]]; [[_quickFixScrollView window] performSelector:@selector(makeFirstResponder:) withObject:_quickFixScrollView.textView afterDelay:0 ]; [_quickFixScrollView.textView performSelector:@selector(scrollToEndOfDocument:) withObject:self afterDelay:0 ]; }else{ [[ NSNotificationCenter defaultCenter ] removeObserver:_quickFixObservation]; _quickFixObservation = nil; [_quickFixScrollView setHidden:YES]; [ self layoutCmdline:[self superview]]; } } -(NSUInteger)quickFixColWidth { return _quickFixScrollView.colWidth; } - (XVimCommandField*)commandField { return _command; } - (void)layoutCmdline:(NSView*) parent{ NSRect frame = [parent frame]; [NSClassFromString(@"DVTFontAndColorTheme") addObserver:self forKeyPath:@"currentTheme" options:NSKeyValueObservingOptionNew context:nil]; [self setBoundsOrigin:NSMakePoint(0,0)]; DVTFontAndColorTheme* theme = [NSClassFromString(@"DVTFontAndColorTheme") performSelector:@selector(currentTheme)]; NSFont *sourceFont = [theme sourcePlainTextFont]; // Calculate inset CGFloat horizontalInset = 0; CGFloat verticalInset = MAX((DEFAULT_COMMAND_FIELD_HEIGHT - [sourceFont pointSize]) / 2, 0); CGSize inset = CGSizeMake(horizontalInset, verticalInset); CGFloat tallestSubviewHeight = DEFAULT_COMMAND_FIELD_HEIGHT ; // Set colors [_static setTextColor:[theme sourcePlainTextColor]]; [_static setBackgroundColor:[theme sourceTextBackgroundColor]]; [_static setFont:sourceFont]; [_command setTextColor:[theme sourcePlainTextColor]]; [_command setBackgroundColor:[theme sourceTextBackgroundColor]]; [_command setInsertionPointColor:[theme sourceTextInsertionPointColor]]; [_command setFont:sourceFont]; [_argument setTextColor:[theme sourcePlainTextColor]]; [_argument setFont:sourceFont]; [_error setFont:sourceFont]; [_quickFixScrollView.textView setBackgroundColor:[theme consoleTextBackgroundColor]]; [_quickFixScrollView.textView setFont:[theme consoleExecutableOutputTextFont]]; [_quickFixScrollView.textView setTypingAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[theme consoleDebuggerOutputTextColor], NSForegroundColorAttributeName, nil] ]; CGFloat argumentSize = MIN(frame.size.width, 100); // Layout command area [_error setFrameSize:NSMakeSize(frame.size.width, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_error setFrameOrigin:NSMakePoint(0, 0)]; [_quickFixScrollView setFrameOrigin:NSMakePoint(0, 0)]; if ( [_quickFixScrollView isHidden]) { [_quickFixScrollView setFrameSize:NSMakeSize(frame.size.width, DEFAULT_COMMAND_FIELD_HEIGHT ) ]; } else { NSSize idealQuickfixSize = [ [_quickFixScrollView.textView string] sizeForWidth:frame.size.width height:(frame.size.height*0.5) font:[theme consoleExecutableOutputTextFont]]; idealQuickfixSize.width = frame.size.width ; [_quickFixScrollView setFrameSize:idealQuickfixSize ]; tallestSubviewHeight = idealQuickfixSize.height ; } [_static setFrameSize:NSMakeSize(frame.size.width, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_static setFrameOrigin:NSMakePoint(0, 0)]; [_command setFrameSize:NSMakeSize(frame.size.width, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_command setFrameOrigin:NSMakePoint(0, 0)]; [_argument setFrameSize:NSMakeSize(argumentSize, DEFAULT_COMMAND_FIELD_HEIGHT)]; [_argument setFrameOrigin:NSMakePoint(frame.size.width - argumentSize, 0)]; NSView *border = nil; NSView *nsview = nil; for( NSView* v in [parent subviews] ){ if( [NSStringFromClass([v class]) isEqualToString:@"DVTBorderedView"] ){ border = v; }else if( [NSStringFromClass([v class]) isEqualToString:@"NSView"] ){ nsview = v; } } if( nsview != nil && border != nil && [border isHidden] ){ self.frame = NSMakeRect(0, 0, parent.frame.size.width, +tallestSubviewHeight); nsview.frame = NSMakeRect(0, tallestSubviewHeight, parent.frame.size.width, parent.frame.size.height-tallestSubviewHeight); }else{ self.frame = NSMakeRect(0, border.frame.size.height, parent.frame.size.width, tallestSubviewHeight); nsview.frame = NSMakeRect(0, border.frame.size.height+tallestSubviewHeight, parent.frame.size.width, parent.frame.size.height-border.frame.size.height-tallestSubviewHeight); } [_static setInset:inset]; [_error setInset:inset]; [_argument setInset:inset]; [_command setInset:inset]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if( [keyPath isEqualToString:@"hidden"]) { [self layoutCmdline:[self superview]]; }else if( [keyPath isEqualToString:@"DVTFontAndColorCurrentTheme"] ){ [self layoutCmdline:[self superview]]; } } -(void)_didBecomeKey:(id)sender { IDEEditor* editor = [[_editorArea primaryEditorContext] editor]; if ([editor isKindOfClass:NSClassFromString(@"IDESourceCodeEditor")]) { XVIM_WINDOWMANAGER.editor = (IDESourceCodeEditor*)[[_editorArea primaryEditorContext] editor]; TRACE_LOG(@"New key editor = %@", editor); } } -(void)viewDidMoveToWindow { if ([self window]!=nil) { [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didBecomeKey:) name:NSWindowDidBecomeKeyNotification object:[self window]]; if ([[self window]isKeyWindow]) { [ self _didBecomeKey:self ]; } } } - (void)didFrameChanged:(NSNotification*)notification { [self layoutCmdline:[notification object]]; } - (void)fontAndColorSourceTextSettingsChanged:(NSNotification*)notification{ [self layoutCmdline:[self superview]]; } + (XVimCommandLine*)associateOf:(id)object { return (XVimCommandLine*)objc_getAssociatedObject(object, &KEY_COMMAND_LINE); } - (void)associateWith:(id)object { objc_setAssociatedObject(object, &KEY_COMMAND_LINE, self, OBJC_ASSOCIATION_RETAIN); } @end
{ "content_hash": "6f97c332c84c9f1f23179540af45bea9", "timestamp": "", "source": "github", "line_count": 330, "max_line_length": 195, "avg_line_length": 37.57878787878788, "alnum_prop": 0.6788968631561971, "repo_name": "antmd/XVim1", "id": "2161f16c50bdd1e76011e555f1b97cefdf82e955", "size": "12401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XVim/XVimCommandLine.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "115" }, { "name": "C++", "bytes": "6672" }, { "name": "Objective-C", "bytes": "2440144" }, { "name": "Ruby", "bytes": "510" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; public interface SetLabelsGlobalForwardingRuleRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.SetLabelsGlobalForwardingRuleRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the globalSetLabelsRequestResource field is set. */ boolean hasGlobalSetLabelsRequestResource(); /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The globalSetLabelsRequestResource. */ com.google.cloud.compute.v1.GlobalSetLabelsRequest getGlobalSetLabelsRequestResource(); /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED]; * </code> */ com.google.cloud.compute.v1.GlobalSetLabelsRequestOrBuilder getGlobalSetLabelsRequestResourceOrBuilder(); /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The project. */ java.lang.String getProject(); /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The bytes for project. */ com.google.protobuf.ByteString getProjectBytes(); /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The resource. */ java.lang.String getResource(); /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for resource. */ com.google.protobuf.ByteString getResourceBytes(); }
{ "content_hash": "bab1d33276ca2be38a1bc7ef75b57eb9", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 142, "avg_line_length": 25.30841121495327, "alnum_prop": 0.6469719350073855, "repo_name": "googleapis/java-compute", "id": "f128472db600c3ec5c97b874d1b7aa9ad8f3b8f5", "size": "3302", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/SetLabelsGlobalForwardingRuleRequestOrBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "95819909" }, { "name": "Python", "bytes": "823" }, { "name": "Shell", "bytes": "21977" } ], "symlink_target": "" }
package at.jku.pervasive.ecg; import java.io.File; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import javax.bluetooth.BluetoothStateException; import com.intel.bluetooth.EmulatorTestsHelper; /** * Idea taken from * http://bluecove.org/bluecove-emu/xref-test/net/sf/bluecove/ExampleTest.html */ public class HeartManSimulator { private final String baseAddress = "0B100000000%1$s"; private final AtomicInteger count = new AtomicInteger(0); private final Map<String, HeartManMock> mocks; private final List<Thread> serverThreads; public HeartManSimulator() throws BluetoothStateException { super(); serverThreads = new LinkedList<Thread>(); mocks = new HashMap<String, HeartManMock>(1); EmulatorTestsHelper.startInProcessServer(); EmulatorTestsHelper.useThreadLocalEmulator(); } public String createDevice() throws BluetoothStateException { String address = String.format(baseAddress, count.incrementAndGet()); HeartManMock mock = new HeartManMock(); mocks.put(address, mock); Thread t = EmulatorTestsHelper.runNewEmulatorStack(mock); serverThreads.add(t); return address; } public String createFileDevice(File file) throws BluetoothStateException { String address = String.format(baseAddress, count.incrementAndGet()); HeartManMock mock = new FileHeartManMock(file); mocks.put(address, mock); Thread t = EmulatorTestsHelper.runNewEmulatorStack(mock); serverThreads.add(t); return address; } public void sendValue(String address, double value) { HeartManMock mock = mocks.get(address); if (mock != null) { mock.sendValue(value); } } public void stopServer() throws InterruptedException { for (HeartManMock mock : mocks.values()) { mock.stop(); } for (Thread serverThread : serverThreads) { if ((serverThread != null) && (serverThread.isAlive())) { serverThread.interrupt(); serverThread.join(); } } EmulatorTestsHelper.stopInProcessServer(); } }
{ "content_hash": "cd906d27c8a580fd22a3ea3132eaa06c", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 78, "avg_line_length": 27.766233766233768, "alnum_prop": 0.7221702525724977, "repo_name": "pangratz/heartman-bluetooth-recorder", "id": "8aba38627ab5357dfe74653d2e0b0a7bfa90dd13", "size": "2138", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/at/jku/pervasive/ecg/HeartManSimulator.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "47138" } ], "symlink_target": "" }