text
stringlengths
2
1.04M
meta
dict
namespace SIM.Tool.Windows.MainWindowComponents { using System; using System.Windows; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Pipelines; using SIM.Tool.Base.Plugins; using Sitecore.Diagnostics.Base.Annotations; using Sitecore.Diagnostics.Logging; [UsedImplicitly] public class PublishButton : IMainWindowButton { #region Constants private const string CancelOption = "Cancel, don't publish"; private const string IncrementalOption = "Incremental, only recent changes"; private const string RepublishOption = "Republish, entire site (slow)"; private const string SmartOption = "Smart, entire site"; #endregion #region Fields protected string Mode; #endregion #region Constructors public PublishButton() { this.Mode = null; } public PublishButton(string mode) { this.Mode = mode; } #endregion #region Public methods public static void PublishSite(InstallWizardArgs args) { MainWindowHelper.RefreshInstances(); var instance = InstanceManager.GetInstance(args.InstanceName); new PublishButton().OnClick(MainWindow.Instance, instance); } public static void PublishSite(InstallModulesWizardArgs args) { new PublishButton().OnClick(MainWindow.Instance, args.Instance); } public bool IsEnabled(Window mainWindow, Instance instance) { return instance != null; } public void OnClick(Window mainWindow, Instance instance) { using (new ProfileSection("Publish", this)) { ProfileSection.Argument("mainWindow", mainWindow); ProfileSection.Argument("instance", instance); var modeText = this.GetMode(mainWindow); if (modeText == null || modeText == CancelOption) { return; } var mode = this.ParseMode(modeText); MainWindowHelper.Publish(instance, mainWindow, mode); } } #endregion #region Private methods private string GetMode(Window mainWindow) { if (string.IsNullOrEmpty(this.Mode)) { var options = new[] { CancelOption, IncrementalOption, SmartOption, RepublishOption }; return WindowHelper.AskForSelection("Publish", "Publish", "Choose publish mode", options, mainWindow, IncrementalOption); } return this.Mode; } private PublishMode ParseMode(string result) { if (result.StartsWith("Incremental", StringComparison.OrdinalIgnoreCase)) { return PublishMode.Incremental; } if (result.StartsWith("Smart", StringComparison.OrdinalIgnoreCase)) { return PublishMode.Smart; } if (result.StartsWith("Republish", StringComparison.OrdinalIgnoreCase)) { return PublishMode.Republish; } throw new NotSupportedException(result + " is not supported publish mode"); } #endregion } }
{ "content_hash": "d7747afb98df8716d06417bb1153ee25", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 129, "avg_line_length": 23.849206349206348, "alnum_prop": 0.6562396006655574, "repo_name": "dsolovay/Sitecore-Instance-Manager", "id": "c15bff1ba5b3032a91403b795a781b8e86b1ba6f", "size": "3007", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/SIM.Tool.Windows/MainWindowComponents/PublishButton.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1320884" }, { "name": "PowerShell", "bytes": "13655" } ], "symlink_target": "" }
require 'spec_helper.rb' describe 'CredentialListMapping' do it "can create" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings.create(credential_list_sid: 'CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') }.to raise_exception(Twilio::REST::TwilioError) values = {'CredentialListSid' => 'CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', } expect( @holodeck.has_request?(Holodeck::Request.new( method: 'post', url: 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings.json', data: values, ))).to eq(true) end it "receives create responses" do @holodeck.mock(Twilio::Response.new( 201, %q[ { "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "date_created": "Wed, 11 Sep 2013 17:51:38 +0000", "date_updated": "Wed, 11 Sep 2013 17:51:38 +0000", "friendly_name": "Production Gateways IP Address - Scranton", "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" } ] )) actual = @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings.create(credential_list_sid: 'CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') expect(actual).to_not eq(nil) end it "can read" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings.list() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'get', url: 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings.json', ))).to eq(true) end it "receives read_full responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "credential_list_mappings": [ { "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "date_created": "Wed, 11 Sep 2013 17:51:38 +0000", "date_updated": "Wed, 11 Sep 2013 17:51:38 +0000", "friendly_name": "Production Gateways IP Address - Scranton", "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" } ], "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0", "next_page_uri": null, "start": 0, "end": 0, "page": 0, "page_size": 50, "previous_page_uri": null, "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0" } ] )) actual = @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings.list() expect(actual).to_not eq(nil) end it "receives read_empty responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "credential_list_mappings": [], "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0", "next_page_uri": null, "start": 0, "end": 0, "page": 0, "page_size": 50, "previous_page_uri": null, "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0" } ] )) actual = @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings.list() expect(actual).to_not eq(nil) end it "can fetch" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings('CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'get', url: 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', ))).to eq(true) end it "receives fetch responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "date_created": "Wed, 11 Sep 2013 17:51:38 +0000", "date_updated": "Wed, 11 Sep 2013 17:51:38 +0000", "friendly_name": "Production Gateways IP Address - Scranton", "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" } ] )) actual = @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings('CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch() expect(actual).to_not eq(nil) end it "can delete" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings('CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').delete() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'delete', url: 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', ))).to eq(true) end it "receives delete responses" do @holodeck.mock(Twilio::Response.new( 204, nil, )) actual = @client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .sip \ .domains('SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .credential_list_mappings('CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').delete() expect(actual).to eq(true) end end
{ "content_hash": "48c91e36b1c836222c0167908c46a054", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 203, "avg_line_length": 41.29441624365482, "alnum_prop": 0.6274124154886294, "repo_name": "philnash/twilio-ruby", "id": "f0fd1a577ab5b4057559a66afe3209e63ff2fe25", "size": "8275", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "spec/integration/api/v2010/account/sip/domain/credential_list_mapping_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "108" }, { "name": "Makefile", "bytes": "1003" }, { "name": "Ruby", "bytes": "10247081" } ], "symlink_target": "" }
// Copyright (c) 2015-2016 jyuch // Released under the MIT license // https://github.com/jyuch/ReflectionToStringBuilder/blob/master/LICENSE using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Jyuch.ReflectionToStringBuilder.Tests { [TestClass] public class IgnoreStaticMemberTests { [TestMethod] public void IgnoreStaticMember() { var staticPropertyValue = "StaticProperty"; var property1Value = "Property1"; HasStaticMemberClass.StaticProperty1 = staticPropertyValue; var source = new HasStaticMemberClass() { Property1 = property1Value }; var expected = $"{nameof(HasStaticMemberClass)}{{" + $"{nameof(HasStaticMemberClass.Property1)}={property1Value}}}"; var actual = ToStringBuilder.ToString(source); Console.WriteLine(actual); Assert.AreEqual(expected, actual); } } class HasStaticMemberClass { public static string StaticProperty1 {get;set;} public string Property1 { get; set; } } }
{ "content_hash": "bb9da93fbf439066d5d9c89d47d3491b", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 83, "avg_line_length": 32.142857142857146, "alnum_prop": 0.6471111111111111, "repo_name": "jyuch/ReflectionToStringBuilder", "id": "bec1accee5d1594d6ef193df7f530856534c6f94", "size": "1127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ReflectionToStringBuilder.Tests/IgnoreStaticMemberTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "31526" } ], "symlink_target": "" }
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Species' db.delete_table('datasets_species') # Deleting field 'Instance.species' db.delete_column('datasets_instance', 'species_id') # Renaming column for 'Dataset.species' to match new field type. db.rename_column('datasets_dataset', 'species_id', 'species') # Changing field 'Dataset.species' db.alter_column('datasets_dataset', 'species', self.gf('django.db.models.fields.CharField')(max_length=75, null=True)) # Removing index on 'Dataset', fields ['species'] db.delete_index('datasets_dataset', ['species_id']) def backwards(self, orm): # Adding index on 'Dataset', fields ['species'] db.create_index('datasets_dataset', ['species_id']) # Adding model 'Species' db.create_table('datasets_species', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(default='', max_length=100)), )) db.send_create_signal('datasets', ['Species']) # Adding field 'Instance.species' db.add_column('datasets_instance', 'species', self.gf('django.db.models.fields.related.ForeignKey')(default=2, related_name='instances', to=orm['datasets.Species']), keep_default=False) # Renaming column for 'Dataset.species' to match new field type. db.rename_column('datasets_dataset', 'species', 'species_id') # Changing field 'Dataset.species' db.alter_column('datasets_dataset', 'species_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, to=orm['datasets.Species'])) models = { 'datasets.dataset': { 'Meta': {'ordering': "['-created_at']", 'object_name': 'Dataset'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 12, 16, 0, 0)'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}), 'species': ('django.db.models.fields.CharField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}) }, 'datasets.feature': { 'Meta': {'object_name': 'Feature'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instances': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'features'", 'null': 'True', 'to': "orm['datasets.Instance']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'datasets.featurevalue': { 'Meta': {'ordering': "('_order',)", 'object_name': 'FeatureValue'}, '_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'feature': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'values'", 'to': "orm['datasets.Feature']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'values'", 'to': "orm['datasets.Instance']"}), 'value': ('django.db.models.fields.FloatField', [], {}) }, 'datasets.instance': { 'Meta': {'ordering': "['pk']", 'object_name': 'Instance'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 12, 16, 0, 0)'}), 'dataset': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'instances'", 'to': "orm['datasets.Dataset']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label_values': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'instances'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['datasets.LabelValue']"}) }, 'datasets.labelname': { 'Meta': {'object_name': 'LabelName'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "'no label'", 'max_length': '100', 'blank': 'True'}) }, 'datasets.labelvalue': { 'Meta': {'ordering': "('_order',)", 'object_name': 'LabelValue'}, '_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label_name': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'label_values'", 'null': 'True', 'to': "orm['datasets.LabelName']"}), 'value': ('django.db.models.fields.CharField', [], {'default': "'none'", 'max_length': '100'}) } } complete_apps = ['datasets']
{ "content_hash": "2e98236cfdab7a407ea3bf7da7ece437", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 209, "avg_line_length": 57.81318681318681, "alnum_prop": 0.5730849648355826, "repo_name": "sloria/sepal", "id": "6286630266c36afc7603b32434227c6265bd1cce", "size": "5285", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sepal/datasets/migrations/0011_auto__del_species__del_field_instance_species__chg_field_dataset_speci.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "95193" }, { "name": "CoffeeScript", "bytes": "12754" }, { "name": "JavaScript", "bytes": "5567783" }, { "name": "PHP", "bytes": "184012" }, { "name": "Python", "bytes": "239084" }, { "name": "Ruby", "bytes": "1462" }, { "name": "Scala", "bytes": "232" }, { "name": "Shell", "bytes": "10863" } ], "symlink_target": "" }
package com.amazonaws.services.storagegateway.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.storagegateway.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ListVolumeInitiatorsRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListVolumeInitiatorsRequestMarshaller { private static final MarshallingInfo<String> VOLUMEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("VolumeARN").build(); private static final ListVolumeInitiatorsRequestMarshaller instance = new ListVolumeInitiatorsRequestMarshaller(); public static ListVolumeInitiatorsRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ListVolumeInitiatorsRequest listVolumeInitiatorsRequest, ProtocolMarshaller protocolMarshaller) { if (listVolumeInitiatorsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listVolumeInitiatorsRequest.getVolumeARN(), VOLUMEARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "a9fb09286a070a57ff0c6c8de6545167", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 159, "avg_line_length": 34.04545454545455, "alnum_prop": 0.7476635514018691, "repo_name": "jentfoo/aws-sdk-java", "id": "edd82876a14d958b1618071e645f7bbd000fbe0d", "size": "2078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-storagegateway/src/main/java/com/amazonaws/services/storagegateway/model/transform/ListVolumeInitiatorsRequestMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
package handlers_test import ( "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/ml-tv/tv-api/src/components/users/handlers" "github.com/ml-tv/tv-api/src/components/users/payloads" "github.com/ml-tv/tv-api/src/components/users/routes" "github.com/ml-tv/tv-api/src/core/network/http/httptests" "github.com/ml-tv/tv-api/src/core/primitives/models/lifecycle" "github.com/ml-tv/tv-api/src/core/security/auth" "github.com/stretchr/testify/assert" ) func callAddUser(t *testing.T, params *handlers.AddUserParams) *httptest.ResponseRecorder { ri := &httptests.RequestInfo{ Endpoint: routes.UserEndpoints[routes.EndpointAddUser], Params: params, } return httptests.NewRequest(t, ri) } func TestAddUser(t *testing.T) { globalT := t defer lifecycle.PurgeModels(t) tests := []struct { description string code int params *handlers.AddUserParams }{ { "Empty User", http.StatusBadRequest, &handlers.AddUserParams{}, }, { "Valid User", http.StatusCreated, &handlers.AddUserParams{Name: "Name", Email: "email+TestHandlerAdd@fake.com", Password: "password"}, }, { "Duplicate Email", http.StatusConflict, &handlers.AddUserParams{Name: "Name", Email: "email+TestHandlerAdd@fake.com", Password: "password"}, }, } for _, tc := range tests { t.Run(tc.description, func(t *testing.T) { rec := callAddUser(t, tc.params) assert.Equal(t, tc.code, rec.Code) if httptests.Is2XX(rec.Code) { var u payloads.User if err := json.NewDecoder(rec.Body).Decode(&u); err != nil { t.Fatal(err) } assert.NotEmpty(t, u.ID) assert.Equal(t, tc.params.Email, u.Email) lifecycle.SaveModels(globalT, &auth.User{ID: u.ID}) } }) } }
{ "content_hash": "47fa9b3d811508c31ae54e5ee79ad3bb", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 103, "avg_line_length": 24.9, "alnum_prop": 0.6833046471600689, "repo_name": "ml-tv/tv-api", "id": "28d667f86a1600bc018b5e4a12ee83c70b1f7ffc", "size": "1743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/users/handlers/user_add_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "152940" }, { "name": "Makefile", "bytes": "289" }, { "name": "PLSQL", "bytes": "1042" }, { "name": "PLpgSQL", "bytes": "1008" }, { "name": "Shell", "bytes": "344" } ], "symlink_target": "" }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.tyson.electricbuddy.DetailsActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout>
{ "content_hash": "026c081a4ea6c8e0b3298db615d0cdf7", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 74, "avg_line_length": 42.6875, "alnum_prop": 0.7379209370424598, "repo_name": "AmitGoelNYC/Electric-Buddy", "id": "430db97b0318a14862143e475eb323d7042ded0b", "size": "683", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_details.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "86055" } ], "symlink_target": "" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; /** * * @author mattbettinson */ public interface Config { /** * Testing Constants */ static final boolean TESTING = false; /** * GenericHID Constants */ static final int MAIN_JOYSTICK = 1; static final int SECONDARY_JOYSTICK = 2; /** * PWM Constants */ static final int[] LDRIVE = { 1, 2 }; static final int[] RDRIVE = { 3, 4 }; static final int[] SHOOTER = { 7, 8 }; static final int RETRIEVE = 5; static final int HOCKEY = 6; /** * Analog Constants */ static final int ULTRASONIC = 1; /** * Digital Constants */ static final int[] LENCODER = { 3, 4 }; static final int[] RENCODER = { 1, 2 }; static final int[] SENCODER = { 5, 6 }; static final int TLIMIT_SWITCH = 8; static final int BLIMIT_SWITCH = 9; static final int RLIMIT_SWITCH = 7; /** * Relay Constants */ static final int LIGHTS = 1; /** * Value Constants */ static final double[] PID = { 0.1, 0.0, 0.0 }; static final int[] CAM_HSL = { 0, 23, 31, 142, 73, 255 }; static final int[] CAM_RGB = { 191, 255, 129, 229, 117, 190 }; static final double LE_DPP = 0.0190; static final double RE_DPP = 0.0240; static final double SE_DPP = 0.18; }
{ "content_hash": "aa33bd03694f68969df43fe79735cc2f", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 63, "avg_line_length": 20.323076923076922, "alnum_prop": 0.6237698713096139, "repo_name": "bettinson/CameraBot", "id": "cb7924979f7b6f6ec9a94c6ddc080d1e0c3b90c6", "size": "1321", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/edu/wpi/first/wpilibj/templates/Config.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "10287" } ], "symlink_target": "" }
- Command - Display - EggTimer - ExecuteExpression - Expression - SensorGraph - SensorInput - SensorWidget - ShoppingList - Speak - SpeechRecognition - Status - SwitchWidget - Time - TodoList - Webcam ``` ls src/Homie/Dashboard/Widgets/*.php | awk -F "/" '{print "- " substr($5, 0, length($5)-3)}' | grep -v WidgetMetadataVo ``` ## Add a new widget - implement AbstractWidget in PHP (@Widget annotation) - assets/templates/widgets/NAME.html - assets/js/controller/modules/dashboard/widgets/NAME.js
{ "content_hash": "f4c8bcddecaba710e17b74543b083d72", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 119, "avg_line_length": 20.12, "alnum_prop": 0.7196819085487077, "repo_name": "brainexe/homie", "id": "8230f54dd0371ac20692afddd8c174816f5c6773", "size": "528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Features/Dashboard.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13970" }, { "name": "Dockerfile", "bytes": "1344" }, { "name": "HTML", "bytes": "108322" }, { "name": "JavaScript", "bytes": "150477" }, { "name": "Lua", "bytes": "356" }, { "name": "PHP", "bytes": "736276" }, { "name": "Shell", "bytes": "140" } ], "symlink_target": "" }
import functools import matplotlib.widgets import vaex.ui.plugin from vaex.ui import undo from vaex.ui.qt import * from vaex.ui.icons import iconfile import logging import vaex.ui.undo as undo import vaex.ui.qt as dialogs import re logger = logging.getLogger("vaex.plugin.tasks") def loglog(plot_window): for layer in plot_window.layers: for i, expression in enumerate(layer.state.expressions): layer.set_expression("log10(%s)" % expression, i) plot_window.queue_history_change("task: log/log") def removelog(plot_window): def remove_log(expression): return re.sub("^\s*(log|log2|log10)\((.*?)\)\s*$", "\\2", expression) for layer in plot_window.layers: for i, expression in enumerate(layer.state.expressions): layer.set_expression(remove_log(expression), i) plot_window.queue_history_change("task: remove log/log") def loglog_and_sigma3(plot_window): removelog(plot_window) loglog(plot_window) plot_window.queue_history_change(None) sigma3(plot_window) plot_window.queue_history_change("task: log/log and 3 sigma region") def sigma3(plot_window): if plot_window.layers: layer = plot_window.layers[0] if layer.dataset.is_local(): executor = vaex.execution.Executor() else: executor = vaex.remote.ServerExecutor() subspace = layer.dataset.subspace(*layer.state.expressions, executor=executor, delay=True) means = subspace.mean() with dialogs.ProgressExecution(plot_window, "Calculating mean", executor=executor) as progress: progress.add_task(means) progress.execute() logger.debug("get means") means = means.get() logger.debug("got means") vars = subspace.var(means=means) with dialogs.ProgressExecution(plot_window, "Calculating variance", executor=executor) as progress: progress.add_task(vars) progress.execute() #limits = limits.get() vars = vars.get() stds = vars**0.5 sigmas = 3 limits = list(zip(means-sigmas*stds, means+sigmas*stds)) #plot_window.ranges_show = limits plot_window.set_ranges(range(len(limits)), limits, add_to_history=True, reason="3 sigma region") #plot_window.update_all_layers() #for layer in plot_window.layers: # layer.flag_needs_update() logger.debug("means=%r", means) logger.debug("vars=%r", vars) logger.debug("limits=%r", limits) plot_window.queue_history_change("task: 3 sigma region") #plot_window.queue_update() def subtract_mean(plot_window): if plot_window.layers: layer = plot_window.layers[0] executor = vaex.execution.Executor() subspace = layer.dataset.subspace(*layer.state.expressions, executor=executor, delay=True) means = subspace.mean() with dialogs.ProgressExecution(plot_window, "Calculating mean", executor=executor): executor.execute() means = means.get() new_expressions = ["(%s) - %s" % (expression, mean) for expression, mean in zip(layer.state.expressions, means)] for i in range(len(new_expressions)): vmin, vmax = layer.plot_window.state.ranges_viewport[i] vmin -= means[i] vmax -= means[i] layer.plot_window.set_range(vmin, vmax, i) for i in range(len(new_expressions)): layer.set_expression(new_expressions[i], i) plot_window.update_all_layers() plot_window.queue_history_change("task: remove mean") @vaex.ui.plugin.pluginclass class TasksPlugin(vaex.ui.plugin.PluginPlot): name = "tasks" def __init__(self, dialog): super(TasksPlugin, self).__init__(dialog) dialog.plug_toolbar(self.plug_toolbar, 1.6) def plug_toolbar(self): logger.info("adding %s plugin" % self.name) self.menu = QtGui.QMenu("&Tasks") self.dialog.menu_bar.addMenu(self.menu) self.tasks_button = QtGui.QToolButton() self.tasks_button.setIcon(QtGui.QIcon(iconfile('gear'))) self.tasks_button.setText("Tasks") self.tasks_button.setPopupMode(QtGui.QToolButton.InstantPopup) self.tasks_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.tasks_button.setMenu(self.menu) #self.action_tasks = QtGui.QAction(QtGui.QIcon(iconfile('gear')), 'Tasks', self.dialog) self.dialog.toolbar.addWidget(self.tasks_button) self.action_tasks_loglog = QtGui.QAction(QtGui.QIcon(iconfile('gear')), 'Log-Log', self.dialog) self.menu.addAction(self.action_tasks_loglog) self.action_tasks_loglog.triggered.connect(lambda *arg: loglog(self.dialog)) self.action_tasks_loglog = QtGui.QAction(QtGui.QIcon(iconfile('gear')), '3 sigma region', self.dialog) self.menu.addAction(self.action_tasks_loglog) self.action_tasks_loglog.triggered.connect(lambda *arg: sigma3(self.dialog)) self.action_tasks_loglog_3sigma = QtGui.QAction(QtGui.QIcon(iconfile('gear')), 'Log-Log and 3 sigma region', self.dialog) self.menu.addAction(self.action_tasks_loglog_3sigma) self.action_tasks_loglog_3sigma.triggered.connect(lambda *arg: loglog_and_sigma3(self.dialog)) self.action_tasks_removelog = QtGui.QAction(QtGui.QIcon(iconfile('gear')), 'Remove log', self.dialog) self.menu.addAction(self.action_tasks_removelog) self.action_tasks_removelog.triggered.connect(lambda *arg: removelog(self.dialog)) self.action_tasks_subtract_mean = QtGui.QAction(QtGui.QIcon(iconfile('gear')), 'Subtract mean', self.dialog) self.menu.addAction(self.action_tasks_subtract_mean) self.action_tasks_subtract_mean.triggered.connect(lambda *arg: subtract_mean(self.dialog)) def __(self): self.action_store = QtGui.QAction(QtGui.QIcon(iconfile('gear')), 'Store', self.dialog) self.action_store.setShortcut("Ctrl+B") self.action_store_toolbar = QtGui.QAction(QtGui.QIcon(iconfile('star')), 'Store', self.dialog) self.dialog.toolbar.addAction(self.action_store_toolbar) self.action_store.triggered.connect(self.on_store) self.action_store_toolbar.triggered.connect(self.on_store) self.changed_handle = storage_plots.changed.connect(self.load_options_menu) self.load_options_menu() self.dialog.menu_mode.addSeparator() self.action_zoom_rect = QtGui.QAction(QtGui.QIcon(iconfile('zoom')), '&Zoom to rect', self.dialog) self.action_zoom_rect.setShortcut("Ctrl+Alt+Z") self.dialog.menu_mode.addAction(self.action_zoom_rect) self.action_zoom_x = QtGui.QAction(QtGui.QIcon(iconfile('zoom_x')), '&Zoom x', self.dialog) self.action_zoom_y = QtGui.QAction(QtGui.QIcon(iconfile('zoom_y')), '&Zoom y', self.dialog) self.action_zoom = QtGui.QAction(QtGui.QIcon(iconfile('zoom')), '&Zoom(you should not read this)', self.dialog) self.action_zoom_x.setShortcut("Ctrl+Alt+X") self.action_zoom_y.setShortcut("Ctrl+Alt+Y") self.dialog.menu_mode.addAction(self.action_zoom_x) self.dialog.menu_mode.addAction(self.action_zoom_y) self.dialog.menu_mode.addSeparator() self.action_zoom_out = QtGui.QAction(QtGui.QIcon(iconfile('zoom_out')), '&Zoom out', self.dialog) self.action_zoom_in = QtGui.QAction(QtGui.QIcon(iconfile('zoom_in')), '&Zoom in', self.dialog) self.action_zoom_fit = QtGui.QAction(QtGui.QIcon(iconfile('arrow_out')), '&Reset view', self.dialog) #self.action_zoom_use = QtGui.QAction(QtGui.QIcon(iconfile('chart_bar')), '&Use zoom area', self.dialog) self.action_zoom_out.setShortcut("Ctrl+Alt+-") self.action_zoom_in.setShortcut("Ctrl+Alt++") self.action_zoom_fit.setShortcut("Ctrl+Alt+0") self.dialog.menu_mode.addAction(self.action_zoom_out) self.dialog.menu_mode.addAction(self.action_zoom_in) self.dialog.menu_mode.addAction(self.action_zoom_fit) self.dialog.action_group_main.addAction(self.action_zoom_rect) self.dialog.action_group_main.addAction(self.action_zoom_x) self.dialog.action_group_main.addAction(self.action_zoom_y) #self.dialog.toolbar.addAction(self.action_zoom_out) #self.dialog.add_shortcut(self.action_zoom_in,"+") #self.dialog.add_shortcut(self.action_zoom_out,"-") #self.dialog.add_shortcut(self.action_zoom_rect,"Z") #self.dialog.add_shortcut(self.action_zoom_x,"Alt+X") #self.dialog.add_shortcut(self.action_zoom_y,"Alt+Y") #self.dialog.add_shortcut(self.action_zoom_fit, "0") self.dialog.toolbar.addAction(self.action_zoom) self.zoom_menu = QtGui.QMenu() self.action_zoom.setMenu(self.zoom_menu) self.zoom_menu.addAction(self.action_zoom_rect) self.zoom_menu.addAction(self.action_zoom_x) self.zoom_menu.addAction(self.action_zoom_y) if self.dialog.dimensions == 1: self.lastActionZoom = self.action_zoom_x # this makes more sense for histograms as default else: self.lastActionZoom = self.action_zoom_rect self.dialog.toolbar.addSeparator() #self.dialog.toolbar.addAction(self.action_zoom_out) self.dialog.toolbar.addAction(self.action_zoom_fit) self.action_zoom.triggered.connect(self.onActionZoom) self.action_zoom_out.triggered.connect(self.onZoomOut) self.action_zoom_in.triggered.connect(self.onZoomIn) self.action_zoom_fit.triggered.connect(self.onZoomFit) #self.action_zoom_use.triggered.connect(self.onZoomUse) self.action_zoom.setCheckable(True) self.action_zoom_rect.setCheckable(True) self.action_zoom_x.setCheckable(True) self.action_zoom_y.setCheckable(True)
{ "content_hash": "b0f61cf2413b73fbeede12a0cc80aa4c", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 123, "avg_line_length": 40.0762331838565, "alnum_prop": 0.74107642385588, "repo_name": "maartenbreddels/vaex", "id": "d2b572543ac1291064e32c12e4cdd043832270a2", "size": "8937", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/vaex-ui/vaex/ui/plugin/tasks.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1888" }, { "name": "C++", "bytes": "81166" }, { "name": "CSS", "bytes": "6604" }, { "name": "GLSL", "bytes": "6204" }, { "name": "HTML", "bytes": "177613" }, { "name": "JavaScript", "bytes": "1489136" }, { "name": "Makefile", "bytes": "432" }, { "name": "PHP", "bytes": "33807" }, { "name": "Python", "bytes": "1893232" }, { "name": "Shell", "bytes": "4639" } ], "symlink_target": "" }
namespace FabricAdcHub.User.Interfaces { public enum DisconnectReason { NetworkError, ProtocolError } }
{ "content_hash": "3d6389db475b2c823e5ad2f2e3537c60", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 39, "avg_line_length": 16.625, "alnum_prop": 0.6466165413533834, "repo_name": "Caraul/FabricAdcHub", "id": "dda438f882090aee1c1e4b9d3325c919960b3f6e", "size": "135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FabricAdcHub.User.Interfaces/DisconnectReason.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "219758" }, { "name": "PowerShell", "bytes": "7999" } ], "symlink_target": "" }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ReportViewerButton.xaml.cs" company="None"> // None // </copyright> // <summary> // Interaction logic for ReportViewerButton.xaml // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace TfsWorkbench.ReportViewer { using System; using System.Windows; /// <summary> /// Interaction logic for ReportViewerButton.xaml /// </summary> public partial class ReportViewerButton { /// <summary> /// The controller property. /// </summary> private static readonly DependencyProperty controllerProperty = DependencyProperty.Register( "Controller", typeof(IReportController), typeof(ReportViewerButton)); /// <summary> /// Initializes a new instance of the <see cref="ReportViewerButton"/> class. /// </summary> /// <param name="controller">The controller.</param> public ReportViewerButton(IReportController controller) { if (controller == null) { throw new ArgumentNullException("controller"); } this.Controller = controller; InitializeComponent(); } /// <summary> /// Gets the controller property. /// </summary> /// <value>The controller property.</value> public static DependencyProperty ControllerProperty { get { return controllerProperty; } } /// <summary> /// Gets or sets the controller. /// </summary> /// <value>The controller.</value> public IReportController Controller { get { return (IReportController)this.GetValue(ControllerProperty); } set { this.SetValue(ControllerProperty, value); } } } }
{ "content_hash": "04d778b980c7c1f7e10cf17caf48615f", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 120, "avg_line_length": 33.21666666666667, "alnum_prop": 0.5188158554942298, "repo_name": "omnibs/tfsworkbench-fork", "id": "2bd773f203e0ebf33c972cc7eacb473f54ce7a91", "size": "1995", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "solutions/ReportViewer/ReportViewerButton.xaml.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "3147810" }, { "name": "Shell", "bytes": "263" }, { "name": "XSLT", "bytes": "218276" } ], "symlink_target": "" }
""" Robust location and covariance estimators. Here are implemented estimators that are resistant to outliers. """ # Author: Virgile Fritsch <virgile.fritsch@inria.fr> # # License: BSD 3 clause import warnings import numbers import numpy as np from scipy import linalg from scipy.stats import chi2 from . import empirical_covariance, EmpiricalCovariance from ..utils.extmath import fast_logdet from ..utils import check_random_state, check_array # Minimum Covariance Determinant # Implementing of an algorithm by Rousseeuw & Van Driessen described in # (A Fast Algorithm for the Minimum Covariance Determinant Estimator, # 1999, American Statistical Association and the American Society # for Quality, TECHNOMETRICS) # XXX Is this really a public function? It's not listed in the docs or # exported by sklearn.covariance. Deprecate? def c_step(X, n_support, remaining_iterations=30, initial_estimates=None, verbose=False, cov_computation_method=empirical_covariance, random_state=None): """C_step procedure described in [Rouseeuw1984]_ aiming at computing MCD. Parameters ---------- X : array-like, shape (n_samples, n_features) Data set in which we look for the n_support observations whose scatter matrix has minimum determinant. n_support : int, > n_samples / 2 Number of observations to compute the robust estimates of location and covariance from. remaining_iterations : int, optional Number of iterations to perform. According to [Rouseeuw1999]_, two iterations are sufficient to get close to the minimum, and we never need more than 30 to reach convergence. initial_estimates : 2-tuple, optional Initial estimates of location and shape from which to run the c_step procedure: - initial_estimates[0]: an initial location estimate - initial_estimates[1]: an initial covariance estimate verbose : boolean, optional Verbose mode. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. cov_computation_method : callable, default empirical_covariance The function which will be used to compute the covariance. Must return shape (n_features, n_features) Returns ------- location : array-like, shape (n_features,) Robust location estimates. covariance : array-like, shape (n_features, n_features) Robust covariance estimates. support : array-like, shape (n_samples,) A mask for the `n_support` observations whose scatter matrix has minimum determinant. References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS """ X = np.asarray(X) random_state = check_random_state(random_state) return _c_step(X, n_support, remaining_iterations=remaining_iterations, initial_estimates=initial_estimates, verbose=verbose, cov_computation_method=cov_computation_method, random_state=random_state) def _c_step(X, n_support, random_state, remaining_iterations=30, initial_estimates=None, verbose=False, cov_computation_method=empirical_covariance): n_samples, n_features = X.shape dist = np.inf # Initialisation support = np.zeros(n_samples, dtype=bool) if initial_estimates is None: # compute initial robust estimates from a random subset support[random_state.permutation(n_samples)[:n_support]] = True else: # get initial robust estimates from the function parameters location = initial_estimates[0] covariance = initial_estimates[1] # run a special iteration for that case (to get an initial support) precision = linalg.pinvh(covariance) X_centered = X - location dist = (np.dot(X_centered, precision) * X_centered).sum(1) # compute new estimates support[np.argsort(dist)[:n_support]] = True X_support = X[support] location = X_support.mean(0) covariance = cov_computation_method(X_support) # Iterative procedure for Minimum Covariance Determinant computation det = fast_logdet(covariance) # If the data already has singular covariance, calculate the precision, # as the loop below will not be entered. if np.isinf(det): precision = linalg.pinvh(covariance) previous_det = np.inf while (det < previous_det and remaining_iterations > 0 and not np.isinf(det)): # save old estimates values previous_location = location previous_covariance = covariance previous_det = det previous_support = support # compute a new support from the full data set mahalanobis distances precision = linalg.pinvh(covariance) X_centered = X - location dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1) # compute new estimates support = np.zeros(n_samples, dtype=bool) support[np.argsort(dist)[:n_support]] = True X_support = X[support] location = X_support.mean(axis=0) covariance = cov_computation_method(X_support) det = fast_logdet(covariance) # update remaining iterations for early stopping remaining_iterations -= 1 previous_dist = dist dist = (np.dot(X - location, precision) * (X - location)).sum(axis=1) # Check if best fit already found (det => 0, logdet => -inf) if np.isinf(det): results = location, covariance, det, support, dist # Check convergence if np.allclose(det, previous_det): # c_step procedure converged if verbose: print("Optimal couple (location, covariance) found before" " ending iterations (%d left)" % (remaining_iterations)) results = location, covariance, det, support, dist elif det > previous_det: # determinant has increased (should not happen) warnings.warn("Warning! det > previous_det (%.15f > %.15f)" % (det, previous_det), RuntimeWarning) results = previous_location, previous_covariance, \ previous_det, previous_support, previous_dist # Check early stopping if remaining_iterations == 0: if verbose: print('Maximum number of iterations reached') results = location, covariance, det, support, dist return results def select_candidates(X, n_support, n_trials, select=1, n_iter=30, verbose=False, cov_computation_method=empirical_covariance, random_state=None): """Finds the best pure subset of observations to compute MCD from it. The purpose of this function is to find the best sets of n_support observations with respect to a minimization of their covariance matrix determinant. Equivalently, it removes n_samples-n_support observations to construct what we call a pure data set (i.e. not containing outliers). The list of the observations of the pure data set is referred to as the `support`. Starting from a random support, the pure data set is found by the c_step procedure introduced by Rousseeuw and Van Driessen in [Rouseeuw1999]_. Parameters ---------- X : array-like, shape (n_samples, n_features) Data (sub)set in which we look for the n_support purest observations. n_support : int, [(n + p + 1)/2] < n_support < n The number of samples the pure data set must contain. select : int, int > 0 Number of best candidates results to return. n_trials : int, nb_trials > 0 or 2-tuple Number of different initial sets of observations from which to run the algorithm. Instead of giving a number of trials to perform, one can provide a list of initial estimates that will be used to iteratively run c_step procedures. In this case: - n_trials[0]: array-like, shape (n_trials, n_features) is the list of `n_trials` initial location estimates - n_trials[1]: array-like, shape (n_trials, n_features, n_features) is the list of `n_trials` initial covariances estimates n_iter : int, nb_iter > 0 Maximum number of iterations for the c_step procedure. (2 is enough to be close to the final solution. "Never" exceeds 20). random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. cov_computation_method : callable, default empirical_covariance The function which will be used to compute the covariance. Must return shape (n_features, n_features) verbose : boolean, default False Control the output verbosity. See Also --------- c_step Returns ------- best_locations : array-like, shape (select, n_features) The `select` location estimates computed from the `select` best supports found in the data set (`X`). best_covariances : array-like, shape (select, n_features, n_features) The `select` covariance estimates computed from the `select` best supports found in the data set (`X`). best_supports : array-like, shape (select, n_samples) The `select` best supports found in the data set (`X`). References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS """ random_state = check_random_state(random_state) n_samples, n_features = X.shape if isinstance(n_trials, numbers.Integral): run_from_estimates = False elif isinstance(n_trials, tuple): run_from_estimates = True estimates_list = n_trials n_trials = estimates_list[0].shape[0] else: raise TypeError("Invalid 'n_trials' parameter, expected tuple or " " integer, got %s (%s)" % (n_trials, type(n_trials))) # compute `n_trials` location and shape estimates candidates in the subset all_estimates = [] if not run_from_estimates: # perform `n_trials` computations from random initial supports for j in range(n_trials): all_estimates.append( _c_step( X, n_support, remaining_iterations=n_iter, verbose=verbose, cov_computation_method=cov_computation_method, random_state=random_state)) else: # perform computations from every given initial estimates for j in range(n_trials): initial_estimates = (estimates_list[0][j], estimates_list[1][j]) all_estimates.append(_c_step( X, n_support, remaining_iterations=n_iter, initial_estimates=initial_estimates, verbose=verbose, cov_computation_method=cov_computation_method, random_state=random_state)) all_locs_sub, all_covs_sub, all_dets_sub, all_supports_sub, all_ds_sub = \ zip(*all_estimates) # find the `n_best` best results among the `n_trials` ones index_best = np.argsort(all_dets_sub)[:select] best_locations = np.asarray(all_locs_sub)[index_best] best_covariances = np.asarray(all_covs_sub)[index_best] best_supports = np.asarray(all_supports_sub)[index_best] best_ds = np.asarray(all_ds_sub)[index_best] return best_locations, best_covariances, best_supports, best_ds def fast_mcd(X, support_fraction=None, cov_computation_method=empirical_covariance, random_state=None): """Estimates the Minimum Covariance Determinant matrix. Read more in the :ref:`User Guide <robust_covariance>`. Parameters ---------- X : array-like, shape (n_samples, n_features) The data matrix, with p features and n samples. support_fraction : float, 0 < support_fraction < 1 The proportion of points to be included in the support of the raw MCD estimate. Default is None, which implies that the minimum value of support_fraction will be used within the algorithm: `[n_sample + n_features + 1] / 2`. cov_computation_method : callable, default empirical_covariance The function which will be used to compute the covariance. Must return shape (n_features, n_features) random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Notes ----- The FastMCD algorithm has been introduced by Rousseuw and Van Driessen in "A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS". The principle is to compute robust estimates and random subsets before pooling them into a larger subsets, and finally into the full data set. Depending on the size of the initial sample, we have one, two or three such computation levels. Note that only raw estimates are returned. If one is interested in the correction and reweighting steps described in [Rouseeuw1999]_, see the MinCovDet object. References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS .. [Butler1993] R. W. Butler, P. L. Davies and M. Jhun, Asymptotics For The Minimum Covariance Determinant Estimator, The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400 Returns ------- location : array-like, shape (n_features,) Robust location of the data. covariance : array-like, shape (n_features, n_features) Robust covariance of the features. support : array-like, type boolean, shape (n_samples,) A mask of the observations that have been used to compute the robust location and covariance estimates of the data set. """ random_state = check_random_state(random_state) X = check_array(X, ensure_min_samples=2, estimator='fast_mcd') n_samples, n_features = X.shape # minimum breakdown value if support_fraction is None: n_support = int(np.ceil(0.5 * (n_samples + n_features + 1))) else: n_support = int(support_fraction * n_samples) # 1-dimensional case quick computation # (Rousseeuw, P. J. and Leroy, A. M. (2005) References, in Robust # Regression and Outlier Detection, John Wiley & Sons, chapter 4) if n_features == 1: if n_support < n_samples: # find the sample shortest halves X_sorted = np.sort(np.ravel(X)) diff = X_sorted[n_support:] - X_sorted[:(n_samples - n_support)] halves_start = np.where(diff == np.min(diff))[0] # take the middle points' mean to get the robust location estimate location = 0.5 * (X_sorted[n_support + halves_start] + X_sorted[halves_start]).mean() support = np.zeros(n_samples, dtype=bool) X_centered = X - location support[np.argsort(np.abs(X_centered), 0)[:n_support]] = True covariance = np.asarray([[np.var(X[support])]]) location = np.array([location]) # get precision matrix in an optimized way precision = linalg.pinvh(covariance) dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1) else: support = np.ones(n_samples, dtype=bool) covariance = np.asarray([[np.var(X)]]) location = np.asarray([np.mean(X)]) X_centered = X - location # get precision matrix in an optimized way precision = linalg.pinvh(covariance) dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1) # Starting FastMCD algorithm for p-dimensional case if (n_samples > 500) and (n_features > 1): # 1. Find candidate supports on subsets # a. split the set in subsets of size ~ 300 n_subsets = n_samples // 300 n_samples_subsets = n_samples // n_subsets samples_shuffle = random_state.permutation(n_samples) h_subset = int(np.ceil(n_samples_subsets * (n_support / float(n_samples)))) # b. perform a total of 500 trials n_trials_tot = 500 # c. select 10 best (location, covariance) for each subset n_best_sub = 10 n_trials = max(10, n_trials_tot // n_subsets) n_best_tot = n_subsets * n_best_sub all_best_locations = np.zeros((n_best_tot, n_features)) try: all_best_covariances = np.zeros((n_best_tot, n_features, n_features)) except MemoryError: # The above is too big. Let's try with something much small # (and less optimal) all_best_covariances = np.zeros((n_best_tot, n_features, n_features)) n_best_tot = 10 n_best_sub = 2 for i in range(n_subsets): low_bound = i * n_samples_subsets high_bound = low_bound + n_samples_subsets current_subset = X[samples_shuffle[low_bound:high_bound]] best_locations_sub, best_covariances_sub, _, _ = select_candidates( current_subset, h_subset, n_trials, select=n_best_sub, n_iter=2, cov_computation_method=cov_computation_method, random_state=random_state) subset_slice = np.arange(i * n_best_sub, (i + 1) * n_best_sub) all_best_locations[subset_slice] = best_locations_sub all_best_covariances[subset_slice] = best_covariances_sub # 2. Pool the candidate supports into a merged set # (possibly the full dataset) n_samples_merged = min(1500, n_samples) h_merged = int(np.ceil(n_samples_merged * (n_support / float(n_samples)))) if n_samples > 1500: n_best_merged = 10 else: n_best_merged = 1 # find the best couples (location, covariance) on the merged set selection = random_state.permutation(n_samples)[:n_samples_merged] locations_merged, covariances_merged, supports_merged, d = \ select_candidates( X[selection], h_merged, n_trials=(all_best_locations, all_best_covariances), select=n_best_merged, cov_computation_method=cov_computation_method, random_state=random_state) # 3. Finally get the overall best (locations, covariance) couple if n_samples < 1500: # directly get the best couple (location, covariance) location = locations_merged[0] covariance = covariances_merged[0] support = np.zeros(n_samples, dtype=bool) dist = np.zeros(n_samples) support[selection] = supports_merged[0] dist[selection] = d[0] else: # select the best couple on the full dataset locations_full, covariances_full, supports_full, d = \ select_candidates( X, n_support, n_trials=(locations_merged, covariances_merged), select=1, cov_computation_method=cov_computation_method, random_state=random_state) location = locations_full[0] covariance = covariances_full[0] support = supports_full[0] dist = d[0] elif n_features > 1: # 1. Find the 10 best couples (location, covariance) # considering two iterations n_trials = 30 n_best = 10 locations_best, covariances_best, _, _ = select_candidates( X, n_support, n_trials=n_trials, select=n_best, n_iter=2, cov_computation_method=cov_computation_method, random_state=random_state) # 2. Select the best couple on the full dataset amongst the 10 locations_full, covariances_full, supports_full, d = select_candidates( X, n_support, n_trials=(locations_best, covariances_best), select=1, cov_computation_method=cov_computation_method, random_state=random_state) location = locations_full[0] covariance = covariances_full[0] support = supports_full[0] dist = d[0] return location, covariance, support, dist class MinCovDet(EmpiricalCovariance): """Minimum Covariance Determinant (MCD): robust estimator of covariance. The Minimum Covariance Determinant covariance estimator is to be applied on Gaussian-distributed data, but could still be relevant on data drawn from a unimodal, symmetric distribution. It is not meant to be used with multi-modal data (the algorithm used to fit a MinCovDet object is likely to fail in such a case). One should consider projection pursuit methods to deal with multi-modal datasets. Read more in the :ref:`User Guide <robust_covariance>`. Parameters ---------- store_precision : bool Specify if the estimated precision is stored. assume_centered : Boolean If True, the support of the robust location and the covariance estimates is computed, and a covariance estimate is recomputed from it, without centering the data. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, the robust location and covariance are directly computed with the FastMCD algorithm without additional treatment. support_fraction : float, 0 < support_fraction < 1 The proportion of points to be included in the support of the raw MCD estimate. Default is None, which implies that the minimum value of support_fraction will be used within the algorithm: [n_sample + n_features + 1] / 2 random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Attributes ---------- raw_location_ : array-like, shape (n_features,) The raw robust estimated location before correction and re-weighting. raw_covariance_ : array-like, shape (n_features, n_features) The raw robust estimated covariance before correction and re-weighting. raw_support_ : array-like, shape (n_samples,) A mask of the observations that have been used to compute the raw robust estimates of location and shape, before correction and re-weighting. location_ : array-like, shape (n_features,) Estimated robust location covariance_ : array-like, shape (n_features, n_features) Estimated robust covariance matrix precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) support_ : array-like, shape (n_samples,) A mask of the observations that have been used to compute the robust estimates of location and shape. dist_ : array-like, shape (n_samples,) Mahalanobis distances of the training set (on which `fit` is called) observations. References ---------- .. [Rouseeuw1984] `P. J. Rousseeuw. Least median of squares regression. J. Am Stat Ass, 79:871, 1984.` .. [Rouseeuw1999] `A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS` .. [Butler1993] `R. W. Butler, P. L. Davies and M. Jhun, Asymptotics For The Minimum Covariance Determinant Estimator, The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400` """ _nonrobust_covariance = staticmethod(empirical_covariance) def __init__(self, store_precision=True, assume_centered=False, support_fraction=None, random_state=None): self.store_precision = store_precision self.assume_centered = assume_centered self.support_fraction = support_fraction self.random_state = random_state def fit(self, X, y=None): """Fits a Minimum Covariance Determinant with the FastMCD algorithm. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training data, where n_samples is the number of samples and n_features is the number of features. y : not used, present for API consistence purpose. Returns ------- self : object Returns self. """ X = check_array(X, ensure_min_samples=2, estimator='MinCovDet') random_state = check_random_state(self.random_state) n_samples, n_features = X.shape # check that the empirical covariance is full rank if (linalg.svdvals(np.dot(X.T, X)) > 1e-8).sum() != n_features: warnings.warn("The covariance matrix associated to your dataset " "is not full rank") # compute and store raw estimates raw_location, raw_covariance, raw_support, raw_dist = fast_mcd( X, support_fraction=self.support_fraction, cov_computation_method=self._nonrobust_covariance, random_state=random_state) if self.assume_centered: raw_location = np.zeros(n_features) raw_covariance = self._nonrobust_covariance(X[raw_support], assume_centered=True) # get precision matrix in an optimized way precision = linalg.pinvh(raw_covariance) raw_dist = np.sum(np.dot(X, precision) * X, 1) self.raw_location_ = raw_location self.raw_covariance_ = raw_covariance self.raw_support_ = raw_support self.location_ = raw_location self.support_ = raw_support self.dist_ = raw_dist # obtain consistency at normal models self.correct_covariance(X) # re-weight estimator self.reweight_covariance(X) return self def correct_covariance(self, data): """Apply a correction to raw Minimum Covariance Determinant estimates. Correction using the empirical correction factor suggested by Rousseeuw and Van Driessen in [Rouseeuw1984]_. Parameters ---------- data : array-like, shape (n_samples, n_features) The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns ------- covariance_corrected : array-like, shape (n_features, n_features) Corrected robust covariance estimate. """ correction = np.median(self.dist_) / chi2(data.shape[1]).isf(0.5) covariance_corrected = self.raw_covariance_ * correction self.dist_ /= correction return covariance_corrected def reweight_covariance(self, data): """Re-weight raw Minimum Covariance Determinant estimates. Re-weight observations using Rousseeuw's method (equivalent to deleting outlying observations from the data set before computing location and covariance estimates). [Rouseeuw1984]_ Parameters ---------- data : array-like, shape (n_samples, n_features) The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns ------- location_reweighted : array-like, shape (n_features, ) Re-weighted robust location estimate. covariance_reweighted : array-like, shape (n_features, n_features) Re-weighted robust covariance estimate. support_reweighted : array-like, type boolean, shape (n_samples,) A mask of the observations that have been used to compute the re-weighted robust location and covariance estimates. """ n_samples, n_features = data.shape mask = self.dist_ < chi2(n_features).isf(0.025) if self.assume_centered: location_reweighted = np.zeros(n_features) else: location_reweighted = data[mask].mean(0) covariance_reweighted = self._nonrobust_covariance( data[mask], assume_centered=self.assume_centered) support_reweighted = np.zeros(n_samples, dtype=bool) support_reweighted[mask] = True self._set_covariance(covariance_reweighted) self.location_ = location_reweighted self.support_ = support_reweighted X_centered = data - self.location_ self.dist_ = np.sum( np.dot(X_centered, self.get_precision()) * X_centered, 1) return location_reweighted, covariance_reweighted, support_reweighted
{ "content_hash": "ec4b4489ae2304d67cd47e2084313bcd", "timestamp": "", "source": "github", "line_count": 716, "max_line_length": 79, "avg_line_length": 42.184357541899445, "alnum_prop": 0.6390875380744272, "repo_name": "wazeerzulfikar/scikit-learn", "id": "985dda92f990cbd1baf0d7012a8a6b06aa03c080", "size": "30204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sklearn/covariance/robust_covariance.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3366" }, { "name": "C", "bytes": "451996" }, { "name": "C++", "bytes": "140322" }, { "name": "Makefile", "bytes": "1512" }, { "name": "PowerShell", "bytes": "17042" }, { "name": "Python", "bytes": "7246657" }, { "name": "Shell", "bytes": "19959" } ], "symlink_target": "" }
package com.example.bot.spring.amazon.fsm; import com.example.bot.spring.amazon.bot.Conversation; import com.example.bot.spring.amazon.model.BotActionResponse; import org.springframework.stereotype.Component; import org.statefulj.fsm.RetryException; import org.statefulj.fsm.model.Action; import static com.example.bot.spring.amazon.model.ResponseType.HI_AMAZON; @Component public class HelloAction implements Action<Conversation> { @Override public void execute(Conversation c, String event, Object... args) throws RetryException { c.addResponse( BotActionResponse.builder() .responseType(HI_AMAZON).build() ); } }
{ "content_hash": "5eda29ad5845aa5866bca5a1576a5aee", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 93, "avg_line_length": 34.35, "alnum_prop": 0.735080058224163, "repo_name": "locheng2016/ask", "id": "1062098a66c02a5daffa47cdc8d17d922380e17a", "size": "687", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample-spring-boot-kitchensink/src/main/java/com/example/bot/spring/amazon/fsm/HelloAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "283925" } ], "symlink_target": "" }
<?php require '../includes/connect.php'; require 'includes/playerdata.php'; $kit = $_POST['kittype']; $kit = stripslashes($kit); $kit = mysql_real_escape_string($kit); if($kit != 'black') { $tier = $_POST['kittier']; $tier = stripslashes($tier); $tier = mysql_real_escape_string($tier); } $training = $_POST['training']; $training = stripslashes($training); $training = mysql_real_escape_string($training); $getcost = mysql_query("SELECT cost FROM operationkits WHERE type='$kit'"); $basecost = mysql_result($getcost, 0); if($kit != 'black') { $totalcost = $basecost*$tier; $trainfactor = $training*1.5; $totalcost = $totalcost*$trainfactor; } else { $tier = 10; $trainfactor = $training*1.5; $totalcost = $basecost*$trainfactor; } $getplayerinfo = mysql_query("SELECT * FROM $factiondb WHERE factionuser='$username' AND factionname='$chosencolony'"); $playerarray = mysql_fetch_array($getplayerinfo); $playerbank = $playerarray['factionbank']; $playercentres = $playerarray['warcentre']; $gettraining = mysql_query("SELECT COUNT(*) FROM recruits WHERE factionuser='$username' AND factionname='$chosencolony' AND trainingtime > 0 AND allegiance='$allegiance'"); $currenttrain = mysql_result($gettraining); if($allegiance == 'authority') { $trainavail = $playercentres*2; $trainavail = $trainavail - $currenttrain; } else { $trainavail = $playercentres - $currenttrain; } if($totalcost > $playerbank) { header('Location: training.php?msg=1'); } elseif($trainavail == 0) { header('Location: training.php?msg=2'); } else { $updateplayerbank = mysql_query("UPDATE $factiondb SET factionbank=factionbank-$totalcost WHERE factionuser='$username' AND factionname='$chosencolony'"); $traintroops = mysql_query("INSERT INTO recruits(type, tier, allegiance, skill, trainingtime, factionuser, colony) VALUES('$kit','$tier','$allegiance','1','$training','$username','$chosencolony')"); } header('Location: training.php'); ?>
{ "content_hash": "b551b24dbeeecf43d4c84f4ee10d95d6", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 199, "avg_line_length": 28.685714285714287, "alnum_prop": 0.6817729083665338, "repo_name": "cuabar/delenda", "id": "0f58adeb40461cc0acfb1af8a7e4a5b60c9e2fc1", "size": "2008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "game/traintroops.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9625" }, { "name": "HTML", "bytes": "813" }, { "name": "JavaScript", "bytes": "162132" }, { "name": "PHP", "bytes": "467702" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata"> <name>Date_Deceased__c</name> <label>Kuolinpäivä</label> </CustomFieldTranslation>
{ "content_hash": "f7d2638db39fd2b1154b6bef27651363", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 72, "avg_line_length": 40.6, "alnum_prop": 0.7192118226600985, "repo_name": "SalesforceFoundation/HEDAP", "id": "59ec75b86ad9ae7efc238473acbddcedb4aca8e4", "size": "205", "binary": false, "copies": "1", "ref": "refs/heads/feature/234", "path": "force-app/main/default/objectTranslations/Contact-fi/Date_Deceased__c.fieldTranslation-meta.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Apex", "bytes": "1599605" }, { "name": "CSS", "bytes": "621" }, { "name": "HTML", "bytes": "145319" }, { "name": "JavaScript", "bytes": "61802" }, { "name": "Python", "bytes": "28442" }, { "name": "RobotFramework", "bytes": "26714" } ], "symlink_target": "" }
"""Fuzzing engine initialization.""" import importlib from clusterfuzz._internal import fuzzing from clusterfuzz.fuzz import engine def run(include_private=True, include_lowercase=False): """Initialise builtin fuzzing engines.""" if include_private: engines = fuzzing.ENGINES else: engines = fuzzing.PUBLIC_ENGINES for engine_name in engines: mod = importlib.import_module( f'clusterfuzz._internal.bot.fuzzers.{engine_name}.engine') engine.register(engine_name, mod.Engine) if include_lowercase and engine_name.lower() != engine_name: engine.register(engine_name.lower(), mod.Engine)
{ "content_hash": "7da7d76ab6f266acc8aa029fb0bae95f", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 66, "avg_line_length": 28.727272727272727, "alnum_prop": 0.7310126582278481, "repo_name": "google/clusterfuzz", "id": "25fd6386c945bad65e68c7ecf6b9f28a9e00e833", "size": "1207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/clusterfuzz/_internal/bot/fuzzers/init.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "21721" }, { "name": "C", "bytes": "3485" }, { "name": "C++", "bytes": "16326" }, { "name": "CSS", "bytes": "16789" }, { "name": "Dockerfile", "bytes": "25218" }, { "name": "Go", "bytes": "16253" }, { "name": "HTML", "bytes": "503044" }, { "name": "JavaScript", "bytes": "9433" }, { "name": "Jinja", "bytes": "3308" }, { "name": "PowerShell", "bytes": "17307" }, { "name": "Python", "bytes": "5085058" }, { "name": "Ruby", "bytes": "93" }, { "name": "Shell", "bytes": "80910" }, { "name": "Starlark", "bytes": "1951" } ], "symlink_target": "" }
package org.h3t.aspect; import java.lang.reflect.Field; import java.lang.reflect.Method; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.Enhancer; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.FieldSignature; import org.aspectj.lang.reflect.MethodSignature; import org.h3t.util.BeanProperty; import org.hibernate.proxy.HibernateProxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class EntityAspect implements LazyAspect{ private final static Logger log = LoggerFactory.getLogger(EntityAspect.class); public Object getField(ProceedingJoinPoint joinPoint) throws Throwable { Field field = ((FieldSignature)joinPoint.getSignature()).getField(); log.debug("Intercepting read of {}", field); Object parentEntity = joinPoint.getTarget(); Object ret = joinPoint.proceed(); if (ret instanceof HibernateProxy && isLazy(field)){ log.debug("Found lazy proxy for {}", field); HibernateProxy proxy = (HibernateProxy)ret; if (proxy.getHibernateLazyInitializer().isUninitialized()){ log.debug("Proxy not initialized. Creating proxy for {}", field); Class[] interfaces = new Class[]{EntitySerializer.class}; Callback[] callbacks = new Callback[]{new FieldLazyLoader(parentEntity, field), new SerializationInterceptor(ret)}; ret = Enhancer.create(field.getType(), interfaces, new EntityCallbackFilter(), callbacks); field.set(parentEntity, ret); } } return ret; } public Object invokeMethod(ProceedingJoinPoint joinPoint) throws Throwable { Method method = ((MethodSignature)joinPoint.getSignature()).getMethod(); log.debug("Intercepting invocation of {}", method); Object parentEntity = joinPoint.getTarget(); Object ret = joinPoint.proceed(); if (ret instanceof HibernateProxy && isLazy(method)){ log.debug("Found lazy proxy for {}", method); HibernateProxy proxy = (HibernateProxy)ret; if (proxy.getHibernateLazyInitializer().isUninitialized()){ log.debug("Proxy not initialized. Creating proxy for {}", method); Class[] interfaces = new Class[]{EntitySerializer.class}; Callback[] callbacks = new Callback[]{new MethodLazyLoader(parentEntity, method), new SerializationInterceptor(ret)}; ret = Enhancer.create(method.getReturnType(), interfaces, new EntityCallbackFilter(), callbacks); new BeanProperty<Object>(method).set(parentEntity, ret); } } return ret; } }
{ "content_hash": "6ec491f7990161a36e3e692be32ab6d2", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 121, "avg_line_length": 39.274193548387096, "alnum_prop": 0.7523613963039014, "repo_name": "H3T/H3T", "id": "8676be18aa5f35f1a9bcdc22f73005d7bfef0196", "size": "2435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/h3t/aspect/EntityAspect.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Groovy", "bytes": "757" }, { "name": "Java", "bytes": "60179" }, { "name": "Shell", "bytes": "5079" } ], "symlink_target": "" }
extern void dfi_writeheader(FILE *dfifile); extern void dfi_writetrack(FILE *dfifile, const int track, const int side, const unsigned char *rawtrackdata, const unsigned long rawdatalength, const unsigned int rotations); #endif
{ "content_hash": "d700895a46b86ecf96bc310deeeabf74", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 175, "avg_line_length": 45.8, "alnum_prop": 0.7991266375545851, "repo_name": "picosonic/bbc-fdc", "id": "1ee33216a0512619d00c4c1fd11196ef7deaca11", "size": "373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/dfi.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "446370" }, { "name": "GLSL", "bytes": "391" }, { "name": "Game Maker Language", "bytes": "427" }, { "name": "Makefile", "bytes": "5921" }, { "name": "Shell", "bytes": "3034" } ], "symlink_target": "" }
package com.shaojun.myapp.widget.loopview; import android.os.Handler; import android.os.Message; // Referenced classes of package com.qingchifan.view: // LoopView final class MessageHandler extends Handler { public static final int WHAT_INVALIDATE_LOOP_VIEW = 1000; public static final int WHAT_SMOOTH_SCROLL = 2000; public static final int WHAT_ITEM_SELECTED = 3000; final LoopView loopview; MessageHandler(LoopView loopview) { this.loopview = loopview; } @Override public final void handleMessage(Message msg) { switch (msg.what) { case WHAT_INVALIDATE_LOOP_VIEW: loopview.invalidate(); break; case WHAT_SMOOTH_SCROLL: loopview.smoothScroll(LoopView.ACTION.FLING); break; case WHAT_ITEM_SELECTED: loopview.onItemSelected(); break; } } }
{ "content_hash": "8166add5ed78ef70b41e4ebba5dd279d", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 61, "avg_line_length": 25.7027027027027, "alnum_prop": 0.6151419558359621, "repo_name": "JeremyAiYt/MyApp", "id": "3c766435d3c7815acdfa51e4c9fec09b9e0eb4d6", "size": "1126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/shaojun/myapp/widget/loopview/MessageHandler.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1103943" } ], "symlink_target": "" }
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; namespace Handyman.Azure.Functions.Http.ApiVersioning { internal class QueryStringApiVersionReader : IApiVersionReader { public StringValues Read(HttpRequest request) { return request.Query["api-version"]; } } }
{ "content_hash": "1c453b6d971bbd76ecdf94873ae8a375", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 66, "avg_line_length": 25.615384615384617, "alnum_prop": 0.7057057057057057, "repo_name": "JonasSamuelsson/Handyman", "id": "c229e49705512b22e61a64a85dfdca5b44d124f7", "size": "335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Handyman.Azure.Functions/src/Http/ApiVersioning/QueryStringApiVersionReader.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "756641" }, { "name": "PowerShell", "bytes": "8967" } ], "symlink_target": "" }
package br.edu.fametro.portal.business; import java.util.ArrayList; import java.util.Date; import java.util.List; import br.edu.fametro.portal.model.atores.AcessaSistema; import br.edu.fametro.portal.model.atores.Professor; import br.edu.fametro.portal.model.enums.GrupoAtendimento; import br.edu.fametro.portal.model.enums.TipoAtendimento; import br.edu.fametro.portal.model.enums.TipoUsuario; import br.edu.fametro.portal.model.solicitacoes.Solicitacao; import br.edu.fametro.portal.model.solicitacoes.secretaria.AbonoFalta; import br.edu.fametro.portal.model.solicitacoes.secretaria.RevisaoNota; public class SolicitacaoBusiness { private List<Solicitacao> banco; public SolicitacaoBusiness() { banco = new ArrayList<Solicitacao>(); } public List<Solicitacao> getBanco() { return banco; } public SolicitacaoBusiness simulaBanco(List<Solicitacao> list) { if(list != null){ SolicitacaoBusiness simulador = new SolicitacaoBusiness(); for(Solicitacao s : list){ simulador.adicionar(s); } return simulador; } return null; } public int getSize() { return banco.size(); } public boolean isEmpty() { if (this.banco == null || this.getSize() == 0) return true; else return false; } public boolean adicionar(Solicitacao nova) { if (!isEmpty()) { if (banco.contains(nova)) { return false; } } return banco.add(nova); } public Solicitacao pesquisaSolicitacao(Solicitacao s) { if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.equals(s)) return solicitacao; } } return null; } public Solicitacao pesquisaId(long id) { if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getId() == id) return solicitacao; } } return null; } public Solicitacao pesquisaCodigo(String codigo) { if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getCodigo().equals(codigo)) return solicitacao; } } return null; } public List<Solicitacao> pesquisaGrupoAtendimento(GrupoAtendimento grupoAtendimento) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getGrupoAtendimento().equals(grupoAtendimento)) result.add(solicitacao); } } return result; } public List<Solicitacao> pesquisaTipoAtendimento(TipoAtendimento tipoAtendimento) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getTipoAtendimento().equals(tipoAtendimento)) result.add(solicitacao); } } return result; } public List<Solicitacao> pesquisaTipoUsuario(TipoUsuario tipoUsuario) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getTipo().equals(tipoUsuario)) result.add(solicitacao); } } return result; } public List<Solicitacao> pesquisaDataAbertura(Date abertura) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getAbertura().equals(abertura)) result.add(solicitacao); } } return result; } public List<Solicitacao> pesquisaDataFechamento(Date fechamento) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getFechamento().equals(fechamento)) result.add(solicitacao); } } return result; } public List<Solicitacao> pesquisaAssunto(String assunto) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getAssunto().equals(assunto)) result.add(solicitacao); } } return result; } public List<Solicitacao> pesquisaCliente(AcessaSistema cliente) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao.getCliente().equals(cliente)) result.add(solicitacao); } } return result; } public List<Solicitacao> pesquisaProfessor(Professor professor) { List<Solicitacao> result = new ArrayList<Solicitacao>(); if (!isEmpty()) { for (Solicitacao solicitacao : banco) { if (solicitacao instanceof RevisaoNota) { if (((RevisaoNota) solicitacao).getProfessor().equals(professor)) { result.add(solicitacao); } } else if (solicitacao instanceof AbonoFalta) { if (((AbonoFalta) solicitacao).getProfessor().equals(professor)) { result.add(solicitacao); } } } } return result; } public boolean alterar(Solicitacao solicitacao) { if (!isEmpty()) { int index = banco.indexOf(solicitacao); if (index > -1) { banco.add(index, solicitacao); return true; } } return false; } public boolean remover(Solicitacao s) { if (!isEmpty()) { if (banco.contains(s)) { return banco.remove(s); } } return false; } }
{ "content_hash": "a190dfa86948bc7a5f98d93d93c0c1de", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 87, "avg_line_length": 24.376146788990827, "alnum_prop": 0.6654121189311253, "repo_name": "FlavioAlvez/PortalFametro", "id": "54cf8deecd04047f24b6a0e25c2eabe72d2edce4", "size": "5314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/br/edu/fametro/portal/business/SolicitacaoBusiness.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "457431" }, { "name": "HTML", "bytes": "4585013" }, { "name": "Java", "bytes": "256856" }, { "name": "JavaScript", "bytes": "412151" } ], "symlink_target": "" }
package eu.se_bastiaan.tvnl.service.recommendation; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import com.bumptech.glide.Glide; import com.bumptech.glide.request.FutureTarget; import java.io.IOException; import java.util.concurrent.ExecutionException; import eu.se_bastiaan.tvnl.R; public class RecommendationBuilder { private Context context; private NotificationManager notificationManager; private int id; private int priority; private int smallIcon; private String title; private String description; private String imageUri; private String backgroundUri; private PendingIntent intent; public RecommendationBuilder() { } public RecommendationBuilder setContext(Context context) { this.context = context; return this; } public RecommendationBuilder setId(int id) { this.id = id; return this; } public RecommendationBuilder setPriority(int priority) { this.priority = priority; return this; } public RecommendationBuilder setTitle(String title) { this.title = title; return this; } public RecommendationBuilder setDescription(String description) { this.description = description; return this; } public RecommendationBuilder setImage(String uri) { imageUri = uri; return this; } public RecommendationBuilder setBackgroundContentUri(String uri) { backgroundUri = uri; return this; } public RecommendationBuilder setIntent(PendingIntent intent) { this.intent = intent; return this; } public RecommendationBuilder setSmallIcon(int resourceId) { smallIcon = resourceId; return this; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public Notification build() throws IOException { if (notificationManager == null) { notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); } Bundle extras = new Bundle(); if (backgroundUri != null) { extras.putString(Notification.EXTRA_BACKGROUND_IMAGE_URI, backgroundUri); } FutureTarget<Bitmap> futureTarget = Glide.with(context) .load(imageUri) .asBitmap() .into((int) context.getResources().getDimension(R.dimen.card_info_width), (int) context.getResources().getDimension(R.dimen.card_thumbnail_height)); Bitmap image = null; try { image = futureTarget.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } Glide.clear(futureTarget); Notification notification = new NotificationCompat.BigPictureStyle( new NotificationCompat.Builder(context) .setContentTitle(title) .setContentText(description) .setPriority(priority) .setLocalOnly(true) .setOngoing(true) .setColor(context.getResources().getColor(R.color.primary)) .setCategory(Notification.CATEGORY_RECOMMENDATION) .setLargeIcon(image) .setSmallIcon(smallIcon) .setContentIntent(intent) .setExtras(extras)) .build(); notificationManager.notify(id, notification); notificationManager = null; return notification; } @Override public String toString() { return "RecommendationBuilder{" + ", id=" + id + ", priority=" + priority + ", smallIcon=" + smallIcon + ", title='" + title + '\'' + ", description='" + description + '\'' + ", imageUri='" + imageUri + '\'' + ", backgroundUri='" + backgroundUri + '\'' + ", intent=" + intent + '}'; } }
{ "content_hash": "4c821f98a360a97e536a78c3bcc95b39", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 164, "avg_line_length": 30.618055555555557, "alnum_prop": 0.6064867316851894, "repo_name": "se-bastiaan/TVNL-AndroidTV", "id": "5d10c591b4ebedbfd9269c20d8745b27175beda5", "size": "4409", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "app/src/main/java/eu/se_bastiaan/tvnl/service/recommendation/RecommendationBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "335356" } ], "symlink_target": "" }
import sys import os def setup_path(): modules = ['requests', 'envoy', 'sugargame2', 'spyral','parsley'] for module in modules: sys.path.insert(0, os.path.abspath('libraries/%s/' % module))
{ "content_hash": "00628fc387eede5c2d2013e199fc1707", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 69, "avg_line_length": 29.571428571428573, "alnum_prop": 0.642512077294686, "repo_name": "danShumway/python_math", "id": "bb00952d5e8582483f99e9aa07c19b1e9b7ccff4", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/PythonMath.activity/libraries/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "917248" } ], "symlink_target": "" }
namespace Google.Cloud.PubSub.V1.Snippets { // [START pubsub_v1_generated_SubscriberServiceApi_DeleteSnapshot_sync_flattened_resourceNames] using Google.Cloud.PubSub.V1; public sealed partial class GeneratedSubscriberServiceApiClientSnippets { /// <summary>Snippet for DeleteSnapshot</summary> /// <remarks> /// This snippet has been automatically generated and should be regarded as a code template only. /// It will require modifications to work: /// - It may require correct/in-range values for request initialization. /// - It may require specifying regional endpoints when creating the service client as shown in /// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint. /// </remarks> public void DeleteSnapshotResourceNames() { // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SnapshotName snapshot = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"); // Make the request subscriberServiceApiClient.DeleteSnapshot(snapshot); } } // [END pubsub_v1_generated_SubscriberServiceApi_DeleteSnapshot_sync_flattened_resourceNames] }
{ "content_hash": "de22f7d831892389611705e6fac93e08", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 105, "avg_line_length": 50.111111111111114, "alnum_prop": 0.6940133037694013, "repo_name": "googleapis/google-cloud-dotnet", "id": "db7660584356b4fbd7356ef9871bde173c5e488a", "size": "1975", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apis/Google.Cloud.PubSub.V1/Google.Cloud.PubSub.V1.GeneratedSnippets/SubscriberServiceApiClient.DeleteSnapshotResourceNamesSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "319820004" }, { "name": "Dockerfile", "bytes": "3415" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65881" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('records', '0002_auto_20151024_1555'), ] operations = [ migrations.AlterField( model_name='note', name='created_by', field=models.ForeignKey(related_name='records_note_creations', to_field='id', to=settings.AUTH_USER_MODEL, help_text=b'The user which originally created this item'), ), migrations.AlterField( model_name='note', name='modified_by', field=models.ForeignKey(related_name='records_note_modifications', to_field='id', to=settings.AUTH_USER_MODEL, help_text=b'The user which last modified this item'), ), ]
{ "content_hash": "d511bf88ecd4c9ae0583edc3c6cf7291", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 177, "avg_line_length": 34.25, "alnum_prop": 0.6411192214111923, "repo_name": "savioabuga/phoenix", "id": "b322079e19d48057cfd0fe709f7c6439c982b997", "size": "846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "phoenix/records/migrations/0003_auto_20151101_0325.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "304737" }, { "name": "HTML", "bytes": "162984" }, { "name": "JavaScript", "bytes": "78353" }, { "name": "Nginx", "bytes": "1635" }, { "name": "Python", "bytes": "156404" }, { "name": "Shell", "bytes": "4586" } ], "symlink_target": "" }
Please include a short resume of the changes and what is the purpose of PR. Any relevant information should be added to help: * **QA Team** (Quality Assurance) with tests. * **reviewers** to understand what are the stakes of the pull request. **Fixes** # (issue) ## Type of change - [ ] Patch fixing an issue (non-breaking change) - [ ] New functionality (non-breaking change) - [ ] Breaking change (patch or feature) that might cause side effects breaking part of the Software - [ ] Updating documentation (missing information, typo...) ## Target serie - [ ] 20.04.x - [ ] 20.10.x - [ ] 21.04.x - [ ] 21.10.x (master) <h2> How this pull request can be tested ? </h2> Please describe the **procedure** to verify that the goal of the PR is matched. Provide clear instructions so that it can be **correctly tested**. Any **relevant details** of the configuration to perform the test should be added. ## Checklist - [ ] I have followed the **coding style guidelines** provided by Centreon - [ ] I have commented my code, especially new **classes**, **functions** or any **legacy code** modified. (***docblock***) - [ ] I have commented my code, especially **hard-to-understand areas** of the PR. - [ ] I have made corresponding changes to the **documentation**. - [ ] I have **rebased** my development branch on the base branch (master, maintenance).
{ "content_hash": "7ec5769ca5a78b5224d5f5fa782702f3", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 146, "avg_line_length": 39.970588235294116, "alnum_prop": 0.70345842531273, "repo_name": "centreon/centreon-broker", "id": "3f6fa1cb9b3c42a3713c439ae35377a690f0f472", "size": "1375", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": ".github/PULL_REQUEST_TEMPLATE.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "4890239" }, { "name": "CMake", "bytes": "90878" }, { "name": "Go", "bytes": "2893" }, { "name": "Lua", "bytes": "97710" }, { "name": "PLSQL", "bytes": "39417" }, { "name": "Perl", "bytes": "3536" }, { "name": "Python", "bytes": "40379" }, { "name": "Shell", "bytes": "23949" } ], "symlink_target": "" }
package com.lcw.one.notify.rest; import com.lcw.one.notify.service.IMessageSenderService; import com.lcw.one.notify.service.impl.SimpleMessageSenderServiceImpl; import com.lcw.one.util.http.ResponseMessage; import com.lcw.one.util.http.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.Map; @RestController @RequestMapping(value = "/${restPath}/message/sender") @Api(description = "消息 - 发送消息") public class MsgSenderRestController { private static final Logger logger = LoggerFactory.getLogger(MsgSenderRestController.class); @Autowired private IMessageSenderService msgSenderService; @ApiOperation(value = "发送消息到指定用户") @PostMapping("/byUserId") public ResponseMessage sendMessageByUserId(String[] userIdList, String templateId, @RequestBody Map<String, Object> placeholderMap) { msgSenderService.sendMessage(Arrays.asList(userIdList), templateId, placeholderMap); return Result.success(); } @ApiOperation(value = "发送消息到指定用户") @PostMapping("/byRoleId") public ResponseMessage sendMessageByRoleId(String[] roleIdList, String templateId, @RequestBody Map<String, Object> placeholderMap) { msgSenderService.sendMessageByRoleId(Arrays.asList(roleIdList), templateId, placeholderMap); return Result.success(); } @ApiOperation(value = "发送消息到指定用户") @PostMapping("/byOfficeId") public ResponseMessage sendMessageByOfficeId(String[] officeIdList, String templateId, @RequestBody Map<String, Object> placeholderMap) { msgSenderService.sendMessageByOfficeId(Arrays.asList(officeIdList), templateId, placeholderMap); return Result.success(); } @ApiOperation(value = "发送邮件") @PostMapping("/sendEmail") public ResponseMessage sendEmail(String email, String title, String content) { msgSenderService.sendEmail(email, title, content); return Result.success(); } @ApiOperation(value = "发送邮件") @PostMapping("/sendSMS") public ResponseMessage sendSMS(String mobile, String content) { msgSenderService.sendSMS(mobile, content); return Result.success(); } @ApiOperation(value = "发送WebSocket") @PostMapping("/sendWebSocket") public ResponseMessage sendWebSocket() { msgSenderService.sendWebSocket(); return Result.success(); } }
{ "content_hash": "78d2f99d14223fce5fb898edfa4c7efc", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 141, "avg_line_length": 36.25352112676056, "alnum_prop": 0.7432012432012433, "repo_name": "lcw2004/one", "id": "3b41be3c1cf93d0634f78063f620fe2d68a1abd6", "size": "2660", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "one-notify/src/main/java/com/lcw/one/notify/rest/MsgSenderRestController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "324243" }, { "name": "HTML", "bytes": "3232" }, { "name": "Java", "bytes": "982089" }, { "name": "JavaScript", "bytes": "968008" }, { "name": "Shell", "bytes": "4214" }, { "name": "Vue", "bytes": "435509" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_77) on Thu Nov 17 16:02:09 CET 2016 --> <title>PlotData</title> <meta name="date" content="2016-11-17"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PlotData"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/StatisticsBarPlotter.html" title="class in de.qaware.chronix.client.benchmark.resultpresenter.plot"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html" target="_top">Frames</a></li> <li><a href="PlotData.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">de.qaware.chronix.client.benchmark.resultpresenter.plot</div> <h2 title="Class PlotData" class="title">Class PlotData</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>de.qaware.chronix.client.benchmark.resultpresenter.plot.PlotData</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">PlotData</span> extends java.lang.Object</pre> <div class="block">Created by mcqueen666 on 17.10.16.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#queryFunction">queryFunction</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#tsdbName">tsdbName</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>private java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#unit">unit</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private java.lang.Number</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#value">value</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#PlotData--">PlotData</a></span>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#PlotData-java.lang.String-java.lang.String-java.lang.Number-java.lang.String-">PlotData</a></span>(java.lang.String&nbsp;tsdbName, java.lang.String&nbsp;queryFunction, java.lang.Number&nbsp;value, java.lang.String&nbsp;unit)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#getQueryFunction--">getQueryFunction</a></span>()</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#getTsdbName--">getTsdbName</a></span>()</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#getUnit--">getUnit</a></span>()</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>java.lang.Number</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#getValue--">getValue</a></span>()</code>&nbsp;</td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#setQueryFunction-java.lang.String-">setQueryFunction</a></span>(java.lang.String&nbsp;queryFunction)</code>&nbsp;</td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#setTsdbName-java.lang.String-">setTsdbName</a></span>(java.lang.String&nbsp;tsdbName)</code>&nbsp;</td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#setUnit-java.lang.String-">setUnit</a></span>(java.lang.String&nbsp;unit)</code>&nbsp;</td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html#setValue-java.lang.Number-">setValue</a></span>(java.lang.Number&nbsp;value)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="tsdbName"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>tsdbName</h4> <pre>private&nbsp;java.lang.String tsdbName</pre> </li> </ul> <a name="queryFunction"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>queryFunction</h4> <pre>private&nbsp;java.lang.String queryFunction</pre> </li> </ul> <a name="value"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>value</h4> <pre>private&nbsp;java.lang.Number value</pre> </li> </ul> <a name="unit"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>unit</h4> <pre>private&nbsp;java.lang.String unit</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="PlotData--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PlotData</h4> <pre>public&nbsp;PlotData()</pre> </li> </ul> <a name="PlotData-java.lang.String-java.lang.String-java.lang.Number-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PlotData</h4> <pre>public&nbsp;PlotData(java.lang.String&nbsp;tsdbName, java.lang.String&nbsp;queryFunction, java.lang.Number&nbsp;value, java.lang.String&nbsp;unit)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getTsdbName--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getTsdbName</h4> <pre>public&nbsp;java.lang.String&nbsp;getTsdbName()</pre> </li> </ul> <a name="setTsdbName-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setTsdbName</h4> <pre>public&nbsp;void&nbsp;setTsdbName(java.lang.String&nbsp;tsdbName)</pre> </li> </ul> <a name="getQueryFunction--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getQueryFunction</h4> <pre>public&nbsp;java.lang.String&nbsp;getQueryFunction()</pre> </li> </ul> <a name="setQueryFunction-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setQueryFunction</h4> <pre>public&nbsp;void&nbsp;setQueryFunction(java.lang.String&nbsp;queryFunction)</pre> </li> </ul> <a name="getValue--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getValue</h4> <pre>public&nbsp;java.lang.Number&nbsp;getValue()</pre> </li> </ul> <a name="setValue-java.lang.Number-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setValue</h4> <pre>public&nbsp;void&nbsp;setValue(java.lang.Number&nbsp;value)</pre> </li> </ul> <a name="getUnit--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getUnit</h4> <pre>public&nbsp;java.lang.String&nbsp;getUnit()</pre> </li> </ul> <a name="setUnit-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setUnit</h4> <pre>public&nbsp;void&nbsp;setUnit(java.lang.String&nbsp;unit)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../../../de/qaware/chronix/client/benchmark/resultpresenter/plot/StatisticsBarPlotter.html" title="class in de.qaware.chronix.client.benchmark.resultpresenter.plot"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html" target="_top">Frames</a></li> <li><a href="PlotData.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "04c3427ed47982beaecfd6e359a884bd", "timestamp": "", "source": "github", "line_count": 454, "max_line_length": 391, "avg_line_length": 36.05506607929515, "alnum_prop": 0.6392571323843851, "repo_name": "ChronixDB/chronix.benchmark", "id": "dfe4252c1f167de2af567ca21292bb4af59eb561", "size": "16369", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/de/qaware/chronix/client/benchmark/resultpresenter/plot/PlotData.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "488330" } ], "symlink_target": "" }
import { Event, Emitter } from 'vs/base/common/event'; import { URI } from 'vs/base/common/uri'; import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { Registry } from 'vs/platform/registry/common/platform'; import { IOutputChannel, IOutputService, OUTPUT_VIEW_ID, OUTPUT_SCHEME, LOG_SCHEME, LOG_MIME, OUTPUT_MIME } from 'vs/workbench/contrib/output/common/output'; import { IOutputChannelDescriptor, Extensions, IOutputChannelRegistry } from 'vs/workbench/services/output/common/output'; import { OutputLinkProvider } from 'vs/workbench/contrib/output/common/outputLinkProvider'; import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService'; import { ITextModel } from 'vs/editor/common/model'; import { ILogService } from 'vs/platform/log/common/log'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IOutputChannelModel, IOutputChannelModelService } from 'vs/workbench/services/output/common/outputChannelModel'; import { IViewsService } from 'vs/workbench/common/views'; import { OutputViewPane } from 'vs/workbench/contrib/output/browser/outputView'; const OUTPUT_ACTIVE_CHANNEL_KEY = 'output.activechannel'; class OutputChannel extends Disposable implements IOutputChannel { scrollLock: boolean = false; readonly model: IOutputChannelModel; readonly id: string; readonly label: string; readonly uri: URI; constructor( readonly outputChannelDescriptor: IOutputChannelDescriptor, @IOutputChannelModelService outputChannelModelService: IOutputChannelModelService ) { super(); this.id = outputChannelDescriptor.id; this.label = outputChannelDescriptor.label; this.uri = URI.from({ scheme: OUTPUT_SCHEME, path: this.id }); this.model = this._register(outputChannelModelService.createOutputChannelModel(this.id, this.uri, outputChannelDescriptor.log ? LOG_MIME : OUTPUT_MIME, outputChannelDescriptor.file)); } append(output: string): void { this.model.append(output); } update(): void { this.model.update(); } clear(till?: number): void { this.model.clear(till); } } export class OutputService extends Disposable implements IOutputService, ITextModelContentProvider { declare readonly _serviceBrand: undefined; private channels: Map<string, OutputChannel> = new Map<string, OutputChannel>(); private activeChannelIdInStorage: string; private activeChannel?: OutputChannel; private readonly _onActiveOutputChannel = this._register(new Emitter<string>()); readonly onActiveOutputChannel: Event<string> = this._onActiveOutputChannel.event; constructor( @IStorageService private readonly storageService: IStorageService, @IInstantiationService private readonly instantiationService: IInstantiationService, @ITextModelService textModelResolverService: ITextModelService, @ILogService private readonly logService: ILogService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IViewsService private readonly viewsService: IViewsService, ) { super(); this.activeChannelIdInStorage = this.storageService.get(OUTPUT_ACTIVE_CHANNEL_KEY, StorageScope.WORKSPACE, ''); // Register as text model content provider for output textModelResolverService.registerTextModelContentProvider(OUTPUT_SCHEME, this); instantiationService.createInstance(OutputLinkProvider); // Create output channels for already registered channels const registry = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels); for (const channelIdentifier of registry.getChannels()) { this.onDidRegisterChannel(channelIdentifier.id); } this._register(registry.onDidRegisterChannel(this.onDidRegisterChannel, this)); // Set active channel to first channel if not set if (!this.activeChannel) { const channels = this.getChannelDescriptors(); this.setActiveChannel(channels && channels.length > 0 ? this.getChannel(channels[0].id) : undefined); } this._register(this.lifecycleService.onShutdown(() => this.dispose())); } provideTextContent(resource: URI): Promise<ITextModel> | null { const channel = <OutputChannel>this.getChannel(resource.path); if (channel) { return channel.model.loadModel(); } return null; } async showChannel(id: string, preserveFocus?: boolean): Promise<void> { const channel = this.getChannel(id); if (this.activeChannel?.id !== channel?.id) { this.setActiveChannel(channel); this._onActiveOutputChannel.fire(id); } const outputView = await this.viewsService.openView<OutputViewPane>(OUTPUT_VIEW_ID, !preserveFocus); if (outputView && channel) { outputView.showChannel(channel, !!preserveFocus); } } getChannel(id: string): OutputChannel | undefined { return this.channels.get(id); } getChannelDescriptor(id: string): IOutputChannelDescriptor | undefined { return Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(id); } getChannelDescriptors(): IOutputChannelDescriptor[] { return Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannels(); } getActiveChannel(): IOutputChannel | undefined { return this.activeChannel; } private async onDidRegisterChannel(channelId: string): Promise<void> { const channel = this.createChannel(channelId); this.channels.set(channelId, channel); if (!this.activeChannel || this.activeChannelIdInStorage === channelId) { this.setActiveChannel(channel); this._onActiveOutputChannel.fire(channelId); const outputView = this.viewsService.getActiveViewWithId<OutputViewPane>(OUTPUT_VIEW_ID); if (outputView) { outputView.showChannel(channel, true); } } } private createChannel(id: string): OutputChannel { const channelDisposables: IDisposable[] = []; const channel = this.instantiateChannel(id); channel.model.onDispose(() => { if (this.activeChannel === channel) { const channels = this.getChannelDescriptors(); const channel = channels.length ? this.getChannel(channels[0].id) : undefined; this.setActiveChannel(channel); if (this.activeChannel) { this._onActiveOutputChannel.fire(this.activeChannel.id); } } Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).removeChannel(id); dispose(channelDisposables); }, channelDisposables); return channel; } private instantiateChannel(id: string): OutputChannel { const channelData = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(id); if (!channelData) { this.logService.error(`Channel '${id}' is not registered yet`); throw new Error(`Channel '${id}' is not registered yet`); } return this.instantiationService.createInstance(OutputChannel, channelData); } private setActiveChannel(channel: OutputChannel | undefined): void { this.activeChannel = channel; if (this.activeChannel) { this.storageService.store(OUTPUT_ACTIVE_CHANNEL_KEY, this.activeChannel.id, StorageScope.WORKSPACE); } else { this.storageService.remove(OUTPUT_ACTIVE_CHANNEL_KEY, StorageScope.WORKSPACE); } } } export class LogContentProvider { private channelModels: Map<string, IOutputChannelModel> = new Map<string, IOutputChannelModel>(); constructor( @IOutputService private readonly outputService: IOutputService, @IOutputChannelModelService private readonly outputChannelModelService: IOutputChannelModelService ) { } provideTextContent(resource: URI): Promise<ITextModel> | null { if (resource.scheme === LOG_SCHEME) { let channelModel = this.getChannelModel(resource); if (channelModel) { return channelModel.loadModel(); } } return null; } private getChannelModel(resource: URI): IOutputChannelModel | undefined { const channelId = resource.path; let channelModel = this.channelModels.get(channelId); if (!channelModel) { const channelDisposables: IDisposable[] = []; const outputChannelDescriptor = this.outputService.getChannelDescriptors().filter(({ id }) => id === channelId)[0]; if (outputChannelDescriptor && outputChannelDescriptor.file) { channelModel = this.outputChannelModelService.createOutputChannelModel(channelId, resource, outputChannelDescriptor.log ? LOG_MIME : OUTPUT_MIME, outputChannelDescriptor.file); channelModel.onDispose(() => dispose(channelDisposables), channelDisposables); this.channelModels.set(channelId, channelModel); } } return channelModel; } }
{ "content_hash": "317825582f4ddf548d0decaab018af18", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 185, "avg_line_length": 39.24311926605505, "alnum_prop": 0.7687901811805962, "repo_name": "hoovercj/vscode", "id": "7af6a57b0130b5c60fb54176a4d4e72efb026a80", "size": "8906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/vs/workbench/contrib/output/browser/outputServices.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5527" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "1640" }, { "name": "C++", "bytes": "1038" }, { "name": "CSS", "bytes": "429597" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "628" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "28219" }, { "name": "Inno Setup", "bytes": "108702" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "839590" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "553" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "PHP", "bytes": "998" }, { "name": "Perl", "bytes": "857" }, { "name": "Perl6", "bytes": "1065" }, { "name": "PowerShell", "bytes": "6526" }, { "name": "Python", "bytes": "2119" }, { "name": "R", "bytes": "362" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "532" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "31357" }, { "name": "Swift", "bytes": "220" }, { "name": "TypeScript", "bytes": "13413255" }, { "name": "Visual Basic", "bytes": "893" } ], "symlink_target": "" }
/* * THE FILE HAS BEEN AUTOGENERATED BY THE IJH TOOL. * Please be aware that all changes made to this file manually * will be overwritten by the tool if it runs again. */ #include <jni.h> /* Header for class org.apache.harmony.test.stress.jni.localrefs.LocalRefsTest5 */ #ifndef _ORG_APACHE_HARMONY_TEST_STRESS_JNI_LOCALREFS_LOCALREFSTEST5_H #define _ORG_APACHE_HARMONY_TEST_STRESS_JNI_LOCALREFS_LOCALREFSTEST5_H #ifdef __cplusplus extern "C" { #endif /* Static final fields */ #undef org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_TM_ERROR_NONE #define org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_TM_ERROR_NONE 0L #undef org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_TM_ERROR_INTERRUPT #define org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_TM_ERROR_INTERRUPT 52L #undef org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_TM_ERROR_ILLEGAL_STATE #define org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_TM_ERROR_ILLEGAL_STATE 118L /* Native methods */ /* * Method: org.apache.harmony.test.stress.jni.localrefs.LocalRefsTest5.init()V */ JNIEXPORT void JNICALL Java_org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_init(JNIEnv *, jclass); /* * Method: org.apache.harmony.test.stress.jni.localrefs.LocalRefsTest5.nativeMethod(I)I */ JNIEXPORT jint JNICALL Java_org_apache_harmony_test_stress_jni_localrefs_LocalRefsTest5_nativeMethod(JNIEnv *, jobject, jint); #ifdef __cplusplus } #endif #endif /* _ORG_APACHE_HARMONY_TEST_STRESS_JNI_LOCALREFS_LOCALREFSTEST5_H */
{ "content_hash": "994b40672fc609e4d39e93a22665afc5", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 97, "avg_line_length": 29.333333333333332, "alnum_prop": 0.7784090909090909, "repo_name": "freeVM/freeVM", "id": "b6632756052dcbb979fc90cff4ab6372cecf6dc1", "size": "2391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/jni/localrefs/LocalRefsTest5.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "116828" }, { "name": "C", "bytes": "17860389" }, { "name": "C++", "bytes": "19007206" }, { "name": "CSS", "bytes": "217777" }, { "name": "Java", "bytes": "152108632" }, { "name": "Objective-C", "bytes": "106412" }, { "name": "Objective-J", "bytes": "11029421" }, { "name": "Perl", "bytes": "305690" }, { "name": "Scilab", "bytes": "34" }, { "name": "Shell", "bytes": "153821" }, { "name": "XSLT", "bytes": "152859" } ], "symlink_target": "" }
INCLUDE(TestingSetup) # Variables that are set externally SET(java_binary_dir ${CMAKE_CURRENT_BINARY_DIR}) SET(java_source_dir ${CMAKE_CURRENT_SOURCE_DIR}) # Java Add Dependencies Macro # Author: Brian Panneton # Description: This macro adds the java test dependencies. # Parameters: # dependencies = any target dependencies needed for java tests MACRO(ADD_TEST_JAVA_DEPENDENCIES dependencies) IF(NOT ("${dependencies}" STREQUAL "")) SET_PROPERTY(GLOBAL APPEND PROPERTY JAVA_TEST_DEPENDENCIES "${dependencies}" ) ENDIF() ENDMACRO() # Java Add File Dependencies Macro # Author: Brian Panneton # Description: This macro adds the java test file dependencies. # Note: The tests already depend on their own file # Parameters: # dependencies = any dependencies needed for java tests MACRO(ADD_TEST_JAVA_FILE_DEPENDENCIES dependencies) IF(NOT ("${dependencies}" STREQUAL "")) SET_PROPERTY(GLOBAL APPEND PROPERTY JAVA_TEST_FILE_DEPENDENCIES "${dependencies}" ) ENDIF() ENDMACRO() # Java Add Classpath Macro # Author: Brian Panneton # Description: This macro adds the java test classpaths. # Parameters: # cp = any classpaths needed for java tests MACRO(ADD_TEST_JAVA_CLASSPATH cp) GET_PROPERTY(classpath GLOBAL PROPERTY JAVA_TEST_CLASSPATH) IF(NOT ("${cp}" STREQUAL "")) SET_PROPERTY(GLOBAL PROPERTY JAVA_TEST_CLASSPATH "${classpath}${sep}${cp}" ) ENDIF() ENDMACRO() # Java Add LDPath Macro # Author: Brian Panneton # Description: This macro adds the java test ldpaths. # Parameters: # ld = any ldpaths needed for java tests MACRO(ADD_TEST_JAVA_LDPATH ld) GET_PROPERTY(ldpath GLOBAL PROPERTY JAVA_TEST_LDPATH) IF("${ld}" STRGREATER "") SET_PROPERTY(GLOBAL PROPERTY JAVA_TEST_LDPATH "${ldpath}${sep}${ld}" ) ENDIF() ENDMACRO() # Java Add Path Macro # Author: Brian Panneton # Description: This macro adds the java test paths. # Parameters: # p = any paths needed for java tests MACRO(ADD_TEST_JAVA_PATH p) GET_PROPERTY(path GLOBAL PROPERTY JAVA_TEST_PATH) IF("${p}" STRGREATER "") SET_PROPERTY(GLOBAL PROPERTY JAVA_TEST_PATH "${path}${sep}${p}" ) ENDIF() ENDMACRO() # Add Java Test Macro # Author: Brian Panneton # Description: This macro builds and adds the java test in one shot. There is # no need to build a test separately, because there isn't a case # that you don't want to run it. # Parameters: # executable = executable name # ${ARGN} = any arguments for the executable # MACRO(ADD_TEST_JAVA executable) PARSE_TEST_ARGS("${ARGN}") GET_PROPERTY(java_file_dependencies GLOBAL PROPERTY JAVA_TEST_FILE_DEPENDENCIES) GET_PROPERTY(java_classpath GLOBAL PROPERTY JAVA_TEST_CLASSPATH) GET_PROPERTY(java_ldpath GLOBAL PROPERTY JAVA_TEST_LDPATH) GET_PROPERTY(java_path GLOBAL PROPERTY JAVA_TEST_PATH) ADD_CUSTOM_COMMAND( OUTPUT ${java_binary_dir}/${executable}.class WORKING_DIRECTORY ${java_binary_dir} DEPENDS ${java_source_dir}/${executable}.java ${java_file_dependencies} COMMAND ${JAVA_COMPILE} ARGS -cp "\"${java_classpath}\"" -d "\"${java_binary_dir}\"" ${java_source_dir}/${executable}.java ) SET_PROPERTY(GLOBAL APPEND PROPERTY JAVA_TEST_TARGETS "${java_binary_dir}/${executable}.class") # Dlls need to be in the path dir for java IF(WIN32) IF("${java_path}" STREQUAL "") SET(java_path ${java_ldpath}) ENDIF() ENDIF() SET_CORE("${java_binary_dir}") ADD_TEST(Java${is_core}_${executable}${dup} ${CMAKE_COMMAND} -D "EXECUTABLE=${executable}" -D "ARGUMENTS=${arguments}" -D "CLASSPATH=${java_classpath}" -D "LDPATH=${java_ldpath}" -D "PATH=${java_path}" -D "SEPARATOR=${sep}" -P "${java_binary_dir}/TestDriverJava.cmake" ) IF(NOT "${tdep}" STREQUAL "") SET_TESTS_PROPERTIES(Java${is_core}_${executable}${dup} PROPERTIES DEPENDS ${tdep}) ENDIF() ENDMACRO() # Java Clean Macro # Author: Brian Panneton # Description: This macro sets up the java test for a make clean. # Parameters: # executable = executable name # ${ARGN} = files that the executable created MACRO(CLEAN_TEST_JAVA executable) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${ARGN} ) ENDMACRO() # Java Create Target Macro # Author: Brian Panneton # Description: This macro sets up the java test target # Parameters: none MACRO(CREATE_TARGET_TEST_JAVA) IF(EXISTS JavaCore_ALLTEST) SET(JavaCore_ALLTEST JavaCore_ALLTEST) ENDIF() GET_PROPERTY(java_dependencies GLOBAL PROPERTY JAVA_TEST_DEPENDENCIES) SET_CORE("${java_binary_dir}") GET_PROPERTY(targets GLOBAL PROPERTY JAVA_TEST_TARGETS) ADD_CUSTOM_TARGET(Java${is_core}_ALLTEST ALL DEPENDS ${JavaCore_ALLTEST} ${targets}) IF(NOT ("${java_dependencies}" STREQUAL "")) ADD_DEPENDENCIES(Java${is_core}_ALLTEST ${java_dependencies}) ENDIF() IF(NOT ("${is_core}" STREQUAL "")) SET_PROPERTY(GLOBAL PROPERTY JAVA_TEST_TARGETS "") ENDIF() ENDMACRO() # Configure the java 'driver' file CONFIGURE_FILE(${TESTING_SUITE_DIR}/TestingSuite/TestDriverJava.cmake.in ${java_binary_dir}/TestDriverJava.cmake @ONLY)
{ "content_hash": "f36f489c09bc191b7588b3c9f3a38d8f", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 119, "avg_line_length": 33.41520467836257, "alnum_prop": 0.6323066153307665, "repo_name": "timkrentz/SunTracker", "id": "5fac4cf3aab53ae3db8a94a038c83a75788acf1d", "size": "5714", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "IMU/VTK-6.2.0/ThirdParty/xdmf3/vtkxdmf3/CMake/TestingSuite/AddTestsJava.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "185699" }, { "name": "Assembly", "bytes": "38582" }, { "name": "Batchfile", "bytes": "110" }, { "name": "C", "bytes": "48362836" }, { "name": "C++", "bytes": "70478135" }, { "name": "CMake", "bytes": "1755036" }, { "name": "CSS", "bytes": "147795" }, { "name": "Cuda", "bytes": "30026" }, { "name": "D", "bytes": "2152" }, { "name": "GAP", "bytes": "14495" }, { "name": "GLSL", "bytes": "190912" }, { "name": "Groff", "bytes": "66799" }, { "name": "HTML", "bytes": "295090" }, { "name": "Java", "bytes": "203238" }, { "name": "JavaScript", "bytes": "1146098" }, { "name": "Lex", "bytes": "47145" }, { "name": "Makefile", "bytes": "5461" }, { "name": "Objective-C", "bytes": "74727" }, { "name": "Objective-C++", "bytes": "265817" }, { "name": "Pascal", "bytes": "3407" }, { "name": "Perl", "bytes": "178176" }, { "name": "Prolog", "bytes": "4556" }, { "name": "Python", "bytes": "16497901" }, { "name": "Shell", "bytes": "48835" }, { "name": "Smarty", "bytes": "1368" }, { "name": "Tcl", "bytes": "1955829" }, { "name": "Yacc", "bytes": "180651" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>euclidean-geometry: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.6 / euclidean-geometry - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> euclidean-geometry <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-21 00:31:44 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-21 00:31:44 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.6 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/euclidean-geometry&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/EuclideanGeometry&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: plane geometry&quot; &quot;keyword: Euclid&quot; &quot;keyword: ruler and compass&quot; &quot;category: Mathematics/Geometry/General&quot; ] authors: [ &quot;Jean Duprat &lt;Jean.Duprat@ens-lyon.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/euclidean-geometry/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/euclidean-geometry.git&quot; synopsis: &quot;Basis of the Euclid&#39;s plane geometry&quot; description: &quot;&quot;&quot; This is a more recent version of the basis of Euclid&#39;s plane geometry, the previous version was the contribution intitled RulerCompassGeometry. The plane geometry is defined as a set of points, with two predicates : Clokwise for the orientation and Equidistant for the metric and three constructors, Ruler for the lines, Compass for the circles and Intersection for the points. For using it, we suggest to compile the files the name of which begin by a capital letter and a number from A1 to N7 in the lexicographic order and to keep modifiable the files of tacics (from Tactic1 to Tactic4) and the files of examples (Hilbert and Bolyai).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/euclidean-geometry/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=64bd0e87e9d61dfc9de79aeb1d91875f&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-euclidean-geometry.8.7.0 coq.8.6</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.6). The following dependencies couldn&#39;t be met: - coq-euclidean-geometry -&gt; coq &gt;= 8.7 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-euclidean-geometry.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "dd664fb7eb52657eefde9a88317ea33a", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 278, "avg_line_length": 45.71176470588235, "alnum_prop": 0.5683953159181573, "repo_name": "coq-bench/coq-bench.github.io", "id": "2b926df8f27d482dd549c369e6c81c7616cf59be", "size": "7796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.6/euclidean-geometry/8.7.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* $OpenBSD: geodesc.c,v 1.2 2003/08/07 16:59:37 mickey Exp $ */ /* * Copyright (c) 2003 Markus Friedl <markus@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Geode SC1100 Information Appliance On a Chip * http://www.national.com/ds.cgi/SC/SC1100.pdf */ #include <sys/cdefs.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/device.h> #include <machine/bus.h> #include <dev/pci/pcivar.h> #include <dev/pci/pcidevs.h> #include <arch/i386/pci/geodescreg.h> struct geodesc_softc { struct device sc_dev; bus_space_tag_t sc_iot; bus_space_handle_t sc_ioh; }; int geodesc_match(struct device *, void *, void *); void geodesc_attach(struct device *, struct device *, void *); int geodesc_wdogctl_cb(void *, int); struct cfattach geodesc_ca = { sizeof(struct geodesc_softc), geodesc_match, geodesc_attach }; struct cfdriver geodesc_cd = { NULL, "geodesc", DV_DULL }; int geodesc_match(struct device *parent, void *match, void *aux) { struct pci_attach_args *pa = aux; if (PCI_VENDOR(pa->pa_id) == PCI_VENDOR_NS && PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_NS_SC1100_XBUS) return (1); return (0); } #define WDSTSBITS "\20\x04WDRST\x03WDSMI\x02WDINT\x01WDOVF" void geodesc_attach(struct device *parent, struct device *self, void *aux) { struct geodesc_softc *sc = (void *) self; struct pci_attach_args *pa = aux; uint16_t cnfg, cba; uint8_t sts, rev, iid; pcireg_t reg; reg = pci_conf_read(pa->pa_pc, pa->pa_tag, SC1100_F5_SCRATCHPAD); sc->sc_iot = pa->pa_iot; if (bus_space_map(sc->sc_iot, reg, 64, 0, &sc->sc_ioh)) { printf(": unable to map registers at 0x%x\n", reg); return; } cba = bus_space_read_2(sc->sc_iot, sc->sc_ioh, GCB_CBA); if (cba != reg) { printf(": cba mismatch: cba 0x%x != reg 0x%x\n", cba, reg); bus_space_unmap(sc->sc_iot, sc->sc_ioh, 64); return; } sts = bus_space_read_1(sc->sc_iot, sc->sc_ioh, GCB_WDSTS); cnfg = bus_space_read_2(sc->sc_iot, sc->sc_ioh, GCB_WDCNFG); iid = bus_space_read_1(sc->sc_iot, sc->sc_ioh, GCB_IID); rev = bus_space_read_1(sc->sc_iot, sc->sc_ioh, GCB_REV); printf(": iid %d revision %d wdstatus %b\n", iid, rev, sts, WDSTSBITS); /* setup and register watchdog */ bus_space_write_2(sc->sc_iot, sc->sc_ioh, GCB_WDTO, 0); sts |= WDOVF_CLEAR; bus_space_write_1(sc->sc_iot, sc->sc_ioh, GCB_WDSTS, sts); cnfg &= ~WDCNFG_MASK;; cnfg |= WDTYPE1_RESET|WDPRES_DIV_512; bus_space_write_2(sc->sc_iot, sc->sc_ioh, GCB_WDCNFG, cnfg); wdog_register(sc, geodesc_wdogctl_cb); } int geodesc_wdogctl_cb(void *self, int period) { struct geodesc_softc *sc = self; if (period > 0x03ff) period = 0x03ff; bus_space_write_2(sc->sc_iot, sc->sc_ioh, GCB_WDTO, period * 64); return (period); }
{ "content_hash": "587a90190c1322acfe96efa8a9820d90", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 75, "avg_line_length": 29.53913043478261, "alnum_prop": 0.6847218133647336, "repo_name": "MarginC/kame", "id": "ef70b184e15e983d3fa4ee8204c6f5fcb5cf7f65", "size": "3397", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "openbsd/sys/arch/i386/pci/geodesc.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arc", "bytes": "7491" }, { "name": "Assembly", "bytes": "14375563" }, { "name": "Awk", "bytes": "313712" }, { "name": "Batchfile", "bytes": "6819" }, { "name": "C", "bytes": "356715789" }, { "name": "C++", "bytes": "4231647" }, { "name": "DIGITAL Command Language", "bytes": "11155" }, { "name": "Emacs Lisp", "bytes": "790" }, { "name": "Forth", "bytes": "253695" }, { "name": "GAP", "bytes": "9964" }, { "name": "Groff", "bytes": "2220485" }, { "name": "Lex", "bytes": "168376" }, { "name": "Logos", "bytes": "570213" }, { "name": "Makefile", "bytes": "1778847" }, { "name": "Mathematica", "bytes": "16549" }, { "name": "Objective-C", "bytes": "529629" }, { "name": "PHP", "bytes": "11283" }, { "name": "Perl", "bytes": "151251" }, { "name": "Perl6", "bytes": "2572" }, { "name": "Ruby", "bytes": "7283" }, { "name": "Scheme", "bytes": "76872" }, { "name": "Shell", "bytes": "583253" }, { "name": "Stata", "bytes": "408" }, { "name": "Yacc", "bytes": "606054" } ], "symlink_target": "" }
var gulp = require('gulp'), concat = require('gulp-concat'), gulpif = require('gulp-if'), notify = require('gulp-notify'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), gutils = require('gulp-util'); module.exports = function (src, out, dest) { return function () { var shouldUglify = function () { return gutils.env.production; }; var appendMin = function () { return Boolean(gutils.env.production && gutils.env.min); } return gulp.src(src) .pipe(gulpif(shouldUglify, uglify())) .pipe(gulpif(appendMin, rename({suffix: '.min'}))) .pipe(concat(out || 'app.js')) .pipe(gulp.dest(dest || 'js')) .pipe(notify('Compiled: <%= file.relative %>!')); }; };
{ "content_hash": "30fd4e53bd29935eeae426a165a0f0d4", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 68, "avg_line_length": 31.807692307692307, "alnum_prop": 0.5453446191051995, "repo_name": "ruysu/gulp-core", "id": "74127498a02d47f8e3b96ccb21312a32363232b3", "size": "827", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/concat.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "16372" } ], "symlink_target": "" }
namespace Ripper.Services.ImageHosts { using System; using System.Collections; using System.IO; using System.Net; using System.Threading; using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images from MyPixHost.com /// </summary> public class MyPixHost : ServiceTemplate { /// <summary> /// Initializes a new instance of the <see cref="MyPixHost"/> class. /// </summary> /// <param name="sSavePath"> /// The s save path. /// </param> /// <param name="strURL"> /// The str url. /// </param> /// <param name="hTbl"> /// The h tbl. /// </param> public MyPixHost(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable) { } /// <summary> /// Do the Download /// </summary> /// <returns> /// Return if Downloaded or not /// </returns> protected override bool DoDownload() { string strImgURL = ImageLinkURL; if (EventTable.ContainsKey(strImgURL)) { return true; } string strFilePath = string.Empty; try { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; return false; } CacheObject ccObj = new CacheObject { IsDownloaded = false, FilePath = strFilePath, Url = strImgURL }; try { EventTable.Add(strImgURL, ccObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (EventTable.ContainsKey(strImgURL)) { return false; } EventTable.Add(strImgURL, ccObj); } string strNewURL = strImgURL.Replace(".php", ".jpg"); strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("/") + 1); strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath)); ////////////////////////////////////////////////////////////////////////// string newAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != newAlteredPath) { strFilePath = newAlteredPath; ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; } try { WebClient client = new WebClient(); client.Headers.Add("Referer: " + strImgURL); client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (WebException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return false; } ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true; CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; return true; } ////////////////////////////////////////////////////////////////////////// } }
{ "content_hash": "6e03db22b4f102b3403f1ea52ec1c334", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 154, "avg_line_length": 32.173611111111114, "alnum_prop": 0.4804662205914095, "repo_name": "half-evil/ripper", "id": "deaa9a4c69240050e8eda8cef73702434ffe8d06", "size": "5122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ripper.Services/ImageHosts/MyPixHost.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "846" }, { "name": "C#", "bytes": "1496000" }, { "name": "Inno Setup", "bytes": "7247" }, { "name": "Shell", "bytes": "2822" }, { "name": "Smalltalk", "bytes": "29810" } ], "symlink_target": "" }
package com.github.sladecek.maze.jmaze.print3d.output; //REV1 import com.github.sladecek.maze.jmaze.geometry.Point3D; import com.github.sladecek.maze.jmaze.print.Color; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Locale; /* * Compose content of Open Scad file. */ final class OpenScadComposer implements java.lang.AutoCloseable { public OpenScadComposer(final OutputStream stream) throws IOException { this.stream = stream; out = new OutputStreamWriter(stream, "UTF8"); } public static String formatColor(final Color color) { final double r = 255.0; return String.format(Locale.US, "[%.2f, %.2f, %.2f]", color.getR() / r, color.getG() / r, color.getB() / r); } public void close() throws IOException { out.close(); stream.close(); } public void beginUnion() throws IOException { out.write("union() {\n"); } public void closeUnion() throws IOException { out.write("}\n"); } private void printPoint(final Point3D p0) throws IOException { out.write(" [ " + p0.getX() + "," + p0.getY() + "," + p0.getZ() + "] "); } /** * Print polyhedron consisting of 8 points. The points must be ordered by x * (most important), then y, then z. */ public void printPolyhedron( final ArrayList<Point3D> points, final ArrayList<ArrayList<Integer>> faces) throws IOException { out.write("polyhedron (points =["); boolean comma = false; for (Point3D p : points) { if (comma) { out.write(", \n"); } printPoint(p); comma = true; } out.write("\n], \n"); out.write("faces = [ "); comma = false; for (ArrayList<Integer> f : faces) { if (comma) { out.write(", \n"); } printFace(f); comma = true; } out.write("\n ] \n"); out.write("); \n"); } private void printFace(ArrayList<Integer> f) throws IOException { out.write("[ "); boolean comma = false; for (Integer i : f) { if (comma) { out.write(", "); } out.write(String.format("%d", i)); comma = true; } out.write("] "); } private final OutputStream stream; private Writer out; }
{ "content_hash": "ea65692959bb1f08b705def199694657", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 80, "avg_line_length": 26.75, "alnum_prop": 0.5471183800623053, "repo_name": "sladecek/jmaze", "id": "3e17c78532001f02d5eff1d5850babb3b13feb29", "size": "2568", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/github/sladecek/maze/jmaze/print3d/output/OpenScadComposer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "355142" } ], "symlink_target": "" }
FROM balenalib/asus-tinker-board-ubuntu:bionic-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.10.2 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" \ && echo "0ca3078d312f2723683aa8aadf455f6a08689926995cd76bd3032329411b8ef3 Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu bionic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.10.2, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "fa4eaf786c6ba89aab5100ef2cc06e0e", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 709, "avg_line_length": 51.96153846153846, "alnum_prop": 0.7081174438687392, "repo_name": "resin-io-library/base-images", "id": "d55257dec766f89b92b1d33287d60ef754ca51c0", "size": "4074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/asus-tinker-board/ubuntu/bionic/3.10.2/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
using System; using System.IO; using Endeca.Control.EacToolkit; using EndecaControl.EacToolkit.Core; #endregion namespace EndecaControl.EacToolkit.Components { public sealed class ForgeComponent : BatchComponent { private const string UPDATE_FILENAME_TEMPLATE = "{0}-sgmt0.records.xml"; internal ForgeComponent(string compId, string appId, HostType host) : base(compId, appId, host) { } public string StampPartialUpdate() { var fileName = String.Format(UPDATE_FILENAME_TEMPLATE, DataPrefix); var newName = String.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), fileName); Logger.Debug(String.Format("Stamping update file {0} to {1}.", fileName, newName)); var token = ShellCmd(String.Format("ren {0} {1}", Path.Combine(OutputDirectory, fileName), newName)); WaitUtilityComplete(token); return newName; } } }
{ "content_hash": "983443035c949b544bbe3b6435a095a6", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 113, "avg_line_length": 32.5, "alnum_prop": 0.6492307692307693, "repo_name": "enab-dev/endeca-control", "id": "4b268716a8c6739b33cc764f9463a8ebd6bbcb10", "size": "1001", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/EacToolkit/Components/ForgeComponent.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "265003" }, { "name": "Shell", "bytes": "465" } ], "symlink_target": "" }
package org.apache.activemq.openwire.codec.v9; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.activemq.openwire.codec.BaseDataStreamMarshaller; import org.apache.activemq.openwire.codec.BooleanStream; import org.apache.activemq.openwire.codec.OpenWireFormat; import org.apache.activemq.openwire.commands.DataStructure; import org.apache.activemq.openwire.commands.DiscoveryEvent; public class DiscoveryEventMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal * * @return short representation of the type data structure */ @Override public byte getDataStructureType() { return DiscoveryEvent.DATA_STRUCTURE_TYPE; } /** * @return a new object instance */ @Override public DataStructure createObject() { return new DiscoveryEvent(); } /** * Un-marshal an object instance from the data input stream * * @param o * the object to un-marshal * @param dataIn * the data input stream to build the object from * @throws IOException */ @Override public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); DiscoveryEvent info = (DiscoveryEvent) o; info.setServiceName(tightUnmarshalString(dataIn, bs)); info.setBrokerName(tightUnmarshalString(dataIn, bs)); } /** * Write the booleans that this object uses to a BooleanStream */ @Override public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { DiscoveryEvent info = (DiscoveryEvent) o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getServiceName(), bs); rc += tightMarshalString1(info.getBrokerName(), bs); return rc + 0; } /** * Write a object instance to data output stream * * @param o * the instance to be marshaled * @param dataOut * the output stream * @throws IOException * thrown if an error occurs */ @Override public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); DiscoveryEvent info = (DiscoveryEvent) o; tightMarshalString2(info.getServiceName(), dataOut, bs); tightMarshalString2(info.getBrokerName(), dataOut, bs); } /** * Un-marshal an object instance from the data input stream * * @param o * the object to un-marshal * @param dataIn * the data input stream to build the object from * @throws IOException */ @Override public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { super.looseUnmarshal(wireFormat, o, dataIn); DiscoveryEvent info = (DiscoveryEvent) o; info.setServiceName(looseUnmarshalString(dataIn)); info.setBrokerName(looseUnmarshalString(dataIn)); } /** * Write the booleans that this object uses to a BooleanStream */ @Override public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { DiscoveryEvent info = (DiscoveryEvent) o; super.looseMarshal(wireFormat, o, dataOut); looseMarshalString(info.getServiceName(), dataOut); looseMarshalString(info.getBrokerName(), dataOut); } }
{ "content_hash": "6cc690ee81651d0e8b4fbaebf8fa3d3f", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 125, "avg_line_length": 32.30701754385965, "alnum_prop": 0.6752647298398045, "repo_name": "apache/activemq-openwire", "id": "13a37e51bf0431a878a47c940952124c9e8aaf0e", "size": "4481", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v9/DiscoveryEventMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11968" }, { "name": "HTML", "bytes": "4032" }, { "name": "Java", "bytes": "4277739" }, { "name": "Scala", "bytes": "6658" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //var appJugador = angular.module('jugador', ['angular.filter','ngRoute','angularUtils.directives.dirPagination']); ////Accede directamente al modulo ProyectoNE definido en app.js 'use strict'; ProyectoNE.factory('PagerService', PagerService); ProyectoNE.controller('ControllerJugador', ControllerJugador); ProyectoNE.config(['$routeProvider', RouteProvider]); ProyectoNE.directive("ngIsolateApp", ngIsolateApp); function ControllerJugador($scope, $http, PagerService) { console.log("inicializo jugador.."); $scope.profile = "USUARIO"; //DEFAULT - USUARIO $scope.tab = "TEAM"; // TEAM - DEF - HELP - LEAGUE $scope.view = "PITCH"; // PITCH - LIST $scope.money = 1000.00; $scope.player = ''; $scope.message = 'Para cambiar tu capitan, usa el menu que aparece al hacer clic en un jugador.'; $scope.modified = false; $scope.substitution = ''; $scope.transfer = ''; $scope.moneyBackup = ''; $scope.jugadoresBackup = {}; $scope.jugadores = {}; $scope.misJugadoresBackup = {}; $scope.misJugadores = {}; $scope.miEquipoBackup = {}; $scope.miEquipo = { nombre: '', //descripcion: '', captain: '112', subcaptain: '138', integrantes: [], transferencias: [] }; /* Funcion para restaurar equipo guardado */ $scope.clear = function() { $scope.miEquipo.transferencias = []; $scope.substitution = ''; $scope.transfer = ''; }; /* Funcion para restaurar equipo guardado */ $scope.reset = function() { if($scope.modified) { // Example with 1 argument $scope.jugadores = angular.copy($scope.jugadoresBackup); $scope.misJugadores = angular.copy($scope.misJugadoresBackup); $scope.miEquipo = angular.copy($scope.miEquipoBackup); $scope.money = angular.copy($scope.moneyBackup); $scope.miEquipo.integrantes = []; $scope.clear(); //isReset = S -> si es una restauracion, no hace backup //isBatch = S -> si es un proceso por lote, no hace verificciones al agregar integrante $scope.getMiEquipo("S", "S"); $scope.setModified(false); console.log('backup restaurado'); } }; /* Funcion para guardar equipo */ $scope.update = function(equipo) { // Example with 2 arguments //angular.copy(equipo, $scope.miEquipoBackup); $scope.jugadoresBackup = angular.copy($scope.jugadores); $scope.misJugadoresBackup = angular.copy($scope.misJugadores); $scope.miEquipoBackup = angular.copy($scope.miEquipo); $scope.moneyBackup = angular.copy($scope.money); console.log('backup hecho'); }; /* Funcion para aumentar el saldo */ $scope.setMoney = function(diferencia){ $scope.money += diferencia; }; /* Funcion para agregar un integrante a mi equipo */ $scope.agregarIntegrante = function(integrante, isBatch, updMoney){ console.log('entro a agregar a mi equipo ' + integrante.nm + '.'); var agregado = false; var existe = false; var transferencia = ($scope.profile === "USUARIO") && ($scope.tab === "DEF"); if (updMoney !== "N") { if ($scope.money < integrante.pc) { NeAlert("ERROR", "Atencion!", "Saldo insuficiente. No se puede agregar al equipo. "+"<br>"+"Jugador: "+integrante.nm); return; } } if(transferencia && isBatch !== "S") { if($scope.transfer === '') { NeAlert("ERROR", "Atencion!", "Ud. no posee una transferencia pendiente."+"<br>"+"Debe seleccionar un jugador de su equipo."); return; } } //angular.forEach($scope.misJugadores, function(jugador, i) { for (var i = 0, len = $scope.misJugadores.length; i < len; i++) { var jugador = $scope.misJugadores[i]; if(jugador.id === integrante.id) { existe = true; $scope.misJugadores.splice(i, 1, integrante); break; } if(jugador.id === '' && !existe && !agregado && jugador.pos === integrante.pos){ //console.log('entro if TRUE '+jugador.nm+" "+integrante.nm); jugador = integrante; $scope.misJugadores.splice(i, 1, integrante); agregado = true; break; } } //}); if (agregado || existe) { //console.log('entro a agregar' + integrante.nm); $scope.miEquipo.integrantes.push( integrante ); integrante.mt = 1; //jugador agregado } if (!existe && !agregado) { NeAlert(null, "Atencion!", "No se puede agregar al equipo."+"<br>"+"Jugador: "+integrante.nm); } if(agregado) { if (updMoney !== "N") { // actualizo el saldo $scope.setMoney(-integrante.pc); } if(transferencia) { // intercambio de titular/suplente var titular = integrante.tit; integrante.tit = $scope.transfer.tit; $scope.transfer.tit = titular; var registrado = false; //si el jugador salio y volvio a entrar, se actualiza el jugador que salio en primer lugar y se marca como registrada la transferencia for (var i = 0, len = $scope.miEquipo.transferencias.length; i < len; i++) { var jugador = $scope.miEquipo.transferencias[i].out; if(jugador.id === integrante.id) { $scope.miEquipo.transferencias[i].out = $scope.transfer; registrado = true; //$scope.transfer = $scope.miEquipo.transferencias[i].out; //$scope.miEquipo.transferencias.splice(i, 1); //console.log("transferencia pendiente: "+$scope.transfer.nm); } } if(!registrado) { //si no esta registrada la transferencia, se agrega la misma if($scope.transfer.id !== integrante.id) { $scope.miEquipo.transferencias.push({ out: $scope.transfer, in: integrante }); console.log("transferencias realizadas: "+$scope.miEquipo.transferencias); } } $scope.transfer = ''; } //modificado if(transferencia && $scope.miEquipo.transferencias.length === 0) $scope.setModified(false); else $scope.setModified(true); } console.log('agregado ' + agregado + ' ' + existe); console.log($scope.miEquipo); console.log($scope.transfer); //console.log($scope.misJugadores); }; /* Funcion para eliminar un integrante de mi equipo */ $scope.eliminarIntegrante = function(integrante, updMoney){ console.log('entro a eliminar de mi equipo: '+integrante.nm); var eliminado = false; var existe1 = false; var transferencia = ($scope.profile === "USUARIO") && ($scope.tab === "DEF"); var index = $scope.miEquipo.integrantes.indexOf(integrante); console.log("index: "+index); if(transferencia) { if($scope.transfer === '') { $scope.transfer = integrante; console.log("transferencia pendiente: "+$scope.transfer.nm); } else { NeAlert("ERROR", "Atencion!", "Ud. posee una transferencia pendiente."+"<br>"+"Jugador: "+$scope.transfer.nm); return; } } if (index > -1) { $scope.miEquipo.integrantes.splice(index, 1); integrante.mt = 0; //jugador agregado eliminado = true; } if(eliminado) { //angular.forEach($scope.misJugadores, function(jugador, i) { for (var i = 0, len = $scope.misJugadores.length; i < len; i++) { var jugador = $scope.misJugadores[i]; if(jugador.id === integrante.id) { existe1 = true; //salir del loop } if(existe1){ //console.log('entro if TRUE '+jugador.nm+" "+integrante.nm); var posicion = jugador.pos; var color = jugador.color; var jugadorNulo = {"id":"","nm":"X","ap":"X","cl":"DEF","club":"","color":color,"pos":posicion,"jr":"","pj":"","pt":"","pv":"","pc":"","eg":"","mt":1}; $scope.misJugadores.splice(i, 1, jugadorNulo); eliminado = true; break; } } //}); //si el jugador entro y volvio a salir, la transferencia pendiente es el salio en primer lugar y se deshace la transferencia for (var i = 0, len = $scope.miEquipo.transferencias.length; i < len; i++) { var jugador = $scope.miEquipo.transferencias[i].in; if(jugador.id === integrante.id) { $scope.transfer = $scope.miEquipo.transferencias[i].out; // intercambio de titular/suplente var titular = integrante.tit; integrante.tit = $scope.transfer.tit; $scope.transfer.tit = titular; $scope.miEquipo.transferencias.splice(i, 1); console.log("transferencia pendiente: "+$scope.transfer.nm); } } if (updMoney !== "N") { // actualizo el saldo $scope.setMoney(integrante.pc); } } else { $scope.transfer = ''; } //modificado $scope.setModified(true); console.log('eliminado'); console.log($scope.miEquipo); console.log($scope.transfer); }; /* Funcion para visualizar datos de un jugador */ $scope.verIntegrante = function(integrante){ console.log("entro a datos de: "+integrante.nm); //console.log(integrante); $scope.player = integrante; w3.show('#jugador'); }; /* Funcion para cancelar una sustitucion */ $scope.cancelSubstitution = function(integrante){ console.log("entro a cancelar una sustitucion: "+integrante.nm); //validar que no haya una modificacion pendiente if($scope.substitution.id === integrante.id) $scope.substitution = ''; }; /* Funcion para iniciar una sustitucion */ $scope.makeSubstitution = function(integrante){ console.log("entro a sustitucion: "+integrante.nm); if( $scope.substitution === '') { $scope.substitution = integrante; //modificado //$scope.setModified(true); } else if ($scope.substitution.id === integrante.id){ $scope.cancelSubstitution(integrante); } else { var sustituido = false; //validar que haya una modificacion pendiente if($scope.substitution.tit === "N" && integrante.tit === "S") { $scope.substitution.tit = "S"; integrante.tit = "N"; sustituido = true; if($scope.miEquipo.captain === integrante.id) $scope.miEquipo.captain = $scope.substitution.id; if($scope.miEquipo.subcaptain === integrante.id) $scope.miEquipo.subcaptain = $scope.substitution.id; } else if($scope.substitution.tit === "S" && integrante.tit === "N") { $scope.substitution.tit = "N"; integrante.tit = "S"; sustituido = true; if($scope.miEquipo.captain === $scope.substitution.id) $scope.miEquipo.captain = integrante.id; if($scope.miEquipo.subcaptain === $scope.substitution.id) $scope.miEquipo.subcaptain = integrante.id; } if(sustituido) { for (var i = 0, len = $scope.misJugadores.length; i < len; i++) { var jugador = $scope.misJugadores[i]; if(jugador.id === integrante.id) { $scope.misJugadores[i].tit = integrante.tit; //$scope.misJugadores[i].mc = integrante.mc; //$scope.misJugadores[i].smc = integrante.smc; //break; } if(jugador.id === $scope.substitution.tit) { $scope.misJugadores[i].tit = $scope.substitution.tit; //$scope.misJugadores[i].mc = $scope.substitution.mc; //$scope.misJugadores[i].msc = $scope.substitution.msc; //break; } } $scope.substitution = ''; } //modificado $scope.setModified(true); console.log("sustitucion realizada."); } }; /* Funcion para verificar que una sustitucion sea factible */ $scope.enabledSubstitution = function(integrante){ //console.log("entro a verificar sustitucion: "+integrante.nm); //validar que sea factible la sustitucion return $scope.substitution !== '' && ($scope.substitution.tit !== integrante.tit && (($scope.substitution.pos === 'POR' && integrante.pos === 'POR') || ($scope.substitution.pos !== 'POR' && integrante.pos !== 'POR'))); }; /* Funcion para modificar capitan */ $scope.setCaptain = function(captain){ console.log("entro a setear capitan: "+captain); if($scope.miEquipo.subcaptain === captain) $scope.miEquipo.subcaptain = $scope.miEquipo.captain; $scope.miEquipo.captain = captain; //modificado $scope.setModified(true); }; /* Funcion para modificar sub-capitan */ $scope.setSubCaptain = function(subcaptain){ console.log("entro a setear sub-capitan: "+subcaptain); if($scope.miEquipo.captain === subcaptain) $scope.miEquipo.captain = $scope.miEquipo.subcaptain; $scope.miEquipo.subcaptain = subcaptain; //modificado $scope.setModified(true); }; /* Funcion para actualizar modificado */ $scope.setModified = function(modified) { $scope.modified = modified; //Actualizar modificado //Actulizar boton de confirmacion $scope.setReadyDefaultTeam(); $scope.setReadyTeam(); }; /* Funcion para cambiar vista */ $scope.setView = function(view) { $scope.view = view; //Hace el cambio de vista }; /* Funcion para cambiar pestaña */ $scope.setTab = function(tab) { console.log('entro a pestanha:' + tab); console.log('modificado: ' + $scope.modified); if(tab === 'DEF') $scope.setMessage('Selecciona un maximo de 3 jugadores de un solo equipo.'); else if(tab === 'TEAM') $scope.setMessage('Para cambiar tu capitan, usa el menu que aparece al hacer clic en un jugador.'); else $scope.setMessage(''); $scope.tab = tab; //Hace el cambio de pestaña $scope.reset(); $scope.setReadyDefaultTeam(); $scope.setReadyTeam(); //$scope.miEquipo = $scope.miEquipoBackup; }; /* Funcion para cambiar perfil */ $scope.setProfile = function(profile) { console.log('entro a perfil: ' + profile); //Hace el cambio de perfil $scope.profile = profile; if(profile === 'DEFAULT') { //$scope.setTab('DEF'); $('#tabDef').click(); } else if(profile === 'USUARIO') { //$scope.setTab('TEAM'); $('#tabTeam').click(); } }; $scope.sesion = {}; /* Funcion que obtiene datos de la sesion */ $scope.getSesion = function() { $.LoadingOverlay("show"); $http.post("GetDatos?ori=datos_sesion", { data: {index: true, spaces: false } }) .then(function(response) { $scope.sesion = response.data.sesion; // $scope.incidencia.integrantes = []; console.log("imprimo sesion.."); console.log($scope.sesion); NeAlert(null, "Atencion!", $scope.getWelcome($scope.sesion)); $.LoadingOverlay("hide"); $scope.getClubes($scope.sesion.torneo); $scope.setProfile($scope.sesion.perfil); }, function(response) { //Second function handles error alert('Error al intentar obtener sesion.'); alert(response); $.LoadingOverlay("hide"); }); }; $scope.getWelcome = function(sesion) { var bienvenido = "Bienvenido/a"; if(sesion.sex === 'M') bienvenido = "Bienvenido"; else if(sesion.sex === 'F') bienvenido = "Bienvenida"; return bienvenido + " " + sesion.nombre + "!"; }; $scope.menu = {}; /* Funcion que obtiene datos del menu */ $scope.getMenu = function(datos) { $.LoadingOverlay("show"); $http.post("GetDatos?ori=menu", { data: {index: false, spaces: false, extraData: [{ app: 'WEB'}] } }) .then(function(response) { $scope.menu = response.data; // $scope.incidencia.integrantes = []; console.log("imprimo menu.."); console.log($scope.menu); $.LoadingOverlay("hide"); }, function(response) { //Second function handles error alert('Error al intentar obtener datos del menu.'); alert(response); $.LoadingOverlay("hide"); }); }; /* Funcion que obtiene datos de los jugadores */ $scope.getJugadores = function(datos) { $.LoadingOverlay("show"); $http.post("GetDatos?ori=datos_jugadores", { data: {index: false, spaces: false, extraData: [{ miEquipo: 'N', club: ''}]} }) .then(function(response) { $scope.jugadores = response.data.jugadores; //console.log("imprimo respuesta.."); //console.log(response); //$scope.dummyItems = $scope.jugadores; // dummy array of items to be paged //console.log('dummyItems'); //console.log($scope.dummyItems); $scope.pager = {}; //$scope.setPage = setPage; initController(); function initController() { // initialize to page 1 $scope.setPage(1); } // cargo mi equipo $scope.getMiEquipo(null, "S"); $.LoadingOverlay("hide"); }, function(response) { //Second function handles error alert('Error al intentar obtener datos de los jugadores.'); alert(response); $.LoadingOverlay("hide"); }); }; /* Funcion que carga mi equipo 2 */ $scope.getMisJugadores = function(datos) { $.LoadingOverlay("show"); $http.post("GetDatos?ori=datos_jugadores", { data: {index: false, spaces: false, extraData: [{ miEquipo: 'S', club: datos}]} }) .then(function(response) { $scope.misJugadores = response.data.jugadores; //console.log("imprimo mis jugadores.."); //console.log(response); // cargo mi equipo $scope.getMiEquipo(null, "S"); $.LoadingOverlay("hide"); }, function(response) { //Second function handles error alert('Error al intentar cargar mi equipo.'); alert(response); $.LoadingOverlay("hide"); }); }; $scope.clubes = {}; /* Funcion que obtiene datos de los clubes */ $scope.getClubes = function(torneo) { $.LoadingOverlay("show"); $http.post("GetDatos?ori=datos_clubes", { data: {index: true, spaces: false, extraData: [{ torneo: torneo }] } }) .then(function(response) { $scope.clubes = response.data.clubes; // $scope.incidencia.integrantes = []; console.log("imprimo clubes.."); console.log($scope.clubes); $.LoadingOverlay("hide"); }, function(response) { //Second function handles error alert('Error al intentar obtener datos de los clubes.'); alert(response); $.LoadingOverlay("hide"); }); }; $scope.posiciones = {}; /* Funcion que obtiene datos de las posiciones */ $scope.getPosiciones = function(datos) { $.LoadingOverlay("show"); $http.post("GetDatos?ori=datos_posiciones", { data: {index: true, spaces: false } }) .then(function(response) { $scope.posiciones = response.data.posiciones; // $scope.incidencia.integrantes = []; console.log("imprimo posiciones.."); console.log($scope.posiciones); $.LoadingOverlay("hide"); }, function(response) { //Second function handles error alert('Error al intentar obtener datos de las posiciones.'); alert(response); $.LoadingOverlay("hide"); }); }; /* Funcion que carga mi equipo */ $scope.getMiEquipo = function(isReset, isBatch) { console.log('entro a cargar mi equipo.'); angular.forEach($scope.jugadores, function(jugador, i) { if(jugador.mt === 1){ $scope.agregarIntegrante(jugador, isBatch, 'N'); } }); if(isReset !== "S") { $scope.update($scope.miEquipo); //$scope.miEquipoBackup = $scope.miEquipo; //$scope.miEquipoBackup = JSON.parse(JSON.stringify($scope.miEquipo)); //$scope.miEquipoBackup = jQuery.extend({}, $scope.miEquipo); } }; /* Funcion que envia los datos del nuevo equipo al servidor */ $scope.enviarEquipo = function(tipo){ $.LoadingOverlay("show"); console.log("entro a eviar.."); /* Envio request al servidor */ $http.post("UpdTeamUser", { data: {nombre: $scope.miEquipo.nombre, jugadores: $scope.miEquipo.integrantes} }) .then(function(response) { // $scope.registro.integrantes = []; console.log("imprimo respuesta.."); console.log(response); // Mensaje //w3.hide('#register'); w3.hide('#confirmTeam'); w3.hide('#confirmTransfer'); NeAlert(response.data.state, "Atencion!", response.data.message); //si la respuesta fue exitosa $scope.update(); $scope.clear(); $scope.setModified(false); if (tipo === 'DEF') { $scope.jugadoresBackup = {}; $scope.jugadores = {}; $scope.misJugadoresBackup = {}; $scope.misJugadores = {}; $scope.getSesion(); $scope.getJugadores(); $scope.getMisJugadores(); } $.LoadingOverlay("hide"); }, function(response) { //Second function handles error alert('Error al intentar enviar datos del nuevo equipo.'); alert(response); $.LoadingOverlay("hide"); }); }; $scope.readyDefaultTeam = false; /* Funcion que verifica que los datos del nuevo equipo esten listos para enviar al servidor */ $scope.setReadyDefaultTeam = function(){ //Verifica que tenga seleccionados todos los jugadores //console.log('integrantes '+$scope.miEquipo.integrantes.length+'/'+$scope.misJugadores.length); $scope.readyDefaultTeam = !($scope.miEquipo.integrantes.length < $scope.misJugadores.length); }; $scope.readyTeam = false; /* Funcion que verifica que los datos del equipo esten listos para enviar al servidor */ $scope.setReadyTeam = function(){ //Verifica que tenga seleccionados todos los jugadores, capitan y sub-capitan y que haya sido modificado //console.log('integrantes '+$scope.miEquipo.integrantes.length); $scope.readyTeam = !($scope.miEquipo.integrantes.length < $scope.misJugadores.length || $scope.miEquipo.subcaptain === null || $scope.miEquipo.captain === null) && $scope.modified; }; /* Funcion que envia los datos del nuevo equipo al servidor */ $scope.enviarEquipoDefault = function(){ if(!($scope.readyDefaultTeam)) { NeAlert("ERROR", "Atencion!", "Debe seleccionar " + $scope.misJugadores.length + " jugadores."); return false; } if (!($("#teamName").val())) { NeAlert("ERROR", "Atencion!", "Debe ingresar el nombre de su equipo."); return false; } $scope.enviarEquipo('DEF'); }; /* Funcion para cambiar el mensaje */ $scope.setMessage = function(message) { $scope.message = message; //Hace el cambio de vista }; /* Funcion para ordenar tabla */ $scope.sort = function(keyname){ console.log('entro a ordenar por:'+keyname); $scope.sortKey = keyname; //set the sortKey to the param passed $scope.reverse = !$scope.reverse; //if true make it false and vice versa }; /* Funcion para mostrar/ocultar menu */ $scope.toggleMenu = function(){ NeToggleMenu(); }; /* Funcion para cambiar pagina de tabla */ $scope.setPage = function(page) { if (page < 1 || page > $scope.pager.totalPages) { return; } // get pager object from service $scope.pager = PagerService.GetPager($scope.jugadores.length, page); // get current page of items $scope.items = $scope.jugadores.slice($scope.pager.startIndex, $scope.pager.endIndex + 1); }; console.log("inicializo aplicacion.."); $scope.getSesion(); $scope.getMenu(); $scope.getJugadores(); $scope.getMisJugadores(); $scope.getPosiciones(); } ControllerJugador.$inject = ['$scope', '$http', 'PagerService']; /* Funcion para navegacion */ function RouteProvider($routeProvider) { $routeProvider .when("/def", { templateUrl : "main_def.html"/*, controller: 'ControllerJugador'*/ }) .when("/team", { templateUrl : "main_team.html"/*, controller: 'ControllerJugador'*/ }) .when("/league", { templateUrl : "main_league.html"/*, controller: 'ControllerJugador'*/ }) .when("/score", { templateUrl : "main_score.html"/*, controller: 'ControllerJugador'*/ }) .when("/help", { templateUrl : "main_help.html"/*, controller: 'ControllerJugador'*/ }) ; }
{ "content_hash": "3db469f917787fe2a08f08d819a70ece", "timestamp": "", "source": "github", "line_count": 727, "max_line_length": 188, "avg_line_length": 38.082530949105916, "alnum_prop": 0.5371667991042404, "repo_name": "jtsoya539/proyecto-ne", "id": "e7cb58a69bdbf8891acf7c96c356e026e6308cbe", "size": "27688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/js/app.jugador.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "283989" }, { "name": "HTML", "bytes": "132470" }, { "name": "Java", "bytes": "63967" }, { "name": "JavaScript", "bytes": "96912" } ], "symlink_target": "" }
package biz.paluch.spinach.api.sync; /** * Asynchronous executed commands related with Disque Cluster. * * @param <K> Key type. * @param <V> Value type. * @author Mark Paluch */ public interface DisqueClusterCommands<K, V> { /** * Blacklist and remove the cluster node from the cluster. * * @param nodeId the node Id * @return String simple-string-reply */ String clusterForget(String nodeId); /** * Get information and statistics about the cluster viewed by the current node. * * @return String bulk-string-reply as a collection of text lines. */ String clusterInfo(); /** * Retrieve cluster leaving state. * * @return String simple-string-reply */ String clusterLeaving(); /** * Enable/disable cluster leaving state for a graceful cluster leave. * * @param state {@literal true} to set the leaving state, {@literal false} to un-set the leaving state * @return String simple-string-reply */ String clusterLeaving(boolean state); /** * Meet another cluster node to include the node into the cluster. The command starts the cluster handshake and returns with * {@literal OK} when the node was added to the cluster. * * @param ip IP address of the host * @param port port number. * @return String simple-string-reply */ String clusterMeet(String ip, int port); /** * Obtain the nodeId for the currently connected node. * * @return String simple-string-reply */ String clusterMyId(); /** * Obtain details about all cluster nodes. Can be parsed using {@link biz.paluch.spinach.cluster.ClusterNodesParser#parse} * * @return String bulk-string-reply as a collection of text lines */ String clusterNodes(); /** * Reset a node performing a soft or hard reset: * <ul> * <li>All other nodes are forgotten</li> * <li>All the assigned / open slots are released</li> * <li>If the node is a slave, it turns into a master</li> * <li>Only for hard reset: a new Node ID is generated</li> * <li>Only for hard reset: currentEpoch and configEpoch are set to 0</li> * <li>The new configuration is saved and the cluster state updated</li> * <li>If the node was a slave, the whole data set is flushed away</li> * </ul> * * @param hard {@literal true} for hard reset. Generates a new nodeId and currentEpoch/configEpoch are set to 0 * @return String simple-string-reply */ String clusterReset(boolean hard); /** * Save the cluster config. * * @return String simple-string-reply */ String clusterSaveconfig(); }
{ "content_hash": "6c288abcc5739108f0a7f8e0594c8b10", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 128, "avg_line_length": 30.032967032967033, "alnum_prop": 0.6425173801683132, "repo_name": "mp911de/spinach", "id": "20240853c5a28010fd5ec76849d075fa8bbcadfa", "size": "3348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/biz/paluch/spinach/api/sync/DisqueClusterCommands.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "390956" }, { "name": "Makefile", "bytes": "3781" } ], "symlink_target": "" }
require 'spec_helper' describe Group do let(:group) do group = Group.new(1) group.instance_variable_set(:@squares, squares) group end describe '#calculate_operator_and_value' do context 'all operators' do context 'group with one square' do let(:squares) { [Square.new(1)] } it 'calculate expected value, no operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(1) expect(group.operator).to eq(Group::NIL) end end context 'group with two squares' do context 'picks division' do before do expect(group).to receive(:sample_any_operator) .and_return(Group::DIV) end context 'number divides evenly' do let(:squares) { [Square.new(4), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(2) expect(group.operator).to eq(Group::DIV) end end context 'number does not divide evenly, picks addition' do before do expect(group).to receive(:sample_any_operator_but_div) .and_return(Group::ADD) end let(:squares) { [Square.new(3), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(11) expect(group.operator).to eq(Group::ADD) end end context 'number does not divide evenly, picks subtraction' do before do expect(group).to receive(:sample_any_operator_but_div) .and_return(Group::SUB) end let(:squares) { [Square.new(3), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(5) expect(group.operator).to eq(Group::SUB) end end end context 'picks subtraction' do before do expect(group).to receive(:sample_any_operator) .and_return(Group::SUB) end let(:squares) { [Square.new(4), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(4) expect(group.operator).to eq(Group::SUB) end end context 'picks multiplication' do before do expect(group).to receive(:sample_any_operator) .and_return(Group::MULT) end let(:squares) { [Square.new(4), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(32) expect(group.operator).to eq(Group::MULT) end end context 'picks addition' do before do expect(group).to receive(:sample_any_operator) .and_return(Group::ADD) end let(:squares) { [Square.new(4), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(12) expect(group.operator).to eq(Group::ADD) end end end context 'group with >2 squares' do before do # it does not pick from all operators expect(group).to_not receive(:sample_any_operator) expect(group).to_not receive(:sample_any_operator_but_div) end context 'picks multiplication' do before do expect(group).to receive(:sample_commutative_operators) .and_return(Group::MULT) end let(:squares) { [Square.new(4), Square.new(2), Square.new(3)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(24) expect(group.operator).to eq(Group::MULT) end end context 'picks addition' do before do expect(group).to receive(:sample_commutative_operators) .and_return(Group::ADD) end let(:squares) { [Square.new(4), Square.new(8), Square.new(1)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:all) expect(group.value).to eq(13) expect(group.operator).to eq(Group::ADD) end end end end context 'commutative operators' do context 'group with one square' do let(:squares) { [Square.new(1)] } it 'calculate expected value, no operator' do group.calculate_operator_and_value(:commutative) expect(group.value).to eq(1) expect(group.operator).to eq(Group::NIL) end end context 'group with two squares' do before do expect(group).to receive(:sample_any_operator) .with(:commutative).and_call_original end context 'picks multiplication' do before do expect(group).to receive(:sample_commutative_operators) .and_return(Group::MULT) end let(:squares) { [Square.new(4), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:commutative) expect(group.value).to eq(32) expect(group.operator).to eq(Group::MULT) end end context 'picks addition' do before do expect(group).to receive(:sample_commutative_operators) .and_return(Group::ADD) end let(:squares) { [Square.new(4), Square.new(8)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:commutative) expect(group.value).to eq(12) expect(group.operator).to eq(Group::ADD) end end end context 'group with >2 squares' do before do # it does not pick from all operators expect(group).to_not receive(:sample_any_operator) expect(group).to_not receive(:sample_any_operator_but_div) end context 'picks multiplication' do before do expect(group).to receive(:sample_commutative_operators) .and_return(Group::MULT) end let(:squares) { [Square.new(4), Square.new(2), Square.new(3)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:commutative) expect(group.value).to eq(24) expect(group.operator).to eq(Group::MULT) end end context 'picks addition' do before do expect(group).to receive(:sample_commutative_operators) .and_return(Group::ADD) end let(:squares) { [Square.new(4), Square.new(8), Square.new(1)] } it 'calculates expected value and operator' do group.calculate_operator_and_value(:commutative) expect(group.value).to eq(13) expect(group.operator).to eq(Group::ADD) end end end end context 'addition only' do context 'group with one square' do let(:squares) { [Square.new(1)] } it 'calculate expected value, no operator' do group.calculate_operator_and_value(:addition) expect(group.value).to eq(1) expect(group.operator).to eq(Group::NIL) end end context 'group with two squares' do let(:squares) { [Square.new(4), Square.new(8)] } it 'calculates expected value and operator' do expect(group).to receive(:sample_any_operator) .and_call_original expect(group).to receive(:sample_commutative_operators) .and_call_original group.calculate_operator_and_value(:addition) expect(group.value).to eq(12) expect(group.operator).to eq(Group::ADD) end end context 'group with >2 squares' do before do # it does not pick from all operators expect(group).to_not receive(:sample_any_operator) expect(group).to_not receive(:sample_any_operator_but_div) end let(:squares) { [Square.new(4), Square.new(8), Square.new(1)] } it 'calculates expected value and operator' do expect(group).to receive(:sample_commutative_operators) .and_call_original group.calculate_operator_and_value(:addition) expect(group.value).to eq(13) expect(group.operator).to eq(Group::ADD) end end end end end
{ "content_hash": "7017c82d6538443d43c274c53bca343e", "timestamp": "", "source": "github", "line_count": 306, "max_line_length": 73, "avg_line_length": 31.143790849673202, "alnum_prop": 0.5372507869884575, "repo_name": "srhmgn/kendrino", "id": "314a1b64bcf5d358ed19adb5a72daeaaf85b37f5", "size": "9530", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/app/lib/kenken/group_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11870" }, { "name": "CoffeeScript", "bytes": "8361" }, { "name": "HTML", "bytes": "6050" }, { "name": "JavaScript", "bytes": "126" }, { "name": "Ruby", "bytes": "76897" } ], "symlink_target": "" }
/*. 公用 */ .nav-toggle{ display: none } .phone-landscape .headContainer ul,.phone-portrait .headContainer ul{ float: left; } /*. phone-portrait 手机竖屏 */ .phone-portrait .nav-toggle{ display: block; } .phone-portrait .xs-hide{ visibility: hidden; max-height: 0; opacity: 0; transition: all 400ms; } .phone-portrait .xs-show{ visibility: visible; opacity: 1; max-height: 400px; transition: all 400ms; } .phone-portrait .u-widget{ background: none; } .phone-portrait .headContainer .u-col-md-3{ width: 100%; } .phone-portrait .headContainer .u-col-md-9{ width: 100%; } .phone-portrait .headContainer ul{ padding: 0; } .phone-portrait .headContainer ul li{ display: block; } .phone-portrait .carousel-indicators{ bottom: -7px; } .phone-portrait .carousel-caption{ padding-bottom: 0; } .phone-portrait .u-gallery .u-col-md-4{ width: 100%; } .phone-portrait .u-media.u-col-md-3{ width: 100%; } .phone-portrait #tab-panel-2 .product-bottom{ min-height: 797px; background-repeat: repeat; } .phone-portrait #tab-panel-3{ padding-top: 135%; } .phone-portrait .idea{ width: 50%; } .phone-portrait .footers .contact .u-col-md-7{ width: 100%; } .phone-portrait .footers .contact .u-col-md-6{ width: 100%; } .phone-portrait .footers .contact .u-col-md-5{ width: 100%; } .phone-portrait .headContaineryy .u-col-md-9{ width: 100% } .phone-portrait .info h1{ font-size: 30px; } .phone-portrait .info h3{ font-size: 16px; } .phone-portrait .banner-content .info{ margin-top: 60px; } .phone-portrait .product-nav .u-col-md-2{ width: 32%; } .phone-portrait .contact-ways{ margin-left: 30px; } /*. phone-portrait 手机横屏 */ .phone-landscape .footers .contact .u-col-md-7{ width: 100%; } .phone-landscape .footers .contact .u-col-md-6{ width: 100%; } .phone-landscape .footers .contact .u-col-md-5{ width: 100%; } .phone-landscape .idea{ width: 50%; } .phone-landscape .u-media.u-col-md-3{ width: 50%; } .phone-landscape #tab-panel-2 .product-bottom{ min-height: 470px; background-repeat: repeat; } .phone-landscape #tab-panel-3{ padding-top: 23%; } .phone-landscape .product-nav .u-col-md-2{ width: 18%; } .phone-landscape .nav-toggle{ display: block; } .phone-landscape .xs-hide{ visibility: hidden; height: 0; transition: height 400ms } .phone-landscape .xs-show{ visibility: visible; height: 400px; transition: height 400ms } .phone-landscape .u-widget{ background: none; } .phone-landscape .headContainer .u-col-md-3{ width: 100%; } .phone-landscape .headContainer .u-col-md-9{ width: 100%; } .phone-landscape .headContainer ul{ padding: 0; } .phone-landscape .headContainer ul li{ display: block; } /*tablet-portrait*/ .tablet-portrait .info h1{ font-size: 40px; } .tablet-portrait .info h3{ font-size: 20px; } .tablet-portrait .u-media.u-col-md-3{ width: 50%; } .tablet-portrait #tab-panel-2 .product-bottom{ min-height: 470px; background-repeat: repeat; } .tablet-portrait #tab-panel-3{ padding-top: 20%; } .tablet-portrait .footers .contact .u-col-md-7{ width: 100%; } .tablet-portrait .footers .contact .u-col-md-6{ width: 100%; } .tablet-portrait .footers .contact .u-col-md-5{ width: 100%; }
{ "content_hash": "bebf205b64d1d81788359ff6a0fc19bd", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 69, "avg_line_length": 17.748603351955307, "alnum_prop": 0.6849228832231665, "repo_name": "iuap-design/designer", "id": "dca06b02262a150738a397bbc16f1989a496829c", "size": "3197", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "static/css/grid.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "257302" }, { "name": "HTML", "bytes": "225511" }, { "name": "JavaScript", "bytes": "2022311" } ], "symlink_target": "" }
--- uid: SolidEdgeFramework.TextCharStyles.Remove(System.String) summary: remarks: syntax: parameters: - id: Name description: Specifies the name of the item to be removed. ---
{ "content_hash": "9007f0675830b017a84d7b013468abc9", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 64, "avg_line_length": 21.555555555555557, "alnum_prop": 0.7010309278350515, "repo_name": "SolidEdgeCommunity/docs", "id": "46225a523ad0a57b397bdac1d6a1bb652f588c4f", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docfx_project/apidoc/SolidEdgeFramework.TextCharStyles.Remove.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "38" }, { "name": "C#", "bytes": "5048212" }, { "name": "C++", "bytes": "2265" }, { "name": "CSS", "bytes": "148" }, { "name": "PowerShell", "bytes": "180" }, { "name": "Smalltalk", "bytes": "1996" }, { "name": "Visual Basic", "bytes": "10236277" } ], "symlink_target": "" }
namespace mitk { class MITKCONTOURMODEL_EXPORT ContourModelSetSerializer : public BaseDataSerializer { public: mitkClassMacro(ContourModelSetSerializer, BaseDataSerializer); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual std::string Serialize() override; protected: ContourModelSetSerializer(); virtual ~ContourModelSetSerializer(); }; } #endif // MITKCONTOURMODELSETSERIALIZER_H
{ "content_hash": "88aeba6974b59c4313eae8904d568312", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 85, "avg_line_length": 25, "alnum_prop": 0.7741176470588236, "repo_name": "RabadanLab/MITKats", "id": "66a8ae58df47e064cb0a19c350987acec490da0d", "size": "580", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Modules/ContourModel/IO/mitkContourModelSetSerializer.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "3346369" }, { "name": "C++", "bytes": "31343449" }, { "name": "CMake", "bytes": "1009499" }, { "name": "CSS", "bytes": "118558" }, { "name": "HTML", "bytes": "102168" }, { "name": "JavaScript", "bytes": "162600" }, { "name": "Jupyter Notebook", "bytes": "228462" }, { "name": "Makefile", "bytes": "25077" }, { "name": "Objective-C", "bytes": "26578" }, { "name": "Python", "bytes": "275885" }, { "name": "QML", "bytes": "28009" }, { "name": "QMake", "bytes": "5583" }, { "name": "Shell", "bytes": "1261" } ], "symlink_target": "" }
package org.apache.struts2.views.java; import org.apache.struts2.StrutsException; import org.apache.struts2.components.template.TemplateRenderingContext; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; /** * Default implementation of the theme */ public class DefaultTheme implements Theme { private static final Logger LOG = LoggerFactory.getLogger(DefaultTheme.class); private String name; protected Map<String, List<TagHandlerFactory>> handlerFactories; protected void setName(String name) { this.name = name; } protected void setHandlerFactories(Map<String, List<TagHandlerFactory>> handlers) { this.handlerFactories = handlers; } /** * Set (replace if exists) the tag handler factories for specific tag * * @param tagName * @param handlers */ protected void setTagHandlerFactories(String tagName, List<TagHandlerFactory> handlers) { if (tagName != null && handlers != null && this.handlerFactories != null) { handlerFactories.put(tagName, handlers); } } /** * Insert a new tag handler into a sequence of tag handlers for a specific tag * TODO: Need to take care of serializers, if handler specified is not a TagSerializer it should never * be placed after the serializer, but if it is not a TagSerializer, it should never * * @param tagName * @param sequence * @param factory */ protected void insertTagHandlerFactory(String tagName, int sequence, TagHandlerFactory factory) { if (tagName != null && factory != null && this.handlerFactories != null) { List<TagHandlerFactory> tagHandlerFactories = handlerFactories.get(tagName); if (tagHandlerFactories == null) { tagHandlerFactories = new ArrayList<TagHandlerFactory>(); //TODO: Could use public FactoryList here } if (sequence > tagHandlerFactories.size()) { sequence = tagHandlerFactories.size(); } //TODO, need to account for TagHandlers vs. TagSerializers here tagHandlerFactories.add(sequence, factory); } } public String getName() { return name; } public void renderTag(String tagName, TemplateRenderingContext context) { if (tagName.endsWith(".java")) { tagName = tagName.substring(0, tagName.length() - ".java".length()); } List<TagHandler> handlers = new ArrayList<TagHandler>(); List<TagHandlerFactory> factories = handlerFactories.get(tagName); if (factories == null) { throw new StrutsException("Unable to find handlers for tag " + tagName); } TagHandler prev = null; for (int x = factories.size() - 1; x >= 0; x--) { prev = factories.get(x).create(prev); prev.setup(context); handlers.add(0, prev); } // TagSerializer ser = (TagSerializer) handlers.get(handlers.size() - 1); TagGenerator gen = (TagGenerator) handlers.get(0); try { if (LOG.isTraceEnabled()) LOG.trace("Rendering tag [#0]", tagName); gen.generate(); } catch (IOException ex) { throw new StrutsException("Unable to write tag: " + tagName); } } }
{ "content_hash": "b91b4bacf4a1baf34e701d5517739d33", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 115, "avg_line_length": 32.80373831775701, "alnum_prop": 0.6393162393162393, "repo_name": "WillJiang/WillJiang", "id": "8ab92648113f408a70929c44d77a85bcca82bdf4", "size": "4384", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/plugins/javatemplates/src/main/java/org/apache/struts2/views/java/DefaultTheme.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "22970" }, { "name": "CSS", "bytes": "74192" }, { "name": "Java", "bytes": "9706375" }, { "name": "JavaScript", "bytes": "4013533" }, { "name": "XSLT", "bytes": "8414" } ], "symlink_target": "" }
fn.bind(ctx, arg1, arg2) // is equivalent to function(arg1, arg2) { return fn.call(ctx, arg1, arg2); } // Lemma 2: fn.bind(context, arg, arg2); // is equivalent to Function.prototype.bind.call(fn, context, arg1, arg2); // Lemma 3: fn.call(ctx, arg1, arg2); // is equivalent to Function.prototype.call.call(fn, ctx, arg1, arg2); //////////////////////////////////////////////////////////////////////////////// function variadicBind(fn, ctx, arg1, arg2) { return fn.bind(ctx, arg1, arg2); } //////////////////////////////////////////////////////////////////////////////// function variadicBind(fn, ctx, arg1, arg2) { return Function.prototype.bind.call( fn, ctx, arg1, arg2 ); /////////////////////// } //////////////////////////////////////////////////////////////////////////////// function variadicBind(fn, ctx, arg1, arg2) { return Function.prototype.call.call(Function.prototype.bind, fn, ctx, arg1, arg2); /////////// fn //////// ////////// ctx //////// // arg1, ... ////// } //////////////////////////////////////////////////////////////////////////////// Function.prototype.call.bind(Function.prototype.bind, fn, ctx, arg1, arg2); //////////////////////////////////////////////////////////////////////////////// Function.prototype.call.bind(Function.prototype.bind);
{ "content_hash": "cd3fcd8524fcb80db570385b60fa8d2e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 83, "avg_line_length": 40.65625, "alnum_prop": 0.4396617986164489, "repo_name": "v0lkan/fun-with-functions", "id": "adbb00240c4adfe9e9df5c5f12344a11b16ca8ad", "size": "1313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "session-001/proof.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "41502" } ], "symlink_target": "" }
namespace isp_button_monitor { // ISP button is attached to GPIO0_1. // TODO: define in arm_pro_mini consts for ISP button and LED ports. static const uint8 ISP_BUTTON_PORT = 0; static const uint8 ISP_BUTTON_BIT = 1; void setup() { Chip_GPIO_SetPinDIRInput(LPC_GPIO, ISP_BUTTON_PORT, ISP_BUTTON_BIT); } void loop() { // If the button is pressed (low), then jump to ROM's ISP mode. // // TODO: add basic debouncing (e.g. N consecutive cycle with button pressed). Not that // we need it but just in case. if (!Chip_GPIO_ReadPortBit(LPC_GPIO, ISP_BUTTON_PORT, ISP_BUTTON_BIT)) { arm_pro_mini::ReinvokeISP(); } } } // namespace isp_button_monitor
{ "content_hash": "a98a7a88af3fd56d42765274d6c85f83", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 88, "avg_line_length": 30.318181818181817, "alnum_prop": 0.6926536731634183, "repo_name": "Xenon-Photon/Arm", "id": "f29b16b3ae2ba13dcb140ced5d39cd957527dc39", "size": "745", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Smart-Garden-Lights/Smart-Garden-Lights/arm_pro_mini_lib/src/isp_button_monitor.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "393" }, { "name": "C", "bytes": "579191" }, { "name": "C++", "bytes": "157784" }, { "name": "Makefile", "bytes": "386970" } ], "symlink_target": "" }
package #PACKAGE_NAME#.dto; import java.io.Serializable; /** * Created by Juan Manuel Romera on 28/5/2017. */ public class User implements Serializable { private String name; private String email; private String password; public User(String name, String email, String password) { this.name = name; this.email = email; this.password = password; } public String getName() { return name; } public String getEmail() { return email; } public String getPassword() { return password; } }
{ "content_hash": "20072822c26936f715853b2b71a3b2c7", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 61, "avg_line_length": 18.21875, "alnum_prop": 0.6174957118353345, "repo_name": "juanmanuelromeraferrio/start-android", "id": "0ddad72dfe3826a3c95ca25fb141acb2165711a9", "size": "583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/main/resources/source/package/java/dto/User.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4406" }, { "name": "HTML", "bytes": "163" }, { "name": "Java", "bytes": "63831" }, { "name": "JavaScript", "bytes": "34024" } ], "symlink_target": "" }
//===--- Module.h - Swift Language Module ASTs ------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the Module class and its subclasses. // //===----------------------------------------------------------------------===// #ifndef SWIFT_MODULE_H #define SWIFT_MODULE_H #include "swift/AST/Decl.h" #include "swift/AST/DeclContext.h" #include "swift/AST/Identifier.h" #include "swift/AST/LookupKinds.h" #include "swift/AST/RawComment.h" #include "swift/AST/Type.h" #include "swift/Basic/OptionSet.h" #include "swift/Basic/SourceLoc.h" #include "swift/Basic/STLExtras.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MD5.h" namespace clang { class Module; } namespace swift { enum class ArtificialMainKind : uint8_t; class ASTContext; class ASTScope; class ASTWalker; class BraceStmt; class Decl; class DeclAttribute; class TypeDecl; enum class DeclKind : uint8_t; class ExtensionDecl; class DebuggerClient; class DeclName; class FileUnit; class FuncDecl; class InfixOperatorDecl; class LinkLibrary; class LookupCache; class ModuleLoader; class NameAliasType; class NominalTypeDecl; class EnumElementDecl; class OperatorDecl; class PostfixOperatorDecl; class PrefixOperatorDecl; class ProtocolConformance; class ProtocolDecl; struct PrintOptions; class ReferencedNameTracker; class TupleType; class Type; class TypeRefinementContext; class ValueDecl; class VarDecl; class VisibleDeclConsumer; /// Discriminator for file-units. enum class FileUnitKind { /// For a .swift source file. Source, /// For the compiler Builtin module. Builtin, /// A serialized Swift AST. SerializedAST, /// An imported Clang module. ClangModule, /// A derived declaration. Derived, }; enum class SourceFileKind { Library, ///< A normal .swift file. Main, ///< A .swift file that can have top-level code. REPL, ///< A virtual file that holds the user's input in the REPL. SIL ///< Came from a .sil file. }; /// Discriminator for resilience strategy. enum class ResilienceStrategy : unsigned { /// Public nominal types: fragile /// Non-inlineable function bodies: resilient /// /// This is the default behavior without any flags. Default, /// Public nominal types: resilient /// Non-inlineable function bodies: resilient /// /// This is the behavior with -enable-resilience. Resilient, /// Public nominal types: fragile /// Non-inlineable function bodies: fragile /// /// This is the behavior with -sil-serialize-all. Fragile }; /// The minimum unit of compilation. /// /// A module is made up of several file-units, which are all part of the same /// output binary and logical module (such as a single library or executable). /// /// \sa FileUnit class ModuleDecl : public TypeDecl, public DeclContext { public: typedef ArrayRef<std::pair<Identifier, SourceLoc>> AccessPathTy; typedef std::pair<ModuleDecl::AccessPathTy, ModuleDecl*> ImportedModule; static bool matchesAccessPath(AccessPathTy AccessPath, DeclName Name) { assert(AccessPath.size() <= 1 && "can only refer to top-level decls"); return AccessPath.empty() || DeclName(AccessPath.front().first).matchesRef(Name); } /// Arbitrarily orders ImportedModule records, for inclusion in sets and such. class OrderImportedModules { public: bool operator()(const ImportedModule &lhs, const ImportedModule &rhs) const { if (lhs.second != rhs.second) return std::less<const ModuleDecl *>()(lhs.second, rhs.second); if (lhs.first.data() != rhs.first.data()) return std::less<AccessPathTy::iterator>()(lhs.first.begin(), rhs.first.begin()); return lhs.first.size() < rhs.first.size(); } }; private: /// If non-NULL, an plug-in that should be used when performing external /// lookups. // FIXME: Do we really need to bloat all modules with this? DebuggerClient *DebugClient = nullptr; SmallVector<FileUnit *, 2> Files; /// Tracks the file that will generate the module's entry point, either /// because it contains a class marked with \@UIApplicationMain /// or \@NSApplicationMain, or because it is a script file. class EntryPointInfoTy { enum class Flags { DiagnosedMultipleMainClasses = 1 << 0, DiagnosedMainClassWithScript = 1 << 1 }; llvm::PointerIntPair<FileUnit *, 2, OptionSet<Flags>> storage; public: EntryPointInfoTy() = default; FileUnit *getEntryPointFile() const { return storage.getPointer(); } void setEntryPointFile(FileUnit *file) { assert(!storage.getPointer()); storage.setPointer(file); } bool hasEntryPoint() const { return storage.getPointer(); } bool markDiagnosedMultipleMainClasses() { bool res = storage.getInt().contains(Flags::DiagnosedMultipleMainClasses); storage.setInt(storage.getInt() | Flags::DiagnosedMultipleMainClasses); return !res; } bool markDiagnosedMainClassWithScript() { bool res = storage.getInt().contains(Flags::DiagnosedMainClassWithScript); storage.setInt(storage.getInt() | Flags::DiagnosedMainClassWithScript); return !res; } }; /// Information about the file responsible for the module's entry point, /// if any. /// /// \see EntryPointInfoTy EntryPointInfoTy EntryPointInfo; struct { unsigned TestingEnabled : 1; unsigned FailedToLoad : 1; unsigned ResilienceStrategy : 2; } Flags; /// The magic __dso_handle variable. VarDecl *DSOHandle; ModuleDecl(Identifier name, ASTContext &ctx); public: static ModuleDecl *create(Identifier name, ASTContext &ctx) { return new (ctx) ModuleDecl(name, ctx); } using Decl::getASTContext; ArrayRef<FileUnit *> getFiles() { return Files; } ArrayRef<const FileUnit *> getFiles() const { return { Files.begin(), Files.size() }; } void addFile(FileUnit &newFile); void removeFile(FileUnit &existingFile); /// Convenience accessor for clients that know what kind of file they're /// dealing with. SourceFile &getMainSourceFile(SourceFileKind expectedKind) const; /// Convenience accessor for clients that know what kind of file they're /// dealing with. FileUnit &getMainFile(FileUnitKind expectedKind) const; DebuggerClient *getDebugClient() const { return DebugClient; } void setDebugClient(DebuggerClient *R) { assert(!DebugClient && "Debugger client already set"); DebugClient = R; } /// Returns true if this module was or is being compiled for testing. bool isTestingEnabled() const { return Flags.TestingEnabled; } void setTestingEnabled(bool enabled = true) { Flags.TestingEnabled = enabled; } /// Returns true if there was an error trying to load this module. bool failedToLoad() const { return Flags.FailedToLoad; } void setFailedToLoad(bool failed = true) { Flags.FailedToLoad = failed; } ResilienceStrategy getResilienceStrategy() const { return ResilienceStrategy(Flags.ResilienceStrategy); } void setResilienceStrategy(ResilienceStrategy strategy) { Flags.ResilienceStrategy = unsigned(strategy); } /// Look up a (possibly overloaded) value set at top-level scope /// (but with the specified access path, which may come from an import decl) /// within the current module. /// /// This does a simple local lookup, not recursively looking through imports. void lookupValue(AccessPathTy AccessPath, DeclName Name, NLKind LookupKind, SmallVectorImpl<ValueDecl*> &Result) const; /// Look up a local type declaration by its mangled name. /// /// This does a simple local lookup, not recursively looking through imports. TypeDecl *lookupLocalType(StringRef MangledName) const; /// Find ValueDecls in the module and pass them to the given consumer object. /// /// This does a simple local lookup, not recursively looking through imports. void lookupVisibleDecls(AccessPathTy AccessPath, VisibleDeclConsumer &Consumer, NLKind LookupKind) const; /// @{ /// Look up the given operator in this module. /// /// If the operator is not found, or if there is an ambiguity, returns null. InfixOperatorDecl *lookupInfixOperator(Identifier name, SourceLoc diagLoc = {}); PrefixOperatorDecl *lookupPrefixOperator(Identifier name, SourceLoc diagLoc = {}); PostfixOperatorDecl *lookupPostfixOperator(Identifier name, SourceLoc diagLoc = {}); PrecedenceGroupDecl *lookupPrecedenceGroup(Identifier name, SourceLoc diagLoc = {}); /// @} /// Finds all class members defined in this module. /// /// This does a simple local lookup, not recursively looking through imports. void lookupClassMembers(AccessPathTy accessPath, VisibleDeclConsumer &consumer) const; /// Finds class members defined in this module with the given name. /// /// This does a simple local lookup, not recursively looking through imports. void lookupClassMember(AccessPathTy accessPath, DeclName name, SmallVectorImpl<ValueDecl*> &results) const; /// Look for the conformance of the given type to the given protocol. /// /// This routine determines whether the given \c type conforms to the given /// \c protocol. /// /// \param type The type for which we are computing conformance. /// /// \param protocol The protocol to which we are computing conformance. /// /// \param resolver The lazy resolver. /// /// \returns The result of the conformance search, which will be /// None if the type does not conform to the protocol or contain a /// ProtocolConformanceRef if it does conform. Optional<ProtocolConformanceRef> lookupConformance(Type type, ProtocolDecl *protocol, LazyResolver *resolver); /// Find a member named \p name in \p container that was declared in this /// module. /// /// \p container may be \c this for a top-level lookup. /// /// If \p privateDiscriminator is non-empty, only matching private decls are /// returned; otherwise, only non-private decls are returned. void lookupMember(SmallVectorImpl<ValueDecl*> &results, DeclContext *container, DeclName name, Identifier privateDiscriminator) const; /// Find all Objective-C methods with the given selector. void lookupObjCMethods( ObjCSelector selector, SmallVectorImpl<AbstractFunctionDecl *> &results) const; /// \sa getImportedModules enum class ImportFilter { All, Public, Private }; /// Looks up which modules are imported by this module. /// /// \p filter controls whether public, private, or any imports are included /// in this list. void getImportedModules(SmallVectorImpl<ImportedModule> &imports, ImportFilter filter = ImportFilter::Public) const; /// Looks up which modules are imported by this module, ignoring any that /// won't contain top-level decls. /// /// This is a performance hack. Do not use for anything but name lookup. /// May go away in the future. void getImportedModulesForLookup(SmallVectorImpl<ImportedModule> &imports) const; /// Finds all top-level decls of this module. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. void getTopLevelDecls(SmallVectorImpl<Decl*> &Results) const; /// Finds all local type decls of this module. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. void getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &Results) const; /// Finds all top-level decls that should be displayed to a client of this /// module. /// /// This includes types, variables, functions, and extensions. /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. /// /// This can differ from \c getTopLevelDecls, e.g. it returns decls from a /// shadowed clang module. void getDisplayDecls(SmallVectorImpl<Decl*> &results) const; /// @{ /// Perform an action for every module visible from this module. /// /// This only includes modules with at least one declaration visible: if two /// import access paths are incompatible, the indirect module will be skipped. /// Modules that can't be used for lookup (including Clang submodules at the /// time this comment was written) are also skipped under certain /// circumstances. /// /// \param topLevelAccessPath If present, include the top-level module in the /// results, with the given access path. /// \param includePrivateTopLevelImports If true, imports listed in all /// file units within this module are traversed. Otherwise (the /// default), only re-exported imports are traversed. /// \param fn A callback of type bool(ImportedModule) or void(ImportedModule). /// Return \c false to abort iteration. /// /// \return True if the traversal ran to completion, false if it ended early /// due to the callback. bool forAllVisibleModules(AccessPathTy topLevelAccessPath, bool includePrivateTopLevelImports, llvm::function_ref<bool(ImportedModule)> fn); bool forAllVisibleModules(AccessPathTy topLevelAccessPath, bool includePrivateTopLevelImports, llvm::function_ref<void(ImportedModule)> fn) { return forAllVisibleModules(topLevelAccessPath, includePrivateTopLevelImports, [=](const ImportedModule &import) -> bool { fn(import); return true; }); } template <typename Fn> bool forAllVisibleModules(AccessPathTy topLevelAccessPath, bool includePrivateTopLevelImports, Fn &&fn) { using RetTy = typename std::result_of<Fn(ImportedModule)>::type; llvm::function_ref<RetTy(ImportedModule)> wrapped{std::forward<Fn>(fn)}; return forAllVisibleModules(topLevelAccessPath, includePrivateTopLevelImports, wrapped); } template <typename Fn> bool forAllVisibleModules(AccessPathTy topLevelAccessPath, Fn &&fn) { return forAllVisibleModules(topLevelAccessPath, false, std::forward<Fn>(fn)); } /// @} using LinkLibraryCallback = llvm::function_ref<void(LinkLibrary)>; /// Generate the list of libraries needed to link this module, based on its /// imports. void collectLinkLibraries(LinkLibraryCallback callback); /// Returns true if the two access paths contain the same chain of /// identifiers. /// /// Source locations are ignored here. static bool isSameAccessPath(AccessPathTy lhs, AccessPathTy rhs); /// \brief Get the path for the file that this module came from, or an empty /// string if this is not applicable. StringRef getModuleFilename() const; /// \returns true if this module is the "swift" standard library module. bool isStdlibModule() const; /// \returns true if this module is the "SwiftShims" module; bool isSwiftShimsModule() const; /// \returns true if this module is the "builtin" module. bool isBuiltinModule() const; /// \returns true if this module is a system module; note that the StdLib is /// considered a system module. bool isSystemModule() const; /// \returns true if traversal was aborted, false otherwise. bool walk(ASTWalker &Walker); /// Register the file responsible for generating this module's entry point. /// /// \returns true if there was a problem adding this file. bool registerEntryPointFile(FileUnit *file, SourceLoc diagLoc, Optional<ArtificialMainKind> kind); /// \returns true if this module has a main entry point. bool hasEntryPoint() const { return EntryPointInfo.hasEntryPoint(); } /// Returns the associated clang module if one exists. const clang::Module *findUnderlyingClangModule(); SourceRange getSourceRange() const { return SourceRange(); } static bool classof(const DeclContext *DC) { return DC->getContextKind() == DeclContextKind::Module; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::Module; } private: // Make placement new and vanilla new/delete illegal for Modules. void *operator new(size_t Bytes) throw() = delete; // Work around MSVC error: attempting to reference a deleted function. #if !defined(_MSC_VER) && !defined(__clang__) void operator delete(void *Data) throw() = delete; #endif void *operator new(size_t Bytes, void *Mem) throw() = delete; public: // Only allow allocation of Modules using the allocator in ASTContext // or by doing a placement new. void *operator new(size_t Bytes, const ASTContext &C, unsigned Alignment = alignof(ModuleDecl)); }; static inline unsigned alignOfFileUnit(); /// A container for module-scope declarations that itself provides a scope; the /// smallest unit of code organization. /// /// FileUnit is an abstract base class; its subclasses represent different /// sorts of containers that can each provide a set of decls, e.g. a source /// file. A module can contain several file-units. class FileUnit : public DeclContext { virtual void anchor(); // FIXME: Stick this in a PointerIntPair. const FileUnitKind Kind; protected: FileUnit(FileUnitKind kind, ModuleDecl &M) : DeclContext(DeclContextKind::FileUnit, &M), Kind(kind) { } virtual ~FileUnit() = default; public: FileUnitKind getKind() const { return Kind; } /// Look up a (possibly overloaded) value set at top-level scope /// (but with the specified access path, which may come from an import decl) /// within this file. /// /// This does a simple local lookup, not recursively looking through imports. virtual void lookupValue(ModuleDecl::AccessPathTy accessPath, DeclName name, NLKind lookupKind, SmallVectorImpl<ValueDecl*> &result) const = 0; /// Look up a local type declaration by its mangled name. /// /// This does a simple local lookup, not recursively looking through imports. virtual TypeDecl *lookupLocalType(StringRef MangledName) const { return nullptr; } /// Find ValueDecls in the module and pass them to the given consumer object. /// /// This does a simple local lookup, not recursively looking through imports. virtual void lookupVisibleDecls(ModuleDecl::AccessPathTy accessPath, VisibleDeclConsumer &consumer, NLKind lookupKind) const {} /// Finds all class members defined in this file. /// /// This does a simple local lookup, not recursively looking through imports. virtual void lookupClassMembers(ModuleDecl::AccessPathTy accessPath, VisibleDeclConsumer &consumer) const {} /// Finds class members defined in this file with the given name. /// /// This does a simple local lookup, not recursively looking through imports. virtual void lookupClassMember(ModuleDecl::AccessPathTy accessPath, DeclName name, SmallVectorImpl<ValueDecl*> &results) const {} /// Find all Objective-C methods with the given selector. virtual void lookupObjCMethods( ObjCSelector selector, SmallVectorImpl<AbstractFunctionDecl *> &results) const = 0; /// Returns the comment attached to the given declaration. /// /// This function is an implementation detail for comment serialization. /// If you just want to get a comment attached to a decl, use /// \c Decl::getRawComment() or \c Decl::getBriefComment(). virtual Optional<CommentInfo> getCommentForDecl(const Decl *D) const { return None; } virtual Optional<StringRef> getGroupNameForDecl(const Decl *D) const { return None; } virtual Optional<StringRef> getSourceFileNameForDecl(const Decl *D) const { return None; } virtual Optional<unsigned> getSourceOrderForDecl(const Decl *D) const { return None; } virtual Optional<StringRef> getGroupNameByUSR(StringRef USR) const { return None; } virtual void collectAllGroups(std::vector<StringRef> &Names) const {} /// Returns an implementation-defined "discriminator" for \p D, which /// distinguishes \p D from other declarations in the same module with the /// same name. /// /// Since this value is used in name mangling, it should be a valid ASCII-only /// identifier. virtual Identifier getDiscriminatorForPrivateValue(const ValueDecl *D) const = 0; /// Finds all top-level decls in this file. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. virtual void getTopLevelDecls(SmallVectorImpl<Decl*> &results) const {} /// Finds all local type decls in this file. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. virtual void getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &results) const {} /// Adds all top-level decls to the given vector. /// /// This includes all decls that should be displayed to clients of the module. /// The order of the results is not guaranteed to be meaningful. /// /// This can differ from \c getTopLevelDecls, e.g. it returns decls from a /// shadowed clang module. virtual void getDisplayDecls(SmallVectorImpl<Decl*> &results) const { getTopLevelDecls(results); } /// Looks up which modules are imported by this file. /// /// \p filter controls whether public, private, or any imports are included /// in this list. virtual void getImportedModules(SmallVectorImpl<ModuleDecl::ImportedModule> &imports, ModuleDecl::ImportFilter filter) const {} /// \see ModuleDecl::getImportedModulesForLookup virtual void getImportedModulesForLookup( SmallVectorImpl<ModuleDecl::ImportedModule> &imports) const { return getImportedModules(imports, ModuleDecl::ImportFilter::Public); } /// Generates the list of libraries needed to link this file, based on its /// imports. virtual void collectLinkLibraries(ModuleDecl::LinkLibraryCallback callback) const {} /// @{ /// Perform an action for every module visible from this file. /// /// \param fn A callback of type bool(ImportedModule) or void(ImportedModule). /// Return \c false to abort iteration. /// /// \return True if the traversal ran to completion, false if it ended early /// due to the callback. bool forAllVisibleModules(llvm::function_ref<bool(ModuleDecl::ImportedModule)> fn); bool forAllVisibleModules(llvm::function_ref<void(ModuleDecl::ImportedModule)> fn) { return forAllVisibleModules([=](ModuleDecl::ImportedModule import) -> bool { fn(import); return true; }); } template <typename Fn> bool forAllVisibleModules(Fn &&fn) { using RetTy = typename std::result_of<Fn(ModuleDecl::ImportedModule)>::type; llvm::function_ref<RetTy(ModuleDecl::ImportedModule)> wrapped{ std::forward<Fn>(fn) }; return forAllVisibleModules(wrapped); } /// @} /// True if this file contains the main class for the module. bool hasMainClass() const { return getMainClass(); } virtual ClassDecl *getMainClass() const { assert(hasEntryPoint()); return nullptr; } virtual bool hasEntryPoint() const { return false; } /// Returns the associated clang module if one exists. virtual const clang::Module *getUnderlyingClangModule() { return nullptr; } /// Traverse the decls within this file. /// /// \returns true if traversal was aborted, false if it completed /// successfully. virtual bool walk(ASTWalker &walker); // Efficiency override for DeclContext::getParentModule(). ModuleDecl *getParentModule() const { return const_cast<ModuleDecl *>(cast<ModuleDecl>(getParent())); } static bool classof(const DeclContext *DC) { return DC->getContextKind() == DeclContextKind::FileUnit; } private: // Make placement new and vanilla new/delete illegal for FileUnits. void *operator new(size_t Bytes) throw() = delete; void *operator new(size_t Bytes, void *Mem) throw() = delete; protected: // Unfortunately we can't remove this altogether because the virtual // destructor requires it to be accessible. void operator delete(void *Data) throw() { llvm_unreachable("Don't use operator delete on a SourceFile"); } public: // Only allow allocation of FileUnits using the allocator in ASTContext // or by doing a placement new. void *operator new(size_t Bytes, ASTContext &C, unsigned Alignment = alignOfFileUnit()); }; static inline unsigned alignOfFileUnit() { return alignof(FileUnit&); } /// A file containing Swift source code. /// /// This is a .swift or .sil file (or a virtual file, such as the contents of /// the REPL). Since it contains raw source, it must be parsed and name-bound /// before being used for anything; a full type-check is also necessary for /// IR generation. class SourceFile final : public FileUnit { public: class LookupCache; class Impl; /// The implicit module import that the SourceFile should get. enum class ImplicitModuleImportKind { None, Builtin, Stdlib }; /// Possible attributes for imports in source files. enum class ImportFlags { /// The imported module is exposed to anyone who imports the parent module. Exported = 0x1, /// This source file has access to testable declarations in the imported /// module. Testable = 0x2 }; /// \see ImportFlags using ImportOptions = OptionSet<ImportFlags>; private: std::unique_ptr<LookupCache> Cache; LookupCache &getCache() const; /// This is the list of modules that are imported by this module. /// /// This is filled in by the Name Binding phase. ArrayRef<std::pair<ModuleDecl::ImportedModule, ImportOptions>> Imports; /// A unique identifier representing this file; used to mark private decls /// within the file to keep them from conflicting with other files in the /// same module. mutable Identifier PrivateDiscriminator; /// The root TypeRefinementContext for this SourceFile. /// /// This is set during type checking. TypeRefinementContext *TRC = nullptr; /// If non-null, used to track name lookups that happen within this file. ReferencedNameTracker *ReferencedNames = nullptr; /// The class in this file marked \@NS/UIApplicationMain. ClassDecl *MainClass = nullptr; /// The source location of the main class. SourceLoc MainClassDiagLoc; /// A hash of all interface-contributing tokens that have been lexed for /// this source file so far. llvm::MD5 InterfaceHash; /// \brief The ID for the memory buffer containing this file's source. /// /// May be -1, to indicate no association with a buffer. int BufferID; /// The list of protocol conformances that were "used" within this /// source file. llvm::SetVector<NormalProtocolConformance *> UsedConformances; /// The scope map that describes this source file. ASTScope *Scope = nullptr; friend ASTContext; friend Impl; ~SourceFile(); public: /// The list of top-level declarations in the source file. std::vector<Decl*> Decls; /// The list of local type declarations in the source file. llvm::SetVector<TypeDecl *> LocalTypeDecls; /// A set of special declaration attributes which require the /// Foundation module to be imported to work. If the foundation /// module is still not imported by the time type checking is /// complete, we diagnose. llvm::SetVector<const DeclAttribute *> AttrsRequiringFoundation; /// A mapping from Objective-C selectors to the methods that have /// those selectors. llvm::DenseMap<ObjCSelector, llvm::TinyPtrVector<AbstractFunctionDecl *>> ObjCMethods; template <typename T> using OperatorMap = llvm::DenseMap<Identifier,llvm::PointerIntPair<T,1,bool>>; OperatorMap<InfixOperatorDecl*> InfixOperators; OperatorMap<PostfixOperatorDecl*> PostfixOperators; OperatorMap<PrefixOperatorDecl*> PrefixOperators; OperatorMap<PrecedenceGroupDecl*> PrecedenceGroups; /// Describes what kind of file this is, which can affect some type checking /// and other behavior. const SourceFileKind Kind; enum ASTStage_t { /// Parsing is underway. Parsing, /// Parsing has completed. Parsed, /// Name binding has completed. NameBound, /// Type checking has completed. TypeChecked }; /// Defines what phases of parsing and semantic analysis are complete for a /// source file. /// /// Only files that have been fully processed (i.e. type-checked) will be /// forwarded on to IRGen. ASTStage_t ASTStage = Parsing; SourceFile(ModuleDecl &M, SourceFileKind K, Optional<unsigned> bufferID, ImplicitModuleImportKind ModImpKind); void addImports(ArrayRef<std::pair<ModuleDecl::ImportedModule, ImportOptions>> IM); bool hasTestableImport(const ModuleDecl *module) const; void clearLookupCache(); void cacheVisibleDecls(SmallVectorImpl<ValueDecl *> &&globals) const; const SmallVectorImpl<ValueDecl *> &getCachedVisibleDecls() const; virtual void lookupValue(ModuleDecl::AccessPathTy accessPath, DeclName name, NLKind lookupKind, SmallVectorImpl<ValueDecl*> &result) const override; virtual void lookupVisibleDecls(ModuleDecl::AccessPathTy accessPath, VisibleDeclConsumer &consumer, NLKind lookupKind) const override; virtual void lookupClassMembers(ModuleDecl::AccessPathTy accessPath, VisibleDeclConsumer &consumer) const override; virtual void lookupClassMember(ModuleDecl::AccessPathTy accessPath, DeclName name, SmallVectorImpl<ValueDecl*> &results) const override; void lookupObjCMethods( ObjCSelector selector, SmallVectorImpl<AbstractFunctionDecl *> &results) const override; virtual void getTopLevelDecls(SmallVectorImpl<Decl*> &results) const override; virtual void getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &results) const override; virtual void getImportedModules(SmallVectorImpl<ModuleDecl::ImportedModule> &imports, ModuleDecl::ImportFilter filter) const override; virtual void collectLinkLibraries(ModuleDecl::LinkLibraryCallback callback) const override; Identifier getDiscriminatorForPrivateValue(const ValueDecl *D) const override; Identifier getPrivateDiscriminator() const { return PrivateDiscriminator; } virtual bool walk(ASTWalker &walker) override; /// Note that the given conformance was used by this source file. void addUsedConformance(NormalProtocolConformance *conformance) { UsedConformances.insert(conformance); } /// Retrieve the set of conformances that were used in this source /// file. ArrayRef<NormalProtocolConformance *> getUsedConformances() const { return UsedConformances.getArrayRef(); } /// @{ /// Look up the given operator in this file. /// /// The file must be name-bound already. If the operator is not found, or if /// there is an ambiguity, returns null. /// /// \param isCascading If true, the lookup of this operator may affect /// downstream files. InfixOperatorDecl *lookupInfixOperator(Identifier name, bool isCascading, SourceLoc diagLoc = {}); PrefixOperatorDecl *lookupPrefixOperator(Identifier name, bool isCascading, SourceLoc diagLoc = {}); PostfixOperatorDecl *lookupPostfixOperator(Identifier name, bool isCascading, SourceLoc diagLoc = {}); PrecedenceGroupDecl *lookupPrecedenceGroup(Identifier name, bool isCascading, SourceLoc diagLoc = {}); /// @} ReferencedNameTracker *getReferencedNameTracker() const { return ReferencedNames; } void setReferencedNameTracker(ReferencedNameTracker *Tracker) { assert(!ReferencedNames && "This file already has a name tracker."); ReferencedNames = Tracker; } /// \brief The buffer ID for the file that was imported, or None if there /// is no associated buffer. Optional<unsigned> getBufferID() const { if (BufferID == -1) return None; return BufferID; } /// If this buffer corresponds to a file on disk, returns the path. /// Otherwise, return an empty string. StringRef getFilename() const; /// Retrieve the scope that describes this source file. ASTScope &getScope(); void dump() const; void dump(raw_ostream &os) const; /// \brief Pretty-print the contents of this source file. /// /// \param Printer The AST printer used for printing the contents. /// \param PO Options controlling the printing process. void print(ASTPrinter &Printer, const PrintOptions &PO); void print(raw_ostream &OS, const PrintOptions &PO); static bool classof(const FileUnit *file) { return file->getKind() == FileUnitKind::Source; } static bool classof(const DeclContext *DC) { return isa<FileUnit>(DC) && classof(cast<FileUnit>(DC)); } /// True if this is a "script mode" source file that admits top-level code. bool isScriptMode() const { switch (Kind) { case SourceFileKind::Main: case SourceFileKind::REPL: return true; case SourceFileKind::Library: case SourceFileKind::SIL: return false; } llvm_unreachable("bad SourceFileKind"); } ClassDecl *getMainClass() const override { return MainClass; } SourceLoc getMainClassDiagLoc() const { assert(hasMainClass()); return MainClassDiagLoc; } /// Register a "main" class for the module, complaining if there is more than /// one. /// /// Should only be called during type-checking. bool registerMainClass(ClassDecl *mainClass, SourceLoc diagLoc); /// True if this source file has an application entry point. /// /// This is true if the source file either is in script mode or contains /// a designated main class. bool hasEntryPoint() const override { return isScriptMode() || hasMainClass(); } /// Get the root refinement context for the file. The root context may be /// null if the context hierarchy has not been built yet. Use /// TypeChecker::getOrBuildTypeRefinementContext() to get a built /// root of the hierarchy. TypeRefinementContext *getTypeRefinementContext(); /// Set the root refinement context for the file. void setTypeRefinementContext(TypeRefinementContext *TRC); void recordInterfaceToken(StringRef token) { assert(!token.empty()); InterfaceHash.update(token); // Add null byte to separate tokens. uint8_t a[1] = {0}; InterfaceHash.update(a); } const llvm::MD5 &getInterfaceHashState() { return InterfaceHash; } void setInterfaceHashState(const llvm::MD5 &state) { InterfaceHash = state; } void getInterfaceHash(llvm::SmallString<32> &str) { llvm::MD5::MD5Result result; InterfaceHash.final(result); llvm::MD5::stringifyResult(result, str); } void dumpInterfaceHash(llvm::raw_ostream &out) { llvm::SmallString<32> str; getInterfaceHash(str); out << str << '\n'; } }; /// This represents the compiler's implicitly generated declarations in the /// Builtin module. class BuiltinUnit final : public FileUnit { public: class LookupCache; private: std::unique_ptr<LookupCache> Cache; LookupCache &getCache() const; friend ASTContext; ~BuiltinUnit() = default; public: explicit BuiltinUnit(ModuleDecl &M); virtual void lookupValue(ModuleDecl::AccessPathTy accessPath, DeclName name, NLKind lookupKind, SmallVectorImpl<ValueDecl*> &result) const override; /// Find all Objective-C methods with the given selector. void lookupObjCMethods( ObjCSelector selector, SmallVectorImpl<AbstractFunctionDecl *> &results) const override; Identifier getDiscriminatorForPrivateValue(const ValueDecl *D) const override { llvm_unreachable("no private values in the Builtin module"); } static bool classof(const FileUnit *file) { return file->getKind() == FileUnitKind::Builtin; } static bool classof(const DeclContext *DC) { return isa<FileUnit>(DC) && classof(cast<FileUnit>(DC)); } }; /// Represents an externally-loaded file of some kind. class LoadedFile : public FileUnit { protected: ~LoadedFile() = default; LoadedFile(FileUnitKind Kind, ModuleDecl &M) noexcept : FileUnit(Kind, M) { assert(classof(this) && "invalid kind"); } public: /// Returns an arbitrary string representing the storage backing this file. /// /// This is usually a filesystem path. virtual StringRef getFilename() const; /// Look up an operator declaration. /// /// \param name The operator name ("+", ">>", etc.) /// /// \param fixity One of PrefixOperator, InfixOperator, or PostfixOperator. virtual OperatorDecl *lookupOperator(Identifier name, DeclKind fixity) const { return nullptr; } /// Look up a precedence group. /// /// \param name The precedence group name. virtual PrecedenceGroupDecl *lookupPrecedenceGroup(Identifier name) const { return nullptr; } virtual bool isSystemModule() const { return false; } static bool classof(const FileUnit *file) { return file->getKind() == FileUnitKind::SerializedAST || file->getKind() == FileUnitKind::ClangModule; } static bool classof(const DeclContext *DC) { return isa<FileUnit>(DC) && classof(cast<FileUnit>(DC)); } }; inline SourceFile & ModuleDecl::getMainSourceFile(SourceFileKind expectedKind) const { assert(!Files.empty() && "No files added yet"); assert(cast<SourceFile>(Files.front())->Kind == expectedKind); return *cast<SourceFile>(Files.front()); } inline FileUnit &ModuleDecl::getMainFile(FileUnitKind expectedKind) const { assert(expectedKind != FileUnitKind::Source && "must use specific source kind; see getMainSourceFile"); assert(!Files.empty() && "No files added yet"); assert(Files.front()->getKind() == expectedKind); return *Files.front(); } /// Wraps either a swift module or a clang one. /// FIXME: Should go away once swift modules can support submodules natively. class ModuleEntity { llvm::PointerUnion<const ModuleDecl *, const /* clang::Module */ void *> Mod; public: ModuleEntity() = default; ModuleEntity(const ModuleDecl *Mod) : Mod(Mod) {} ModuleEntity(const clang::Module *Mod) : Mod(static_cast<const void *>(Mod)){} StringRef getName() const; std::string getFullName() const; bool isSystemModule() const; bool isBuiltinModule() const; const ModuleDecl *getAsSwiftModule() const; explicit operator bool() const { return !Mod.isNull(); } }; } // end namespace swift namespace llvm { template <> class DenseMapInfo<swift::ModuleDecl::ImportedModule> { using ModuleDecl = swift::ModuleDecl; public: static ModuleDecl::ImportedModule getEmptyKey() { return {{}, llvm::DenseMapInfo<ModuleDecl *>::getEmptyKey()}; } static ModuleDecl::ImportedModule getTombstoneKey() { return {{}, llvm::DenseMapInfo<ModuleDecl *>::getTombstoneKey()}; } static unsigned getHashValue(const ModuleDecl::ImportedModule &val) { auto pair = std::make_pair(val.first.size(), val.second); return llvm::DenseMapInfo<decltype(pair)>::getHashValue(pair); } static bool isEqual(const ModuleDecl::ImportedModule &lhs, const ModuleDecl::ImportedModule &rhs) { return lhs.second == rhs.second && ModuleDecl::isSameAccessPath(lhs.first, rhs.first); } }; } #endif
{ "content_hash": "740188d42a47a50dc2858efc55ebcd5d", "timestamp": "", "source": "github", "line_count": 1216, "max_line_length": 81, "avg_line_length": 34, "alnum_prop": 0.6890238003095975, "repo_name": "gmilos/swift", "id": "0eda3f78d705f53b1b61a6f29f022299c7ee2238", "size": "41344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/swift/AST/Module.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2144" }, { "name": "Batchfile", "bytes": "26" }, { "name": "C", "bytes": "49224" }, { "name": "C++", "bytes": "21616196" }, { "name": "CMake", "bytes": "336306" }, { "name": "DTrace", "bytes": "3545" }, { "name": "Emacs Lisp", "bytes": "54383" }, { "name": "LLVM", "bytes": "56821" }, { "name": "Makefile", "bytes": "1841" }, { "name": "Objective-C", "bytes": "227649" }, { "name": "Objective-C++", "bytes": "209206" }, { "name": "Perl", "bytes": "2211" }, { "name": "Python", "bytes": "689921" }, { "name": "Ruby", "bytes": "2091" }, { "name": "Shell", "bytes": "190243" }, { "name": "Swift", "bytes": "16436819" }, { "name": "Vim script", "bytes": "13393" } ], "symlink_target": "" }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h" #include "third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_node.h" #include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h" #include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h" #include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" namespace blink { namespace { class NGAbsoluteUtilsTest : public RenderingTest { protected: NGConstraintSpace CreateConstraintSpace( WritingDirectionMode writing_direction) { NGConstraintSpaceBuilder builder(WritingMode::kHorizontalTb, writing_direction, /* is_new_fc */ true); builder.SetAvailableSize({LayoutUnit(200), LayoutUnit(300)}); return builder.ToConstraintSpace(); } void SetUp() override { RenderingTest::SetUp(); SetBodyInnerHTML(R"HTML( <style> #target { position: absolute; border: solid; border-width: 9px 17px 17px 9px; padding: 11px 19px 19px 11px; } </style> <div id=target> <!-- Use a compressible element to simulate min/max sizes of {0, N} --> <textarea style="width: 100%; height: 88px;"> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </div> </div> )HTML"); RunDocumentLifecycle(); element_ = GetDocument().getElementById("target"); ltr_space_ = CreateConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}); rtl_space_ = CreateConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kRtl}); vlr_space_ = CreateConstraintSpace({WritingMode::kVerticalLr, TextDirection::kLtr}); vrl_space_ = CreateConstraintSpace({WritingMode::kVerticalRl, TextDirection::kLtr}); } void SetHorizontalStyle(const String& left, const String& margin_left, const String& width, const String& margin_right, const String& right, const String& writing_mode = "horizontal-tb", const String& box_sizing = "border-box") { element_->SetInlineStyleProperty(CSSPropertyID::kLeft, left); element_->SetInlineStyleProperty(CSSPropertyID::kMarginLeft, margin_left); element_->SetInlineStyleProperty(CSSPropertyID::kWidth, width); element_->SetInlineStyleProperty(CSSPropertyID::kMarginRight, margin_right); element_->SetInlineStyleProperty(CSSPropertyID::kRight, right); element_->SetInlineStyleProperty(CSSPropertyID::kWritingMode, writing_mode); element_->SetInlineStyleProperty(CSSPropertyID::kBoxSizing, box_sizing); RunDocumentLifecycle(); } void SetVerticalStyle(const String& top, const String& margin_top, const String& height, const String& margin_bottom, const String& bottom, const String& writing_mode = "horizontal-tb", const String& box_sizing = "border-box") { element_->SetInlineStyleProperty(CSSPropertyID::kTop, top); element_->SetInlineStyleProperty(CSSPropertyID::kMarginTop, margin_top); element_->SetInlineStyleProperty(CSSPropertyID::kHeight, height); element_->SetInlineStyleProperty(CSSPropertyID::kMarginBottom, margin_bottom); element_->SetInlineStyleProperty(CSSPropertyID::kBottom, bottom); element_->SetInlineStyleProperty(CSSPropertyID::kWritingMode, writing_mode); element_->SetInlineStyleProperty(CSSPropertyID::kBoxSizing, box_sizing); RunDocumentLifecycle(); } void ComputeOutOfFlowInlineDimensions( const NGBlockNode& node, const NGConstraintSpace& space, const NGBoxStrut& border_padding, const NGLogicalStaticPosition& static_position, const WritingDirectionMode container_writing_direction, NGLogicalOutOfFlowDimensions* dimensions) { WritingModeConverter container_converter( container_writing_direction, ToPhysicalSize(space.AvailableSize(), container_writing_direction.GetWritingMode())); NGLogicalAnchorQuery anchor_query; NGAnchorEvaluatorImpl anchor_evaluator( anchor_query, container_converter, /* offset_to_padding_box */ PhysicalOffset(), /* self_writing_mode */ WritingMode::kHorizontalTb); const NGLogicalOutOfFlowInsets insets = ComputeOutOfFlowInsets( node.Style(), space.AvailableSize(), &anchor_evaluator); LogicalSize computed_available_size = ComputeOutOfFlowAvailableSize(node, space, insets, static_position); blink::ComputeOutOfFlowInlineDimensions( node, node.Style(), space, insets, border_padding, static_position, computed_available_size, absl::nullopt, container_writing_direction, /* anchor_evaluator */ nullptr, dimensions); } void ComputeOutOfFlowBlockDimensions( const NGBlockNode& node, const NGConstraintSpace& space, const NGBoxStrut& border_padding, const NGLogicalStaticPosition& static_position, const WritingDirectionMode container_writing_direction, NGLogicalOutOfFlowDimensions* dimensions) { WritingModeConverter container_converter( container_writing_direction, ToPhysicalSize(space.AvailableSize(), container_writing_direction.GetWritingMode())); NGLogicalAnchorQuery anchor_query; NGAnchorEvaluatorImpl anchor_evaluator( anchor_query, container_converter, /* offset_to_padding_box */ PhysicalOffset(), /* self_writing_mode */ WritingMode::kHorizontalTb); const NGLogicalOutOfFlowInsets insets = ComputeOutOfFlowInsets( node.Style(), space.AvailableSize(), &anchor_evaluator); LogicalSize computed_available_size = ComputeOutOfFlowAvailableSize(node, space, insets, static_position); blink::ComputeOutOfFlowBlockDimensions( node, node.Style(), space, insets, border_padding, static_position, computed_available_size, absl::nullopt, container_writing_direction, /* anchor_evaluator */ nullptr, dimensions); } Persistent<Element> element_; NGConstraintSpace ltr_space_; NGConstraintSpace rtl_space_; NGConstraintSpace vlr_space_; NGConstraintSpace vrl_space_; }; TEST_F(NGAbsoluteUtilsTest, Horizontal) { if (!RuntimeEnabledFeatures::LayoutNGEnabled()) return; NGBlockNode node(element_->GetLayoutBox()); element_->SetInlineStyleProperty(CSSPropertyID::kContain, "size"); element_->SetInlineStyleProperty(CSSPropertyID::kContainIntrinsicSize, "60px 4px"); NGBoxStrut ltr_border_padding = ComputeBorders(ltr_space_, node) + ComputePadding(ltr_space_, node.Style()); NGBoxStrut rtl_border_padding = ComputeBorders(rtl_space_, node) + ComputePadding(rtl_space_, node.Style()); NGBoxStrut vlr_border_padding = ComputeBorders(vlr_space_, node) + ComputePadding(vlr_space_, node.Style()); NGBoxStrut vrl_border_padding = ComputeBorders(vrl_space_, node) + ComputePadding(vrl_space_, node.Style()); NGLogicalStaticPosition static_position = { {LayoutUnit(), LayoutUnit()}, NGLogicalStaticPosition::kInlineStart, NGLogicalStaticPosition::kBlockStart}; // Same as regular static position, but with the inline-end edge. NGLogicalStaticPosition static_position_inline_end = { {LayoutUnit(), LayoutUnit()}, NGLogicalStaticPosition::kInlineEnd, NGLogicalStaticPosition::kBlockStart}; NGLogicalOutOfFlowDimensions dimensions; // All auto => width is content, left is 0. SetHorizontalStyle("auto", "auto", "auto", "auto", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(116, dimensions.size.inline_size); EXPECT_EQ(0, dimensions.inset.inline_start); // All auto => width is content, static_position is right SetHorizontalStyle("auto", "auto", "auto", "auto", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position_inline_end, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(116, dimensions.size.inline_size); EXPECT_EQ(200, dimensions.inset.inline_end); // All auto + RTL. SetHorizontalStyle("auto", "auto", "auto", "auto", "auto"); ComputeOutOfFlowInlineDimensions( node, rtl_space_, rtl_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(116, dimensions.size.inline_size); // 200 = 0 + 0 + 116 + 84 + 0 EXPECT_EQ(84, dimensions.inset.inline_end); // left, right, and left are known, compute margins. SetHorizontalStyle("5px", "auto", "160px", "auto", "13px"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 200 = 5 + 11 + 160 + 11 + 13 EXPECT_EQ(16, dimensions.inset.inline_start); EXPECT_EQ(24, dimensions.inset.inline_end); // left, right, and left are known, compute margins, writing mode vertical_lr. SetHorizontalStyle("5px", "auto", "160px", "auto", "13px", "vertical-lr"); ComputeOutOfFlowBlockDimensions( node, vlr_space_, vlr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(16, dimensions.inset.block_start); EXPECT_EQ(24, dimensions.inset.block_end); // left, right, and left are known, compute margins, writing mode vertical_rl. SetHorizontalStyle("5px", "auto", "160px", "auto", "13px", "vertical-rl"); ComputeOutOfFlowBlockDimensions( node, vrl_space_, vrl_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(16, dimensions.inset.block_end); EXPECT_EQ(24, dimensions.inset.block_start); // left, right, and width are known, not enough space for margins LTR. SetHorizontalStyle("5px", "auto", "200px", "auto", "13px"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(5, dimensions.inset.inline_start); EXPECT_EQ(-5, dimensions.inset.inline_end); // left, right, and left are known, not enough space for margins RTL. SetHorizontalStyle("5px", "auto", "200px", "auto", "13px"); ComputeOutOfFlowInlineDimensions( node, rtl_space_, rtl_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kRtl}, &dimensions); EXPECT_EQ(-13, dimensions.inset.inline_start); EXPECT_EQ(13, dimensions.inset.inline_end); // Rule 1 left and width are auto. SetHorizontalStyle("auto", "7px", "auto", "15px", "13px"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(116, dimensions.size.inline_size); // Rule 2 left and right are auto LTR. SetHorizontalStyle("auto", "7px", "160px", "15px", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 200 = 0 + 7 + 160 + 15 + 18 EXPECT_EQ(0 + 7, dimensions.inset.inline_start); EXPECT_EQ(15 + 18, dimensions.inset.inline_end); // Rule 2 left and right are auto RTL. SetHorizontalStyle("auto", "7px", "160px", "15px", "auto"); ComputeOutOfFlowInlineDimensions( node, rtl_space_, rtl_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kRtl}, &dimensions); // 200 = 0 + 7 + 160 + 15 + 18 EXPECT_EQ(0 + 7, dimensions.inset.inline_start); EXPECT_EQ(15 + 18, dimensions.inset.inline_end); // Rule 3 width and right are auto. SetHorizontalStyle("5px", "7px", "auto", "15px", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 200 = 5 + 7 + 116 + 15 + 57 EXPECT_EQ(116, dimensions.size.inline_size); EXPECT_EQ(15 + 57, dimensions.inset.inline_end); // Rule 4: left is auto. SetHorizontalStyle("auto", "7px", "160px", "15px", "13px"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 200 = 5 + 7 + 160 + 15 + 13 EXPECT_EQ(5 + 7, dimensions.inset.inline_start); // Rule 4: left is auto, "box-sizing: content-box". SetHorizontalStyle("auto", "7px", "104px", "15px", "13px", "horizontal-tb", "content-box"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 200 = 5 + 7 + 160 + 15 + 13 EXPECT_EQ(5 + 7, dimensions.inset.inline_start); // Rule 5: right is auto. SetHorizontalStyle("5px", "7px", "160px", "15px", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 200 = 5 + 7 + 160 + 15 + 13 EXPECT_EQ(15 + 13, dimensions.inset.inline_end); // Rule 6: width is auto. SetHorizontalStyle("5px", "7px", "auto", "15px", "13px"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 200 = 5 + 7 + 160 + 15 + 13 EXPECT_EQ(160, dimensions.size.inline_size); } TEST_F(NGAbsoluteUtilsTest, Vertical) { if (!RuntimeEnabledFeatures::LayoutNGEnabled()) return; element_->SetInlineStyleProperty(CSSPropertyID::kContain, "size"); element_->SetInlineStyleProperty(CSSPropertyID::kContainIntrinsicSize, "60px 4px"); NGBlockNode node(element_->GetLayoutBox()); NGBoxStrut ltr_border_padding = ComputeBorders(ltr_space_, node) + ComputePadding(ltr_space_, node.Style()); NGBoxStrut vlr_border_padding = ComputeBorders(vlr_space_, node) + ComputePadding(vlr_space_, node.Style()); NGBoxStrut vrl_border_padding = ComputeBorders(vrl_space_, node) + ComputePadding(vrl_space_, node.Style()); NGLogicalStaticPosition static_position = { {LayoutUnit(), LayoutUnit()}, NGLogicalStaticPosition::kInlineStart, NGLogicalStaticPosition::kBlockStart}; NGLogicalStaticPosition static_position_block_end = { {LayoutUnit(), LayoutUnit()}, NGLogicalStaticPosition::kInlineStart, NGLogicalStaticPosition::kBlockEnd}; NGLogicalOutOfFlowDimensions dimensions; // Set inline-dimensions in-case any block dimensions require it. ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // All auto, compute margins. SetVerticalStyle("auto", "auto", "auto", "auto", "auto"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(60, dimensions.size.block_size); EXPECT_EQ(0, dimensions.inset.block_start); // All auto, static position bottom. ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position_block_end, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(300, dimensions.inset.block_end); // If top, bottom, and height are known, compute margins. SetVerticalStyle("5px", "auto", "260px", "auto", "13px"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 300 = 5 + 11 + 260 + 11 + 13 EXPECT_EQ(5 + 11, dimensions.inset.block_start); EXPECT_EQ(11 + 13, dimensions.inset.block_end); // If top, bottom, and height are known, "writing-mode: vertical-lr". SetVerticalStyle("5px", "auto", "260px", "auto", "13px", "vertical-lr"); ComputeOutOfFlowInlineDimensions( node, vlr_space_, vlr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 300 = 5 + 11 + 260 + 11 + 13 EXPECT_EQ(5 + 11, dimensions.inset.inline_start); EXPECT_EQ(11 + 13, dimensions.inset.inline_end); // If top, bottom, and height are known, "writing-mode: vertical-rl". SetVerticalStyle("5px", "auto", "260px", "auto", "13px", "vertical-rl"); ComputeOutOfFlowInlineDimensions( node, vrl_space_, vrl_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 300 = 5 + 11 + 260 + 11 + 13 EXPECT_EQ(5 + 11, dimensions.inset.inline_start); EXPECT_EQ(11 + 13, dimensions.inset.inline_end); // If top, bottom, and height are known, negative auto margins. SetVerticalStyle("5px", "auto", "300px", "auto", "13px"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 300 = 5 + (-9) + 300 + (-9) + 13 EXPECT_EQ(5 - 9, dimensions.inset.block_start); EXPECT_EQ(-9 + 13, dimensions.inset.block_end); // Rule 1: top and height are unknown. SetVerticalStyle("auto", "7px", "auto", "15px", "13px"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(60, dimensions.size.block_size); // Rule 2: top and bottom are unknown. SetVerticalStyle("auto", "7px", "260px", "15px", "auto"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 300 = 0 + 7 + 260 + 15 + 18 EXPECT_EQ(0 + 7, dimensions.inset.block_start); EXPECT_EQ(15 + 18, dimensions.inset.block_end); // Rule 3: height and bottom are unknown. SetVerticalStyle("5px", "7px", "auto", "15px", "auto"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(60, dimensions.size.block_size); // Rule 4: top is unknown. SetVerticalStyle("auto", "7px", "260px", "15px", "13px"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); // 300 = 5 + 7 + 260 + 15 + 13 EXPECT_EQ(5 + 7, dimensions.inset.block_start); // Rule 5: bottom is unknown. SetVerticalStyle("5px", "7px", "260px", "15px", "auto"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(260, dimensions.size.block_size); } TEST_F(NGAbsoluteUtilsTest, CenterStaticPosition) { if (!RuntimeEnabledFeatures::LayoutNGEnabled()) return; NGBlockNode node(element_->GetLayoutBox()); NGLogicalStaticPosition static_position = { {LayoutUnit(150), LayoutUnit(200)}, NGLogicalStaticPosition::kInlineCenter, NGLogicalStaticPosition::kBlockCenter}; SetHorizontalStyle("auto", "auto", "auto", "auto", "auto"); SetVerticalStyle("auto", "auto", "auto", "auto", "auto"); NGBoxStrut border_padding; NGLogicalOutOfFlowDimensions dimensions; ComputeOutOfFlowInlineDimensions( node, ltr_space_, border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(100, dimensions.size.inline_size); EXPECT_EQ(100, dimensions.inset.inline_start); EXPECT_EQ(0, dimensions.inset.inline_end); ComputeOutOfFlowInlineDimensions( node, ltr_space_, border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kRtl}, &dimensions); EXPECT_EQ(100, dimensions.size.inline_size); EXPECT_EQ(100, dimensions.inset.inline_start); EXPECT_EQ(0, dimensions.inset.inline_end); ComputeOutOfFlowBlockDimensions( node, ltr_space_, border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(150, dimensions.size.block_size); EXPECT_EQ(125, dimensions.inset.block_start); EXPECT_EQ(25, dimensions.inset.block_end); } TEST_F(NGAbsoluteUtilsTest, MinMax) { if (!RuntimeEnabledFeatures::LayoutNGEnabled()) return; element_->SetInlineStyleProperty(CSSPropertyID::kMinWidth, "70px"); element_->SetInlineStyleProperty(CSSPropertyID::kMaxWidth, "150px"); element_->SetInlineStyleProperty(CSSPropertyID::kMinHeight, "70px"); element_->SetInlineStyleProperty(CSSPropertyID::kMaxHeight, "150px"); element_->SetInlineStyleProperty(CSSPropertyID::kContain, "size"); NGBlockNode node(element_->GetLayoutBox()); NGBoxStrut ltr_border_padding = ComputeBorders(ltr_space_, node) + ComputePadding(ltr_space_, node.Style()); NGLogicalStaticPosition static_position = { {LayoutUnit(), LayoutUnit()}, NGLogicalStaticPosition::kInlineStart, NGLogicalStaticPosition::kBlockStart}; NGLogicalOutOfFlowDimensions dimensions; // WIDTH TESTS // width < min gets set to min. SetHorizontalStyle("auto", "auto", "5px", "auto", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(70, dimensions.size.inline_size); // width > max gets set to max. SetHorizontalStyle("auto", "auto", "200px", "auto", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(150, dimensions.size.inline_size); // Unspecified width becomes min_max, gets clamped to min. SetHorizontalStyle("auto", "auto", "auto", "auto", "auto"); ComputeOutOfFlowInlineDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(70, dimensions.size.inline_size); // HEIGHT TESTS // height < min gets set to min. SetVerticalStyle("auto", "auto", "5px", "auto", "auto"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(70, dimensions.size.block_size); // height > max gets set to max. SetVerticalStyle("auto", "auto", "200px", "auto", "auto"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(150, dimensions.size.block_size); // // Unspecified height becomes estimated, gets clamped to min. SetVerticalStyle("auto", "auto", "auto", "auto", "auto"); ComputeOutOfFlowBlockDimensions( node, ltr_space_, ltr_border_padding, static_position, {WritingMode::kHorizontalTb, TextDirection::kLtr}, &dimensions); EXPECT_EQ(70, dimensions.size.block_size); } } // namespace } // namespace blink
{ "content_hash": "e8a83bfca158cd46513c8b6e3aea5a1c", "timestamp": "", "source": "github", "line_count": 550, "max_line_length": 82, "avg_line_length": 44.00181818181818, "alnum_prop": 0.6884013057311681, "repo_name": "nwjs/chromium.src", "id": "a642a6b9584423a7adbb4ece99e985aa9c24bb07", "size": "24201", "binary": false, "copies": "1", "ref": "refs/heads/nw70", "path": "third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php // $Id: calendar-datebox.tpl.php,v 1.1.2.2 2010/12/31 14:16:12 karens Exp $ /** * @file * Template to display the date box in a calendar. * * - $view: The view. * - $granularity: The type of calendar this box is in -- year, month, day, or week. * - $mini: Whether or not this is a mini calendar. * - $class: The class for this box -- mini-on, mini-off, or day. * - $day: The day of the month. * - $date: The current date, in the form YYYY-MM-DD. * - $link: A formatted link to the calendar day view for this day. * - $url: The url to the calendar day view for this day. * - $selected: Whether or not this day has any items. * - $items: An array of items for this day. */ ?> <div class="<?php print $granularity ?> <?php print $class; ?>"> <?php print !empty($selected) ? $link : $day; ?> </div>
{ "content_hash": "1227437c419c7efcaa5d5c9846f9996c", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 120, "avg_line_length": 43, "alnum_prop": 0.6352509179926561, "repo_name": "joausaga/sitiowebmp", "id": "cad484032937edfd4b119b0ee51fde97f98e214f", "size": "817", "binary": false, "copies": "82", "ref": "refs/heads/master", "path": "sites/all/modules/calendar/calendar_multiday/theme/calendar-datebox.tpl.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using PowerArgs.Games; using Newtonsoft.Json; using System; using System.Text; namespace LevelEditor { public static class LevelExporter { private const string CodeGenPrefix = "// REQUIRED FOR CODE-GEN - "; public static string ToCSharp(Level level) { var builder = new StringBuilder(); var indent = ""; // json comment builder.AppendLine(CodeGenPrefix + JsonConvert.SerializeObject(level)); // usings builder.AppendLine($"using System;"); builder.AppendLine($"using {nameof(PowerArgs)}.{nameof(PowerArgs.Games)};"); builder.AppendLine($"using System.Collections.Generic;"); builder.AppendLine(); // start namespace builder.AppendLine("namespace GeneratedLevels\n{"); // start class IncrementIndent(ref indent); builder.AppendLine($"{indent}public class {level.Name} : Level"); builder.AppendLine(indent + "{"); IncrementIndent(ref indent); // start constructor builder.AppendLine($"{indent}public {level.Name}()"); builder.AppendLine(indent + "{"); IncrementIndent(ref indent); //constructor body builder.AppendLine($"{indent}this.{nameof(Level.Name)} = \"{level.Name}\";"); builder.AppendLine($"{indent}this.{nameof(Level.Width)} = {level.Width};"); builder.AppendLine($"{indent}this.{nameof(Level.Height)} = {level.Height};"); foreach(var item in level.Items) { builder.AppendLine($"{indent}this.{nameof(Level.Items)}.Add({CreateItemLiteral(item)});"); } // finish constructor DecrementIndent(ref indent); builder.AppendLine(indent + "}"); // finish class DecrementIndent(ref indent); builder.AppendLine(indent + "}"); // finish namespace DecrementIndent(ref indent); builder.AppendLine(indent + "}"); return builder.ToString(); } private static void IncrementIndent(ref string currentIndent) => currentIndent = currentIndent + " "; private static void DecrementIndent(ref string currentIndent) => currentIndent = currentIndent.Substring(0, currentIndent.Length - " ".Length); internal static Level FromCSharp(string text) { if(text.StartsWith(CodeGenPrefix) == false) { throw new FormatException("The given text does not have the required code gen comment at the beginning of the file"); } var json = ""; for(var i = CodeGenPrefix.Length; i < text.Length; i++) { if(text[i] == '\n' || text[i] == '\r') { break; } else { json += text[i]; } } return JsonConvert.DeserializeObject<Level>(json); } private static string CreateItemLiteral(LevelItem item) { var ret = $"new {nameof(LevelItem)}()"; ret += " { "; ret += $"{nameof(LevelItem.X)} = {item.X}, "; ret += $"{nameof(LevelItem.Y)} = {item.Y}, "; ret += $"{nameof(LevelItem.Width)} = {item.Width}, "; ret += $"{nameof(LevelItem.Height)} = {item.Height}, "; var symbol = item.Symbol == '\\' ? "\\\\" : item.Symbol == '\'' ? "\\'" : item.Symbol.ToString(); ret += $"{nameof(LevelItem.Symbol)} = '{symbol}', "; if(item.FG.HasValue) { ret += $"{nameof(LevelItem.FG)} = {nameof(ConsoleColor)}.{item.FG}, "; } if (item.BG.HasValue) { ret += $"{nameof(LevelItem.BG)} = {nameof(ConsoleColor)}.{item.BG}, "; } ret += $"{nameof(LevelItem.Tags)} = new List<string>()" + " {"; foreach(var tag in item.Tags) { ret += '"' + tag.Replace("\"", "\\\"") + '"' + ", "; } ret += " }"; ret += " }"; return ret; } } }
{ "content_hash": "ed8fc1c6ca55e0e91508e4f307474d40", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 154, "avg_line_length": 34.12698412698413, "alnum_prop": 0.5053488372093023, "repo_name": "BlackFrog1/PowerArgs", "id": "5a6e85349bf850734c1d1f9f420f512f574448f3", "size": "4302", "binary": false, "copies": "1", "ref": "refs/heads/slash_issue", "path": "LevelEditor/LevelExporter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1289824" }, { "name": "HTML", "bytes": "6873" } ], "symlink_target": "" }
require_relative 'core/file' require_relative 'core/object' require_relative 'core/string' require_relative 'core/quantifiable_stdout'
{ "content_hash": "43738430e2e0d1af5dac591567809451", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 43, "avg_line_length": 33.75, "alnum_prop": 0.8148148148148148, "repo_name": "mojavelinux/asciidoctor-pdf", "id": "949643d15adc1f9e9610fc3be14eb0e7f2347018", "size": "166", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "lib/asciidoctor/pdf/ext/core.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1841879" }, { "name": "Shell", "bytes": "6274" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Essentials: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="doxygen-awesome.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Essentials &#160;<span id="projectnumber">2.0.0</span> </div> <div id="projectbrief">High-Performance C++ GPU Graph Analytics</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html#ad3801b8e207beb8fdf1fb38d4e16cd53">launch</a>(cuda::standard_context_t &amp;context, const func_t &amp;f, args_t &amp;&amp;... args)</td><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html#a38664e291ea726844c8ee560e7c14fca">launch_blocked</a>(cuda::standard_context_t &amp;context, func_t &amp;f, const std::size_t num_elements, args_t &amp;&amp;... args)</td><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>launch_box_t</b>() (defined in <a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a>)</td><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>launch_cooperative</b>(cuda::standard_context_t &amp;context, const func_t &amp;f, const std::size_t num_elements, args_t &amp;&amp;... args) (defined in <a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a>)</td><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html#a4e1e253415c9f214cac78014d265d33d">launch_strided</a>(cuda::standard_context_t &amp;context, func_t &amp;f, const std::size_t num_elements, args_t &amp;&amp;... args)</td><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>params_t</b> typedef (defined in <a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a>)</td><td class="entry"><a class="el" href="structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t.html">gunrock::cuda::launch_box::launch_box_t&lt; lp_v &gt;</a></td><td class="entry"></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
{ "content_hash": "b255ffa9631dea58cf9cc3494134c80c", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 566, "avg_line_length": 63.00917431192661, "alnum_prop": 0.6798194525334886, "repo_name": "gunrock/gunrock", "id": "daa46866521e02d62ab8d677431ed3b048753f75", "size": "6868", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "docs/structgunrock_1_1cuda_1_1launch__box_1_1launch__box__t-members.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "98" }, { "name": "C++", "bytes": "407497" }, { "name": "CMake", "bytes": "13561" }, { "name": "Cuda", "bytes": "89255" }, { "name": "Makefile", "bytes": "6906" }, { "name": "Shell", "bytes": "1999" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Flora, Jena 69(20): 309 (1886) #### Original name Lecidea brebissonii Fée ### Remarks null
{ "content_hash": "ecd25f5bb7dbcb482b61b5e4c23df3dc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 30, "avg_line_length": 11.846153846153847, "alnum_prop": 0.6948051948051948, "repo_name": "mdoering/backbone", "id": "95828f7f3c9874dd0dc8e2d243cc6ec279ac4d13", "size": "219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Teloschistaceae/Blastenia/Blastenia brebissonii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use strict'; // Package an app and its local npm dependencies for deployment to Cloud Foundry const _ = require('underscore'); const map = _.map; const pairs = _.pairs; const object = _.object; const extend = _.extend; const partial = _.partial; const noop = _.noop; const isEmpty = _.isEmpty; const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const commander = require('commander'); /* eslint no-process-exit: 1 */ const additionalDir = 'additionally_packed'; const makeSymlink = (additionalDirPath, path, cb) => { fs.unlink(path, (err) => { if(err) noop(); fs.symlink(additionalDirPath, path, cb); }); }; // Create the directories we need const mkdirs = (root, additional, cb) => { // Create .cfpack directory fs.mkdir('.cfpack', (err) => { if(err) noop(); makeSymlink(path.join(root, 'lib'), '.cfpack/lib', () => { if(err) noop(); else if (isEmpty(additional)) cb(); else { const additionalDirPath = path.join(root, additional); fs.access(additionalDirPath, (err) => { if(err) cb(); else makeSymlink(additionalDirPath, path.join('.cfpack', additionalDir), cb); }); } }); }); }; // Adjust a file: dependency to our packed app structure, by converting // relative path from the module to a relative path to our package root const local = (root, additional, d) => { const vendoredPath = path.resolve(d[1].substr(5)). replace(additional, additionalDir); const dependencyPath = path.join('file:.cfpack', path.relative(root, vendoredPath)); return !/file:/.test(d[1]) ? d : [d[0], dependencyPath]; }; // Adjust local dependencies to our packed app structure and write new // package.json. const repackage = (root, additional, cb) => { const mod = require(path.join(process.cwd(), 'package.json')); const loc = partial(local, root, additional); const rmod = extend({}, mod, { dependencies: object(map(pairs(mod.dependencies), loc)) }, { devDependencies: object(map(pairs(mod.devDependencies), loc)) }); fs.writeFile(path.join('.cfpack', 'package.json'), JSON.stringify(rmod, undefined, 2), cb); }; const executeZip = (directories, ignore, cb) => { // We're using the system zip command here, may be better to use a // Javascript zip library instead const files = '-type f -not -regex "\\./\\.cfpack/package\\.json" ' + '-not -regex ".*/\\.git" -not -regex ".*test\\.js"'; const ex = cp.exec('(find . ' + directories + ' ' + files + ' | zip -q -x@' + ignore + ' -@ .cfpack/app.zip) && ' + '(zip -q -j .cfpack/app.zip .cfpack/package.json)', { cwd: process.cwd() }); ex.stdout.on('data', (data) => { process.stdout.write(data); }); ex.stderr.on('data', (data) => { process.stderr.write(data); }); ex.on('close', (code) => { cb(code); }); }; // Produce the packaged app zip const zip = (ignore, include, cb) => { fs.unlink(path.resolve('.cfpack', 'app.zip'), (err) => { if (err) noop(); let directories = '.cfpack/lib/*'; fs.access(include, (err) => { if (include && include.length !== 0) directories += err ? '' : ` ${include}/*`; executeZip(directories, ignore, cb); }); }); }; // Return the Abacus root directory const rootDir = (dir) => { if (dir === '/') return dir; try { if (JSON.parse(fs.readFileSync( path.resolve(dir, 'package.json')).toString()).name === 'cf-abacus') return dir; return rootDir(path.resolve(dir, '..')); } catch (e) { return rootDir(path.resolve(dir, '..')); } }; // Package an app for deployment to Cloud Foundry const runCLI = () => { // Parse command line options commander // Accept root directory of local dependencies as a parameter, default // to the Abacus root directory .option( '-r, --root <dir>', 'root local dependencies directory', process.env.ABACUS_ROOT || rootDir(process.cwd())) .option( '-a, --additional <dir>', 'additional directory that will be packed', process.env.ADDITIONAL_PACK_DIR) .parse(process.argv); // Create the directories we need mkdirs(commander.root, commander.additional, (err) => { if (err) { console.log('Couldn\'t setup cfpack layout -', err); process.exit(1); } // Generate the repackaged package.json repackage(commander.root, commander.additional, (err) => { if (err) { console.log('Couldn\'t write package.json -', err); process.exit(1); } // Produce the packaged app zip // zip(path.join(commander.root, '.gitignore'), (err) => { zip(path.join(commander.root, '.gitignore'), commander.additional ? path.join('.cfpack', additionalDir) : '', (err) => { if (err) { console.log('Couldn\'t produce .cfpack/app.zip -', err); process.exit(1); } }); }); }); }; // Export our CLI module.exports.runCLI = runCLI;
{ "content_hash": "d0c301f8bb7e36c8d4690e8974d6acae", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 80, "avg_line_length": 30.02994011976048, "alnum_prop": 0.6029910269192422, "repo_name": "rajkiranrbala/cf-abacus", "id": "3b4ff98859af7fac48bb52bc80928ae3294a1e79", "size": "5015", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/cfpack/src/index.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6015" }, { "name": "JavaScript", "bytes": "1932262" }, { "name": "Ruby", "bytes": "3026" }, { "name": "Shell", "bytes": "39467" } ], "symlink_target": "" }
<page-content [heading]="i18n.dashboard.latestUsers" hideBack [headingActions]="headingActions$ | async"> <div class="container"> <div class="row"> <ng-container *ngFor="let user of users"> <div class="col-12 col-xs-6 col-lg-4"> <a class="d-flex flex-column undecorated" [routerLink]="path(user)" (click)="navigate(user, $event)"> <div class="text-center"> <div class="images"> <avatar [roundBorders]="false" class="main-image" size="xlarge" [image]="user.image"></avatar> </div> </div> <div class="content-text" [title]="user.display"> {{ user.display }} </div> </a> </div> </ng-container> </div> </div> </page-content>
{ "content_hash": "937348afab5873f510c7890748116927", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 77, "avg_line_length": 35.608695652173914, "alnum_prop": 0.5177045177045178, "repo_name": "cyclosproject/cyclos4-ui", "id": "608b54cc5a3e975d280b39bff78d3f223551ec15", "size": "819", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/ui/dashboard/latest-users.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4329" }, { "name": "HTML", "bytes": "764844" }, { "name": "JavaScript", "bytes": "788" }, { "name": "SCSS", "bytes": "159779" }, { "name": "TypeScript", "bytes": "1809903" } ], "symlink_target": "" }
package jef.net.ftpserver.usermanager; import java.util.ArrayList; import java.util.List; import jef.net.ftpserver.ftplet.Authority; import jef.net.ftpserver.ftplet.User; import jef.net.ftpserver.usermanager.impl.BaseUser; /** * Factory for {@link User} instances. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class UserFactory { private String name = null; private String password = null; private int maxIdleTimeSec = 0; // no limit private String homeDir = null; private boolean isEnabled = true; private List<Authority> authorities = new ArrayList<Authority>(); /** * Creates a user based on the configuration set on the factory * @return The created user */ public User createUser() { BaseUser user = new BaseUser(); user.setName(name); user.setPassword(password); user.setHomeDirectory(homeDir); user.setEnabled(isEnabled); user.setAuthorities(authorities); user.setMaxIdleTime(maxIdleTimeSec); return user; } /** * Get the user name for users created by this factory * @return The user name */ public String getName() { return name; } /** * Set the user name for users created by this factory * @param name The user name */ public void setName(String name) { this.name = name; } /** * Get the password for users created by this factory * @return The password */ public String getPassword() { return password; } /** * Set the user name for users created by this factory * @param password The password */ public void setPassword(String password) { this.password = password; } /** * Get the max idle time for users created by this factory * @return The max idle time in seconds */ public int getMaxIdleTime() { return maxIdleTimeSec; } /** * Set the user name for users created by this factory * @param maxIdleTimeSec The max idle time in seconds */ public void setMaxIdleTime(int maxIdleTimeSec) { this.maxIdleTimeSec = maxIdleTimeSec; } /** * Get the home directory for users created by this factory * @return The home directory path */ public String getHomeDirectory() { return homeDir; } /** * Set the user name for users created by this factory * @param homeDir The home directory path */ public void setHomeDirectory(String homeDir) { this.homeDir = homeDir; } /** * Get the enabled status for users created by this factory * @return true if the user is enabled (allowed to log in) */ public boolean isEnabled() { return isEnabled; } /** * Get the enabled status for users created by this factory * @param isEnabled true if the user should be enabled (allowed to log in) */ public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } /** * Get the authorities for users created by this factory * @return The authorities */ public List<? extends Authority> getAuthorities() { return authorities; } /** * Set the authorities for users created by this factory * @param authorities The authorities */ public void setAuthorities(List<Authority> authorities) { this.authorities = authorities; } }
{ "content_hash": "3c5a3c639d72fbb280b9555d6465ff74", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 75, "avg_line_length": 22.683098591549296, "alnum_prop": 0.6879850977957156, "repo_name": "xuse/ef-others", "id": "4ef34edafe8120f7cce5bb1af536ce8dd4884a37", "size": "4027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common-net/src/main/java/jef/net/ftpserver/usermanager/UserFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "587" }, { "name": "CSS", "bytes": "2036" }, { "name": "HTML", "bytes": "6788" }, { "name": "Java", "bytes": "2570656" }, { "name": "JavaScript", "bytes": "9129" } ], "symlink_target": "" }
import logging import os from redis import Redis import requests import time DEBUG = os.environ.get("DEBUG", "").lower().startswith("y") log = logging.getLogger(__name__) if DEBUG: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logging.getLogger("requests").setLevel(logging.WARNING) redis = Redis("redis") def get_random_bytes(): r = requests.get("http://rng/32") return r.content def hash_bytes(data): r = requests.post("http://hasher/", data=data, headers={"Content-Type": "application/octet-stream"}) hex_hash = r.text return hex_hash def work_loop(interval=1): deadline = 0 loops_done = 0 while True: if time.time() > deadline: log.info("{} units of work done, updating hash counter" .format(loops_done)) redis.incrby("hashes", loops_done) loops_done = 0 deadline = time.time() + interval work_once() loops_done += 1 def work_once(): log.debug("Doing one unit of work") time.sleep(0.1) random_bytes = get_random_bytes() hex_hash = hash_bytes(random_bytes) if not hex_hash.startswith('0'): log.debug("No coin found") return log.info("Coin found: {}...".format(hex_hash[:8])) created = redis.hset("wallet", hex_hash, random_bytes) if not created: log.info("We already had that coin") if __name__ == "__main__": while True: try: work_loop() except: log.exception("In work loop:") log.error("Waiting 10s and restarting.") time.sleep(10)
{ "content_hash": "7ece6904e097ff9902897392b79ba13b", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 75, "avg_line_length": 24.271428571428572, "alnum_prop": 0.581518540317834, "repo_name": "anirbanroydas/DevOps", "id": "01bfade26e39585abbc8a0d37223a2fc26bd9583", "size": "1699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample_microservices/worker/worker.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2883" }, { "name": "JavaScript", "bytes": "750" }, { "name": "Makefile", "bytes": "412" }, { "name": "Python", "bytes": "2396" }, { "name": "Ruby", "bytes": "298" }, { "name": "Shell", "bytes": "90972" } ], "symlink_target": "" }
#ifndef OPENTISSUE_CORE_CONTAINERS_GRID_UTIL_GRID_ISOSURFACE_PROJECTION_H #define OPENTISSUE_CORE_CONTAINERS_GRID_UTIL_GRID_ISOSURFACE_PROJECTION_H // // OpenTissue Template Library // - A generic toolbox for physics-based modeling and simulation. // Copyright (C) 2008 Department of Computer Science, University of Copenhagen. // // OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php // #include <OpenTissue/configuration.h> #include <OpenTissue/core/containers/grid/util/grid_value_at_point.h> #include <OpenTissue/core/containers/grid/util/grid_gradient_at_point.h> namespace OpenTissue { namespace grid { /** * Project Point Cloud Onto Iso-surface. * * @param phi The (signed distance grid) level set grid. * @param begin An iterator to the first point that should * be projected. * @param end An iterator to one position past the last point * that should be projected. * @param project_inside Boolan flag indicating whether points lying inside * should be projected. * @param project_outside Boolan flag indicating whether points lying outside * should be projected. * @param isovalue The isovalue of the iso-surface onto which the points * should be projected. WARNING if value is larger or * smaller than what is actual in stored in phi, then * the projection algorithm may run into an infinite loop. */ template<typename grid_type,typename vector3_iterator> inline void isosurface_projection( grid_type const & phi , vector3_iterator begin , vector3_iterator end , bool project_inside = true , bool project_outside = true , double isovalue = 0.0 ) { typedef typename grid_type::math_types math_types; typedef typename math_types::vector3_type vector3_type; typedef typename math_types::value_type real_type; using std::min; using std::max; using std::fabs; assert(isovalue > OpenTissue::grid::min_element(phi) || !"isosurface_projection(): isovalue exceeded minimum value"); assert(isovalue < OpenTissue::grid::max_element(phi) || !"isosurface_projection(): isovalue exceeded maximum value"); real_type threshold = 0.0001; //--- hmm, I just picked this one!!! for(vector3_iterator v = begin; v!=end; ++v) { vector3_type & p = (*v); real_type distance = value_at_point( phi, p ) - isovalue; if(!project_inside && distance < -threshold) continue; if(!project_outside && distance > threshold ) continue; while ( fabs(distance) > threshold) { vector3_type g = gradient_at_point( phi, p ); while ( g*g < threshold ) { vector3_type noise; random(noise, -threshold, threshold ); p += noise; g = gradient_at_point(phi, p ); } g = unit(g); p -= g * distance; distance = value_at_point( phi, p ) - isovalue; } } } } // namespace grid } // namespace OpenTissue // OPENTISSUE_CORE_CONTAINERS_GRID_UTIL_GRID_ISOSURFACE_PROJECTION_H #endif
{ "content_hash": "da43743494c6dd3301fb350e791953ff", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 123, "avg_line_length": 36.58064516129032, "alnum_prop": 0.607583774250441, "repo_name": "misztal/GRIT", "id": "393b238bb0967fc6618c22c48c41c354a9f2b9f2", "size": "3402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "3RDPARTY/OpenTissue/OpenTissue/core/containers/grid/util/grid_isosurface_projection.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "60469" }, { "name": "C++", "bytes": "7605518" }, { "name": "CMake", "bytes": "80506" }, { "name": "Cuda", "bytes": "383778" }, { "name": "GLSL", "bytes": "2231" }, { "name": "Matlab", "bytes": "50319" }, { "name": "Objective-C", "bytes": "120" }, { "name": "Python", "bytes": "87400" }, { "name": "Shell", "bytes": "3706" } ], "symlink_target": "" }
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>process_arguments (App)</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" /> </head> <body class="standalone-code"> <pre><span class="ruby-comment cmt"># File bin/css-get, line 118</span> <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">process_arguments</span> <span class="ruby-comment cmt"># TO DO - place in local vars, etc</span> <span class="ruby-keyword kw">end</span></pre> </body> </html>
{ "content_hash": "574b36ca42c663b1494705cd1dcc6ffb", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 99, "avg_line_length": 42.05555555555556, "alnum_prop": 0.6618229854689565, "repo_name": "akennedy/css-get", "id": "2d34a610a7f1d46c33a5ccd3ac1feb3d28481bb1", "size": "757", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/classes/App.src/M000007.html", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "440" } ], "symlink_target": "" }
package org.apache.wicket.markup.html; import org.apache.wicket.WicketTestCase; import org.apache.wicket.markup.resolver.ScopedComponentResolver; /** * * @author Juergen Donnerstag */ public class ScopedComponentResolverTest extends WicketTestCase { /** * Create the test. * * @param name * The test name */ public ScopedComponentResolverTest(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); tester.getApplication().getPageSettings().addComponentResolver( new ScopedComponentResolver()); } /** * @throws Exception */ public void testRenderHomePage() throws Exception { executeTest(ScopedPage.class, "ScopedPageExpectedResult.html"); } }
{ "content_hash": "00a748605d533a662673810d6a99ef3a", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 65, "avg_line_length": 18.6, "alnum_prop": 0.7204301075268817, "repo_name": "Servoy/wicket", "id": "c3696b885d5866c95f293f2b72a7b005039e9094", "size": "1546", "binary": false, "copies": "1", "ref": "refs/heads/wicket-1.4.x", "path": "wicket/src/test/java/org/apache/wicket/markup/html/ScopedComponentResolverTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "58903" }, { "name": "HTML", "bytes": "772575" }, { "name": "Java", "bytes": "8970322" }, { "name": "JavaScript", "bytes": "203125" }, { "name": "Perl", "bytes": "2053" }, { "name": "Roff", "bytes": "95314" }, { "name": "Shell", "bytes": "13496" }, { "name": "XSLT", "bytes": "2567" } ], "symlink_target": "" }
class Feedback::ReviewsController < Feedback::ApplicationController respond_to :html, :json, :atom before_filter :find_reviewable before_filter :authenticate_user!, :only => [:create, :update] def index @reviews = @reviewable.reviews end def create @review = Feedback::Review.new( params[:feedback_review].merge(:author => current_user, :reviewable => @reviewable) ) if @review.save! redirect_to_reviewable :notice => "Review saved." end end private def find_reviewable type, id = /^\/(\w*|\w*\/\w*)\/(\d+)/.match(request.original_fullpath).to_a.slice(1,2) @reviewable = type.classify.constantize.find(id) render :status => 404 unless @reviewable end def redirect_to_reviewable(options = {}) url = if @reviewable.is_a?(Feedback::Review) feedback_reviews_path_for(@reviewable, :anchor => "review-#{@review.id}") else @reviewable end redirect_to url, :notice => options[:notice] end end
{ "content_hash": "532f1389c5103fb5c3c5739a9b55dea1", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 90, "avg_line_length": 26.36842105263158, "alnum_prop": 0.6467065868263473, "repo_name": "Epictetus/feedback", "id": "b665274c67859ccc2577f394a5ddd68238b4e08d", "size": "1002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/feedback/reviews_controller.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
var requirejs = require('requirejs'); var Backbone = require('backbone'); var _ = require('lodash'); var dashboards = require('../../../tests/stagecraft_stub/dashboards'); var transactions = require('../../../tests/backdrop_stub/transaction-data'); var controller = require('../../../app/server/controllers/services'); var StagecraftApiClient = requirejs('stagecraft_api_client'); var ServicesView = require('../../../app/server/views/services'); var Collection = requirejs('./extensions/collections/collection'); var PageConfig = requirejs('page_config'); describe('Services Controller', function () { var client_instance, fake_app, req, res; beforeEach(function () { fake_app = {'app': {'get': function(key){ return { 'port':'8989', 'stagecraftUrl':'the url', 'assetPath': '/spotlight/' }[key]; }} }; req = _.extend({ get: function(key) { return { 'Request-Id':'Xb35Gt', 'GOVUK-Request-Id': '1231234123' }[key]; }, originalUrl: '', query: { filter: '' } }, fake_app); res = { send: jasmine.createSpy(), set: jasmine.createSpy(), status: jasmine.createSpy() }; spyOn(PageConfig, 'commonConfig').andReturn({ config: 'setting', assetPath: '/test-spotlight/', assetDigest: 'testAssetDigest' }); spyOn(Backbone.Model.prototype, 'initialize'); spyOn(Backbone.Collection.prototype, 'initialize'); spyOn(ServicesView.prototype, 'initialize'); spyOn(Collection.prototype, 'fetch').andCallFake(function () { this.reset(_.cloneDeep(transactions.data), {silent: true}); this.trigger('sync'); }); spyOn(ServicesView.prototype, 'render').andCallFake(function () { this.html = 'html string'; }); spyOn(StagecraftApiClient.prototype, 'fetch').andCallFake(function () {}); }); afterEach(function() { this.removeAllSpies(); }); it('creates a model containing config and page settings', function () { client_instance = controller('services', req, res); client_instance.trigger('sync'); expect(Backbone.Model.prototype.initialize).toHaveBeenCalledWith(jasmine.objectContaining({ config: 'setting', 'page-type': 'services' })); }); it('passes a keyword filter to the model if defined in the querystring', function () { var queryReq = _.cloneDeep(req); queryReq.query.filter = 'foo'; client_instance = controller('services', queryReq, res); client_instance.trigger('sync'); expect(Backbone.Model.prototype.initialize).toHaveBeenCalledWith(jasmine.objectContaining({ filter: 'foo'})); }); it('passes a department filter to the model if set in the querystring', function () { var queryReq = _.cloneDeep(req); queryReq.query.department = 'home-office'; client_instance = controller('services', queryReq, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); expect(Backbone.Model.prototype.initialize).toHaveBeenCalledWith(jasmine.objectContaining({ departmentFilter: 'home-office' })); }); it('passes a null department filter to the model if set to an invalid value in the querystring', function () { var queryReq = _.cloneDeep(req); queryReq.query.department = 'gnome-office'; client_instance = controller('services', queryReq, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); expect(Backbone.Model.prototype.initialize).toHaveBeenCalledWith(jasmine.objectContaining({ departmentFilter: null })); }); it('sanitizes user input before rendering it', function () { var queryReq = _.cloneDeep(req); queryReq.query.filter = '<script>alert(1)</script>'; client_instance = controller('services', queryReq, res); client_instance.trigger('sync'); expect(Backbone.Model.prototype.initialize).toHaveBeenCalledWith(jasmine.objectContaining({ filter: '&lt;script&gt;alert(1)&lt;/script&gt;' })); }); it('creates a collection', function () { client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); expect(Backbone.Collection.prototype.initialize).toHaveBeenCalledWith(jasmine.any(Array)); }); it('adds KPIs to each service model', function () { var services, service; client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); services = Backbone.Collection.prototype.initialize.mostRecentCall.args[0]; service = _.findWhere(services, { slug: 'accelerated-possession-eviction' }); expect(service['total_cost']).toEqual(345983458); expect(service['number_of_transactions']).toEqual(23534666); expect(service['cost_per_transaction']).toEqual(250); expect(service['digital_takeup']).toEqual(0.43); expect(service['completion_rate']).toEqual(0.73); expect(service['user_satisfaction_score']).toEqual(0.63); }); it('creates a services view', function () { client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); expect(ServicesView.prototype.initialize).toHaveBeenCalledWith(jasmine.objectContaining({ model: jasmine.any(Backbone.Model), collection: jasmine.any(Backbone.Collection) })); }); it('creates a list of showcase services', function () { var showcaseServices, slugs; client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); showcaseServices = ServicesView.prototype.initialize.calls[0].args[0].showcaseServices; slugs = _.pluck(showcaseServices, 'slug'); expect(slugs).toEqual(_.intersection(slugs, controller.showcaseServiceSlugs)); }); it('only lists showcase services that have data', function () { var showcaseServices, dashboardList, slugs; client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); dashboardList = _.reject(client_instance.get('items'), {slug: controller.showcaseServiceSlugs[0]}); client_instance.set('items', dashboardList); client_instance.trigger('sync'); slugs = _.pluck(showcaseServices, 'slug'); showcaseServices = ServicesView.prototype.initialize.calls[0].args[0].showcaseServices; expect(slugs).toEqual(_.intersection(slugs, controller.showcaseServiceSlugs.slice(1))); }); it('renders the services view', function () { client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); expect(ServicesView.prototype.render).toHaveBeenCalled(); }); it('sends the services view html', function () { client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); expect(res.send).toHaveBeenCalledWith('html string'); }); it('has an explicit caching policy', function () { client_instance = controller('services', req, res); client_instance.set({ 'status': 200, 'items': _.cloneDeep(dashboards.items) }); client_instance.trigger('sync'); expect(res.set).toHaveBeenCalledWith('Cache-Control', 'public, max-age=7200'); }); it('has a shorter explicit caching policy for errors', function () { client_instance = controller('services', req, res); client_instance.set({ 'status': 500 }); client_instance.trigger('sync'); expect(res.set).toHaveBeenCalledWith('Cache-Control', 'public, max-age=5'); }); });
{ "content_hash": "654fb9296eb468a24720478ad7acfba1", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 112, "avg_line_length": 33.124, "alnum_prop": 0.6519743992271465, "repo_name": "alphagov/spotlight", "id": "39f4adad1fadbca2e66e1bc34d20a7b16a11d2db", "size": "8281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/server-pure/controllers/spec.services.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "73826" }, { "name": "HTML", "bytes": "44039" }, { "name": "JavaScript", "bytes": "932618" }, { "name": "Shell", "bytes": "696" } ], "symlink_target": "" }
module Vdr Channel = Struct.new("Channel", :id, :name, :bouquet, :frequency, :parameter, :source, :symbol_rate, :video_pid, :audio_pid, :teletext_pid, :conditional_access_id, :service_id, :network_id, :transport_stream_id, :radio_id) class Channel def delete! end end end
{ "content_hash": "8fdd228cf26b5cc3a62b45e8ffef66b6", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 224, "avg_line_length": 31.88888888888889, "alnum_prop": 0.686411149825784, "repo_name": "hvolkmer/vdr-ruby", "id": "34e6dba20a5847f1c009a19892a8d9f3816b2f94", "size": "287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/vdr/channel.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9699" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Bot. Jahrb. Syst. 45:170. 1910 #### Original name null ### Remarks null
{ "content_hash": "6cea1ef25ac9d9a72b020b7813a3d792", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 12.307692307692308, "alnum_prop": 0.6875, "repo_name": "mdoering/backbone", "id": "82dafec71b51a7f974062fb63383eb13870d971a", "size": "208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Grewia/Grewia retinervis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
angular.module('bulkloaderApp') .directive('maskLoader', function () { return { restrict: 'E', replace: true, scope: { message: '@' }, template: '<div class="mask-loader" style="height:'+ window.innerHeight +'px;"><span class="loader-animation">{{message}}</span><span class="text">{{message}}</span></div>' // template: '<div style="background-color: #000777; position: absolute; top: 0; left: 0; z-index: 999999999;" class="mask-loader" ><span class="text">{{message}}</span></div>' } }); /** * MaskLoader factor class as an helper for masking the screens * * * @author Ramana */ var MaskLoader = Class.extend({ _modalDomEl: null, _cloudElementsUtils: null, _createMaskingElement:function (scope, message) { var me = this; var body = me.$document.find('body').eq(0); var angularDomEl = angular.element('<mask-loader message ="'+message+'"></mask-loader>'); me._modalDomEl = me.$compile(angularDomEl)(scope); body.append(me._modalDomEl); }, show:function(scope, message){ var me = this; // me._createMaskingElement(scope, message); if(me._cloudElementsUtils.isEmpty(me._modalDomEl)) { me._createMaskingElement(scope, message); } }, hide:function(){ var me = this; if(!me._cloudElementsUtils.isEmpty(me._modalDomEl)) { me._modalDomEl.remove(); me._modalDomEl = null; } } }); /** * Picker Factory object creation * */ (function (){ var MaskLoaderObject = Class.extend({ instance: new MaskLoader(), /** * Initialize and configure */ $get:['CloudElementsUtils', '$document', '$compile', '$rootScope',function(CloudElementsUtils, $document, $compile, $rootScope){ this.instance._cloudElementsUtils = CloudElementsUtils; this.instance.$document = $document; this.instance.$compile = $compile; this.instance.$rootScope = $rootScope; return this.instance; }] }); angular.module('bulkloaderApp') .provider('MaskLoader',MaskLoaderObject); }());
{ "content_hash": "c6eac03644c6a9b95016e410886053bb", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 187, "avg_line_length": 29.376623376623378, "alnum_prop": 0.5755968169761273, "repo_name": "cloud-elements/element-connect", "id": "108748cf6490b7193ae200d1032e2f162cd0a94d", "size": "2262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/webapp/scripts/directives/MaskLoader.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "126587" }, { "name": "HTML", "bytes": "98679" }, { "name": "JavaScript", "bytes": "547468" } ], "symlink_target": "" }
class MigrateRolesToRolify < ActiveRecord::Migration[4.2] def up remove_column :users, :admin remove_column :users, :super_admin end def down raise ActiveRecord::IrreversibleMigration end end
{ "content_hash": "2434469b1ec255e18c35602a229c5a95", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 57, "avg_line_length": 21.3, "alnum_prop": 0.7323943661971831, "repo_name": "rdunlop/unicycling-registration", "id": "4532218405dba019d8f9f7205bfca82ab8421f19", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20130305155047_migrate_roles_to_rolify.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "149" }, { "name": "CoffeeScript", "bytes": "19855" }, { "name": "Dockerfile", "bytes": "371" }, { "name": "HTML", "bytes": "3892" }, { "name": "Haml", "bytes": "461370" }, { "name": "JavaScript", "bytes": "67910" }, { "name": "Procfile", "bytes": "157" }, { "name": "Ruby", "bytes": "2512669" }, { "name": "SCSS", "bytes": "57821" }, { "name": "Shell", "bytes": "2705" } ], "symlink_target": "" }
package com.baidubce.services.bmr.model; import com.baidubce.model.AbstractBceResponse; public class ScheduleResultResponse extends AbstractBceResponse { private String code; private String msg; private Boolean success; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } }
{ "content_hash": "fa12894089ac7e8e45e43da11f3ecec7", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 65, "avg_line_length": 19.393939393939394, "alnum_prop": 0.634375, "repo_name": "baidubce/bce-sdk-java", "id": "5223e8685026bb233153260574fb6896d4b61338", "size": "640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/baidubce/services/bmr/model/ScheduleResultResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7979509" } ], "symlink_target": "" }
template <typename T> inline void hash_combine(std::size_t& seed, const T& val) { seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } // Auxiliary generic functions to create a hash value using a seed. template <typename T> inline void hash_val(std::size_t& seed, const T& val) { hash_combine(seed, val); } template <typename T, typename... Types> inline void hash_val(std::size_t& seed, const T& val, const Types&... args) { hash_combine(seed, val); hash_val(seed, args...); } // auxiliary generic function to create a hash value out of a heterogeneous list // of arguments. template <typename... Types> inline std::size_t hash_val(const Types&... args) { std::size_t seed = 0; hash_val(seed, args...); return seed; }
{ "content_hash": "00c9f3e688b86e150c201571e3fef2a3", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 80, "avg_line_length": 25.7, "alnum_prop": 0.6549935149156939, "repo_name": "PhilipDaniels/learn", "id": "8dc512959c5324c5b09e46982be003294625b124", "size": "1238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cpp/hashval.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6901" }, { "name": "C#", "bytes": "73608" }, { "name": "C++", "bytes": "127910" }, { "name": "Makefile", "bytes": "205" }, { "name": "PowerShell", "bytes": "19738" }, { "name": "Rust", "bytes": "122220" }, { "name": "Shell", "bytes": "384" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "eca35405ad838480759d72e5ea7789e2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "10496994fd56389914b8e9f6189c7942e0316966", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Tamaricaceae/Reaumuria/Reaumuria floribunda/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/*[ * ATTACH_HOVER_EVENTS * * 주어진 HTML엘리먼트에 Hover 이벤트 발생시 특정 클래스가 할당 되도록 설정 * * aElms array Hover 이벤트를 걸 HTML Element 목록 * sHoverClass string Hover 시에 할당 할 클래스 * ---------------------------------------------------------------------------]*/ /** * @pluginDesc Husky Framework에서 자주 사용되는 유틸성 메시지를 처리하는 플러그인 */ nhn.husky.Utils = jindo.$Class({ name : "Utils", $init : function(){ var oAgentInfo = jindo.$Agent(); var oNavigatorInfo = oAgentInfo.navigator(); if(oNavigatorInfo.ie && oNavigatorInfo.version == 6){ try{ document.execCommand('BackgroundImageCache', false, true); }catch(e){} } }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["htBrowser", jindo.$Agent().navigator()]); }, $ON_ATTACH_HOVER_EVENTS : function(aElms, htOptions){ htOptions = htOptions || []; var sHoverClass = htOptions.sHoverClass || "hover"; var fnElmToSrc = htOptions.fnElmToSrc || function(el){return el}; var fnElmToTarget = htOptions.fnElmToTarget || function(el){return el}; if(!aElms) return; var wfAddClass = jindo.$Fn(function(wev){ jindo.$Element(fnElmToTarget(wev.currentElement)).addClass(sHoverClass); }, this); var wfRemoveClass = jindo.$Fn(function(wev){ jindo.$Element(fnElmToTarget(wev.currentElement)).removeClass(sHoverClass); }, this); for(var i=0, len = aElms.length; i<len; i++){ var elSource = fnElmToSrc(aElms[i]); wfAddClass.attach(elSource, "mouseover"); wfRemoveClass.attach(elSource, "mouseout"); wfAddClass.attach(elSource, "focus"); wfRemoveClass.attach(elSource, "blur"); } } });
{ "content_hash": "a9cf46a3e481ca203031097df9e7acf4", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 80, "avg_line_length": 27.879310344827587, "alnum_prop": 0.642547928262214, "repo_name": "GGomi/crefun_php", "id": "fc0395efe4b9fe6fc8448d2ddbb6b6a6c152d148", "size": "2507", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "smartediter/js_src/util/hp_Utils.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "364879" }, { "name": "HTML", "bytes": "117648" }, { "name": "JavaScript", "bytes": "822222" }, { "name": "PHP", "bytes": "1783022" } ], "symlink_target": "" }
Simple communication between 2 users in real time. Author: André Sardo ### License The Chat App is licensed under the [MIT license](http://opensource.org/licenses/MIT)
{ "content_hash": "99aa488deee5f79e64d7a714e6c7b4a7", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 84, "avg_line_length": 24.428571428571427, "alnum_prop": 0.7660818713450293, "repo_name": "afsardo/ChatLaraVue", "id": "2aaec790a8d3581278fd837f7a1a17929e2d00ff", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "712" }, { "name": "HTML", "bytes": "6056" }, { "name": "JavaScript", "bytes": "9621" }, { "name": "PHP", "bytes": "148411" } ], "symlink_target": "" }
[API docs](site/apidocs/index.html)
{ "content_hash": "03763463efe959f5ef4ed52d9c22228e", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 35, "avg_line_length": 12.666666666666666, "alnum_prop": 0.7105263157894737, "repo_name": "EHRI/rs-aggregator", "id": "7d66b4a88fc50674f4bfb76f1ce103f41999fa3b", "size": "39", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "266793" }, { "name": "Shell", "bytes": "1071" } ], "symlink_target": "" }
<ion-view> <ion-nav-title>{{vm.title}}</ion-nav-title> <ion-content class="has-header has-footer" ng-init="initData()"> <ion-list class="list" can-swipe="true" delegate-handle="trade-list"> <ion-item class="edit-item edit-item-trade h5-sm" item-height="82px" item-width="100%" collection-repeat="item in trades" ng-href="#/trade/content/{{item.id}}/{{item.user_id}}/false"> <!-- <i class="icon ion-ios-arrow-right h1-sm grey edit-item-icon-right"></i> --> <div class="trade-post-item" ng-bind-html="item.update_time | postTime2str"></div> <div class="trade-status" ng-bind-html="item.status | status2str"></div> <div class="row"> <div class="item-info bold item-text-wrap"> {{item.name | htmldecode}} {{item.trademark | htmldecode}} {{item.place | htmldecode}} </div> </div> <div class="row"> <div class="item-info"> <span class="item-price orange bold">{{item.price | money:2}}</span> <span>{{item.price_unit+"/"+item.quantity_unit}}、</span> </div> <div class="item-info"> <span class="item-price orange bold">{{item.quantity | float}}</span> <span>{{item.quantity_unit}}</span> </div> <div class="item-info"> <span class="item-duetype">账期</span> <span class="text-yellow">{{item.account_date}} </span>天 </div> </div> <div class="row"> <div class="item-info"> <span class="item-duetype">我司人员 </span> <span class="royal">{{item.nickname}} </span> </div> </div> <div class="row"> <div class="item-info text-overflow"> <span ng-bind-html="item.trade_type | tradeTypeConverter: item.friend_nickname"></span> </div> </div> </ion-item> </ion-list> <ion-content-empty value="trades" loading="vm.loading" retry="retry()" title="vm.emptyTitle"> </ion-content-empty> </ion-content> <div class="bar bar-footer bar-stable"> <div class="button-bar"> <button class="button button-calm icon ion-ios-calendar-outline" ng-click="openFilterTime()"> {{filterInfo.startTime | date: 'MM 月 dd 日'}} ~ {{filterInfo.endTime | date: 'MM 月 dd 日'}}</button> </div> </div> </ion-view>
{ "content_hash": "fecea5ad24c576fd0cfa3839611433ab", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 147, "avg_line_length": 52.943396226415096, "alnum_prop": 0.4757662152530292, "repo_name": "zeaven/dzsq", "id": "ed1cbc4f8e4a2a1203cfde170babb87a171ba232", "size": "2830", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/appPlugins/teamAssistant/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "828793" }, { "name": "HTML", "bytes": "288686" }, { "name": "Java", "bytes": "776" }, { "name": "JavaScript", "bytes": "4282667" } ], "symlink_target": "" }
package org.apache.mina.transport.udp.bio; import org.apache.mina.transport.udp.AbstractUdpServer; /** * TODO * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class BioUdpServer extends AbstractUdpServer { /** * Create a new instance of BioUdpServer */ public BioUdpServer() { super(); } }
{ "content_hash": "9719cbfb82d455be63e176cb846f43cd", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 67, "avg_line_length": 19.88888888888889, "alnum_prop": 0.6564245810055865, "repo_name": "davcamer/clients", "id": "8ee9a09d2f78428cb1586793b466e543d69dacd7", "size": "1182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects-for-testing/mina/core/src/main/java/org/apache/mina/transport/udp/bio/BioUdpServer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "451169" }, { "name": "C++", "bytes": "602437" }, { "name": "Java", "bytes": "7870117" }, { "name": "JavaScript", "bytes": "258272" }, { "name": "Perl", "bytes": "148772" }, { "name": "Python", "bytes": "126051" }, { "name": "Shell", "bytes": "67869" } ], "symlink_target": "" }
#include "paletteTreeWidget.h" #include <QtGui/QMouseEvent> #include <QtWidgets/QMenu> #include "mainWindow/palette/paletteTree.h" #include "mainWindow/palette/draggableElement.h" #include "dialogs/metamodelingOnFly/chooseTypeDialog.h" using namespace qReal; using namespace gui; const EditorManagerInterface *PaletteTreeWidget::mEditorManager = nullptr; PaletteTreeWidget::PaletteTreeWidget(PaletteTree &palette, MainWindow &mainWindow , const EditorManagerInterface &editorManagerProxy, bool editable) : mMainWindow(mainWindow) , mPaletteTree(palette) , mEditable(editable) { mEditorManager = &editorManagerProxy; } void PaletteTreeWidget::addGroups(QList<QPair<QString, QList<PaletteElement>>> &groups , QMap<QString, QString> const &descriptions , bool hideIfEmpty , const QString &diagramFriendlyName , bool sort) { mPaletteItems.clear(); mPaletteElements.clear(); mElementsSet.clear(); mItemsVisible.clear(); if (groups.isEmpty() && hideIfEmpty) { hide(); return; } clear(); show(); if (sort) { qSort(groups.begin(), groups.end() , [](QPair<QString, QList<PaletteElement>> const &e1 , QPair<QString, QList<PaletteElement>> const &e2) { return e1.first < e2.first; } ); } int expandedCount = 0; for (auto &group : groups) { QTreeWidgetItem * const item = new QTreeWidgetItem; item->setText(0, group.first); item->setToolTip(0, descriptions[group.first]); if (sort) { sortByFriendlyName(group.second); } addItemsRow(group.second, item); addTopLevelItem(item); if (SettingsManager::value(diagramFriendlyName + group.first, 0).toBool()) { ++expandedCount; expandItem(item); } } if (expandedCount == 0) { expand(); } } void PaletteTreeWidget::addItemType(const PaletteElement &data, QTreeWidgetItem *parent) { QTreeWidgetItem *leaf = new QTreeWidgetItem; DraggableElement *element = new DraggableElement(mMainWindow, data, mPaletteTree.iconsView(), *mEditorManager); mElementsSet.insert(data); mPaletteElements.insert(data.id(), element); mPaletteItems.insert(data.id(), leaf); parent->addChild(leaf); setItemWidget(leaf, 0, element); } void PaletteTreeWidget::addItemsRow(QList<PaletteElement> const &items, QTreeWidgetItem *parent) { if (mPaletteTree.itemsCountInARow() == 1 || !mPaletteTree.iconsView()) { foreach (const PaletteElement &element, items) { addItemType(element, parent); } return; } for (QList<PaletteElement>::ConstIterator it = items.begin(); it != items.end();) { QWidget *field = new QWidget; QHBoxLayout *layout = new QHBoxLayout; int count = mPaletteTree.itemsCountInARow(); for (; it != items.end() && --count > 0; ++it) { DraggableElement *element = new DraggableElement(mMainWindow, *it, true, *mEditorManager); element->setToolTip((*it).description()); layout->addWidget(element, count > 0 ? 50 : 0); } field->setLayout(layout); field->setMinimumHeight(80); QTreeWidgetItem *leaf = new QTreeWidgetItem; parent->addChild(leaf); if (mEditable) { leaf->setFlags(leaf->flags() | Qt::ItemIsEditable); } setItemWidget(leaf, 0, field); } } void PaletteTreeWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { if (mEditorManager->isInterpretationMode()) { QMenu menu; ChooseTypeDialog *chooseTypeDialog = new ChooseTypeDialog(mPaletteTree.currentEditor() , *mEditorManager, &mMainWindow); QAction * const addNodePaletteAction = menu.addAction(tr("Add Entity")); QAction * const addEdgePaletteAction = menu.addAction(tr("Add Relastionship")); connect(addNodePaletteAction, SIGNAL(triggered()), chooseTypeDialog, SLOT(nodeButtonClicked())); connect(addEdgePaletteAction, SIGNAL(triggered()), chooseTypeDialog, SLOT(edgeButtonClicked())); connect(chooseTypeDialog, &ChooseTypeDialog::jobDone, &mMainWindow, &MainWindow::loadEditorPlugins); menu.exec(QCursor::pos()); } } QTreeWidget::mousePressEvent(event); } void PaletteTreeWidget::expand() { for (int i = 0; i < topLevelItemCount(); i++) { if (topLevelItem(i)) { expandChildren(topLevelItem(i)); } } } void PaletteTreeWidget::sortByFriendlyName(IdList &ids) { qSort(ids.begin(), ids.end(), idLessThan); } void PaletteTreeWidget::sortByFriendlyName(QList<PaletteElement> &elements) { qSort(elements.begin(), elements.end(), paletteElementLessThan); } void PaletteTreeWidget::editItem(QTreeWidgetItem * const item) { edit(indexFromItem(item)); } void PaletteTreeWidget::expandChildren(QTreeWidgetItem *item) { for (int i = 0; i < item->childCount(); i++) { if (item->child(i)) { expandChildren(item->child(i)); } } item->treeWidget()->expandItem(item); } void PaletteTreeWidget::collapse() { for (int i = 0; i < topLevelItemCount(); i++) { if (topLevelItem(i)) { collapseChildren(topLevelItem(i)); } } } void PaletteTreeWidget::collapseChildren(QTreeWidgetItem *item) { for (int i = 0; i < item->childCount(); i++) { if (item->child(i)) { collapseChildren(item->child(i)); } } item->treeWidget()->collapseItem(item); } bool PaletteTreeWidget::idLessThan(const Id &s1, const Id &s2) { return mEditorManager->friendlyName(s1).toLower() < mEditorManager->friendlyName(s2).toLower(); } bool PaletteTreeWidget::paletteElementLessThan(const PaletteElement &s1, const PaletteElement &s2) { return idLessThan(s1.id(), s2.id()); } void PaletteTreeWidget::setElementVisible(const Id &metatype, bool visible) { if (mPaletteItems.contains(metatype)) { mItemsVisible[mPaletteItems[metatype]] = visible; mPaletteItems[metatype]->setHidden(!visible); updateGroupVisibility(mPaletteItems[metatype]); } } void PaletteTreeWidget::setVisibleForAllElements(bool visible) { for (const Id &element : mPaletteElements.keys()) { setElementVisible(element, visible); } } void PaletteTreeWidget::setElementEnabled(const Id &metatype, bool enabled) { if (mPaletteElements.contains(metatype)) { mPaletteElements[metatype]->setEnabled(enabled); } } void PaletteTreeWidget::setEnabledForAllElements(bool enabled) { foreach (QWidget * const element, mPaletteElements.values()) { element->setEnabled(enabled); } } void PaletteTreeWidget::filter(const QRegExp &regexp) { QHash<QTreeWidgetItem *, int> visibleCount; traverse([this, &regexp, &visibleCount](QTreeWidgetItem *item) { if (DraggableElement * const element = dynamic_cast<DraggableElement *>(itemWidget(item, 0))) { const QString text = element->text(); const bool itemDisabledBySystem = mItemsVisible.contains(item) && !mItemsVisible[item]; item->setHidden(itemDisabledBySystem || !text.contains(regexp)); if (!item->isHidden()) { ++visibleCount[item->parent()]; } } }); for (int i = 0; i < topLevelItemCount(); ++i) { QTreeWidgetItem * const item = topLevelItem(i); item->setHidden(visibleCount[item] == 0); } } void PaletteTreeWidget::traverse(const PaletteTreeWidget::Action &action) const { for (int i = 0; i < topLevelItemCount(); ++i) { traverse(topLevelItem(i), action); } } const QSet<PaletteElement> &PaletteTreeWidget::elementsSet() const { return mElementsSet; } void PaletteTreeWidget::traverse(QTreeWidgetItem * const item, const PaletteTreeWidget::Action &action) const { action(item); for (int i = 0; i < item->childCount(); ++i) { traverse(item->child(i), action); } } void PaletteTreeWidget::updateGroupVisibility(const QTreeWidgetItem * const item) { const auto parent = item->parent(); bool hasVisible = false; for (int i = 0; i < parent->childCount(); ++i) { if (mItemsVisible.contains(parent->child(i)) && mItemsVisible[parent->child(i)]) { hasVisible = true; } } parent->setHidden(!hasVisible); }
{ "content_hash": "605a38b622ae6e654acd4d243ca78c49", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 112, "avg_line_length": 26.647058823529413, "alnum_prop": 0.7197766523828074, "repo_name": "ZiminGrigory/qreal", "id": "c58fc491b5fa1c4f59ad7c1564bf4cd5dcaa05d2", "size": "8305", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "qrgui/mainWindow/palette/paletteTreeWidget.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1181" }, { "name": "C", "bytes": "24683" }, { "name": "C#", "bytes": "18292" }, { "name": "C++", "bytes": "7193523" }, { "name": "CSS", "bytes": "13352" }, { "name": "Dockerfile", "bytes": "796" }, { "name": "HTML", "bytes": "322054" }, { "name": "IDL", "bytes": "1050" }, { "name": "JavaScript", "bytes": "11795" }, { "name": "Lua", "bytes": "607" }, { "name": "Perl", "bytes": "15511" }, { "name": "Perl 6", "bytes": "33909" }, { "name": "Prolog", "bytes": "1132" }, { "name": "Python", "bytes": "25813" }, { "name": "QMake", "bytes": "291868" }, { "name": "Shell", "bytes": "109083" }, { "name": "Tcl", "bytes": "21071" }, { "name": "Terra", "bytes": "4206" }, { "name": "Turing", "bytes": "27844" } ], "symlink_target": "" }
<?php namespace BackBee\CoreDomain\Security; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; /** * @category BackBee * * @copyright Lp digital system * @author k.golovin */ interface ApiUserProviderInterface extends UserProviderInterface { /** * Loads the user for the given public key. * * This method must throw UsernameNotFoundException if the user is not * found. * * @param string $publicApiKey The public key * * @return UserInterface * * @see UsernameNotFoundException * * @throws UsernameNotFoundException if the user is not found */ public function loadUserByPublicKey($publicApiKey); }
{ "content_hash": "eff8184e7d5d35eee09c366d2b461248", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 74, "avg_line_length": 24.529411764705884, "alnum_prop": 0.709832134292566, "repo_name": "ReissClothing/BackBee", "id": "8a1d54ee836b72f81af76626f7caf8791206d0d5", "size": "1618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/BackBee/CoreDomain/Security/ApiUserProviderInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3660" }, { "name": "CSS", "bytes": "3934267" }, { "name": "Cucumber", "bytes": "2840" }, { "name": "HTML", "bytes": "422502" }, { "name": "JavaScript", "bytes": "1440497" }, { "name": "PHP", "bytes": "1190536" }, { "name": "Smarty", "bytes": "13704" } ], "symlink_target": "" }
package com.twu.biblioteca; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertThat; /** * Created by Administrator on 2015/6/3. */ public class BibliotecaAppTest { private ByteArrayOutputStream baos; private BibliotecaApp app; @Before public void before(){ baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); app = new BibliotecaApp(); } @Test public void testWelcome() throws Exception { app.welcome(); assertThat(baos.toString(),containsString("Welcome")); } @Test public void testShowMenu() throws Exception { app.showMenu(); assertThat(baos.toString(), containsString("Main menu")); } }
{ "content_hash": "0f871b34d2acc48d3e873771a9bc1dd6", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 65, "avg_line_length": 25.257142857142856, "alnum_prop": 0.6889140271493213, "repo_name": "sherlockHK/twu-biblioteca-KaiHu", "id": "0f90484217494f8053925b33cdf34e364c692a3c", "size": "884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/com/twu/biblioteca/BibliotecaAppTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "27719" } ], "symlink_target": "" }
"""Tests for policies.""" from optformer.t5x import inference_utils from optformer.t5x import policies from vizier import algorithms as vza from vizier import benchmarks from absl.testing import absltest class PoliciesTest(absltest.TestCase): @absltest.skip("Checkpoint must be installed manually.") def test_e2e(self): experimenter = benchmarks.IsingExperimenter(lamda=0.01) inference_model = inference_utils.InferenceModel.from_checkpoint( **policies.BBOB_INFERENCE_MODEL_KWARGS) designer = policies.OptFormerDesigner( experimenter.problem_statement(), inference_model=inference_model) for _ in range(2): suggestions = designer.suggest(1) trials = [suggestion.to_trial() for suggestion in suggestions] experimenter.evaluate(trials) designer.update(vza.CompletedTrials(trials)) if __name__ == '__main__': absltest.main()
{ "content_hash": "25f6d2c84bc9efaa8791c95aa346e04d", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 74, "avg_line_length": 31.821428571428573, "alnum_prop": 0.7373737373737373, "repo_name": "google-research/optformer", "id": "9a78768de9a560bb42e593fa6636746f46657e34", "size": "1467", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "optformer/t5x/policies_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jupyter Notebook", "bytes": "230191" }, { "name": "Python", "bytes": "197267" } ], "symlink_target": "" }
import argparse import scipy import matplotlib.pyplot as plot import wells.publisher as publisher parser = argparse.ArgumentParser() parser.add_argument("input", help="solution file", type=str) parser.add_argument("--ext", help="output file extension", type=str, default="png") args = parser.parse_args() workspace = scipy.load(args.input) x = workspace["x"] potential = workspace["potential"] n = workspace["n"] eigenvalue = workspace["eigenvalue"] eigenvector = workspace["eigenvector"] delta = workspace["delta"] solution = workspace["solution"] stability_eigenvalues = workspace["stability_eigenvalues"] stability_eigenvectors = workspace["stability_eigenvectors"] idx = stability_eigenvalues.imag.argmax() eigenvalue = stability_eigenvalues[idx] eigenvector = stability_eigenvectors[:, idx] nx = len(x) a = eigenvector[:nx] b = eigenvector[nx:] eigenvector = a + b.conjugate() publisher.init({"figure.figsize": (2.8, 2.8)}) plot.figure() plot.plot(x, eigenvector.real, color="black", linestyle="solid") plot.plot(x, eigenvector.imag, color="orangered", linestyle="solid") plot.xlim(-10, +10) plot.xlabel("$z$") plot.ylabel("$a(z) + b^{*}(z)$") plot.show() prefix = args.input.replace(".npz", "") publisher.publish(prefix + ".stev", args.ext)
{ "content_hash": "f94bcfe83f3fdfb6cb223fdeb4efd44d", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 60, "avg_line_length": 26, "alnum_prop": 0.6647314949201741, "repo_name": "ioreshnikov/wells", "id": "6e809465b4b89accb72c093ed59bdfb7309d3103", "size": "1403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "publish_stability_eigenfunction.py", "mode": "33261", "license": "mit", "language": [ { "name": "FORTRAN", "bytes": "339260" }, { "name": "Python", "bytes": "75886" }, { "name": "Shell", "bytes": "2636" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <txdb.h> #include <chain.h> #include <node/ui_interface.h> #include <pow.h> #include <random.h> #include <shutdown.h> #include <uint256.h> #include <util/system.h> #include <util/translation.h> #include <util/vector.h> #include <stdint.h> static constexpr uint8_t DB_COIN{'C'}; static constexpr uint8_t DB_COINS{'c'}; static constexpr uint8_t DB_BLOCK_FILES{'f'}; static constexpr uint8_t DB_BLOCK_INDEX{'b'}; static constexpr uint8_t DB_BEST_BLOCK{'B'}; static constexpr uint8_t DB_HEAD_BLOCKS{'H'}; static constexpr uint8_t DB_FLAG{'F'}; static constexpr uint8_t DB_REINDEX_FLAG{'R'}; static constexpr uint8_t DB_LAST_BLOCK{'l'}; // Keys used in previous version that might still be found in the DB: static constexpr uint8_t DB_TXINDEX_BLOCK{'T'}; // uint8_t DB_TXINDEX{'t'} std::optional<bilingual_str> CheckLegacyTxindex(CBlockTreeDB& block_tree_db) { CBlockLocator ignored{}; if (block_tree_db.Read(DB_TXINDEX_BLOCK, ignored)) { return _("The -txindex upgrade started by a previous version cannot be completed. Restart with the previous version or run a full -reindex."); } bool txindex_legacy_flag{false}; block_tree_db.ReadFlag("txindex", txindex_legacy_flag); if (txindex_legacy_flag) { // Disable legacy txindex and warn once about occupied disk space if (!block_tree_db.WriteFlag("txindex", false)) { return Untranslated("Failed to write block index db flag 'txindex'='0'"); } return _("The block index db contains a legacy 'txindex'. To clear the occupied disk space, run a full -reindex, otherwise ignore this error. This error message will not be displayed again."); } return std::nullopt; } namespace { struct CoinEntry { COutPoint* outpoint; uint8_t key; explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {} SERIALIZE_METHODS(CoinEntry, obj) { READWRITE(obj.key, obj.outpoint->hash, VARINT(obj.outpoint->n)); } }; } CCoinsViewDB::CCoinsViewDB(fs::path ldb_path, size_t nCacheSize, bool fMemory, bool fWipe) : m_db(std::make_unique<CDBWrapper>(ldb_path, nCacheSize, fMemory, fWipe, true)), m_ldb_path(ldb_path), m_is_memory(fMemory) { } void CCoinsViewDB::ResizeCache(size_t new_cache_size) { // We can't do this operation with an in-memory DB since we'll lose all the coins upon // reset. if (!m_is_memory) { // Have to do a reset first to get the original `m_db` state to release its // filesystem lock. m_db.reset(); m_db = std::make_unique<CDBWrapper>( m_ldb_path, new_cache_size, m_is_memory, /*fWipe*/ false, /*obfuscate*/ true); } } bool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const { return m_db->Read(CoinEntry(&outpoint), coin); } bool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const { return m_db->Exists(CoinEntry(&outpoint)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!m_db->Read(DB_BEST_BLOCK, hashBestChain)) return uint256(); return hashBestChain; } std::vector<uint256> CCoinsViewDB::GetHeadBlocks() const { std::vector<uint256> vhashHeadBlocks; if (!m_db->Read(DB_HEAD_BLOCKS, vhashHeadBlocks)) { return std::vector<uint256>(); } return vhashHeadBlocks; } bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { CDBBatch batch(*m_db); size_t count = 0; size_t changed = 0; size_t batch_size = (size_t)gArgs.GetIntArg("-dbbatchsize", nDefaultDbBatchSize); int crash_simulate = gArgs.GetIntArg("-dbcrashratio", 0); assert(!hashBlock.IsNull()); uint256 old_tip = GetBestBlock(); if (old_tip.IsNull()) { // We may be in the middle of replaying. std::vector<uint256> old_heads = GetHeadBlocks(); if (old_heads.size() == 2) { assert(old_heads[0] == hashBlock); old_tip = old_heads[1]; } } // In the first batch, mark the database as being in the middle of a // transition from old_tip to hashBlock. // A vector is used for future extensibility, as we may want to support // interrupting after partial writes from multiple independent reorgs. batch.Erase(DB_BEST_BLOCK); batch.Write(DB_HEAD_BLOCKS, Vector(hashBlock, old_tip)); for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { CoinEntry entry(&it->first); if (it->second.coin.IsSpent()) batch.Erase(entry); else batch.Write(entry, it->second.coin); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); if (batch.SizeEstimate() > batch_size) { LogPrint(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0)); m_db->WriteBatch(batch); batch.Clear(); if (crash_simulate) { static FastRandomContext rng; if (rng.randrange(crash_simulate) == 0) { LogPrintf("Simulating a crash. Goodbye.\n"); _Exit(0); } } } } // In the last batch, mark the database as consistent with hashBlock again. batch.Erase(DB_HEAD_BLOCKS); batch.Write(DB_BEST_BLOCK, hashBlock); LogPrint(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0)); bool ret = m_db->WriteBatch(batch); LogPrint(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return ret; } size_t CCoinsViewDB::EstimateSize() const { return m_db->EstimateSize(DB_COIN, uint8_t(DB_COIN + 1)); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(gArgs.GetDataDirNet() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(std::make_pair(DB_BLOCK_FILES, nFile), info); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write(DB_REINDEX_FLAG, uint8_t{'1'}); else return Erase(DB_REINDEX_FLAG); } void CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists(DB_REINDEX_FLAG); } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read(DB_LAST_BLOCK, nFile); } /** Specialization of CCoinsViewCursor to iterate over a CCoinsViewDB */ class CCoinsViewDBCursor: public CCoinsViewCursor { public: // Prefer using CCoinsViewDB::Cursor() since we want to perform some // cache warmup on instantiation. CCoinsViewDBCursor(CDBIterator* pcursorIn, const uint256&hashBlockIn): CCoinsViewCursor(hashBlockIn), pcursor(pcursorIn) {} ~CCoinsViewDBCursor() {} bool GetKey(COutPoint &key) const override; bool GetValue(Coin &coin) const override; unsigned int GetValueSize() const override; bool Valid() const override; void Next() override; private: std::unique_ptr<CDBIterator> pcursor; std::pair<char, COutPoint> keyTmp; friend class CCoinsViewDB; }; std::unique_ptr<CCoinsViewCursor> CCoinsViewDB::Cursor() const { auto i = std::make_unique<CCoinsViewDBCursor>( const_cast<CDBWrapper&>(*m_db).NewIterator(), GetBestBlock()); /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ i->pcursor->Seek(DB_COIN); // Cache key of first record if (i->pcursor->Valid()) { CoinEntry entry(&i->keyTmp.second); i->pcursor->GetKey(entry); i->keyTmp.first = entry.key; } else { i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false } return i; } bool CCoinsViewDBCursor::GetKey(COutPoint &key) const { // Return cached key if (keyTmp.first == DB_COIN) { key = keyTmp.second; return true; } return false; } bool CCoinsViewDBCursor::GetValue(Coin &coin) const { return pcursor->GetValue(coin); } unsigned int CCoinsViewDBCursor::GetValueSize() const { return pcursor->GetValueSize(); } bool CCoinsViewDBCursor::Valid() const { return keyTmp.first == DB_COIN; } void CCoinsViewDBCursor::Next() { pcursor->Next(); CoinEntry entry(&keyTmp.second); if (!pcursor->Valid() || !pcursor->GetKey(entry)) { keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false } else { keyTmp.first = entry.key; } } bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) { CDBBatch batch(*this); for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) { batch.Write(std::make_pair(DB_BLOCK_FILES, it->first), *it->second); } batch.Write(DB_LAST_BLOCK, nLastFile); for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) { batch.Write(std::make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it)); } return WriteBatch(batch, true); } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair(DB_FLAG, name), fValue ? uint8_t{'1'} : uint8_t{'0'}); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { uint8_t ch; if (!Read(std::make_pair(DB_FLAG, name), ch)) return false; fValue = ch == uint8_t{'1'}; return true; } bool CBlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex) { AssertLockHeld(::cs_main); std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256())); // Load m_block_index while (pcursor->Valid()) { if (ShutdownRequested()) return false; std::pair<uint8_t, uint256> key; if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) { CDiskBlockIndex diskindex; if (pcursor->GetValue(diskindex)) { // Construct block index object CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = insertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams)) { return error("%s: CheckProofOfWork failed: %s", __func__, pindexNew->ToString()); } pcursor->Next(); } else { return error("%s: failed to read value", __func__); } } else { break; } } return true; } namespace { //! Legacy class to deserialize pre-pertxout database entries without reindex. class CCoins { public: //! whether transaction is a coinbase bool fCoinBase; //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped std::vector<CTxOut> vout; //! at which height this transaction was included in the active block chain int nHeight; //! empty constructor CCoins() : fCoinBase(false), vout(0), nHeight(0) { } template<typename Stream> void Unserialize(Stream &s) { unsigned int nCode = 0; // version unsigned int nVersionDummy; ::Unserialize(s, VARINT(nVersionDummy)); // header code ::Unserialize(s, VARINT(nCode)); fCoinBase = nCode & 1; std::vector<bool> vAvail(2, false); vAvail[0] = (nCode & 2) != 0; vAvail[1] = (nCode & 4) != 0; unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1); // spentness bitmask while (nMaskCode > 0) { unsigned char chAvail = 0; ::Unserialize(s, chAvail); for (unsigned int p = 0; p < 8; p++) { bool f = (chAvail & (1 << p)) != 0; vAvail.push_back(f); } if (chAvail != 0) nMaskCode--; } // txouts themself vout.assign(vAvail.size(), CTxOut()); for (unsigned int i = 0; i < vAvail.size(); i++) { if (vAvail[i]) ::Unserialize(s, Using<TxOutCompression>(vout[i])); } // coinbase height ::Unserialize(s, VARINT_MODE(nHeight, VarIntMode::NONNEGATIVE_SIGNED)); } }; } /** Upgrade the database from older formats. * * Currently implemented: from the per-tx utxo model (0.8..0.14.x) to per-txout. */ bool CCoinsViewDB::Upgrade() { std::unique_ptr<CDBIterator> pcursor(m_db->NewIterator()); pcursor->Seek(std::make_pair(DB_COINS, uint256())); if (!pcursor->Valid()) { return true; } int64_t count = 0; LogPrintf("Upgrading utxo-set database...\n"); LogPrintf("[0%%]..."); /* Continued */ uiInterface.ShowProgress(_("Upgrading UTXO database").translated, 0, true); size_t batch_size = 1 << 24; CDBBatch batch(*m_db); int reportDone = 0; std::pair<unsigned char, uint256> key; std::pair<unsigned char, uint256> prev_key = {DB_COINS, uint256()}; while (pcursor->Valid()) { if (ShutdownRequested()) { break; } if (pcursor->GetKey(key) && key.first == DB_COINS) { if (count++ % 256 == 0) { uint32_t high = 0x100 * *key.second.begin() + *(key.second.begin() + 1); int percentageDone = (int)(high * 100.0 / 65536.0 + 0.5); uiInterface.ShowProgress(_("Upgrading UTXO database").translated, percentageDone, true); if (reportDone < percentageDone/10) { // report max. every 10% step LogPrintf("[%d%%]...", percentageDone); /* Continued */ reportDone = percentageDone/10; } } CCoins old_coins; if (!pcursor->GetValue(old_coins)) { return error("%s: cannot parse CCoins record", __func__); } COutPoint outpoint(key.second, 0); for (size_t i = 0; i < old_coins.vout.size(); ++i) { if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) { Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase); outpoint.n = i; CoinEntry entry(&outpoint); batch.Write(entry, newcoin); } } batch.Erase(key); if (batch.SizeEstimate() > batch_size) { m_db->WriteBatch(batch); batch.Clear(); m_db->CompactRange(prev_key, key); prev_key = key; } pcursor->Next(); } else { break; } } m_db->WriteBatch(batch); m_db->CompactRange({DB_COINS, uint256()}, key); uiInterface.ShowProgress("", 100, false); LogPrintf("[%s].\n", ShutdownRequested() ? "CANCELLED" : "DONE"); return !ShutdownRequested(); }
{ "content_hash": "6604d9c0d1a2a99b1f57fe45e9fc1658", "timestamp": "", "source": "github", "line_count": 461, "max_line_length": 200, "avg_line_length": 35.62906724511931, "alnum_prop": 0.6104109589041096, "repo_name": "achow101/bitcoin", "id": "9a39e90ccd16a4e1be0d965e4956c33b970647fa", "size": "16425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/txdb.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28178" }, { "name": "Batchfile", "bytes": "13" }, { "name": "C", "bytes": "1225820" }, { "name": "C++", "bytes": "9615124" }, { "name": "CMake", "bytes": "29132" }, { "name": "Cap'n Proto", "bytes": "1256" }, { "name": "Dockerfile", "bytes": "1721" }, { "name": "HTML", "bytes": "21833" }, { "name": "Java", "bytes": "541" }, { "name": "M4", "bytes": "237973" }, { "name": "Makefile", "bytes": "141372" }, { "name": "Objective-C++", "bytes": "5497" }, { "name": "Python", "bytes": "2718039" }, { "name": "QMake", "bytes": "438" }, { "name": "Sage", "bytes": "56897" }, { "name": "Scheme", "bytes": "24332" }, { "name": "Shell", "bytes": "207137" } ], "symlink_target": "" }
DIR = $(shell pwd) IDENTIFIER = com.example.fuhaha default: web # -------------------------------- clean: web-clean and-clean ios-clean debug: web-debug and-debug ios-debug # -------------------------------- copy: copy-web copy-and copy-ios copy-web: rsync -av --delete contents/ src_client/platform_web/bin/ --exclude='game.js' --exclude='game.js.mem' --exclude='game.wasm' --exclude='game.html' --exclude='frame.html' copy-and: rsync -av --delete contents/ src_client/platform_android/assets/ --exclude='*.ogg' copy-ios: rsync -av --delete contents/ src_client/platform_ios/assets/ --exclude='*.ogg' # -------------------------------- web: copy-web web-debug web-node web-cert: sh src_server/test/createCertificate.sh web-node: node src_server/node/main.js #node src_server/test/fileServeHttps web-debug: $(MAKE) -C src_client/platform_web debug web-release: copy-web $(MAKE) -C src_client/platform_web release web-clean: $(MAKE) -C src_client/platform_web clean # -------------------------------- and: copy-and and-debug and-install and-install: adb install -r src_client/platform_android/build/outputs/apk/platform_android-all-debug.apk adb logcat and-check-install: adb shell pm list package | grep $(IDENTIFIER) and-debug: cd src_client/platform_android; ./gradlew assembleDebug ls src_client/platform_android/build/outputs/apk/platform_android-all-debug.apk and-release: copy-and cd src_client/platform_android; ./gradlew assembleRelease ls src_client/platform_android/build/outputs/apk/platform_android-all-release.apk and-clean: cd src_client/platform_android; ./gradlew clean # -------------------------------- ios-debug: xcodebuild build -project src_client/platform_ios/fuhaha.xcodeproj -scheme fuhaha -sdk iphonesimulator -configuration Debug ios-clean: xcodebuild clean -project src_client/platform_ios/fuhaha.xcodeproj -scheme fuhaha -sdk iphonesimulator -configuration Debug # --------------------------------
{ "content_hash": "f6a5b3b8622f6f61b629650d48b89abd", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 169, "avg_line_length": 25.973684210526315, "alnum_prop": 0.6788247213779128, "repo_name": "totetero/fuhaha_engine", "id": "6d6fb15cdceced53460e8ee3cf2fcd5c48caa0d6", "size": "1974", "binary": false, "copies": "1", "ref": "refs/heads/engine", "path": "Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "564776" }, { "name": "C++", "bytes": "7115" }, { "name": "HTML", "bytes": "3260" }, { "name": "Java", "bytes": "41266" }, { "name": "JavaScript", "bytes": "66754" }, { "name": "Makefile", "bytes": "3855" }, { "name": "Objective-C", "bytes": "9219" }, { "name": "Shell", "bytes": "12077" }, { "name": "Swift", "bytes": "34280" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta charset="utf-8" /> <title>Login Page - Ace Admin</title> <meta name="description" content="User login page" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> <!-- bootstrap & fontawesome --> <link rel="stylesheet" href='@routes.Assets.at("css/bootstrap.css")' /> <link rel="stylesheet" href='@routes.Assets.at("css/font-awesome.css")' /> <!-- text fonts --> <link rel="stylesheet" href='@routes.Assets.at("css/ace-fonts.css")' /> <!-- ace styles --> <link rel="stylesheet" href='@routes.Assets.at("css/ace.css")' /> <!--[if lte IE 9]> <link rel="stylesheet" href='@routes.Assets.at("css/ace-part2.css")' /> <![endif]--> <link rel="stylesheet" href='@routes.Assets.at("css/ace-rtl.css")' /> <!--[if lte IE 9]> <link rel="stylesheet" href='@routes.Assets.at("css/ace-ie.css")' /> <![endif]--> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src='@routes.Assets.at("js/html5shiv.js")'/> <script src='@routes.Assets.at("js/respond.js")'/> <![endif]--> </head> <body class="login-layout blur-login"> <div class="main-container"> <div class="main-content"> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <div class="login-container"> <div class="center"> <h1> <c style="color:white">GoAgile</c> </h1> </div> <div class="space-6"></div> <div class="position-relative"> <div id="login-box" class="login-box visible widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <img src="@routes.Assets.at("img/cn_group_logo.png")"> <form method="post" action="@routes.Application.newBoard()" style="margin-top: 5%"> <fieldset> <div class="form-group"> <div class="col-sm-9"> <input type="text" name="userName" placeholder="User name" class="form-control"> </div> </div> <div class="form-group"> <div class="col-sm-9"> <input type="text" name="boardName" placeholder="Board name" class="form-control"> </div> </div> <div class="space-6"></div> <label class="block" style="margin-left: 30%;margin-top: 10%"> <span class="block input-icon input-icon-right"> <input type="submit" text="Create"> </span> </label> <div class="space-4"></div> </fieldset> </form> </div><!-- /.widget-main --> </div><!-- /.widget-body --> </div><!-- /.login-box --> </div><!-- /.position-relative --> </div> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.main-content --> </div><!-- /.main-container --> <!-- basic scripts --> <!--[if !IE]> --> <script type="text/javascript"> window.jQuery || document.write("<script src='../assets/js/jquery.js'>"+"<"+"/script>"); </script> <!-- <![endif]--> <!--[if IE]> < <![endif]--> <script src=""></script> <script src="js/jquery.js"></script> <script src='@routes.Assets.at("js/bootstrap.js")'></script> </body> </html>
{ "content_hash": "5a537f6e38aa3fe4f65c45c6266d228a", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 97, "avg_line_length": 27.261904761904763, "alnum_prop": 0.5344978165938865, "repo_name": "rex1234/vmbs_projekt", "id": "f69867dfc36c816532cd9bc7b66b1efbc65d8fdc", "size": "3435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/login.scala.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1023680" }, { "name": "HTML", "bytes": "16081" }, { "name": "Java", "bytes": "13398" }, { "name": "JavaScript", "bytes": "3132216" }, { "name": "Scala", "bytes": "1090" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <artifactId>part2</artifactId> <groupId>ru.amizichenko</groupId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>ru.amizichenko</groupId> <artifactId>lesson9</artifactId> <build> <plugins> <plugin> <artifactId>maven-shade-plugin</artifactId> <version>2.4.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer> <manifestEntries> <Main-Class>ru.amizichenko.tracker.start.StartUITest</Main-Class> </manifestEntries> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "29fd9385233478f1e92820e8a942b54b", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 201, "avg_line_length": 31.972972972972972, "alnum_prop": 0.5604395604395604, "repo_name": "Defo82/Mizichenko", "id": "6bf7291a7cc5a6654f7f68b83012b299333261cb", "size": "1183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "part2/lesson9/dependency-reduced-pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7965" } ], "symlink_target": "" }
@class CardIOPaymentViewController; @class CardIOCreditCardInfo; /// The receiver will be notified when the CardIOPaymentViewController flow completes, due to either success or user-cancellation. /// /// Exactly one of these delegate methods will be called. /// /// Each of them MUST dismiss the CardIOPaymentViewController. @protocol CardIOPaymentViewControllerDelegate<NSObject> @required /// This method will be called if the user cancels the scan. You MUST dismiss paymentViewController. /// @param paymentViewController The active CardIOPaymentViewController. - (void)userDidCancelPaymentViewController:(CardIOPaymentViewController *)paymentViewController; /// This method will be called when there is a successful scan (or manual entry). You MUST dismiss paymentViewController. /// @param cardInfo The results of the scan. /// @param paymentViewController The active CardIOPaymentViewController. - (void)userDidProvideCreditCardInfo:(CardIOCreditCardInfo *)cardInfo inPaymentViewController:(CardIOPaymentViewController *)paymentViewController; @end
{ "content_hash": "3a93d50b9682c44db06adf330b848e3b", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 147, "avg_line_length": 48.13636363636363, "alnum_prop": 0.8224740321057602, "repo_name": "tisunov/InstacabClient", "id": "bf31c44091dca34615d04b13d3a2b8f484ed8554", "size": "1221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Instacab/CardIO/CardIOPaymentViewControllerDelegate.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1972" }, { "name": "C++", "bytes": "15022" }, { "name": "Objective-C", "bytes": "498706" }, { "name": "Ruby", "bytes": "1054" } ], "symlink_target": "" }
<?php class modelController extends baseController { /** * 模型管理列表 */ public function index(){ $limit = $this->getLimit(); $m_model = M('model'); $this->buffer['list'] = $m_model->limit($limit)->select(); $this->display(); } /** * 编辑/新增模型 */ public function edit(){ $mid = intval($_GET['mid']); if($mid){ $this->buffer['info'] =M('model')->getByMid($mid); $this->buffer['field'] =M('model_field')->getByMid($mid); } $this->display(); } public function import(){ $this->display(); } public function importAction(){ import('upload'); $upload = new upload('modelJson', 'tmp'); $upload->setAllowType('application/octet-stream'); $jsonPath = HAO_ROOT .$upload->save(); $jsonData = file_get_contents($jsonPath); $modelArr = json_decode($jsonData, true); M('model')->import($modelArr); $this->showmessage('导入成功!'); } /** * 发表内容 */ public function post(){ import('model', 'fun'); $mid = $this->_getMid(); $this->buffer['mid'] = $mid; $this->buffer['modname'] = M('model')->getModNameById($mid); $this->buffer['list'] = M('model_field')->getFormField($mid); $this->display(); } public function postAction(){ $mid = $this->_getMid(); $modelField = array('modname', 'tablename', 'classable'); $modelWhere = array('mid' => $mid); $modelData = M('model')->selectOne($modelField, $modelWhere); $fieldList = M('model_field')->getFormField($mid, true); $rule = array(); foreach($fieldList as $key => $item){ if($item['formtype'] != 0){ $rule[$key] = $this->_getFieldRule($item); } elseif($item['fieldtype'] == 11){ $tmp[$key] = time(); } else { $tmp[$key] = $item['default']; } } if($modelData['classable']){ $rule['cid'] =array( 'explain' => $modelData['modname'] .'栏目', 'rule' => 'number', ); } $param = $this->getParam($rule, 'post', false); $param = array_merge($param, $tmp); $m_modelSystem = SM($mid); $m_modelSystem->insertData($param); $this->showmessage('发布成功!'); } public function contentlist(){ $page = $this->getPage(); $mid = $this->_getMid(); $modelObj = SM($mid); $data = $modelObj->loadList($page, 30); $this->buffer['field'] = $data['field']; $this->buffer['fieldtype'] = $data['fieldtype']; $this->buffer['list'] = $data['list']; $this->display(); } private function _getFieldRule($item = array()){ $ruleArr = array(); if($item['allownull'] == 1){ $ruleArr[] = 'null'; } if($item['length'] > 0){ $ruleArr[] = 'max:'. $item['length']; } $return = array( 'explain' => $item['viewname'], 'rule' => implode(',', $ruleArr), ); if($item['allowhtml'] == 1){ $return['html'] = true; } return $return; } /** * 获取GET传递来的MID */ private function _getMid(){ $mid = intval($_GET['mid']); if($mid < 1){ $this->showmessage('模型选择错误!'); } return $mid; } }
{ "content_hash": "7cb39a2075e5c0d2a42e051c9fa69d9a", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 66, "avg_line_length": 19.158940397350992, "alnum_prop": 0.5668855858969928, "repo_name": "haosblog/blog", "id": "4fcfb6508fb7fc8c7ed745c1ee098aed79a6047b", "size": "3140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/controller/admin/modelController.class.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "109488" }, { "name": "Java", "bytes": "14870" }, { "name": "JavaScript", "bytes": "705057" }, { "name": "PHP", "bytes": "1523058" } ], "symlink_target": "" }
using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } void read_input(unsigned int& problems, vector<vector<string>>& code_names, vector<unsigned int>& order) { cin >> problems; code_names.resize(problems); for (unsigned int i {0}; i < problems; ++i) { code_names[i].resize(3); cin >> code_names[i][0] >> code_names[i][1] >> code_names[i][2]; sort(code_names[i].begin(), code_names[i].end()); } order.resize(problems); for (auto& problem_id : order) { cin >> problem_id; --problem_id; } } vector<string> choose_code_names(const vector<vector<string>>& code_names, const vector<unsigned int>& order) { vector<string> chosen {code_names[order[0]][0]}; for (unsigned int i {1}; i < order.size(); ++i) { for (unsigned int j {0}; j < 3; ++j) { if (chosen.back() < code_names[order[i]][j]) { chosen.push_back(code_names[order[i]][j]); break; } } } return chosen; } void write_output(const vector<string>& chosen, unsigned int problems) { if (chosen.size() == problems) { for (const auto& code_name : chosen) { cout << code_name << '\n'; } } else { cout << "IMPOSSIBLE\n"; } } int main() { use_io_optimizations(); unsigned int problems; vector<vector<string>> code_names; vector<unsigned int> order; read_input(problems, code_names, order); write_output(choose_code_names(code_names, order), problems); return 0; }
{ "content_hash": "1756b2c328859be7ca44ae910cd3469b", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 74, "avg_line_length": 20.764705882352942, "alnum_prop": 0.5240793201133145, "repo_name": "gshopov/competitive-programming-archive", "id": "db897cb01c6f582ec3d8319dfdc7215e778833c7", "size": "1843", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "timus/volume-08/code_names.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1238266" }, { "name": "Java", "bytes": "21451" }, { "name": "Python", "bytes": "21" } ], "symlink_target": "" }
require 'rack/request' require 'hashr' module Lote module Request refine ::Rack::Request do def params @hashr_params ||= Hashr.new(super) end end end end
{ "content_hash": "26b5ff2e098d8107c615fd1dfe2c1f7e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 42, "avg_line_length": 15.583333333333334, "alnum_prop": 0.6256684491978609, "repo_name": "rosylilly/lote-test", "id": "d11a8852d26e294a978d8d3d6fca73d38aeab7db", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/lote/request.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "14626" } ], "symlink_target": "" }
"""Helper functions for mip-NeRF.""" from jax import lax from jax import random import jax.numpy as jnp from internal import math def pos_enc(x, min_deg, max_deg, append_identity=True): """The positional encoding used by the original NeRF paper.""" scales = jnp.array([2**i for i in range(min_deg, max_deg)]) xb = jnp.reshape((x[..., None, :] * scales[:, None]), list(x.shape[:-1]) + [-1]) four_feat = jnp.sin(jnp.concatenate([xb, xb + 0.5 * jnp.pi], axis=-1)) if append_identity: return jnp.concatenate([x] + [four_feat], axis=-1) else: return four_feat def expected_sin(x, x_var): """Estimates mean and variance of sin(z), z ~ N(x, var).""" # When the variance is wide, shrink sin towards zero. y = jnp.exp(-0.5 * x_var) * math.safe_sin(x) y_var = jnp.maximum( 0, 0.5 * (1 - jnp.exp(-2 * x_var) * math.safe_cos(2 * x)) - y**2) return y, y_var def lift_gaussian(d, t_mean, t_var, r_var, diag): """Lift a Gaussian defined along a ray to 3D coordinates.""" mean = d[..., None, :] * t_mean[..., None] d_mag_sq = jnp.maximum(1e-10, jnp.sum(d**2, axis=-1, keepdims=True)) if diag: d_outer_diag = d**2 null_outer_diag = 1 - d_outer_diag / d_mag_sq t_cov_diag = t_var[..., None] * d_outer_diag[..., None, :] xy_cov_diag = r_var[..., None] * null_outer_diag[..., None, :] cov_diag = t_cov_diag + xy_cov_diag return mean, cov_diag else: d_outer = d[..., :, None] * d[..., None, :] eye = jnp.eye(d.shape[-1]) null_outer = eye - d[..., :, None] * (d / d_mag_sq)[..., None, :] t_cov = t_var[..., None, None] * d_outer[..., None, :, :] xy_cov = r_var[..., None, None] * null_outer[..., None, :, :] cov = t_cov + xy_cov return mean, cov def conical_frustum_to_gaussian(d, t0, t1, base_radius, diag, stable=True): """Approximate a conical frustum as a Gaussian distribution (mean+cov). Assumes the ray is originating from the origin, and base_radius is the radius at dist=1. Doesn't assume `d` is normalized. Args: d: jnp.float32 3-vector, the axis of the cone t0: float, the starting distance of the frustum. t1: float, the ending distance of the frustum. base_radius: float, the scale of the radius as a function of distance. diag: boolean, whether or the Gaussian will be diagonal or full-covariance. stable: boolean, whether or not to use the stable computation described in the paper (setting this to False will cause catastrophic failure). Returns: a Gaussian (mean and covariance). """ if stable: mu = (t0 + t1) / 2 hw = (t1 - t0) / 2 t_mean = mu + (2 * mu * hw**2) / (3 * mu**2 + hw**2) t_var = (hw**2) / 3 - (4 / 15) * ((hw**4 * (12 * mu**2 - hw**2)) / (3 * mu**2 + hw**2)**2) r_var = base_radius**2 * ((mu**2) / 4 + (5 / 12) * hw**2 - 4 / 15 * (hw**4) / (3 * mu**2 + hw**2)) else: t_mean = (3 * (t1**4 - t0**4)) / (4 * (t1**3 - t0**3)) r_var = base_radius**2 * (3 / 20 * (t1**5 - t0**5) / (t1**3 - t0**3)) t_mosq = 3 / 5 * (t1**5 - t0**5) / (t1**3 - t0**3) t_var = t_mosq - t_mean**2 return lift_gaussian(d, t_mean, t_var, r_var, diag) def cylinder_to_gaussian(d, t0, t1, radius, diag): """Approximate a cylinder as a Gaussian distribution (mean+cov). Assumes the ray is originating from the origin, and radius is the radius. Does not renormalize `d`. Args: d: jnp.float32 3-vector, the axis of the cylinder t0: float, the starting distance of the cylinder. t1: float, the ending distance of the cylinder. radius: float, the radius of the cylinder diag: boolean, whether or the Gaussian will be diagonal or full-covariance. Returns: a Gaussian (mean and covariance). """ t_mean = (t0 + t1) / 2 r_var = radius**2 / 4 t_var = (t1 - t0)**2 / 12 return lift_gaussian(d, t_mean, t_var, r_var, diag) def cast_rays(t_vals, origins, directions, radii, ray_shape, diag=True): """Cast rays (cone- or cylinder-shaped) and featurize sections of it. Args: t_vals: float array, the "fencepost" distances along the ray. origins: float array, the ray origin coordinates. directions: float array, the ray direction vectors. radii: float array, the radii (base radii for cones) of the rays. ray_shape: string, the shape of the ray, must be 'cone' or 'cylinder'. diag: boolean, whether or not the covariance matrices should be diagonal. Returns: a tuple of arrays of means and covariances. """ t0 = t_vals[..., :-1] t1 = t_vals[..., 1:] if ray_shape == 'cone': gaussian_fn = conical_frustum_to_gaussian elif ray_shape == 'cylinder': gaussian_fn = cylinder_to_gaussian else: assert False means, covs = gaussian_fn(directions, t0, t1, radii, diag) means = means + origins[..., None, :] return means, covs def integrated_pos_enc(x_coord, min_deg, max_deg, diag=True): """Encode `x` with sinusoids scaled by 2^[min_deg:max_deg-1]. Args: x_coord: a tuple containing: x, jnp.ndarray, variables to be encoded. Should be in [-pi, pi]. x_cov, jnp.ndarray, covariance matrices for `x`. min_deg: int, the min degree of the encoding. max_deg: int, the max degree of the encoding. diag: bool, if true, expects input covariances to be diagonal (full otherwise). Returns: encoded: jnp.ndarray, encoded variables. """ if diag: x, x_cov_diag = x_coord scales = jnp.array([2**i for i in range(min_deg, max_deg)]) shape = list(x.shape[:-1]) + [-1] y = jnp.reshape(x[..., None, :] * scales[:, None], shape) y_var = jnp.reshape(x_cov_diag[..., None, :] * scales[:, None]**2, shape) else: x, x_cov = x_coord num_dims = x.shape[-1] basis = jnp.concatenate( [2**i * jnp.eye(num_dims) for i in range(min_deg, max_deg)], 1) y = math.matmul(x, basis) # Get the diagonal of a covariance matrix (ie, variance). This is equivalent # to jax.vmap(jnp.diag)((basis.T @ covs) @ basis). y_var = jnp.sum((math.matmul(x_cov, basis)) * basis, -2) return expected_sin( jnp.concatenate([y, y + 0.5 * jnp.pi], axis=-1), jnp.concatenate([y_var] * 2, axis=-1))[0] def volumetric_rendering(rgb, density, t_vals, dirs, white_bkgd): """Volumetric Rendering Function. Args: rgb: jnp.ndarray(float32), color, [batch_size, num_samples, 3] density: jnp.ndarray(float32), density, [batch_size, num_samples, 1]. t_vals: jnp.ndarray(float32), [batch_size, num_samples]. dirs: jnp.ndarray(float32), [batch_size, 3]. white_bkgd: bool. Returns: comp_rgb: jnp.ndarray(float32), [batch_size, 3]. disp: jnp.ndarray(float32), [batch_size]. acc: jnp.ndarray(float32), [batch_size]. weights: jnp.ndarray(float32), [batch_size, num_samples] """ t_mids = 0.5 * (t_vals[..., :-1] + t_vals[..., 1:]) t_dists = t_vals[..., 1:] - t_vals[..., :-1] delta = t_dists * jnp.linalg.norm(dirs[..., None, :], axis=-1) # Note that we're quietly turning density from [..., 0] to [...]. density_delta = density[..., 0] * delta alpha = 1 - jnp.exp(-density_delta) trans = jnp.exp(-jnp.concatenate([ jnp.zeros_like(density_delta[..., :1]), jnp.cumsum(density_delta[..., :-1], axis=-1) ], axis=-1)) weights = alpha * trans comp_rgb = (weights[..., None] * rgb).sum(axis=-2) acc = weights.sum(axis=-1) distance = (weights * t_mids).sum(axis=-1) / acc distance = jnp.clip( jnp.nan_to_num(distance, jnp.inf), t_vals[:, 0], t_vals[:, -1]) if white_bkgd: comp_rgb = comp_rgb + (1. - acc[..., None]) return comp_rgb, distance, acc, weights def sample_along_rays(key, origins, directions, radii, num_samples, near, far, randomized, lindisp, ray_shape): """Stratified sampling along the rays. Args: key: jnp.ndarray, random generator key. origins: jnp.ndarray(float32), [batch_size, 3], ray origins. directions: jnp.ndarray(float32), [batch_size, 3], ray directions. radii: jnp.ndarray(float32), [batch_size, 3], ray radii. num_samples: int. near: jnp.ndarray, [batch_size, 1], near clip. far: jnp.ndarray, [batch_size, 1], far clip. randomized: bool, use randomized stratified sampling. lindisp: bool, sampling linearly in disparity rather than depth. ray_shape: string, which shape ray to assume. Returns: t_vals: jnp.ndarray, [batch_size, num_samples], sampled z values. means: jnp.ndarray, [batch_size, num_samples, 3], sampled means. covs: jnp.ndarray, [batch_size, num_samples, 3, 3], sampled covariances. """ batch_size = origins.shape[0] t_vals = jnp.linspace(0., 1., num_samples + 1) if lindisp: t_vals = 1. / (1. / near * (1. - t_vals) + 1. / far * t_vals) else: t_vals = near * (1. - t_vals) + far * t_vals if randomized: mids = 0.5 * (t_vals[..., 1:] + t_vals[..., :-1]) upper = jnp.concatenate([mids, t_vals[..., -1:]], -1) lower = jnp.concatenate([t_vals[..., :1], mids], -1) t_rand = random.uniform(key, [batch_size, num_samples + 1]) t_vals = lower + (upper - lower) * t_rand else: # Broadcast t_vals to make the returned shape consistent. t_vals = jnp.broadcast_to(t_vals, [batch_size, num_samples + 1]) means, covs = cast_rays(t_vals, origins, directions, radii, ray_shape) return t_vals, (means, covs) def resample_along_rays(key, origins, directions, radii, t_vals, weights, randomized, ray_shape, stop_grad, resample_padding): """Resampling. Args: key: jnp.ndarray(float32), [2,], random number generator. origins: jnp.ndarray(float32), [batch_size, 3], ray origins. directions: jnp.ndarray(float32), [batch_size, 3], ray directions. radii: jnp.ndarray(float32), [batch_size, 3], ray radii. t_vals: jnp.ndarray(float32), [batch_size, num_samples+1]. weights: jnp.array(float32), weights for t_vals randomized: bool, use randomized samples. ray_shape: string, which kind of shape to assume for the ray. stop_grad: bool, whether or not to backprop through sampling. resample_padding: float, added to the weights before normalizing. Returns: t_vals: jnp.ndarray(float32), [batch_size, num_samples+1]. points: jnp.ndarray(float32), [batch_size, num_samples, 3]. """ # Do a blurpool. weights_pad = jnp.concatenate([ weights[..., :1], weights, weights[..., -1:], ], axis=-1) weights_max = jnp.maximum(weights_pad[..., :-1], weights_pad[..., 1:]) weights_blur = 0.5 * (weights_max[..., :-1] + weights_max[..., 1:]) # Add in a constant (the sampling function will renormalize the PDF). weights = weights_blur + resample_padding new_t_vals = math.sorted_piecewise_constant_pdf( key, t_vals, weights, t_vals.shape[-1], randomized, ) if stop_grad: new_t_vals = lax.stop_gradient(new_t_vals) means, covs = cast_rays(new_t_vals, origins, directions, radii, ray_shape) return new_t_vals, (means, covs)
{ "content_hash": "a2d05170d5647aafcd9a277258a8175c", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 80, "avg_line_length": 37.343434343434346, "alnum_prop": 0.6086015688395997, "repo_name": "google/mipnerf", "id": "d46759432255a66b84e9e3b455da45236d758b94", "size": "11686", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "internal/mip.py", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef _VKTDYNAMICSTATEVPTESTS_HPP #define _VKTDYNAMICSTATEVPTESTS_HPP /*! * \file * \brief Dynamic State Viewport Tests *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "vktTestCase.hpp" #include "vkPipelineConstructionUtil.hpp" namespace vkt { namespace DynamicState { class DynamicStateVPTests : public tcu::TestCaseGroup { public: DynamicStateVPTests (tcu::TestContext& testCtx, vk::PipelineConstructionType pipelineConstructionType); ~DynamicStateVPTests (void); void init (void); private: DynamicStateVPTests (const DynamicStateVPTests& other); DynamicStateVPTests& operator= (const DynamicStateVPTests& other); vk::PipelineConstructionType m_pipelineConstructionType; }; } // DynamicState } // vkt #endif // _VKTDYNAMICSTATEVPTESTS_HPP
{ "content_hash": "8328214fc1870f55c5d4ac0ef81f247d", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 112, "avg_line_length": 25.11764705882353, "alnum_prop": 0.6873536299765808, "repo_name": "KhronosGroup/VK-GL-CTS", "id": "4f17c92dceffe6e2b8d5bb138ff8688364d8326a", "size": "1638", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "external/vulkancts/modules/vulkan/dynamic_state/vktDynamicStateVPTests.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "320" }, { "name": "C", "bytes": "603883" }, { "name": "C++", "bytes": "23597354" }, { "name": "CMake", "bytes": "120882" }, { "name": "HTML", "bytes": "67517" }, { "name": "Java", "bytes": "246628" }, { "name": "Makefile", "bytes": "89529" }, { "name": "Objective-C", "bytes": "10922" }, { "name": "Objective-C++", "bytes": "19107" }, { "name": "Python", "bytes": "644096" }, { "name": "Shell", "bytes": "2672" } ], "symlink_target": "" }
CLD2-CFFI - Python (CFFI) Bindings for Compact Language Detector 2 ================================================================== `CFFI <cffi.readthedocs.org>`_ bindings for CLD2 ----- |pypi| |build| |win-build| |coverage| |lint| ----- This package contains the CLD (Compact Language Detection) library as maintained by Dick Sites (https://code.google.com/p/cld2/). The first fork was done at revision r161. It also contains python bindings that were originally created by `Mike McCandless <http://code.google.com/p/chromium-compact-language-detector>`_. The bindings have gone through several hands, with the latest changes being made to rework the bindings for `CFFI <cffi.readthedocs.org>`_. These bindings are identical in API to the original cld2 bindings, and as a result can be used as a drop in replacement. The LICENSE_ is the same as Chromium's LICENSE and is included in the LICENSE_ file for reference. ========== Installing ========== Should be as simple as .. code-block:: bash $ pip install cld2-cffi ------------------- Development Version ------------------- The **latest development version** can be installed directly from GitHub: .. code-block:: bash $ pip install --upgrade 'git+https://github.com/GregBowyer/cld2-cffi.git' ===== Usage ===== .. code-block:: python import cld2 isReliable, textBytesFound, details = cld2.detect("This is my sample text") print(' reliable: %s' % (isReliable != 0)) print(' textBytes: %s' % textBytesFound) print(' details: %s' % str(details)) # The output looks like so: # reliable: True # textBytes: 24 # details: (('ENGLISH', 'en', 95, 1736.0), ('Unknown', 'un', 0, 0.0), ('Unknown', 'un', 0, 0.0)) ============= Documentation ============= First, you must get your content (plain text or HTML) encoded into UTF8 bytes. Then, detect like this: .. code-block:: python isReliable, textBytesFound, details = cld2.detect(bytes) ``isReliable`` is True if the top language is much better than 2nd best language. ``textBytesFound`` tells you how many actual bytes CLD analyzed (after removing HTML tags, collapsing areas of too-many-spaces, etc.). ``details`` has an entry per top 3 languages that matched, that includes the percent confidence of the match as well as a separate normalized score. The module exports these global constants: ``cld2.ENCODINGS`` list of the encoding names CLD recognizes (if you provide hintEncoding, it must be one of these names). ``cld2.LANGUAGES`` list of languages and their codes (if you provide hintLanguageCode, it must be one of the codes from these codes). ``cld2.EXTERNAL_LANGUAGES`` list of external languages and their codes. Note that external languages cannot be hinted, but may be matched if you pass ``includeExtendedLanguages=True`` (the default). ``cld2.DETECTED_LANGUAGES`` list of all detectable languages, as best I can determine (this was reverse engineered from a unit test, ie it contains a language X if that language was tested and passes for at least one example text). ======= Authors ======= Please see `AUTHORS <https://github.com/GregBowyer/cld2-cffi/blob/master/BUG_REPORTS.rst>`_. ============== Reporting bugs ============== Please see `BUG_REPORTS <https://github.com/GregBowyer/cld2-cffi/blob/master/BUG_REPORTS.rst>`_. ========== Contribute ========== Please see `CONTRIBUTING <https://github.com/GregBowyer/cld2-cffi/blob/master/CONTRIBUTING.rst>`_. ======= Licence ======= Please see LICENSE_. .. _LICENSE: https://github.com/GregBowyer/cld2-cffi/blob/master/LICENSE .. |pypi| image:: https://img.shields.io/pypi/v/cld2-cffi.svg?style=flat-square&label=latest%20version :target: https://pypi.python.org/pypi/cld2-cffi :alt: Latest version released on PyPi .. |build| image:: https://img.shields.io/travis/GregBowyer/cld2-cffi/master.svg?style=flat-square&label=OSX%20Linux%20build :target: http://travis-ci.org/GregBowyer/cld2-cffi :alt: Build status .. |win-build| image:: https://img.shields.io/appveyor/ci/GregBowyer/cld2-cffi.svg?maxAge=2592000&style=flat-square&label=Windows%20Build :target: https://ci.appveyor.com/project/GregBowyer/cld2-cffi :alt: Windows Build Status:: .. |coverage| image:: https://img.shields.io/codecov/c/github/GregBowyer/cld2-cffi.svg?style=flat-square :target: https://codecov.io/github/GregBowyer/cld2-cffi :alt: Coverage .. |lint| image:: https://landscape.io/github/GregBowyer/cld2-cffi/master/landscape.svg?style=flat-square :target: https://landscape.io/github/GregBowyer/cld2-cffi/master :alt: Code Health
{ "content_hash": "7e6299eea12151f0894d0a34164fb612", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 137, "avg_line_length": 30.344155844155843, "alnum_prop": 0.6884228546971967, "repo_name": "GregBowyer/cld2-cffi", "id": "955a8efc0c0ffb04069f2e3f6d3a48eeda5bd648", "size": "4673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "254056" }, { "name": "C++", "bytes": "107642659" }, { "name": "HTML", "bytes": "668077" }, { "name": "Python", "bytes": "180143" }, { "name": "Shell", "bytes": "17633" } ], "symlink_target": "" }
#include "Time_Cnt.h" static Time_Cnt_backupStruct Time_Cnt_backup; /******************************************************************************* * Function Name: Time_Cnt_SaveConfig ******************************************************************************** * Summary: * Save the current user configuration * * Parameters: * void * * Return: * void * * Global variables: * Time_Cnt_backup: Variables of this global structure are modified to * store the values of non retention configuration registers when Sleep() API is * called. * *******************************************************************************/ void Time_Cnt_SaveConfig(void) { #if (!Time_Cnt_UsingFixedFunction) Time_Cnt_backup.CounterUdb = Time_Cnt_ReadCounter(); #if(!Time_Cnt_ControlRegRemoved) Time_Cnt_backup.CounterControlRegister = Time_Cnt_ReadControlRegister(); #endif /* (!Time_Cnt_ControlRegRemoved) */ #endif /* (!Time_Cnt_UsingFixedFunction) */ } /******************************************************************************* * Function Name: Time_Cnt_RestoreConfig ******************************************************************************** * * Summary: * Restores the current user configuration. * * Parameters: * void * * Return: * void * * Global variables: * Time_Cnt_backup: Variables of this global structure are used to * restore the values of non retention registers on wakeup from sleep mode. * *******************************************************************************/ void Time_Cnt_RestoreConfig(void) { #if (!Time_Cnt_UsingFixedFunction) Time_Cnt_WriteCounter(Time_Cnt_backup.CounterUdb); #if(!Time_Cnt_ControlRegRemoved) Time_Cnt_WriteControlRegister(Time_Cnt_backup.CounterControlRegister); #endif /* (!Time_Cnt_ControlRegRemoved) */ #endif /* (!Time_Cnt_UsingFixedFunction) */ } /******************************************************************************* * Function Name: Time_Cnt_Sleep ******************************************************************************** * Summary: * Stop and Save the user configuration * * Parameters: * void * * Return: * void * * Global variables: * Time_Cnt_backup.enableState: Is modified depending on the enable * state of the block before entering sleep mode. * *******************************************************************************/ void Time_Cnt_Sleep(void) { #if(!Time_Cnt_ControlRegRemoved) /* Save Counter's enable state */ if(Time_Cnt_CTRL_ENABLE == (Time_Cnt_CONTROL & Time_Cnt_CTRL_ENABLE)) { /* Counter is enabled */ Time_Cnt_backup.CounterEnableState = 1u; } else { /* Counter is disabled */ Time_Cnt_backup.CounterEnableState = 0u; } #else Time_Cnt_backup.CounterEnableState = 1u; if(Time_Cnt_backup.CounterEnableState != 0u) { Time_Cnt_backup.CounterEnableState = 0u; } #endif /* (!Time_Cnt_ControlRegRemoved) */ Time_Cnt_Stop(); Time_Cnt_SaveConfig(); } /******************************************************************************* * Function Name: Time_Cnt_Wakeup ******************************************************************************** * * Summary: * Restores and enables the user configuration * * Parameters: * void * * Return: * void * * Global variables: * Time_Cnt_backup.enableState: Is used to restore the enable state of * block on wakeup from sleep mode. * *******************************************************************************/ void Time_Cnt_Wakeup(void) { Time_Cnt_RestoreConfig(); #if(!Time_Cnt_ControlRegRemoved) if(Time_Cnt_backup.CounterEnableState == 1u) { /* Enable Counter's operation */ Time_Cnt_Enable(); } /* Do nothing if Counter was disabled before */ #endif /* (!Time_Cnt_ControlRegRemoved) */ } /* [] END OF FILE */
{ "content_hash": "7d78d27584694dbb94c110f41f8c5b63", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 84, "avg_line_length": 27.41216216216216, "alnum_prop": 0.4858269657382302, "repo_name": "UNCAMotorsports/UNCAMotorsports-2017", "id": "2ef9d9fe0e516e96251d15646a2f7a4860a08caa", "size": "4771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C-CAN/C-CAN_PSoC_DevKit/C-CAN.cydsn/Generated_Source/PSoC5/Time_Cnt_PM.c", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "63969" }, { "name": "Assembly", "bytes": "447884" }, { "name": "C", "bytes": "13519377" }, { "name": "C++", "bytes": "3797876" }, { "name": "HTML", "bytes": "336853" }, { "name": "Objective-C", "bytes": "10014" }, { "name": "PAWN", "bytes": "2750760" }, { "name": "Processing", "bytes": "26452" }, { "name": "Python", "bytes": "1090" }, { "name": "Verilog", "bytes": "168943" } ], "symlink_target": "" }
// Play Area Cursor|Pointers|10050 namespace VRTK { using UnityEngine; /// <summary> /// The Play Area Cursor is used in conjunction with a Pointer script and displays a representation of the play area where the pointer cursor hits. /// </summary> /// <example> /// `VRTK/Examples/012_Controller_PointerWithAreaCollision` shows how a Bezier Pointer with the Play Area Cursor and Collision Detection enabled can be used to traverse a game area but not allow teleporting into areas where the walls or other objects would fall into the play area space enabling the user to enter walls. /// </example> public class VRTK_PlayAreaCursor : MonoBehaviour { [Tooltip("Determines the size of the play area cursor and collider. If the values are left as zero then the Play Area Cursor will be sized to the calibrated Play Area space.")] public Vector2 playAreaCursorDimensions = Vector2.zero; [Tooltip("If this is ticked then if the play area cursor is colliding with any other object then the pointer colour will change to the `Pointer Miss Color` and the `DestinationMarkerSet` event will not be triggered, which will prevent teleporting into areas where the play area will collide.")] public bool handlePlayAreaCursorCollisions = false; [Tooltip("If this is ticked then if the user's headset is outside of the play area cursor bounds then it is considered a collision even if the play area isn't colliding with anything.")] public bool headsetOutOfBoundsIsCollision = false; [Tooltip("A specified VRTK_PolicyList to use to determine whether the play area cursor collisions will be acted upon.")] public VRTK_PolicyList targetListPolicy; [Header("Custom Settings")] [Tooltip("If this is checked then the pointer hit/miss colours will also be used to change the colour of the play area cursor when colliding/not colliding.")] public bool usePointerColor = true; [Tooltip("A custom GameObject to use for the play area cursor representation for when the location is valid.")] public GameObject validLocationObject; [Tooltip("A custom GameObject to use for the play area cursor representation for when the location is invalid.")] public GameObject invalidLocationObject; protected bool headsetPositionCompensation; protected bool playAreaCursorCollided = false; protected bool headsetOutOfBounds = false; protected Transform playArea; protected GameObject playAreaCursor; protected GameObject[] playAreaCursorBoundaries; protected BoxCollider playAreaCursorCollider; protected Transform headset; protected Renderer[] boundaryRenderers = new Renderer[0]; protected GameObject playAreaCursorValidChild; protected GameObject playAreaCursorInvalidChild; protected int btmRightInner = 0; protected int btmLeftInner = 1; protected int topLeftInner = 2; protected int topRightInner = 3; protected int btmRightOuter = 4; protected int btmLeftOuter = 5; protected int topLeftOuter = 6; protected int topRightOuter = 7; /// <summary> /// The HasCollided method returns the state of whether the play area cursor has currently collided with another valid object. /// </summary> /// <returns>A bool to determine the state of collision. `true` if the play area is colliding with a valid object and `false` if not.</returns> public virtual bool HasCollided() { return (playAreaCursorCollided || headsetOutOfBounds); } /// <summary> /// The SetHeadsetPositionCompensation method determines whether the offset position of the headset from the centre of the play area should be taken into consideration when setting the destination marker. If `true` then it will take the offset position into consideration. /// </summary> /// <param name="state">The state of whether to take the position of the headset within the play area into account when setting the destination marker.</param> public virtual void SetHeadsetPositionCompensation(bool state) { headsetPositionCompensation = state; } /// <summary> /// The SetPlayAreaCursorCollision method determines whether play area collisions should be taken into consideration with the play area cursor. /// </summary> /// <param name="state">The state of whether to check for play area collisions.</param> public virtual void SetPlayAreaCursorCollision(bool state) { playAreaCursorCollided = false; if (handlePlayAreaCursorCollisions) { playAreaCursorCollided = (!enabled ? false : state); } } /// <summary> /// The SetMaterialColor method sets the current material colour on the play area cursor. /// </summary> /// <param name="color">The colour to update the play area cursor material to.</param> public virtual void SetMaterialColor(Color color) { if (validLocationObject == null) { if (usePointerColor) { for (int i = 0; i < playAreaCursorBoundaries.Length; i++) { SetCursorColor(playAreaCursorBoundaries[i], color); } } } else { ToggleValidPlayAreaState(!playAreaCursorCollided); if (usePointerColor) { SetCursorColor(playAreaCursor, color); } } } /// <summary> /// The SetPlayAreaCursorTransform method is used to update the position of the play area cursor in world space to the given location. /// </summary> /// <param name="location">The location where to draw the play area cursor.</param> public virtual void SetPlayAreaCursorTransform(Vector3 location) { var offset = Vector3.zero; if (headsetPositionCompensation) { var playAreaPos = new Vector3(playArea.transform.position.x, 0f, playArea.transform.position.z); var headsetPos = new Vector3(headset.position.x, 0f, headset.position.z); offset = playAreaPos - headsetPos; } if (playAreaCursor != null) { if (playAreaCursor.activeInHierarchy && handlePlayAreaCursorCollisions && headsetOutOfBoundsIsCollision) { var checkPoint = new Vector3(location.x, playAreaCursor.transform.position.y + (playAreaCursor.transform.localScale.y * 2), location.z); if (!playAreaCursorCollider.bounds.Contains(checkPoint)) { headsetOutOfBounds = true; } else { headsetOutOfBounds = false; } } playAreaCursor.transform.position = location + offset; } } /// <summary> /// The ToggleState method enables or disables the visibility of the play area cursor. /// </summary> /// <param name="state">The state of whether to show or hide the play area cursor.</param> public virtual void ToggleState(bool state) { state = (!enabled ? false : state); if (playAreaCursor != null) { playAreaCursor.SetActive(state); } } /// <summary> /// The IsActive method returns whether the play area cursor game object is active or not. /// </summary> /// <returns>Returns true if the play area cursor GameObject is active.</returns> public virtual bool IsActive() { return (playAreaCursor != null ? playAreaCursor.activeInHierarchy : false); } /// <summary> /// The GetPlayAreaContainer method returns the created game object that holds the play area cursor representation. /// </summary> /// <returns>The GameObject that is the container of the play area cursor.</returns> public virtual GameObject GetPlayAreaContainer() { return playAreaCursor; } /// <summary> /// The ToggleVisibility method enables or disables the play area cursor renderers to allow the cursor to be seen or hidden. /// </summary> /// <param name="state">The state of the cursor visibility. True will show the renderers and false will hide the renderers.</param> public virtual void ToggleVisibility(bool state) { if (playAreaCursor != null && boundaryRenderers.Length == 0) { boundaryRenderers = playAreaCursor.GetComponentsInChildren<Renderer>(); } for (int i = 0; i < boundaryRenderers.Length; i++) { boundaryRenderers[i].enabled = state; } } protected virtual void OnEnable() { VRTK_PlayerObject.SetPlayerObject(gameObject, VRTK_PlayerObject.ObjectTypes.Pointer); headset = VRTK_DeviceFinder.HeadsetTransform(); playArea = VRTK_DeviceFinder.PlayAreaTransform(); playAreaCursorBoundaries = new GameObject[4]; InitPlayAreaCursor(); } protected virtual void OnDisable() { if (playAreaCursor != null) { Destroy(playAreaCursor); } } protected virtual void Update() { if (enabled && IsActive()) { UpdateCollider(); } } protected virtual void InitPlayAreaCursor() { if (playArea == null) { VRTK_Logger.Error(VRTK_Logger.GetCommonMessage(VRTK_Logger.CommonMessageKeys.SDK_OBJECT_NOT_FOUND, "PlayArea", "Boundaries SDK")); return; } Vector3[] cursorDrawVertices = VRTK_SDK_Bridge.GetPlayAreaVertices(playArea.gameObject); if (validLocationObject != null) { GeneratePlayAreaCursorFromPrefab(cursorDrawVertices); } else { GeneratePlayAreaCursor(cursorDrawVertices); } if (playAreaCursor != null) { playAreaCursor.SetActive(false); VRTK_PlayerObject.SetPlayerObject(playAreaCursor, VRTK_PlayerObject.ObjectTypes.Pointer); CreateCursorCollider(playAreaCursor); playAreaCursor.AddComponent<Rigidbody>().isKinematic = true; VRTK_PlayAreaCollider playAreaCursorScript = playAreaCursor.AddComponent<VRTK_PlayAreaCollider>(); playAreaCursorScript.SetParent(this); playAreaCursorScript.SetIgnoreTarget(targetListPolicy); playAreaCursor.layer = LayerMask.NameToLayer("Ignore Raycast"); } } protected virtual void SetCursorColor(GameObject cursorObject, Color color) { Renderer paRenderer = cursorObject.GetComponentInChildren<Renderer>(); if (paRenderer && paRenderer.material && paRenderer.material.HasProperty("_Color")) { paRenderer.material.color = color; paRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; paRenderer.receiveShadows = false; } } protected virtual void ToggleValidPlayAreaState(bool state) { if (playAreaCursorValidChild != null) { playAreaCursorValidChild.SetActive(state); } if (playAreaCursorInvalidChild != null) { playAreaCursorInvalidChild.SetActive(!state); } } protected virtual string GeneratePlayAreaCursorName() { return VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "PlayAreaCursor"); } protected virtual void GeneratePlayAreaCursorFromPrefab(Vector3[] cursorDrawVertices) { playAreaCursor = new GameObject(GeneratePlayAreaCursorName()); float width = cursorDrawVertices[btmRightOuter].x - cursorDrawVertices[topLeftOuter].x; float length = cursorDrawVertices[topLeftOuter].z - cursorDrawVertices[btmRightOuter].z; if (playAreaCursorDimensions != Vector2.zero) { width = (playAreaCursorDimensions.x == 0 ? playAreaCursor.transform.localScale.x : playAreaCursorDimensions.x); length = (playAreaCursorDimensions.y == 0 ? playAreaCursor.transform.localScale.z : playAreaCursorDimensions.y); } float height = 0.01f; playAreaCursorValidChild = Instantiate(validLocationObject); playAreaCursorValidChild.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, "ValidArea"); playAreaCursorValidChild.transform.SetParent(playAreaCursor.transform); if (invalidLocationObject != null) { playAreaCursorInvalidChild = Instantiate(invalidLocationObject); playAreaCursorInvalidChild.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, "InvalidArea"); playAreaCursorInvalidChild.transform.SetParent(playAreaCursor.transform); } playAreaCursor.transform.localScale = new Vector3(width, height, length); playAreaCursorValidChild.transform.localScale = Vector3.one; if (invalidLocationObject != null) { playAreaCursorInvalidChild.transform.localScale = Vector3.one; } playAreaCursor.SetActive(false); } protected virtual void GeneratePlayAreaCursor(Vector3[] cursorDrawVertices) { if (playAreaCursorDimensions != Vector2.zero) { var customAreaPadding = VRTK_SDK_Bridge.GetPlayAreaBorderThickness(playArea.gameObject); cursorDrawVertices[btmRightOuter] = new Vector3(playAreaCursorDimensions.x / 2, 0f, (playAreaCursorDimensions.y / 2) * -1); cursorDrawVertices[btmLeftOuter] = new Vector3((playAreaCursorDimensions.x / 2) * -1, 0f, (playAreaCursorDimensions.y / 2) * -1); cursorDrawVertices[topLeftOuter] = new Vector3((playAreaCursorDimensions.x / 2) * -1, 0f, playAreaCursorDimensions.y / 2); cursorDrawVertices[topRightOuter] = new Vector3(playAreaCursorDimensions.x / 2, 0f, playAreaCursorDimensions.y / 2); cursorDrawVertices[btmRightInner] = cursorDrawVertices[btmRightOuter] + new Vector3(-customAreaPadding, 0f, customAreaPadding); cursorDrawVertices[btmLeftInner] = cursorDrawVertices[btmLeftOuter] + new Vector3(customAreaPadding, 0f, customAreaPadding); cursorDrawVertices[topLeftInner] = cursorDrawVertices[topLeftOuter] + new Vector3(customAreaPadding, 0f, -customAreaPadding); cursorDrawVertices[topRightInner] = cursorDrawVertices[topRightOuter] + new Vector3(-customAreaPadding, 0f, -customAreaPadding); } float width = cursorDrawVertices[btmRightOuter].x - cursorDrawVertices[topLeftOuter].x; float length = cursorDrawVertices[topLeftOuter].z - cursorDrawVertices[btmRightOuter].z; float height = 0.01f; playAreaCursor = new GameObject(GeneratePlayAreaCursorName()); playAreaCursor.transform.SetParent(null); playAreaCursor.transform.localScale = new Vector3(width, height, length); float playAreaBoundaryX = playArea.transform.localScale.x / 2; float playAreaBoundaryZ = playArea.transform.localScale.z / 2; float heightOffset = 0f; DrawPlayAreaCursorBoundary(0, cursorDrawVertices[btmLeftOuter].x, cursorDrawVertices[btmRightOuter].x, cursorDrawVertices[btmRightInner].z, cursorDrawVertices[btmRightOuter].z, height, new Vector3(0f, heightOffset, playAreaBoundaryZ)); DrawPlayAreaCursorBoundary(1, cursorDrawVertices[btmLeftOuter].x, cursorDrawVertices[btmLeftInner].x, cursorDrawVertices[topLeftOuter].z, cursorDrawVertices[btmLeftOuter].z, height, new Vector3(playAreaBoundaryX, heightOffset, 0f)); DrawPlayAreaCursorBoundary(2, cursorDrawVertices[btmLeftOuter].x, cursorDrawVertices[btmRightOuter].x, cursorDrawVertices[btmRightInner].z, cursorDrawVertices[btmRightOuter].z, height, new Vector3(0f, heightOffset, -playAreaBoundaryZ)); DrawPlayAreaCursorBoundary(3, cursorDrawVertices[btmLeftOuter].x, cursorDrawVertices[btmLeftInner].x, cursorDrawVertices[topLeftOuter].z, cursorDrawVertices[btmLeftOuter].z, height, new Vector3(-playAreaBoundaryX, heightOffset, 0f)); } protected virtual void DrawPlayAreaCursorBoundary(int index, float left, float right, float top, float bottom, float thickness, Vector3 localPosition) { GameObject playAreaCursorBoundary = GameObject.CreatePrimitive(PrimitiveType.Cube); playAreaCursorBoundary.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "PlayAreaCursorBoundary", index); VRTK_PlayerObject.SetPlayerObject(playAreaCursorBoundary, VRTK_PlayerObject.ObjectTypes.Pointer); float width = (right - left) / 1.065f; float length = (top - bottom) / 1.08f; float height = thickness; playAreaCursorBoundary.transform.localScale = new Vector3(width, height, length); Destroy(playAreaCursorBoundary.GetComponent<BoxCollider>()); playAreaCursorBoundary.layer = LayerMask.NameToLayer("Ignore Raycast"); playAreaCursorBoundary.transform.SetParent(playAreaCursor.transform); playAreaCursorBoundary.transform.localPosition = localPosition; playAreaCursorBoundaries[index] = playAreaCursorBoundary; } protected virtual void CreateCursorCollider(GameObject cursor) { playAreaCursorCollider = cursor.AddComponent<BoxCollider>(); playAreaCursorCollider.isTrigger = true; playAreaCursorCollider.center = new Vector3(0f, 65f, 0f); playAreaCursorCollider.size = new Vector3(1f, 1f, 1f); } protected virtual void UpdateCollider() { var playAreaHeightAdjustment = 1f; var newBCYSize = (headset.transform.position.y - playArea.transform.position.y) * 100f; var newBCYCenter = (newBCYSize != 0 ? (newBCYSize / 2) + playAreaHeightAdjustment : 0); playAreaCursorCollider.size = new Vector3(playAreaCursorCollider.size.x, newBCYSize, playAreaCursorCollider.size.z); playAreaCursorCollider.center = new Vector3(playAreaCursorCollider.center.x, newBCYCenter, playAreaCursorCollider.center.z); } } public class VRTK_PlayAreaCollider : MonoBehaviour { protected VRTK_PlayAreaCursor parent; protected VRTK_PolicyList targetListPolicy; public virtual void SetParent(VRTK_PlayAreaCursor setParent) { parent = setParent; } public virtual void SetIgnoreTarget(VRTK_PolicyList list = null) { targetListPolicy = list; } protected virtual void OnDisable() { if (parent) { parent.SetPlayAreaCursorCollision(false); } } protected virtual void OnTriggerStay(Collider collider) { if (parent && parent.enabled && parent.gameObject.activeInHierarchy && ValidTarget(collider)) { parent.SetPlayAreaCursorCollision(true); } } protected virtual void OnTriggerExit(Collider collider) { if (parent && ValidTarget(collider)) { parent.SetPlayAreaCursorCollision(false); } } protected virtual bool ValidTarget(Collider collider) { return (!VRTK_PlayerObject.IsPlayerObject(collider.gameObject) && !(VRTK_PolicyList.Check(collider.gameObject, targetListPolicy))); } } }
{ "content_hash": "b85ec0d623020a657298b92bd8148232", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 324, "avg_line_length": 47.93006993006993, "alnum_prop": 0.6421067989495185, "repo_name": "SyntonicApps/vr-office", "id": "fe499dc849d799f525477b00821ce6a976b213b7", "size": "20564", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/VRTK/Scripts/Pointers/VRTK_PlayAreaCursor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2698594" }, { "name": "GLSL", "bytes": "33408" } ], "symlink_target": "" }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/logging.h" #include "base/string_util.h" #include "base/values.h" #include "base/utf_string_conversions.h" namespace base { #if defined(OS_WIN) static const char kPrettyPrintLineEnding[] = "\r\n"; #else static const char kPrettyPrintLineEnding[] = "\n"; #endif /* static */ const char* JSONWriter::kEmptyArray = "[]"; /* static */ void JSONWriter::Write(const Value* const node, bool pretty_print, std::string* json) { WriteWithOptionalEscape(node, pretty_print, true, json); } /* static */ void JSONWriter::WriteWithOptionalEscape(const Value* const node, bool pretty_print, bool escape, std::string* json) { json->clear(); // Is there a better way to estimate the size of the output? json->reserve(1024); JSONWriter writer(pretty_print, json); writer.BuildJSONString(node, 0, escape); if (pretty_print) json->append(kPrettyPrintLineEnding); } JSONWriter::JSONWriter(bool pretty_print, std::string* json) : json_string_(json), pretty_print_(pretty_print) { DCHECK(json); } void JSONWriter::BuildJSONString(const Value* const node, int depth, bool escape) { switch (node->GetType()) { case Value::TYPE_NULL: json_string_->append("null"); break; case Value::TYPE_BOOLEAN: { bool value; bool result = node->GetAsBoolean(&value); DCHECK(result); json_string_->append(value ? "true" : "false"); break; } case Value::TYPE_INTEGER: { int value; bool result = node->GetAsInteger(&value); DCHECK(result); StringAppendF(json_string_, "%d", value); break; } case Value::TYPE_REAL: { double value; bool result = node->GetAsReal(&value); DCHECK(result); std::string real = DoubleToString(value); // Ensure that the number has a .0 if there's no decimal or 'e'. This // makes sure that when we read the JSON back, it's interpreted as a // real rather than an int. if (real.find('.') == std::string::npos && real.find('e') == std::string::npos && real.find('E') == std::string::npos) { real.append(".0"); } // The JSON spec requires that non-integer values in the range (-1,1) // have a zero before the decimal point - ".52" is not valid, "0.52" is. if (real[0] == '.') { real.insert(0, "0"); } else if (real.length() > 1 && real[0] == '-' && real[1] == '.') { // "-.1" bad "-0.1" good real.insert(1, "0"); } json_string_->append(real); break; } case Value::TYPE_STRING: { std::string value; bool result = node->GetAsString(&value); DCHECK(result); if (escape) { JsonDoubleQuote(UTF8ToUTF16(value), true, json_string_); } else { JsonDoubleQuote(value, true, json_string_); } break; } case Value::TYPE_LIST: { json_string_->append("["); if (pretty_print_) json_string_->append(" "); const ListValue* list = static_cast<const ListValue*>(node); for (size_t i = 0; i < list->GetSize(); ++i) { if (i != 0) { json_string_->append(","); if (pretty_print_) json_string_->append(" "); } Value* value = NULL; bool result = list->Get(i, &value); DCHECK(result); BuildJSONString(value, depth, escape); } if (pretty_print_) json_string_->append(" "); json_string_->append("]"); break; } case Value::TYPE_DICTIONARY: { json_string_->append("{"); if (pretty_print_) json_string_->append(kPrettyPrintLineEnding); const DictionaryValue* dict = static_cast<const DictionaryValue*>(node); for (DictionaryValue::key_iterator key_itr = dict->begin_keys(); key_itr != dict->end_keys(); ++key_itr) { if (key_itr != dict->begin_keys()) { json_string_->append(","); if (pretty_print_) json_string_->append(kPrettyPrintLineEnding); } Value* value = NULL; bool result = dict->GetWithoutPathExpansion(*key_itr, &value); DCHECK(result); if (pretty_print_) IndentLine(depth + 1); AppendQuotedString(*key_itr); if (pretty_print_) { json_string_->append(": "); } else { json_string_->append(":"); } BuildJSONString(value, depth + 1, escape); } if (pretty_print_) { json_string_->append(kPrettyPrintLineEnding); IndentLine(depth); json_string_->append("}"); } else { json_string_->append("}"); } break; } default: // TODO(jhughes): handle TYPE_BINARY NOTREACHED() << "unknown json type"; } } void JSONWriter::AppendQuotedString(const std::wstring& str) { JsonDoubleQuote(WideToUTF16Hack(str), true, json_string_); } void JSONWriter::IndentLine(int depth) { // It may be faster to keep an indent string so we don't have to keep // reallocating. json_string_->append(std::string(depth * 3, ' ')); } } // namespace base
{ "content_hash": "8724339ddcde18ed9c53dec09e10308d", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 80, "avg_line_length": 29.16, "alnum_prop": 0.5368655692729767, "repo_name": "rwatson/chromium-capsicum", "id": "ffdad767a4627939877ba18a117d9ed22abf8d5c", "size": "5832", "binary": false, "copies": "1", "ref": "refs/heads/chromium-capsicum", "path": "base/json/json_writer.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.apereo.portal.layout.dlm.remoting; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.builder.CompareToBuilder; import org.apereo.portal.groups.IEntityGroup; import org.apereo.portal.groups.IGroupMember; import org.apereo.portal.portlet.om.PortletCategory; import org.apereo.portal.portlets.groupselector.EntityEnum; import org.apereo.portal.security.IPermission; /** Entity bean for JSON output. Used for categories, groups, and people. */ public class JsonEntityBean implements Serializable, Comparable<JsonEntityBean> { private static final long serialVersionUID = 1L; private EntityEnum entityType; private String id; private String name; private String creatorId; private String description; private String principalString; private String targetString; private List<JsonEntityBean> children = new ArrayList<JsonEntityBean>(); private boolean childrenInitialized = false; public JsonEntityBean() {} public JsonEntityBean(PortletCategory category) { this.entityType = EntityEnum.CATEGORY; this.id = category.getId(); this.name = category.getName(); this.creatorId = category.getCreatorId(); this.description = category.getDescription(); this.targetString = category.getId(); // e.g. 'local.25' } public JsonEntityBean(IGroupMember groupMember, EntityEnum entityType) { this.entityType = entityType; this.id = groupMember.getKey(); String prefix = ""; // default switch (entityType) { case PORTLET: prefix = IPermission.PORTLET_PREFIX; // E.g. groupMember.getKey()=56 break; case PERSON: // No prefix -- e.g. groupMember.getKey()=admin break; default: throw new IllegalArgumentException("Unsupported entityType: " + entityType); } this.targetString = prefix + groupMember.getKey(); } public JsonEntityBean(IEntityGroup entityGroup, EntityEnum entityType) { this.entityType = entityType; this.id = entityGroup.getKey(); this.name = entityGroup.getName(); this.creatorId = entityGroup.getCreatorID(); this.description = entityGroup.getDescription(); this.targetString = entityGroup.getKey(); // e.g. 'local.19' and 'pags.Authenticated Users' } public EntityEnum getEntityType() { return entityType; } public String getEntityTypeAsString() { return entityType.toString().toUpperCase(); } public void setEntityType(String entityType) { this.entityType = EntityEnum.getEntityEnum(entityType); } public void setEntityType(EntityEnum entityType) { this.entityType = entityType; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCreatorId() { return creatorId; } public void setCreatorId(String creatorId) { this.creatorId = creatorId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPrincipalString() { return principalString; } public void setPrincipalString(String principalString) { this.principalString = principalString; } /** * Identifies this bean uniquely as a permissions target. NOTE: This id is not the fname (for * portlets) or name field (for groups), but rater a unique String like 'PORTLET_ID.19' or * 'local.36' or 'pags.Authenticated Users' * * @since 4.0.14 */ public String getTargetString() { return targetString; } /** @since 4.0.14 */ public void setTargetString(String targetString) { this.targetString = targetString; } /** * Compute a hash based on type and ID to uniquely identify this bean. This method helps avoid * the unlikely case where a group and person in the same principal list have the same ID. * * <p>Periods are replaced to avoid issues in JSP EL and form names can't contain spaces. Also * SpEL parsing of form field names fails with characters such as dash or parenthesis (which * PAGS groups can have) and likely other characters so they are also replaced with underscores. * * @return EntityType + "_" + ID */ public String getTypeAndIdHash() { assert (entityType != null); assert (id != null); String idStr = id.replaceAll("\\W", "__"); return entityType.toString().toLowerCase() + "_" + idStr; } public List<JsonEntityBean> getChildren() { return children; } public void setChildren(List<JsonEntityBean> children) { this.children = children; } /** * Convenience method to add a child to this object's list of children. * * @param child Object to add */ public void addChild(JsonEntityBean child) { children.add(child); } public boolean isChildrenInitialized() { return childrenInitialized; } public void setChildrenInitialized(boolean childrenInitialized) { this.childrenInitialized = childrenInitialized; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (childrenInitialized ? 1231 : 1237); result = prime * result + ((creatorId == null) ? 0 : creatorId.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((entityType == null) ? 0 : entityType.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JsonEntityBean other = (JsonEntityBean) obj; if (childrenInitialized != other.childrenInitialized) return false; if (creatorId == null) { if (other.creatorId != null) return false; } else if (!creatorId.equals(other.creatorId)) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (entityType == null) { if (other.entityType != null) return false; } else if (!entityType.equals(other.entityType)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public int compareTo(JsonEntityBean entity) { return (new CompareToBuilder()) .append(this.name, entity.getName()) .append(this.entityType, entity.getEntityType()) .append(this.creatorId, entity.getCreatorId()) .append(this.description, entity.getDescription()) .append(this.entityType, entity.getEntityType()) .append(this.id, entity.getId()) .append(this.principalString, this.getPrincipalString()) .toComparison(); } @Override public String toString() { return "JsonEntityBean [entityType=" + entityType + ", id=" + id + ", name=" + name + ", creatorId=" + creatorId + ", description=" + description + ", principalString=" + principalString + "]"; } }
{ "content_hash": "eb7378c9e9d46f01d4187662996baf89", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 100, "avg_line_length": 33.37651821862348, "alnum_prop": 0.6157205240174672, "repo_name": "stalele/uPortal", "id": "09da6077244109a1652ee4a6e7f0b31740187325", "size": "9033", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/layout/dlm/remoting/JsonEntityBean.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "238557" }, { "name": "Groovy", "bytes": "56453" }, { "name": "HTML", "bytes": "223563" }, { "name": "Java", "bytes": "9899148" }, { "name": "JavaScript", "bytes": "811252" }, { "name": "Perl", "bytes": "1769" }, { "name": "Shell", "bytes": "3135" }, { "name": "XSLT", "bytes": "259363" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Sencha Forum Browser</title> <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" /> <link rel="stylesheet" type="text/css" href="forum.css" /> <script type="text/javascript" src="../../bootstrap.js"></script> <script type="text/javascript" src="classes/Models.js"></script> <script type="text/javascript" src="classes/ForumList.js"></script> <script type="text/javascript" src="classes/TopicContainer.js"></script> <script type="text/javascript" src="classes/TopicGrid.js"></script> <script type="text/javascript" src="classes/Main.js"></script> <script type="text/javascript"> Ext.Loader.setConfig({enabled: true}); Ext.Loader.setPath('Ext.ux', '../ux/'); Ext.require([ 'Ext.grid.*', 'Ext.tree.*', 'Ext.data.*', 'Ext.toolbar.*', 'Ext.tab.Panel', 'Ext.layout.container.Border', 'Ext.ux.PreviewPlugin' ]); Ext.onReady(function(){ Ext.QuickTips.init(); new ForumBrowser.Main(); }); </script> </head> <body> </body> </html>
{ "content_hash": "3fb2f8ec89fbe4f7aa16e0d075646609", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 84, "avg_line_length": 37.72727272727273, "alnum_prop": 0.5815261044176707, "repo_name": "flyboarder/AirOS_pre2.0", "id": "6e258fc8726fe960f73db77a499fb9c11cc6b6f7", "size": "1245", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "web/extjs/4.0.1/examples/forum/forum.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "25909154" }, { "name": "PHP", "bytes": "98458" }, { "name": "Python", "bytes": "1965" }, { "name": "Ruby", "bytes": "7793" }, { "name": "Shell", "bytes": "9078" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('legislative', '0014_auto_20171214_2215'), ] operations = [ migrations.AlterModelOptions( name='billtext', options={'ordering': ['bill__identifier', '-date']}, ), migrations.AddField( model_name='billtext', name='text_state_kw', field=models.CharField(blank=True, max_length=140, null=True), ), ]
{ "content_hash": "be453d981a9fe782ae1f8e18dcd92e7c", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 74, "avg_line_length": 25.272727272727273, "alnum_prop": 0.579136690647482, "repo_name": "access-missouri/am-django-project", "id": "1604f615dfe8625526cce13c4eee62baee8f824a", "size": "627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "am/legislative/migrations/0015_auto_20171215_1559.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "208381" }, { "name": "HTML", "bytes": "75543" }, { "name": "JavaScript", "bytes": "68836" }, { "name": "Makefile", "bytes": "803" }, { "name": "Python", "bytes": "241729" }, { "name": "Ruby", "bytes": "105" } ], "symlink_target": "" }