text
stringlengths
2
1.04M
meta
dict
package org.apache.beam.runners.direct; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; import org.apache.beam.runners.direct.CommittedResult.OutputType; import org.apache.beam.runners.direct.DirectRunner.UncommittedBundle; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.AppliedPTransform; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.PCollection; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link StepTransformResult}. */ @RunWith(JUnit4.class) public class StepTransformResultTest { private AppliedPTransform<?, ?, ?> transform; private BundleFactory bundleFactory; private PCollection<Integer> pc; @Before public void setup() { TestPipeline p = TestPipeline.create(); pc = p.apply(Create.of(1, 2, 3)); transform = DirectGraphs.getGraph(p).getProducer(pc); bundleFactory = ImmutableListBundleFactory.create(); } @Test public void producedBundlesProducedOutputs() { UncommittedBundle<Integer> bundle = bundleFactory.createBundle(pc); TransformResult<Integer> result = StepTransformResult.<Integer>withoutHold(transform).addOutput(bundle).build(); assertThat( result.getOutputBundles(), Matchers.<UncommittedBundle<?>>containsInAnyOrder(bundle)); } @Test public void withAdditionalOutputProducedOutputs() { TransformResult<Integer> result = StepTransformResult.<Integer>withoutHold(transform) .withAdditionalOutput(OutputType.PCOLLECTION_VIEW) .build(); assertThat(result.getOutputTypes(), containsInAnyOrder(OutputType.PCOLLECTION_VIEW)); } @Test public void producedBundlesAndAdditionalOutputProducedOutputs() { TransformResult<Integer> result = StepTransformResult.<Integer>withoutHold(transform) .addOutput(bundleFactory.createBundle(pc)) .withAdditionalOutput(OutputType.PCOLLECTION_VIEW) .build(); assertThat(result.getOutputTypes(), hasItem(OutputType.PCOLLECTION_VIEW)); } @Test public void noBundlesNoAdditionalOutputProducedOutputsFalse() { TransformResult<Integer> result = StepTransformResult.<Integer>withoutHold(transform).build(); assertThat(result.getOutputTypes(), emptyIterable()); } }
{ "content_hash": "1e871a8d2da90c2121f8581db3f2866f", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 98, "avg_line_length": 32.98701298701299, "alnum_prop": 0.7586614173228347, "repo_name": "josauder/AOP_incubator_beam", "id": "d3a2cca844446f9f05f117e1ea23071caa011044", "size": "3345", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "runners/direct-java/src/test/java/org/apache/beam/runners/direct/StepTransformResultTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "5178" }, { "name": "Groovy", "bytes": "20493" }, { "name": "Java", "bytes": "9630218" }, { "name": "Protocol Buffer", "bytes": "1407" }, { "name": "Shell", "bytes": "10104" } ], "symlink_target": "" }
<?php namespace CDGNG\PhpFiles; class Code extends Data { public function isExist($code) { return array_key_exists($code, $this->data); } public function remove($property) { unset($this->data[$property]); } }
{ "content_hash": "c794196b036eba4d2b6c9a451413e5a3", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 52, "avg_line_length": 15.75, "alnum_prop": 0.5992063492063492, "repo_name": "supagroflorac/CDGNG", "id": "48823ad1e0393233aaa21b1bf08656822008408e", "size": "252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/PhpFiles/Code.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "292" }, { "name": "HTML", "bytes": "22905" }, { "name": "JavaScript", "bytes": "2886" }, { "name": "PHP", "bytes": "54478" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/RelativeLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="6dp" android:layout_marginRight="6dp" android:orientation="vertical" > <TextView android:id="@+id/headline" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_gravity="center_vertical" android:gravity="center_vertical" android:lines="1" android:singleLine="true" android:text="@string/logcat" android:textAppearance="?android:attr/textAppearanceLarge" /> <cgeo.geocaching.test.BottomAwareScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_above="@+id/buttonRun" android:layout_alignParentLeft="true" android:layout_below="@+id/headline" > <TextView android:id="@+id/logOutput" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="8sp" tools:ignore="SmallSp" /> </cgeo.geocaching.test.BottomAwareScrollView> <Button android:id="@+id/buttonRun" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="false" android:onClick="runTests" android:text="@string/run_tests" /> <requestFocus android:layout_alignTop="@+id/buttonRun" android:layout_centerHorizontal="true" android:layout_marginTop="18dp" /> </RelativeLayout>
{ "content_hash": "fb9bad4e075f05e27ed516cac5ccac2b", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 74, "avg_line_length": 36.333333333333336, "alnum_prop": 0.6559633027522935, "repo_name": "eric-stanley/cgeo", "id": "43225ac18c9538e468fc07d97f09b379073430f3", "size": "1962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/res/layout/cgeo_tests_activity.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Frontend\EstadisticasBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('estadisticas'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "53e0e05661777d110e93b818595b67af", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 30.620689655172413, "alnum_prop": 0.7207207207207207, "repo_name": "thekingtork/Cloud", "id": "8775bf32b97931cca28c2e7cd4549d8065c4daee", "size": "888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Frontend/EstadisticasBundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "211" }, { "name": "PHP", "bytes": "112920" } ], "symlink_target": "" }
<?php Class MY_Controller extends CI_Controller { //bien gui du lieu sang ben view public $data = array(); function __construct() { //ke thua tu CI_Controller parent::__construct(); $controller = $this->uri->segment(1); switch ($controller) { case 'admin' : { //xu ly cac du lieu khi truy cap vao trang admin $this->load->helper('admin'); $this->admin_check_login(); break; } default: { //xu ly cac du lieu khi truy cap vao trang admin $this->load->helper('user'); $this->user_check_login(); $this->load->library('cart'); $this->data['total_items'] = $this->cart->total_items(); $this->load->model('account_model'); $account_id = $this->session->userdata('account_id'); $shop_info= $this->account_model->join_shops($account_id); $this->data['shop_info']=$shop_info; $buyer_info= $this->account_model->join_buyer($account_id); $this->data['buyer_info']=$buyer_info; } } } /* * Kiem tra trang thai dang nhap cua admin */ private function admin_check_login() { $controller = $this->uri->rsegment('1'); $controller = strtolower($controller); // controller la cai can truoc khi lam gi $login = $this->session->userdata('login'); //neu ma chua dang nhap,ma truy cap 1 controller khac login if(!$login && $controller != 'login') { redirect(admin_url('login')); } //neu ma admin da dang nhap thi khong cho phep vao trang login nua. if($login && $controller == 'login') { redirect(admin_url('home')); } elseif (!in_array($controller, array('login', 'home'))) { $admin_role = $this->session->userdata('admin_role'); $admin_root = $this->config->item('root_admin'); if($admin_role != $admin_root){ $permissions_admin = $this->session->userdata('permissions'); $controller = $this->uri->rsegment(1); $action = $this->uri->rsegment(2); $check = true; if(!isset($permissions_admin->{$controller})){ $check = false; } $permissions_action = $permissions_admin->{$controller}; if(!in_array($action, $permissions_action)){ $check = false; } if(!$check){ $this->session->set_flashdata('message', 'Ban khong co quyen truy cap trang nay'); redirect(base_url('admin')); } } //kiem tra quyen admin } } private function user_check_login() { $controller = $this->uri->rsegment('1'); $controller = strtolower($controller); $login = $this->session->userdata('account_id'); //neu ma chua dang nhap,ma truy cap 1 controller khac login if(!$login && $controller == 'post') { $this->session->set_flashdata('message', 'Ban phải đăng nhập mới thực hiện chức năng này'); redirect(user_url('login')); } //neu ma admin da dang nhap thi khong cho phep vao trang login nua. if(!$login && $controller == 'cart') { $product_id= $this->uri->segment(4); $this->session->set_userdata('current_url', $product_id); $this->session->set_flashdata('message', 'Ban phải đăng nhập mới thực hiện chức năng này'); redirect(user_url('login')); } if(!$login && $controller == 'profile') { $this->session->set_flashdata('message', 'Ban phải đăng nhập mới thực hiện chức năng này'); redirect(user_url('login')); } elseif (!in_array($controller, array('login','register','listproduct', 'home','user','contact','rule'))) { $account_id = $this->session->userdata('account_id'); $shop_id = $this->session->userdata('shop_id'); $buyer_id = $this->session->userdata('buyer_id'); if($account_id){ $permissions_user = $this->session->userdata('permissions_ac'); $controller = $this->uri->rsegment(1); $action = $this->uri->rsegment(2); $check = true; if(!isset($permissions_user->{$controller})){ $check = false; } $permissions_action = $permissions_user->{$controller}; if(!in_array($action, $permissions_action)){ $check = false; } if(!$check){ $this->session->set_flashdata('message', 'Tài khoản của bạn không thể thực hiện chức năng này'); redirect(user_url('login')); } } //kiem tra quyen admin } } }
{ "content_hash": "815e585e8c1c56d765f35032806ef2f3", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 112, "avg_line_length": 32.16770186335404, "alnum_prop": 0.491600695114887, "repo_name": "anhptse03395/e-market", "id": "e2a2ee254bb39241a9b4e86d4c6e17e3b5d80f5e", "size": "5245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/core/MY_Controller.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1189" }, { "name": "CSS", "bytes": "670909" }, { "name": "HTML", "bytes": "533375" }, { "name": "JavaScript", "bytes": "1714280" }, { "name": "PHP", "bytes": "2372402" } ], "symlink_target": "" }
require('./helper'); var describe = require('mocha').describe, it = require('mocha').it, expect = require('chai').expect, beforeEach = require('mocha').beforeEach, $ = require('jquery'), incrementer = require('./app'); describe('Hello World', function () { beforeEach(function () { $('body').html('<div>1</div>'); }); it('should start with 1', function () { expect($('div').text()).equal('1'); }); it('should increment to 6', function () { incrementer(5); expect($('div').text()).equal('6'); }); it('should start with 1', function () { expect($('div').text()).equal('1'); }); });
{ "content_hash": "d537549bbc03db8137ba4d636f48c363", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 45, "avg_line_length": 29.217391304347824, "alnum_prop": 0.53125, "repo_name": "pauleveritt/pycharm_polyglot", "id": "91a8536bfc1e9c0aaa6a2a5d514e489e8030d217", "size": "672", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/jsdom/test5.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "260" }, { "name": "HTML", "bytes": "2398" }, { "name": "JavaScript", "bytes": "10298" }, { "name": "Python", "bytes": "1060" } ], "symlink_target": "" }
package com.stewsters; import com.bulletphysics.collision.broadphase.AxisSweep3; import com.bulletphysics.collision.broadphase.BroadphaseInterface; import com.bulletphysics.collision.dispatch.CollisionConfiguration; import com.bulletphysics.collision.dispatch.CollisionDispatcher; import com.bulletphysics.collision.dispatch.DefaultCollisionConfiguration; import com.bulletphysics.collision.shapes.CollisionShape; import com.bulletphysics.collision.shapes.StaticPlaneShape; import com.bulletphysics.dynamics.DiscreteDynamicsWorld; import com.bulletphysics.dynamics.DynamicsWorld; import com.bulletphysics.dynamics.RigidBody; import com.bulletphysics.dynamics.RigidBodyConstructionInfo; import com.bulletphysics.dynamics.constraintsolver.ConstraintSolver; import com.bulletphysics.dynamics.constraintsolver.SequentialImpulseConstraintSolver; import com.bulletphysics.linearmath.DefaultMotionState; import com.bulletphysics.linearmath.Transform; import javax.vecmath.Quat4f; import javax.vecmath.Vector3f; import java.util.LinkedList; public class PhysicsWorld { public final static float gravityAcceleration = -9.81f; CollisionDispatcher myCd; BroadphaseInterface myBi; ConstraintSolver myCs; CollisionConfiguration myCc; Vector3f worldAabbMin = new Vector3f(-100, -100, -100); Vector3f worldAabbMax = new Vector3f(100, 100, 100); RigidBody groundRigidBody; public DynamicsWorld myWorld; public LinkedList<Ball> balls; public LinkedList<Box> boxes; //boxen? public PhysicsWorld() { balls = new LinkedList<Ball>(); boxes = new LinkedList<Box>(); myCc = new DefaultCollisionConfiguration(); myBi = new AxisSweep3(worldAabbMin, worldAabbMax); myCd = new CollisionDispatcher(myCc); myCs = new SequentialImpulseConstraintSolver(); myWorld = new DiscreteDynamicsWorld(myCd, myBi, myCs, myCc); myWorld.setGravity(new Vector3f(0, 0, gravityAcceleration)); addGround(); addGoal(40f); addGoal(-40f); } private void addGround() { //ADD STATIC GROUND CollisionShape groundShape = new StaticPlaneShape(new Vector3f(0, 0, 1), 0); Transform myTransform = new Transform(); myTransform.origin.set(new Vector3f(0, 0, 0)); //ground plane position myTransform.setRotation(new Quat4f(0, 0, 0, 1)); DefaultMotionState groundMotionState = new DefaultMotionState(myTransform); RigidBodyConstructionInfo groundCI = new RigidBodyConstructionInfo(0, groundMotionState, groundShape, new Vector3f(0, 0, 0)); groundCI.restitution = 0.6f; // this preserves bounce groundRigidBody = new RigidBody(groundCI); myWorld.addRigidBody(groundRigidBody); } private void addGoal(float y){ addBox(new Vector3f(0,y,6f), new Vector3f(12f,0.5f,6f)); //top addBox(new Vector3f(0,y,22f), new Vector3f(12f,0.5f,2f)); //bottom addBox(new Vector3f(20,y,12f), new Vector3f(8f,0.5f,12f)); //top addBox(new Vector3f(-20,y,12f), new Vector3f(8f,0.5f,12f)); //bottom } private void addBox(Vector3f pos, Vector3f halfSize) { Box box = new Box(0, pos, halfSize); myWorld.addRigidBody(box.getRigidBody()); boxes.add(box); } public void addBallAt(Vector3f location, Vector3f velocity) { Ball ball = new Ball(2f, 2.8f, location.x, location.y, location.z); myWorld.addRigidBody(ball.getRigidBody()); ball.getRigidBody().setLinearVelocity(velocity); balls.add(ball); } }
{ "content_hash": "a11e82fb94d89cce1d6e0b528d87ed9d", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 133, "avg_line_length": 38.354838709677416, "alnum_prop": 0.7269414073451079, "repo_name": "stewsters/ballToss", "id": "a72dcaf1f28e6a949feb34be3feee3f16ab07c15", "size": "3567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/stewsters/PhysicsWorld.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "6021" } ], "symlink_target": "" }
/* Leola Programming Language Author: Tony Sparks See license.txt */ package leola.ast; import leola.vm.EvalException; /** * Namespace definition Statement * * @author Tony * */ public class NamespaceStmt extends Stmt { /** * The namespace */ private Stmt stmt; /** * Name */ private String name; /** * @param stmt * @param name */ public NamespaceStmt(Stmt stmt, String name) { this.stmt = becomeParentOf(stmt); this.name = name; } /* (non-Javadoc) * @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor) */ @Override public void visit(ASTNodeVisitor v) throws EvalException { v.visit(this); } /** * @return the stmt */ public Stmt getStmt() { return stmt; } /** * @return the name */ public String getName() { return name; } }
{ "content_hash": "904a8092d9d1106b14cf2bbd5bd4d001", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 62, "avg_line_length": 15.745762711864407, "alnum_prop": 0.5511302475780409, "repo_name": "tonysparks/leola", "id": "2e7900374321dcd7578cfb0ffd24e56fb322f93b", "size": "929", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/leola/ast/NamespaceStmt.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "951160" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SecurityFramework.Opportunity.Arial { public partial class Assessment : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
{ "content_hash": "5cdb8f39746c6ce47a6c3deb4d3a3dab", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 60, "avg_line_length": 20.058823529411764, "alnum_prop": 0.7038123167155426, "repo_name": "rdonalson/SecurityFramework", "id": "b84e75c687cbb35547724675f6a1570c54e07fdc", "size": "343", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SecurityFramework/Opportunity/Arial/Assessment.aspx.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "46588" }, { "name": "C#", "bytes": "348556" }, { "name": "CSS", "bytes": "29429" }, { "name": "JavaScript", "bytes": "870090" } ], "symlink_target": "" }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */ function openNav() { document.getElementById("mySidenav").style.width = "250px"; document.body.style.backgroundColor = "rgba(0,0,0,0.4)"; } /* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */ function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.body.style.backgroundColor = "white"; } /* Checks user's login status and sets logout link accordingly */ function getLogsStatus() { // Fetches json from userapi servlet and uses to set the login // and logout links for the front end. fetch('/userapi').then(response => response.json()).then(logStatus => { const link = document.getElementById("loginout-link"); // If the user is logged in and is at the login screen then the // login link should skip login and head into home. If the user is // not on the login screen then the url will be to sign out. if(logStatus.isLoggedIn) { if(window.location.pathname === "/index.html" || window.location.pathname === "/"){ console.log('User is Logged In'); window.location.pathname = "/Home/home.html"; } else{ link.href = logStatus.Url; } } // If the user is not logged in and is at the login screen then the // login link should require them to login before heading into home. // If the user is somehow not on the login screen and isn't logged in // then the url will point to the login sceen. else { if(window.location.pathname === "/index.html" || window.location.pathname === "/"){ console.log('User is not Logged In'); link.href = logStatus.Url; } else{ window.alert("You must log in."); window.location.pathname = "/"; } } }); }
{ "content_hash": "53857016d2d8486cd57b1120c94a9edb", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 141, "avg_line_length": 42.92063492063492, "alnum_prop": 0.6401627218934911, "repo_name": "googleinterns/step51-2020", "id": "ef947f2f91dddb488643ac2e944c66570444dc6a", "size": "2704", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DSA-Campaign-Uplift-Estimation/src/main/webapp/Resources/NavBar/navbar_script.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "180925" }, { "name": "HTML", "bytes": "54523" }, { "name": "Java", "bytes": "111505" }, { "name": "JavaScript", "bytes": "94405" }, { "name": "PHP", "bytes": "5303" }, { "name": "Python", "bytes": "88845" } ], "symlink_target": "" }
'use strict'; describe('Directive: capture', function () { // load the directive's module and view beforeEach(module('facepagesApp')); beforeEach(module('app/main/capture/capture.html')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); it('should make hidden element visible', inject(function ($compile) { element = angular.element('<capture></capture>'); element = $compile(element)(scope); scope.$apply(); expect(element.text()).toBe('this is the capture directive'); })); });
{ "content_hash": "5ebf29c70bb101553973496a466f90bc", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 71, "avg_line_length": 26.904761904761905, "alnum_prop": 0.6637168141592921, "repo_name": "matthewharwood/facepages", "id": "c18560a64707921656751afcb4e8e3af328e9ae4", "size": "565", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/app/account/signup/capture/capture.directive.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11255" }, { "name": "JavaScript", "bytes": "77248" }, { "name": "Ruby", "bytes": "123" } ], "symlink_target": "" }
package com.amazonaws.services.storagegateway.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.storagegateway.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * StartGatewayRequest Marshaller */ public class StartGatewayRequestMarshaller implements Marshaller<Request<StartGatewayRequest>, StartGatewayRequest> { public Request<StartGatewayRequest> marshall( StartGatewayRequest startGatewayRequest) { if (startGatewayRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<StartGatewayRequest> request = new DefaultRequest<StartGatewayRequest>( startGatewayRequest, "AWSStorageGateway"); request.addHeader("X-Amz-Target", "StorageGateway_20130630.StartGateway"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator(); jsonGenerator.writeStartObject(); if (startGatewayRequest.getGatewayARN() != null) { jsonGenerator.writeFieldName("GatewayARN").writeValue( startGatewayRequest.getGatewayARN()); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", "application/x-amz-json-1.1"); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
{ "content_hash": "dde68899b825a805bb057901d6c8c4a9", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 87, "avg_line_length": 33.333333333333336, "alnum_prop": 0.6961538461538461, "repo_name": "dump247/aws-sdk-java", "id": "e0491ae7ababddd99c819459b5596c352530ab98", "size": "3187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-storagegateway/src/main/java/com/amazonaws/services/storagegateway/model/transform/StartGatewayRequestMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "117958" }, { "name": "Java", "bytes": "104374753" }, { "name": "Scilab", "bytes": "3375" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <corners android:radius="8dp" /> <gradient android:angle="270" android:centerX="5%" android:centerColor="#FFC524" android:startColor="#EFEF1A" android:endColor="#DB4527" android:type="linear" /> <size android:width="270dp" android:height="45dp" /> <stroke android:width="1dp" android:color="#878787" /> </shape>
{ "content_hash": "822b2f5c246268aba0d9a39b59a51cf4", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 65, "avg_line_length": 24.416666666666668, "alnum_prop": 0.552901023890785, "repo_name": "sv1jsb/Keep-score", "id": "40e868ccc842a2c1de5d169901230e8f0250ed25", "size": "586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/orangebuttonnormal.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "1202" }, { "name": "Java", "bytes": "223926" } ], "symlink_target": "" }
from get_database_names import get_database_names from get_database_path import get_database_path from get_next_database import get_next_database from build_local_dbs import build_local_dbs from run_query import run_query from select import select from insert import insert # ensure the databases are already generated build_local_dbs()
{ "content_hash": "24dd95b593540c6a6ce501ce193bac10", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 49, "avg_line_length": 33.8, "alnum_prop": 0.8224852071005917, "repo_name": "CodyKochmann/pi-cluster", "id": "4b9373f70a94ff17df8d409d141f3e3ea7c90f22", "size": "489", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "software/src/SQLiteCluster/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17" }, { "name": "HTML", "bytes": "524" }, { "name": "Python", "bytes": "1275353" }, { "name": "Shell", "bytes": "569" } ], "symlink_target": "" }
// Copyright (c) 2008 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Camille Wormser, Pierre Alliez, Stephane Tayeb #ifndef CGAL_AABB_NODE_H #define CGAL_AABB_NODE_H #include <CGAL/Profile_counter.h> #include <CGAL/Cartesian_converter.h> #include <CGAL/intersections.h> #include <CGAL/Bbox_3.h> #include <vector> namespace CGAL { /** * @class AABB_node * * */ template<typename AABBTraits> class AABB_node { public: typedef typename AABBTraits::Bounding_box Bounding_box; /// Constructor AABB_node() : m_bbox() , m_p_left_child(NULL) , m_p_right_child(NULL) { }; /// Non virtual Destructor /// Do not delete children because the tree hosts and delete them ~AABB_node() { }; /// Returns the bounding box of the node const Bounding_box& bbox() const { return m_bbox; } /** * @brief Builds the tree by recursive expansion. * @param first the first primitive to insert * @param last the last primitive to insert * @param range the number of primitive of the range * * [first,last[ is the range of primitives to be added to the tree. */ template<typename ConstPrimitiveIterator> void expand(ConstPrimitiveIterator first, ConstPrimitiveIterator beyond, const std::size_t range, const AABBTraits&); /** * @brief General traversal query * @param query the query * @param traits the traversal traits that define the traversal behaviour * @param nb_primitives the number of primitive * * General traversal query. The traits class allows using it for the various * traversal methods we need: listing, counting, detecting intersections, * drawing the boxes. */ template<class Traversal_traits, class Query> void traversal(const Query& query, Traversal_traits& traits, const std::size_t nb_primitives) const; private: typedef AABBTraits AABB_traits; typedef AABB_node<AABB_traits> Node; typedef typename AABB_traits::Primitive Primitive; /// Helper functions const Node& left_child() const { return *static_cast<Node*>(m_p_left_child); } const Node& right_child() const { return *static_cast<Node*>(m_p_right_child); } const Primitive& left_data() const { return *static_cast<Primitive*>(m_p_left_child); } const Primitive& right_data() const { return *static_cast<Primitive*>(m_p_right_child); } Node& left_child() { return *static_cast<Node*>(m_p_left_child); } Node& right_child() { return *static_cast<Node*>(m_p_right_child); } Primitive& left_data() { return *static_cast<Primitive*>(m_p_left_child); } Primitive& right_data() { return *static_cast<Primitive*>(m_p_right_child); } private: /// node bounding box Bounding_box m_bbox; /// children nodes, either pointing towards children (if children are not leaves), /// or pointing toward input primitives (if children are leaves). void *m_p_left_child; void *m_p_right_child; private: // Disabled copy constructor & assignment operator typedef AABB_node<AABBTraits> Self; AABB_node(const Self& src); Self& operator=(const Self& src); }; // end class AABB_node template<typename Tr> template<typename ConstPrimitiveIterator> void AABB_node<Tr>::expand(ConstPrimitiveIterator first, ConstPrimitiveIterator beyond, const std::size_t range, const Tr& traits) { m_bbox = traits.compute_bbox_object()(first, beyond); // sort primitives along longest axis aabb traits.sort_primitives_object()(first, beyond, m_bbox); switch(range) { case 2: m_p_left_child = &(*first); m_p_right_child = &(*(++first)); break; case 3: m_p_left_child = &(*first); m_p_right_child = static_cast<Node*>(this)+1; right_child().expand(first+1, beyond, 2,traits); break; default: const std::size_t new_range = range/2; m_p_left_child = static_cast<Node*>(this) + 1; m_p_right_child = static_cast<Node*>(this) + new_range; left_child().expand(first, first + new_range, new_range,traits); right_child().expand(first + new_range, beyond, range - new_range,traits); } } template<typename Tr> template<class Traversal_traits, class Query> void AABB_node<Tr>::traversal(const Query& query, Traversal_traits& traits, const std::size_t nb_primitives) const { // Recursive traversal switch(nb_primitives) { case 2: traits.intersection(query, left_data()); if( traits.go_further() ) { traits.intersection(query, right_data()); } break; case 3: traits.intersection(query, left_data()); if( traits.go_further() && traits.do_intersect(query, right_child()) ) { right_child().traversal(query, traits, 2); } break; default: if( traits.do_intersect(query, left_child()) ) { left_child().traversal(query, traits, nb_primitives/2); if( traits.go_further() && traits.do_intersect(query, right_child()) ) { right_child().traversal(query, traits, nb_primitives-nb_primitives/2); } } else if( traits.do_intersect(query, right_child()) ) { right_child().traversal(query, traits, nb_primitives-nb_primitives/2); } } } } // end namespace CGAL #endif // CGAL_AABB_NODE_H
{ "content_hash": "c509ea2d423842c1e6e698367a00419d", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 84, "avg_line_length": 30.246231155778894, "alnum_prop": 0.6552583485628842, "repo_name": "alexandrustaetu/natural_editor", "id": "dda29f4d0890d6071a3c6a2194738b9acc0c50a6", "size": "6019", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "external/CGAL-4.4-beta1/include/CGAL/internal/AABB_tree/AABB_node.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "85830" }, { "name": "C++", "bytes": "341100" }, { "name": "Shell", "bytes": "2362" } ], "symlink_target": "" }
from thefuck.utils import for_app, memoize from thefuck.system import Path path_to_scm = { '.git': 'git', '.hg': 'hg', } wrong_scm_patterns = { 'git': 'fatal: Not a git repository', 'hg': 'abort: no repository found', } @memoize def _get_actual_scm(): for path, scm in path_to_scm.items(): if Path(path).is_dir(): return scm @for_app(*wrong_scm_patterns.keys()) def match(command): scm = command.script_parts[0] pattern = wrong_scm_patterns[scm] return pattern in command.output and _get_actual_scm() def get_new_command(command): scm = _get_actual_scm() return u' '.join([scm] + command.script_parts[1:])
{ "content_hash": "1e5f2d15b1e8402b947318f1b7601f42", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 58, "avg_line_length": 21.09375, "alnum_prop": 0.6237037037037036, "repo_name": "scorphus/thefuck", "id": "78c44949bb107c6601665afdbd388e7eef82790f", "size": "675", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "thefuck/rules/scm_correction.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "536" }, { "name": "Python", "bytes": "536648" }, { "name": "Shell", "bytes": "134" } ], "symlink_target": "" }
.SUFFIXES: #--------------------------------------------------------------------------------- all: install: @$(MAKE) -C ppu install --no-print-directory @$(MAKE) -C spu install --no-print-directory clean: @echo clean ... .PHONY: all clean install
{ "content_hash": "49e8548244f5bb1cb9c40090a4427306", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 82, "avg_line_length": 19.53846153846154, "alnum_prop": 0.44881889763779526, "repo_name": "RazorX11/PSL1GHT", "id": "54f062f2375455cb511eb3cb232f37ef23424a48", "size": "456", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "common/vectormath/Makefile", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_rand_04.cpp Label Definition File: CWE789_Uncontrolled_Mem_Alloc__new.label.xml Template File: sources-sinks-04.tmpl.cpp */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: rand Set data to result of rand(), which may be zero * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with new [] and check the size of the memory to be allocated * BadSink : Allocate memory with new [], but incorrectly check the size of the memory to be allocated * Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE) * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #define HELLO_STRING L"hello" /* The two variables below are declared "const", so a tool should be able to identify that reads of these will always return their initialized values. */ static const int STATIC_CONST_TRUE = 1; /* true */ static const int STATIC_CONST_FALSE = 0; /* false */ namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_rand_04 { #ifndef OMITBAD void bad() { size_t data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* POTENTIAL FLAW: Set data to a random value */ data = rand(); } if(STATIC_CONST_TRUE) { { wchar_t * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the wcscpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > wcslen(HELLO_STRING)) { myString = new wchar_t[data]; /* Copy a small string into myString */ wcscpy(myString, HELLO_STRING); printWLine(myString); delete [] myString; } else { printLine("Input is less than the length of the source string"); } } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_TRUE to STATIC_CONST_FALSE */ static void goodB2G1() { size_t data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* POTENTIAL FLAW: Set data to a random value */ data = rand(); } if(STATIC_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { wchar_t * myString; /* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough * for the wcscpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > wcslen(HELLO_STRING) && data < 100) { myString = new wchar_t[data]; /* Copy a small string into myString */ wcscpy(myString, HELLO_STRING); printWLine(myString); delete [] myString; } else { printLine("Input is less than the length of the source string or too large"); } } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { size_t data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* POTENTIAL FLAW: Set data to a random value */ data = rand(); } if(STATIC_CONST_TRUE) { { wchar_t * myString; /* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough * for the wcscpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > wcslen(HELLO_STRING) && data < 100) { myString = new wchar_t[data]; /* Copy a small string into myString */ wcscpy(myString, HELLO_STRING); printWLine(myString); delete [] myString; } else { printLine("Input is less than the length of the source string or too large"); } } } } /* goodG2B1() - use goodsource and badsink by changing the first STATIC_CONST_TRUE to STATIC_CONST_FALSE */ static void goodG2B1() { size_t data; /* Initialize data */ data = 0; if(STATIC_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a relatively small number for memory allocation */ data = 20; } if(STATIC_CONST_TRUE) { { wchar_t * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the wcscpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > wcslen(HELLO_STRING)) { myString = new wchar_t[data]; /* Copy a small string into myString */ wcscpy(myString, HELLO_STRING); printWLine(myString); delete [] myString; } else { printLine("Input is less than the length of the source string"); } } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { size_t data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* FIX: Use a relatively small number for memory allocation */ data = 20; } if(STATIC_CONST_TRUE) { { wchar_t * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the wcscpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > wcslen(HELLO_STRING)) { myString = new wchar_t[data]; /* Copy a small string into myString */ wcscpy(myString, HELLO_STRING); printWLine(myString); delete [] myString; } else { printLine("Input is less than the length of the source string"); } } } } void good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_rand_04; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "0111c2282dd25aac4ec274d133a363e1", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 113, "avg_line_length": 31.507751937984494, "alnum_prop": 0.5576331652109731, "repo_name": "maurer/tiamat", "id": "18274238fad27f88bf759dd81d768a966bebba2d", "size": "8129", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s02/CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_rand_04.cpp", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
.class public abstract Landroid/support/v4/widget/SearchViewCompat$OnCloseListenerCompat; .super Ljava/lang/Object; # instance fields .field final a:Ljava/lang/Object; # direct methods .method public constructor <init>()V .locals 1 invoke-direct {p0}, Ljava/lang/Object;-><init>()V invoke-static {}, Landroid/support/v4/widget/SearchViewCompat;->a()Landroid/support/v4/widget/z; move-result-object v0 invoke-interface {v0, p0}, Landroid/support/v4/widget/z;->a(Landroid/support/v4/widget/SearchViewCompat$OnCloseListenerCompat;)Ljava/lang/Object; move-result-object v0 iput-object v0, p0, Landroid/support/v4/widget/SearchViewCompat$OnCloseListenerCompat;->a:Ljava/lang/Object; return-void .end method # virtual methods .method public onClose()Z .locals 1 const/4 v0, 0x0 return v0 .end method
{ "content_hash": "f3bce3b52e15aff425d644f6f776ba19", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 149, "avg_line_length": 23.694444444444443, "alnum_prop": 0.738569753810082, "repo_name": "vishnudevk/MiBandDecompiled", "id": "0f90e57869657a3c0cc9b9f1cff0dfdd251689b4", "size": "853", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Original Files/source/smali/android/support/v4/widget/SearchViewCompat$OnCloseListenerCompat.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "109824" }, { "name": "Java", "bytes": "8906016" }, { "name": "Lua", "bytes": "134432" } ], "symlink_target": "" }
class AddMarketToPromotionPromos < ActiveRecord::Migration def change if Promotion.config.localisable add_column :promotion_promos, :market, :string add_index :promotion_promos, :market end end end
{ "content_hash": "063b5aa091be812b1d136f05e2d84ccf", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 58, "avg_line_length": 27.75, "alnum_prop": 0.7342342342342343, "repo_name": "madetech/made-promotion-engine", "id": "b5c8cbfae61ce2c635b44a1907d43c8a421b97de", "size": "222", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20130502162134_add_market_to_promotion_promos.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "859" }, { "name": "CoffeeScript", "bytes": "1174" }, { "name": "JavaScript", "bytes": "678" }, { "name": "Ruby", "bytes": "55785" } ], "symlink_target": "" }
<?php namespace OnticBase\Database\Adapter; use Zend\Db\Adapter\Adapter; use Zend\Db\Adapter\AdapterInterface; use Zend\Db\Adapter\Driver\DriverInterface; use Zend\Db\Adapter\Platform\PlatformInterface; use Zend\Db\Adapter\Profiler\ProfilerInterface; use Zend\Db\ResultSet\ResultSetInterface; class MasterSlaveAdapter extends Adapter implements MasterSlaveAdapterInterface { /** * Slave database adapter. * * @var AdapterInterface */ protected $slaveAdapter; /** * Class constructor. * * @param AdapterInterface $slaveAdapter * @param DriverInterface|array $driver * @param PlatformInterface $platform * @param ResultSetInterface $queryResultPrototype * @param ProfilerInterface $profiler * @return MasterSlaveAdapter */ public function __construct(AdapterInterface $slaveAdapter, $driver, PlatformInterface $platform = null, ResultSetInterface $queryResultPrototype = null, ProfilerInterface $profiler = null) { $this->slaveAdapter = $slaveAdapter; parent::__construct($driver, $platform, $queryResultPrototype, $profiler); } /** * Retrieve the slave database adapter. * * @return AdapterInterface */ public function getSlaveAdapter() { return $this->slaveAdapter; } }
{ "content_hash": "380299e59b26846e0a9821ccdc1817d4", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 190, "avg_line_length": 26.666666666666668, "alnum_prop": 0.72890625, "repo_name": "ontic/zend-module-base", "id": "7adbda4044fb99e1d81830f6cdb033ae8ef47433", "size": "1775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/OnticBase/Database/Adapter/MasterSlaveAdapter.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "28696" } ], "symlink_target": "" }
package org.apache.helix.integration.task; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixException; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.mock.statemodel.MockTaskStateModelFactory; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.IdealState; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.Task; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskSynchronizedTestBase; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestJobFailureTaskNotStarted extends TaskSynchronizedTestBase { private static final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB; private static final String UNBALANCED_DB_NAME = "UnbalancedDB"; private MockParticipantManager _blockedParticipant; private MockParticipantManager _normalParticipant; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; _numDbs = 1; _numNodes = 2; _numPartitions = 2; _numReplicas = 1; _gSetupTool.addCluster(CLUSTER_NAME, true); setupParticipants(); setupDBs(); startParticipantsWithStuckTaskStateModelFactory(); createManagers(); _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); // Enable cancellation ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient); ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME); clusterConfig.stateTransitionCancelEnabled(true); _configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR).build(); } protected void startParticipantsWithStuckTaskStateModelFactory() { Map<String, TaskFactory> taskFactoryReg = new HashMap<String, TaskFactory>(); taskFactoryReg.put(MockTask.TASK_COMMAND, new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new MockTask(context); } }); List<String> instances = _gSetupTool.getClusterManagementTool().getInstancesInCluster(CLUSTER_NAME); _participants[0] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instances.get(0)); StateMachineEngine stateMachine = _participants[0].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new MockTaskStateModelFactory(_participants[0], taskFactoryReg)); _participants[0].syncStart(); _blockedParticipant = _participants[0]; _participants[1] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instances.get(1)); stateMachine = _participants[1].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[1], taskFactoryReg)); _participants[1].syncStart(); _normalParticipant = _participants[1]; } @Test public void testTaskNotStarted() throws InterruptedException { setupUnbalancedDB(); final String BLOCK_WORKFLOW_NAME = "blockWorkflow"; final String FAIL_WORKFLOW_NAME = "failWorkflow"; final String FAIL_JOB_NAME = "failJob"; ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient); final int numTask = configAccessor.getClusterConfig(CLUSTER_NAME).getMaxConcurrentTaskPerInstance(); // Tasks targeting the unbalanced DB, the instance is setup to stuck on INIT->RUNNING, so it // takes all threads // on that instance. JobConfig.Builder blockJobBuilder = new JobConfig.Builder().setWorkflow(BLOCK_WORKFLOW_NAME) .setTargetResource(UNBALANCED_DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setNumConcurrentTasksPerInstance(numTask); Workflow.Builder blockWorkflowBuilder = new Workflow.Builder(BLOCK_WORKFLOW_NAME).addJob("blockJob", blockJobBuilder); _driver.start(blockWorkflowBuilder.build()); Assert.assertTrue(TaskTestUtil.pollForAllTasksBlock(_manager.getHelixDataAccessor(), _blockedParticipant.getInstanceName(), numTask, 10000)); // Now, all HelixTask threads are stuck at INIT->RUNNING for task state transition(user task // can't be submitted) // New tasks assigned to the instance won't start INIT->RUNNING transition at all. // A to-be-failed job, 2 tasks, 1 stuck and 1 fail, making the job fail. JobConfig.Builder failJobBuilder = new JobConfig.Builder().setWorkflow(FAIL_WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setJobCommandConfigMap( ImmutableMap.of(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FAILED.name())); Workflow.Builder failWorkflowBuilder = new Workflow.Builder(FAIL_WORKFLOW_NAME).addJob(FAIL_JOB_NAME, failJobBuilder); _driver.start(failWorkflowBuilder.build()); _driver.pollForJobState(FAIL_WORKFLOW_NAME, TaskUtil.getNamespacedJobName(FAIL_WORKFLOW_NAME, FAIL_JOB_NAME), TaskState.FAILED); _driver.pollForWorkflowState(FAIL_WORKFLOW_NAME, TaskState.FAILED); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(FAIL_WORKFLOW_NAME, FAIL_JOB_NAME)); for (int pId : jobContext.getPartitionSet()) { String assignedParticipant = jobContext.getAssignedParticipant(pId); if (assignedParticipant == null) { continue; // May not have been assigned at all due to quota limitations } if (jobContext.getAssignedParticipant(pId).equals(_blockedParticipant.getInstanceName())) { Assert.assertEquals(jobContext.getPartitionState(pId), TaskPartitionState.TASK_ABORTED); } else if (assignedParticipant.equals(_normalParticipant.getInstanceName())) { Assert.assertEquals(jobContext.getPartitionState(pId), TaskPartitionState.TASK_ERROR); } else { throw new HelixException("There should be only 2 instances, 1 blocked, 1 normal."); } } } private void setupUnbalancedDB() throws InterruptedException { // Start with Full-Auto mode to create the partitions, Semi-Auto won't create partitions. _gSetupTool.addResourceToCluster(CLUSTER_NAME, UNBALANCED_DB_NAME, 50, MASTER_SLAVE_STATE_MODEL, IdealState.RebalanceMode.FULL_AUTO.toString()); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, UNBALANCED_DB_NAME, 1); // Set preference list to put all partitions to one instance. IdealState idealState = _gSetupTool.getClusterManagementTool() .getResourceIdealState(CLUSTER_NAME, UNBALANCED_DB_NAME); Set<String> partitions = idealState.getPartitionSet(); for (String partition : partitions) { idealState.setPreferenceList(partition, Lists.newArrayList(_blockedParticipant.getInstanceName())); } idealState.setRebalanceMode(IdealState.RebalanceMode.SEMI_AUTO); _gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, UNBALANCED_DB_NAME, idealState); Assert.assertTrue(_clusterVerifier.verifyByPolling(10000, 100)); } }
{ "content_hash": "68f683a7bb2f75091bbd7658002e8373", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 100, "avg_line_length": 44.12972972972973, "alnum_prop": 0.7589416952474277, "repo_name": "lei-xia/helix", "id": "9536634b388a73fe3b61e3f09b485cbbebe8d117", "size": "8971", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailureTaskNotStarted.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1275" }, { "name": "CSS", "bytes": "8751" }, { "name": "HTML", "bytes": "45086" }, { "name": "Java", "bytes": "6361970" }, { "name": "JavaScript", "bytes": "2052" }, { "name": "Pascal", "bytes": "1940" }, { "name": "Python", "bytes": "185190" }, { "name": "Shell", "bytes": "142958" }, { "name": "SourcePawn", "bytes": "1247" }, { "name": "TypeScript", "bytes": "158324" } ], "symlink_target": "" }
<?php namespace Stomp\Tests\Functional\Stomp; use PHPUnit_Framework_TestCase; use Stomp\Client; use Stomp\StatefulStomp; use Stomp\Transport\Frame; use Stomp\Transport\Message; /** * StatefulTestBase * Generic tests for stateful stomp client. * * @package Stomp\Tests\Functional\Stomp * @author Jens Radtke <swefl.oss@fin-sn.de> */ abstract class StatefulTestBase extends PHPUnit_Framework_TestCase { /** * @var Client[] */ private $clients = []; protected function tearDown() { foreach ($this->clients as $client) { if ($client->isConnected()) { $client->disconnect(true); } } parent::tearDown(); } /** * @return Client */ abstract protected function getClient(); /** * @return StatefulStomp * @throws \Stomp\Exception\ConnectionException */ final protected function getStatefulStomp() { $client = $this->getClient(); $client->getConnection()->setReadTimeout(0, 750000); $this->clients[] = $client; return new StatefulStomp($client); } public function testSubscribeAndSend() { $stomp = $this->getStatefulStomp(); $queue = '/queue/tests-sub'; $stomp->subscribe($queue); $message = new Message(sprintf('send-message-%d', rand(0, PHP_INT_MAX))); $this->assertTrue($stomp->send($queue, $message)); $received = $stomp->read(); $this->assertInstanceOf(Frame::class, $received, 'No Message received!'); $this->assertEquals($message->body, $received->body, 'Wrong Message received!'); } public function testMultipleSubscribe() { $stomp = $this->getStatefulStomp(); $queues = ['/queue/tests-multisub-a', '/queue/tests-multisub-b', '/queue/tests-multisub-c']; $messages = []; foreach ($queues as $queue) { $stomp->subscribe($queue); $messages[$queue] = new Message(sprintf('send-message-%d', rand(0, PHP_INT_MAX))); } foreach ($messages as $queue => $message) { $this->assertTrue($stomp->send($queue, $message)); } while ((!empty($messages)) && ($message = $stomp->read())) { foreach ($stomp->getSubscriptions() as $subscription) { if ($subscription->belongsTo($message)) { $this->assertEquals( $messages[$subscription->getDestination()]->body, $message->body, 'Message is not matching original message send to queue.' ); unset($messages[$subscription->getDestination()]); } } } $this->assertEmpty($messages, 'Not all messages have been received!'); foreach ($stomp->getSubscriptions() as $subscription) { $stomp->unsubscribe($subscription->getSubscriptionId()); } $this->assertEmpty($stomp->getSubscriptions()); } public function testTransactions() { $queue = '/queue/tests-transactions'; $stomp = $this->getStatefulStomp(); $stomp->subscribe($queue); $stomp->begin(); $stomp->send($queue, new Message('message-a')); // should never be delivered $stomp->abort(); $stomp->begin(); $stomp->send($queue, new Message('message-b')); // expected to be delivered $stomp->commit(); $message = $stomp->read(); $this->assertInstanceOf(Frame::class, $message); $this->assertEquals($message->body, 'message-b'); } public function testAckAndNack() { $queue = '/queue/tests-ack-nack'; $receiver = $this->getStatefulStomp(); $producer = $this->getStatefulStomp(); $receiver->subscribe($queue, null, 'client'); $producer->send($queue, new Message('message-a', ['persistent' => 'true'])); $producer->send($queue, new Message('message-b', ['persistent' => 'true'])); $producer->getClient()->disconnect(true); for ($i = 0; $i < 2; $i++) { $frame = $receiver->read(); $this->assertInstanceOf(Frame::class, $frame); $receiver->nack($frame); } $frameA = $receiver->read(); $this->assertInstanceOf(Frame::class, $frameA); $this->assertEquals('message-a', $frameA->body); $receiver->ack($frameA); $frameB = $receiver->read(); $this->assertInstanceOf(Frame::class, $frameB); $this->assertEquals('message-b', $frameB->body); $receiver->ack($frameB); } }
{ "content_hash": "ff4992f2052562c469771c95ae794bce", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 100, "avg_line_length": 30.392156862745097, "alnum_prop": 0.5625806451612904, "repo_name": "fin-sn-de/stomp-php", "id": "7162e0f7d33a4230e7ff448f98a34f0715212902", "size": "4829", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Functional/Stomp/StatefulTestBase.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Erlang", "bytes": "19421" }, { "name": "PHP", "bytes": "234926" }, { "name": "Shell", "bytes": "5153" } ], "symlink_target": "" }
/* @test @summary Test SoftChannel allSoundOff method */ import javax.sound.midi.*; import javax.sound.sampled.*; import com.sun.media.sound.*; public class AllSoundOff { private static void assertEquals(Object a, Object b) throws Exception { if(!a.equals(b)) throw new RuntimeException("assertEquals fails!"); } private static void assertTrue(boolean value) throws Exception { if(!value) throw new RuntimeException("assertTrue fails!"); } public static void main(String[] args) throws Exception { SoftTestUtils soft = new SoftTestUtils(); MidiChannel channel = soft.synth.getChannels()[0]; channel.noteOn(60, 64); soft.read(1); VoiceStatus[] v = soft.synth.getVoiceStatus(); assertEquals(v[0].note, 60); assertEquals(v[0].active, true); channel.allSoundOff(); soft.read(1); v = soft.synth.getVoiceStatus(); assertEquals(v[0].active, false); soft.close(); } }
{ "content_hash": "4a87465f4aa742caf52b6d081145a363", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 73, "avg_line_length": 25.390243902439025, "alnum_prop": 0.6205571565802114, "repo_name": "rokn/Count_Words_2015", "id": "3444242a687d0439347d0f22969820ae82724ba7", "size": "2247", "binary": false, "copies": "30", "ref": "refs/heads/master", "path": "testing/openjdk/jdk/test/javax/sound/midi/Gervill/SoftChannel/AllSoundOff.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
<!-- BEGIN SIDEBAR --> <div class="page-sidebar-wrapper"> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed --> <div class="page-sidebar navbar-collapse collapse"> <ul class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> <!-- DOC: To remove the sidebar toggler from the sidebar you just need to completely remove the below "sidebar-toggler-wrapper" LI element --> <li class="sidebar-toggler-wrapper"> <!-- BEGIN SIDEBAR TOGGLER BUTTON --> <div class="sidebar-toggler"> </div> <!-- END SIDEBAR TOGGLER BUTTON --> </li> <!-- DOC: To remove the search box from the sidebar you just need to completely remove the below "sidebar-search-wrapper" LI element --> <li class="sidebar-search-wrapper"> </br> <!-- END RESPONSIVE QUICK SEARCH FORM --> </li> <li class="<?php echo $menusolicitudes; ?>"> <a href="javascript:;"> <i class="icon-wallet"></i> <span class="title">Solicitudes</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li class="<?php echo $oficios; ?>"> <a href="<?php echo site_url('') ?>admin/mostrar"> Auditoría</a> </li> <li class="<?php echo $asignar; ?>"> <a href="<?php echo site_url('') ?>asignar/mostrar"> Asignar</a> </li> </ul> </li> <li class="<?php echo $menucatalogos; ?>"> <a href="javascript:;"> <i class="icon-briefcase"></i> <span class="title">Catalogos</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li class="<?php echo $catalogoemp; ?>"> <a href="<?php echo site_url('') ?>usuario/mostrar"> Usuarios</a> </li> </ul> </li> </ul> <!-- END SIDEBAR MENU --> </div> </div>
{ "content_hash": "a2b0252350f749e57c25f593f48b2e8b", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 154, "avg_line_length": 37.803030303030305, "alnum_prop": 0.4533066132264529, "repo_name": "Eduardo2505/Auditoria", "id": "6a3f22d460f0a6ef5c20e121b7d351a9b0d48af9", "size": "2496", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/plantilla/menu.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "290" }, { "name": "ApacheConf", "bytes": "1115" }, { "name": "CSS", "bytes": "2719894" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "HTML", "bytes": "4230616" }, { "name": "JavaScript", "bytes": "5611904" }, { "name": "PHP", "bytes": "16453273" }, { "name": "Shell", "bytes": "444" } ], "symlink_target": "" }
'use strict'; angular.module('courses').directive('upload', function() { return { scope: { file:'=' }, link: function(scope, element) { /* jshint ignore:start */ $(element).on('change', function(changeEvent) { console.log(changeEvent); var files = changeEvent.target.files; console.log(files.length); if (files.length) { var r = new FileReader(); r.onload = function(e) { var contents = e.target.result; //console.log(contents); var lines = contents.split('\r'); console.log(lines.length); // for (var i=1; i<lines.length; i++) { console.log(lines[i]); } }; r.readAsText(files[0]); } }); /* jshint ignore:end */ } }; } );
{ "content_hash": "dc0543a6c0cc1e506b82c72e8645d663", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 64, "avg_line_length": 28.093023255813954, "alnum_prop": 0.34271523178807944, "repo_name": "ekretschmann/sparesys", "id": "f54bfd0000bd0cca3f62d83633618ca9a2a7e514", "size": "1208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/modules/courses/directives/upload.client.directive.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "55980" }, { "name": "HTML", "bytes": "647756" }, { "name": "JavaScript", "bytes": "745132" } ], "symlink_target": "" }
package com.elastisys.scale.cloudpool.aws.commons.poolclient; import java.util.Collection; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.SpotInstanceRequest; import com.amazonaws.services.ec2.model.Tag; /** * An AWS client interface that extends the {@link Ec2Client} with methods for * dealing with spot requests. */ public interface SpotClient extends Ec2Client { /** * Retrieves meta data about a particular {@link SpotInstanceRequest}. * * @param spotRequestId * The id of the spot request. * @return * @throws AmazonClientException */ SpotInstanceRequest getSpotInstanceRequest(String spotRequestId) throws AmazonClientException; /** * Returns all {@link SpotInstanceRequest}s that satisfy a number of * {@link Filter}s. * * @param filters * The {@link Filter}s that need to be satisfied by returned * {@link SpotInstanceRequest}s. * @return * @throws AmazonClientException */ List<SpotInstanceRequest> getSpotInstanceRequests(Collection<Filter> filters) throws AmazonClientException; /** * Places a number of new {@link SpotInstanceRequest}s and (optionally) tags * the spot instance requests with a given set of {@link Tag}s. * * @param bidPrice * The bid price to set for the {@link SpotInstanceRequest}. * @param instanceTemplate * A description of the desired spot {@link Instance}. * @param count * The number of spot instances to request. * @param tags * Tags to set on the created spot instance requests. May be * empty. * @return The placed {@link SpotInstanceRequest}s. * @throws AmazonClientException */ public List<SpotInstanceRequest> placeSpotRequests(double bidPrice, Ec2ProvisioningTemplate instanceTemplate, int count, List<Tag> tags) throws AmazonClientException; /** * Cancels a collection of {@link SpotInstanceRequest}s. * * @param spotInstanceRequestIds * The identifiers of all {@link SpotInstanceRequest}s to cancel. * @throws AmazonClientException */ void cancelSpotRequests(List<String> spotInstanceRequestIds) throws AmazonClientException; }
{ "content_hash": "5431bb5d1fe7510cc7375af132761bfa", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 124, "avg_line_length": 36.35294117647059, "alnum_prop": 0.683252427184466, "repo_name": "Eeemil/scale.cloudpool", "id": "f28bade5e3b74f0d308cf78507c3f4d4f6adebb7", "size": "2472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws/commons/src/main/java/com/elastisys/scale/cloudpool/aws/commons/poolclient/SpotClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2446001" }, { "name": "Shell", "bytes": "36881" } ], "symlink_target": "" }
package org.springframework.core.codec; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import org.springframework.core.ResolvableType; import org.springframework.core.testfixture.codec.AbstractEncoderTests; import org.springframework.util.MimeTypeUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze */ class ByteBufferEncoderTests extends AbstractEncoderTests<ByteBufferEncoder> { private final byte[] fooBytes = "foo".getBytes(StandardCharsets.UTF_8); private final byte[] barBytes = "bar".getBytes(StandardCharsets.UTF_8); ByteBufferEncoderTests() { super(new ByteBufferEncoder()); } @Override @Test public void canEncode() { assertThat(this.encoder.canEncode(ResolvableType.forClass(ByteBuffer.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); assertThat(this.encoder.canEncode(ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN)).isFalse(); assertThat(this.encoder.canEncode(ResolvableType.forClass(ByteBuffer.class), MimeTypeUtils.APPLICATION_JSON)).isTrue(); // SPR-15464 assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse(); } @Override @Test public void encode() { Flux<ByteBuffer> input = Flux.just(this.fooBytes, this.barBytes) .map(ByteBuffer::wrap); testEncodeAll(input, ByteBuffer.class, step -> step .consumeNextWith(expectBytes(this.fooBytes)) .consumeNextWith(expectBytes(this.barBytes)) .verifyComplete()); } }
{ "content_hash": "205d841917813fbe0f0ff899a6bdac1e", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 78, "avg_line_length": 28, "alnum_prop": 0.7723214285714286, "repo_name": "spring-projects/spring-framework", "id": "1bc0e3f665d6ed8f2189c6615e7046d5e6b67627", "size": "2189", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spring-core/src/test/java/org/springframework/core/codec/ByteBufferEncoderTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "32003" }, { "name": "CSS", "bytes": "1019" }, { "name": "Dockerfile", "bytes": "257" }, { "name": "FreeMarker", "bytes": "30820" }, { "name": "Groovy", "bytes": "6902" }, { "name": "HTML", "bytes": "1203" }, { "name": "Java", "bytes": "43939386" }, { "name": "JavaScript", "bytes": "280" }, { "name": "Kotlin", "bytes": "571613" }, { "name": "PLpgSQL", "bytes": "305" }, { "name": "Python", "bytes": "254" }, { "name": "Ruby", "bytes": "1060" }, { "name": "Shell", "bytes": "5374" }, { "name": "Smarty", "bytes": "700" }, { "name": "XSLT", "bytes": "2945" } ], "symlink_target": "" }
/// <binding AfterBuild='devAfterBuild' ProjectOpened='initProject' /> /* This file in the main entry point for defining grunt tasks and using grunt plugins. Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409 */ module.exports = function (grunt) { grunt.loadNpmTasks('grunt-bower-task'); grunt.loadNpmTasks('grunt-sync'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('dts-generator'); grunt.loadNpmTasks("grunt-ts"); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-tsd'); grunt.registerTask("initProject", ["clean:dev", "bower:install", "tsd:refresh"]); grunt.registerTask('devAfterBuild', ["sync:default", "dtsGenerator:default"]); grunt.registerTask('devWatch', ["devAfterBuild", "watch:default"]); grunt.registerTask("devBuildAndTest", ["devAfterBuild", "jasmine:tests"]); grunt.registerTask("distBuild", ["initProject", "ts:distBuild", "devBuildAndTest"]); grunt.initConfig({ ts: { distBuild: { tsconfig: true, options: { fast: "never", } } }, bower: { install: { options: { targetDir: "wwwroot/libs", } } }, watch: { /* when typescript files are compiled with vs, then sync to wwwroot */ default: { files: ["artifacts/dev/**/*"], tasks: ["devAfterBuild"], options: { debounceDelay: 100, }, }, }, clean: { dev: ["artifacts", "dist"] }, sync: { default: { files: [{ cwd: "src", src: ["**/*.d.ts"], dest: "dist/typings", }, { cwd: "src", src: ["**/*.less", "**/*.html"], dest: "dist/src", }, { cwd: "artifacts/dev", src: ["**/*.js"], dest: "dist/src", } ], pretend: false, verbose: true } }, dtsGenerator: { options: { name: 'ModCheck', baseDir: 'artifacts/dev', // project:"artifacts/dev", // src:["artifacts/dev/**/*.ts","typings/tsd.d.ts"], out: 'dist/typings/ModCheck.d.ts' // exclude: ["typings/q/*.d.ts"], // main: 'ModCheck/index', // externs: ["./koExtensions/knockoutExtensions.d.ts", "./utils/utils.d.ts"] }, default: { src: ['artifacts/dev/**/*.d.ts'], } }, jasmine: { tests: { src: [], options: { specs: ['tests/**/*.js'], // vendor: "node_modules/**/*.js", template: require('grunt-template-jasmine-requirejs'), templateOptions: { requireConfig: { // baseUrl: '.grunt/grunt-contrib-jasmine/src/main/js/' paths: { "ModCheck": "artifacts/dev" } } } } } }, tsd: { 'refresh': { 'options': { 'command': 'reinstall', 'latest': true, 'config': 'tsd.json', 'opts': {} } } }, }); grunt.event.on('watch', function (action, filepath, target) { grunt.log.writeln(target + ': ' + filepath + ' has ' + action); }); };
{ "content_hash": "7c9fc775dc4716af68b89d9eeb5dc0d2", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 93, "avg_line_length": 32.464, "alnum_prop": 0.4122720551996057, "repo_name": "conficient/ModCheck", "id": "77f2a4c9f9855fb09186573c9f7d75bab7bf1ce2", "size": "4060", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gruntfile.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1588" }, { "name": "CSS", "bytes": "268" }, { "name": "HTML", "bytes": "1929" }, { "name": "JavaScript", "bytes": "215653" }, { "name": "TypeScript", "bytes": "506" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DertInfo.WEB.BLL.Interfaces { interface INotificationService { //Create Methods int AddNotification(string type, string message, string userAssigned); //Read Methods Models.Notification GetNotificationById(int notificationId); //List Methods List<Models.Notification> ListActiveNotificationsByUser(string username); //Update Methods //Delete Methods bool DeleteNotification(int notificationId); //Special Methods bool DeactivateNotification(int notificationId); } }
{ "content_hash": "392e02d4782f439aef820b42e48424db", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 81, "avg_line_length": 23.419354838709676, "alnum_prop": 0.6776859504132231, "repo_name": "dertinfo-david/dertinfo-web", "id": "aa84aa7f629440381bd31b2e3f16677b1b9154c7", "size": "728", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BLL/Interfaces/INotificationService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "103" }, { "name": "C#", "bytes": "2371440" }, { "name": "CSS", "bytes": "335396" }, { "name": "HTML", "bytes": "26375" }, { "name": "JavaScript", "bytes": "1406026" } ], "symlink_target": "" }
package org.deventropy.junithelper.derby; import static org.junit.Assert.*; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.commons.io.output.WriterOutputStream; import org.junit.AfterClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TemporaryFolder; /** * @author Bindul Bhowmik * */ public class SimpleDerbyScriptRunnerTest { private static final String DB_NAME = "my-test-database-simple01-tmpfolder-nulllog"; private TemporaryFolder tempFolder = new TemporaryFolder(); private EmbeddedDerbyResource embeddedDerbyResource = new EmbeddedDerbyResource(DerbyResourceConfig.buildDefault().useInMemoryDatabase(DB_NAME), tempFolder); @Rule public RuleChain derbyRuleChain = RuleChain.outerRule(tempFolder).around(embeddedDerbyResource); // private Logger log = LogManager.getLogger(); /** * Cleanup stuff. */ @AfterClass public static void cleanupDerbySystem () { // Cleanup for next test DerbyUtils.shutdownDerbySystemQuitely(false); } @Test public void testLoggingChanges () throws SQLException, IOException { final StringWriter logData1 = new StringWriter(); final WriterOutputStream wos1 = new WriterOutputStream(logData1, Charset.defaultCharset()); final StringWriter logData2 = new StringWriter(); final WriterOutputStream wos2 = new WriterOutputStream(logData2, Charset.defaultCharset()); Connection connection = null; try { connection = DriverManager.getConnection(embeddedDerbyResource.getJdbcUrl()); final DerbyScriptRunner scriptRunner = new DerbyScriptRunner(connection); scriptRunner.setDefaultScriptLogStream(wos1); // Run one with a output stream here scriptRunner.executeScript("classpath:/org/deventropy/junithelper/derby/simple01/ddl.sql", wos2, true); logData2.flush(); assertTrue("Expected log doesnt exist", logData2.toString().contains("rows inserted/updated/deleted")); assertTrue("Should have nothing in the default", logData1.toString().isEmpty()); scriptRunner.executeScript("classpath:/org/deventropy/junithelper/derby/simple01/dml.sql"); wos1.flush(); logData1.flush(); assertTrue("Expected log doesnt exist", logData1.toString().contains("row inserted/updated/deleted")); } finally { DerbyUtils.closeQuietly(connection); } } @Test(expected = UnsupportedEncodingException.class) public void testUnsupportedEncryption () throws SQLException, IOException { Connection connection = null; try { connection = DriverManager.getConnection(embeddedDerbyResource.getJdbcUrl()); final DerbyScriptRunner scriptRunner = new DerbyScriptRunner(connection, "UTF-64"); scriptRunner.executeScript("classpath:/org/deventropy/junithelper/derby/simple01/dml.sql"); } finally { DerbyUtils.closeQuietly(connection); } } }
{ "content_hash": "4fc23ed7d78dfc05ffcf6eae3baa4df1", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 106, "avg_line_length": 30.806122448979593, "alnum_prop": 0.7757535607817158, "repo_name": "deventropy/junit-helper", "id": "6934253a4ef4138c5cdbf0339ceb9a2d58bb5b7a", "size": "3652", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "junit-helper-derby/src/test/java/org/deventropy/junithelper/derby/SimpleDerbyScriptRunnerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "94443" } ], "symlink_target": "" }
/* Author: Matei Zaharia Developed as part of the SNAP project (http://snap.cs.berkeley.edu/) */ package siren import java.util.Arrays import scala.math.abs /** * A simple insert-only hashtable with keys and values as longs. Requires an "empty value" * that won't be used by any real entries to be set in order to identify missing entries. */ class IntIntMap(emptyValue: Int = 0, estimatedSize: Int = 16, loadFactor: Double = 0.7) extends Traversable[(Int, Int)] with Serializable { private var elements = 0 // number of elements currently in table private var capacity = math.max(10, (estimatedSize / loadFactor).toInt) private var data = new Array[Int](2*capacity) private var growThreshold = (capacity * loadFactor).toInt Arrays.fill(data, emptyValue) def getData: Array[Int] = data override def size = elements def currentCapacity = capacity // given a key, return its location in the index // performs modified linear probing -- initially increase step size, // then use step size of 1 to guarantee that all cells are visited private val STEP_LIMIT = 5 def probe(key: Int): Int = { var pos = abs(hash(key)) % capacity //println("pos: " + pos) var i = 1 var numProbes = 0 // look for open position near the hash pos if it's taken // will terminate upon (1) finding the key, or (2) finding an open position while (data(2*pos) != key /* key isn't stored at this pos */ && data(2*pos+1) != emptyValue /* something else is */) { // this position is occupied, and not by the key pos = (pos + i) % capacity numProbes += 1 if (numProbes < STEP_LIMIT) i += 1 else i = 1 //println("i: " + i) //println("pos: " + pos) } pos } def update(key: Int, value: Int): Unit = { if (value == emptyValue) throw new IllegalArgumentException("update() called with empty value") /* var pos = abs(hash(key)) % capacity //println("in update, pos: " + pos + ", key: " + key) var i = 1 while (data(2*pos) != key && data(2*pos+1) != emptyValue) { pos = (pos + i) % capacity //println("pos increased to " + pos) i += 1 } */ var pos = probe(key) if (data(2*pos) != key || data(2*pos+1) == emptyValue) { elements += 1 if (elements > growThreshold) { //println("calling growTable from update") growTable() // if you call growTable, you also need to recompute the pos, b/c that slot may not be free anymore /* pos = abs(hash(key)) % capacity //println("in update, pos: " + pos + ", key: " + key) i = 1 while (data(2*pos) != key && data(2*pos+1) != emptyValue) { pos = (pos + i) % capacity //println("pos increased to " + pos) i += 1 } */ pos = probe(key) } } //println("in update, pos: " + pos + ", key: " + key) //println("about to update with key " + key + ", pos " + pos) data(2*pos) = key data(2*pos+1) = value //println("data updated: " + data.mkString(", ")) } def apply(key: Int): Int = { /* var pos = abs(hash(key)) % capacity //println("pos: " + pos) //println("key: " + key) var i = 1 while (data(2*pos+1) != emptyValue) { //println("pos: " + pos) if (data(2*pos) == key) return data(2*pos+1) pos = (pos + i) % capacity i += 1 } return emptyValue */ val pos = probe(key) if (data(2*pos) == key) data(2*pos+1) else emptyValue } def getOrUpdate(key: Int, value: Int): Int = { if (value == emptyValue) throw new IllegalArgumentException("getOrUpdate() called with empty value") /* var pos = abs(hash(key)) % capacity var i = 1 while (data(2*pos) != key && data(2*pos+1) != emptyValue) { pos = (pos + i) % capacity i += 1 } */ var pos = probe(key) if (data(2*pos) == key) { return data(2*pos+1) } else { data(2*pos) = key data(2*pos+1) = value elements += 1 if (elements > growThreshold) { //println("calling growTable from getOrUpdate") growTable() } return emptyValue } } // MurmurHash3 from http://sites.google.com/site/murmurhash private final def hash(key: Int): Int = { var x = key x ^= x >>> 16; x *= 0x85ebca6b; x ^= x >>> 13; x *= 0xc2b2ae35; x ^= x >>> 16; return x; } // Double the capacity and re-hash everything into a new table private def growTable() { var oldData = data var oldCapacity = capacity capacity = (capacity * 1.25).toInt data = new Array[Int](2 * capacity) Arrays.fill(data, emptyValue) elements = 0 for (i <- 0 until oldCapacity) if (oldData(2*i + 1) != emptyValue) { //println("calling update from growTable with key of " + oldData(2*i)) update(oldData(2*i), oldData(2*i + 1)) } growThreshold = (capacity * loadFactor).toInt //println("returning from growTable") } override def foreach[T](func: ((Int, Int)) => T) { for (i <- 0 until capacity) if (data(2*i+1) != emptyValue) func((data(2*i), data(2*i+1))) } }
{ "content_hash": "cffc6113481d70f2b6a4691ceb347b14", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 172, "avg_line_length": 28.084656084656086, "alnum_prop": 0.5648078372268275, "repo_name": "amplab/siren-release", "id": "2d1157ea0f6f7f0f1cd165d633ebc3bd4c8d2381", "size": "5308", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/scala/siren/IntIntMap.scala", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Scala", "bytes": "120025" }, { "name": "Shell", "bytes": "291" } ], "symlink_target": "" }
Reveal.initialize({ width: 1920, height: 1080, margin: 0.2, controls: true, progress: true, // Push each slide change to the browser history history: true, center: true, // Number of milliseconds between automatically proceeding to the // next slide, disabled when set to 0, this value can be overwritten // by using a data-autoslide attribute on your slides autoSlide: 0, transition: Reveal.getQueryHash().transition || 'linear', // default/cube/page/concave/zoom/linear/fade/none // Optional libraries used to extend on reveal.js dependencies: [ { src: 'lib/js/classList.js', condition: function () { return !document.body.classList; } }, { src: 'plugin/markdown/marked.js', condition: function () { return !!document.querySelector('[data-markdown]'); } }, { src: 'plugin/markdown/markdown.js', condition: function () { return !!document.querySelector('[data-markdown]'); } }, { src: 'plugin/highlight/highlight.js', async: true, callback: function () { hljs.initHighlightingOnLoad(); } }, { src: 'plugin/zoom-js/zoom.js', async: true, condition: function () { return !!document.body.classList; } }, { src: 'plugin/notes/notes.js', async: true, condition: function () { return !!document.body.classList; } }/*, { src: 'plugin/remotes/remotes.js', async: true, condition: function () { return !!document.body.classList; } }*//*, { src: 'plugin/math/math.js', async: true, condition: function () { return !!document.body.classList; } }*/ ] });
{ "content_hash": "afca84e9d3504059c90ca6fcef075459", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 112, "avg_line_length": 36.8936170212766, "alnum_prop": 0.591118800461361, "repo_name": "pascalwhoop/reveal.js", "id": "405b9758a71d6f63a0e8af331812ea0936273027", "size": "1734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "revealjsConfig.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "201059" }, { "name": "HTML", "bytes": "56456" }, { "name": "JavaScript", "bytes": "256538" } ], "symlink_target": "" }
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.RTCIceCandidate (js_newRTCIceCandidate, newRTCIceCandidate, js_getCandidate, getCandidate, js_getSdpMid, getSdpMid, js_getSdpMLineIndex, getSdpMLineIndex, RTCIceCandidate, castToRTCIceCandidate, gTypeRTCIceCandidate) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"RTCIceCandidate\"]($1)" js_newRTCIceCandidate :: Nullable Dictionary -> IO RTCIceCandidate -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate Mozilla RTCIceCandidate documentation> newRTCIceCandidate :: (MonadIO m, IsDictionary dictionary) => Maybe dictionary -> m RTCIceCandidate newRTCIceCandidate dictionary = liftIO (js_newRTCIceCandidate (maybeToNullable (fmap toDictionary dictionary))) foreign import javascript unsafe "$1[\"candidate\"]" js_getCandidate :: RTCIceCandidate -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate.candidate Mozilla RTCIceCandidate.candidate documentation> getCandidate :: (MonadIO m, FromJSString result) => RTCIceCandidate -> m result getCandidate self = liftIO (fromJSString <$> (js_getCandidate (self))) foreign import javascript unsafe "$1[\"sdpMid\"]" js_getSdpMid :: RTCIceCandidate -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate.sdpMid Mozilla RTCIceCandidate.sdpMid documentation> getSdpMid :: (MonadIO m, FromJSString result) => RTCIceCandidate -> m result getSdpMid self = liftIO (fromJSString <$> (js_getSdpMid (self))) foreign import javascript unsafe "$1[\"sdpMLineIndex\"]" js_getSdpMLineIndex :: RTCIceCandidate -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate.sdpMLineIndex Mozilla RTCIceCandidate.sdpMLineIndex documentation> getSdpMLineIndex :: (MonadIO m) => RTCIceCandidate -> m Word getSdpMLineIndex self = liftIO (js_getSdpMLineIndex (self))
{ "content_hash": "bec09dc64cd1d12b46b957dfe57f7d70", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 138, "avg_line_length": 48.724137931034484, "alnum_prop": 0.7321302193913659, "repo_name": "manyoo/ghcjs-dom", "id": "fe9d4e5a4d28aab1aad9c04163ee271bf5b0e903", "size": "2826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCIceCandidate.hs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "90" }, { "name": "Haskell", "bytes": "3948159" }, { "name": "JavaScript", "bytes": "603" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">CocoShader</string> </resources>
{ "content_hash": "87d8304a8301fefe469985c11ffd7d79", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 47, "avg_line_length": 28, "alnum_prop": 0.6696428571428571, "repo_name": "Larusso/CocoShader", "id": "f3ab18e147528a5340da6f5db6ea11d6232de5df", "size": "112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "proj.android/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1013" }, { "name": "C++", "bytes": "18303" }, { "name": "GLSL", "bytes": "5150" }, { "name": "Java", "bytes": "218710" }, { "name": "JavaScript", "bytes": "9022" }, { "name": "Makefile", "bytes": "1482" }, { "name": "Objective-C", "bytes": "1889" }, { "name": "Objective-C++", "bytes": "9657" }, { "name": "Python", "bytes": "32712" } ], "symlink_target": "" }
package com.toparchy.molecule.bi.shipBuilding.data; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import com.toparchy.molecule.bi.shipBuilding.model.ShipProject; import com.toparchy.molecule.bi.shipBuilding.model.ShipYard; @ApplicationScoped public class ShipProjectRepository { @PersistenceContext(unitName = "bi") private EntityManager biEm; public ShipProject findById(String id) { return biEm.find(ShipProject.class, id); } public List<ShipProject> findByShipYard(ShipYard shipYard) { CriteriaBuilder cb = biEm.getCriteriaBuilder(); CriteriaQuery<ShipProject> criteria = cb.createQuery(ShipProject.class); Root<ShipProject> shipProject = criteria.from(ShipProject.class); criteria.select(shipProject).where(cb.equal(shipProject.get("shipYard"), shipYard)); return biEm.createQuery(criteria).getResultList(); } public List<ShipProject> findAllShipProject() { CriteriaBuilder cb = biEm.getCriteriaBuilder(); CriteriaQuery<ShipProject> criteria = cb.createQuery(ShipProject.class); Root<ShipProject> shipProject = criteria.from(ShipProject.class); criteria.select(shipProject); return biEm.createQuery(criteria).getResultList(); } }
{ "content_hash": "8e26d1d00e7f0faa45b4a05e388b7d01", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 86, "avg_line_length": 37.51282051282051, "alnum_prop": 0.7867395762132604, "repo_name": "currying/molecule", "id": "be3ca0dac065233273e7af5cea7b30ae790a2f88", "size": "1463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "molecule/src/main/java/com/toparchy/molecule/bi/shipBuilding/data/ShipProjectRepository.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1403817" }, { "name": "HTML", "bytes": "438060" }, { "name": "Java", "bytes": "3111708" }, { "name": "JavaScript", "bytes": "3472435" }, { "name": "PHP", "bytes": "481124" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>nfix: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / nfix - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> nfix <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-05 16:11:41 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-05 16:11:41 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 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/nfix&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Nfix&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: mutual fixpoint functions&quot; &quot;category: Miscellaneous/Coq Extensions&quot; ] authors: [ &quot;Stéphane Lescuyer&quot; ] bug-reports: &quot;https://github.com/coq-contribs/nfix/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/nfix.git&quot; synopsis: &quot;Nfix: a Coq extension for fixpoints on nested inductives&quot; description: &quot;This plugin provides a syntactic extension that allows one to write mutual fixpoints over nested inductives.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/nfix/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=c06d488d04c34946bb90d5abbf8a2387&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-nfix.8.8.0 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-nfix -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-nfix.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "b4b53433e6cf2be3bc41c92580708ab1", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 159, "avg_line_length": 40.98757763975155, "alnum_prop": 0.5343233823306561, "repo_name": "coq-bench/coq-bench.github.io", "id": "de9a89c967c9ce0d1aa7723ecef186de89fc5bcf", "size": "6625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.11.1/nfix/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php # This file was automatically converted from the October CMS language files. Thank you October CMS for all the great work! # https://octobercms.com lucid::add_phrases([ 'access_log:created_at'=>'Data e ora', 'access_log:email'=>'Indirizzo e-mail', 'access_log:first_name'=>'Nome', 'access_log:hint'=>'Questo registro visualizza un elenco dei tentativi di accesso di un amministratore avvenuti con successo. I record sono mantenuti per un totale di :days giorni.', 'access_log:ip_address'=>'Indirizzo IP', 'access_log:last_name'=>'Cognome', 'access_log:login'=>'Login', 'access_log:menu_description'=>'Visualizza una lista degli accessi da parte degli amministratori.', 'access_log:menu_label'=>'Registro accessi', 'account:apply'=>'Applica', 'account:cancel'=>'Annulla', 'account:delete'=>'Elimina', 'account:email_placeholder'=>'email', 'account:enter_email'=>'Inserisci in tuo indirizzo e-mail', 'account:enter_login'=>'Inserisci il tuo username.', 'account:enter_new_password'=>'Inserisci una nuova password', 'account:forgot_password'=>'Password dimenticata?', 'account:login'=>'Accedi', 'account:login_placeholder'=>'login', 'account:ok'=>'OK', 'account:password_placeholder'=>'password', 'account:password_reset'=>'Reimposta password', 'account:reset'=>'Reimposta', 'account:reset_error'=>'I dati forniti per la reimpostazione della password non sono validi. Riprova!', 'account:reset_fail'=>'Impossibile ripristinare la password!', 'account:reset_success'=>'La tua password è stata reimpostata con successo. Ora puoi effettuare l\'accesso.', 'account:restore'=>'Ripristina', 'account:restore_error'=>'Nessun utente con username \':login\' è stato trovato.', 'account:restore_success'=>'Le istruzioni per reimpostare la password sono state inviate al tuo indirizzo e-mail.', 'account:sign_out'=>'Esci', 'ajax_handler:invalid_name'=>'Nome del gestore AJAX non valido: :name.', 'ajax_handler:not_found'=>'Il gestore AJAX \':name\' non è stato trovato.', 'app:name'=>'October CMS', 'app:tagline'=>'Tornare alle origini', 'asset:already_exists'=>'Un file o cartella con questo nome è già esistente', 'asset:create_directory'=>'Crea cartella', 'asset:create_file'=>'Crea file', 'asset:delete'=>'Elimina', 'asset:destination_not_found'=>'Cartella di destinazione non trovata', 'asset:directory_name'=>'Nome della cartella', 'asset:directory_popup_title'=>'Nuova cartella', 'asset:drop_down_add_title'=>'Aggiungi...', 'asset:drop_down_operation_title'=>'Azioni...', 'asset:error_deleting_dir'=>'Errore durante l\'eliminazinoe della cartella :name.', 'asset:error_deleting_dir_not_empty'=>'Errore durante l\'eliminazione della cartella :name. La cartella non è vuota.', 'asset:error_deleting_directory'=>'Errore durante l\'eliminazione della cartella originale :dir', 'asset:error_deleting_file'=>'Errore durante l\'eliminazione del file :name.', 'asset:error_moving_directory'=>'Errore durante lo spostamento della cartella :dir', 'asset:error_moving_file'=>'Errore durante lo spostamento del file :file', 'asset:error_renaming'=>'Errore nella rinominazione del file o della cartella', 'asset:error_uploading_file'=>'Errore durante il caricamento del file \':name\': :error', 'asset:file_not_valid'=>'File non valido', 'asset:invalid_name'=>'Il nome può contenere solo numeri, lettere latine, spazi e i simboli seguenti: ._-', 'asset:invalid_path'=>'Il percorso può contenere solo numeri, lettere latine, spazi e i simboli seguenti: ._-/', 'asset:menu_label'=>'Assets', 'asset:move'=>'Sposta', 'asset:move_button'=>'Sposta', 'asset:move_destination'=>'Cartella di destinazione', 'asset:move_please_select'=>'seleziona', 'asset:move_popup_title'=>'Sposta assets', 'asset:name_cant_be_empty'=>'Il nome non può essere vuoto', 'asset:new'=>'Nuovo file', 'asset:original_not_found'=>'Il file o la cartella originali non sono stati trovati', 'asset:path'=>'Percorso', 'asset:rename'=>'Rinomina', 'asset:rename_new_name'=>'Nuovo nome', 'asset:rename_popup_title'=>'Rinomina', 'asset:select'=>'Seleziona', 'asset:select_destination_dir'=>'Seleziona una cartella di destinazione', 'asset:selected_files_not_found'=>'Files selezionati non trovati.', 'asset:too_large'=>'Il file caricato è troppo grande. La dimensione massima consentita è :max_size', 'asset:type_not_allowed'=>'Solo i seguenti tipi di file sono consentiti: :allowed_types', 'asset:unsaved_label'=>'Asset(s) non salvati', 'asset:upload_files'=>'Carica file(s)', 'auth:title'=>'Area di Amministrazione', 'backend_preferences:locale'=>'Lingua', 'backend_preferences:locale_comment'=>'Seleziona la lingua da utilizzare.', 'backend_preferences:menu_description'=>'Gestisci le preferenze del tuo account, come la lingua.', 'backend_preferences:menu_label'=>'Preferenze pannello di controllo', 'behavior:missing_property'=>'La classe :class deve definire la proprietà $:property utilizzata dalla funzione :behavior.', 'branding:app_name'=>'Nome dell\'applicazione', 'branding:app_name_description'=>'Questo campo verrà visualizzato nella barra del titolo del pannello di controllo.', 'branding:app_tagline'=>'Slogan dell\'applicazione', 'branding:app_tagline_description'=>'Questo campo verrà visualizzato nella schermata di login del pannello di controllo.', 'branding:brand'=>'Marchio', 'branding:colors'=>'Colori', 'branding:custom_stylesheet'=>'Foglio di stile personalizzato', 'branding:logo'=>'Logo', 'branding:logo_description'=>'Carica un logo personalizzato da utilizzare nel pannello di controllo.', 'branding:menu_description'=>'Personalizza l\'area di amministrazione, come il nome, i colori ed il logo.', 'branding:menu_label'=>'Personalizza pannello di controllo', 'branding:primary_dark'=>'Principale (Scuro)', 'branding:primary_light'=>'Principale (Chiaro)', 'branding:secondary_dark'=>'Secondario (Scuro)', 'branding:secondary_light'=>'Secondario (Chiaro)', 'branding:styles'=>'Stili', 'cms:menu_label'=>'CMS', 'cms_object:delete_success'=>'Template eliminati correttamente: :count.', 'cms_object:error_creating_directory'=>'Errore nella creazione della cartella :name. Verifica le autorizzazioni di scrittura.', 'cms_object:error_deleting'=>'Errore nella cancellazione del file \':name\'. Verifica le autorizzazioni di scrittura.', 'cms_object:error_saving'=>'Errore nel salvataggio del file \':name\'. Verifica le autorizzazioni di scrittura.', 'cms_object:file_already_exists'=>'File \':name\' già esistente.', 'cms_object:file_name_required'=>'Il campo Nome file è obbligatorio.', 'cms_object:invalid_file'=>'Nome file non valido: :name. I nomi dei file possono contenere solo caratteri alfanumerici, underscores, trattini e punti. Alcuni esempi di nome di file corretti: page.htm, page, subdirectory/page', 'cms_object:invalid_file_extension'=>'Estensione del file non valida: :invalid. Le estensioni consentite sono: :allowed.', 'cms_object:invalid_property'=>'La proprietà \':name\' non può essere impostata', 'combiner:not_found'=>'Il file combinatore \':name\' non è stato trovato.', 'component:alias'=>'Alias', 'component:alias_description'=>'Un nome univoco fornito a questo componente quando utilizzato nella pagina o nel layout.', 'component:invalid_request'=>'Il template non può essere salvato a causa di dati dei componenti non validi.', 'component:menu_label'=>'Componenti', 'component:method_not_found'=>'Il componente \':name\' non contiene il metodo \':method\'.', 'component:no_description'=>'Nessuna descrizione fornita', 'component:no_records'=>'Nessun componente trovato', 'component:not_found'=>'Il componente \':name\' non è stato trovato.', 'component:unnamed'=>'Senza nome', 'component:validation_message'=>'L\'alias del componente è obbligatorio e può contenere solo lettere latine, numeri e underscores. L\'alias deve iniziare con una lettera.', 'config:not_found'=>'Il file di configurazione :file definito per :location non è stato trovato.', 'config:required'=>'La configurazione utilizzata in :location deve fornire un valore \':property\'.', 'content:delete_confirm_multiple'=>'Sei sicuro di voler eliminare i file o le cartelle di contenuti selezionate?', 'content:delete_confirm_single'=>'Sei sicuro di voler eliminare questo file di contenuti?', 'content:menu_label'=>'Contenuti', 'content:new'=>'Nuovo file di contenuti', 'content:no_list_records'=>'Nessun file di contenuto trovato', 'content:not_found_name'=>'Il file di contenuti \':name\' non è stato trovato.', 'content:unsaved_label'=>'Contenuti non salvati', 'dashboard:add_widget'=>'Aggiungi widget', 'dashboard:columns'=>'{1} colonna|[2,Inf] colonne', 'dashboard:full_width'=>'intera larghezza', 'dashboard:menu_label'=>'Dashboard', 'dashboard:status:maintenance'=>'in manutenzione', 'dashboard:status:online'=>'online', 'dashboard:status:update_available'=>'{0} aggiornamenti disponibili!|{1} aggiornamento disponibile!|[2,Inf] aggiornamenti disponibili!', 'dashboard:status:widget_title_default'=>'Stato del sistema', 'dashboard:widget_columns_description'=>'La larghezza del widget, un numero compreso tra 1 e 10.', 'dashboard:widget_columns_error'=>'La larghezza del widget deve essere un numero compreso tra 1 e 10.', 'dashboard:widget_columns_label'=>'Larghezza :columns', 'dashboard:widget_inspector_description'=>'Configura il widget', 'dashboard:widget_inspector_title'=>'Configurazione widget', 'dashboard:widget_label'=>'Widget', 'dashboard:widget_new_row_description'=>'Inserisci il widget su una nuova riga.', 'dashboard:widget_new_row_label'=>'Forza nuova riga', 'dashboard:widget_title_error'=>'Il titolo del widget è un campo obbligatorio.', 'dashboard:widget_title_label'=>'Titolo del widget', 'dashboard:widget_width'=>'Larghezza', 'directory:create_fail'=>'Impossibile creare la cartella: :name', 'editor:code'=>'Codice', 'editor:code_folding'=>'Raggruppa il codice', 'editor:content'=>'Contenuto', 'editor:description'=>'Descrizione', 'editor:enter_fullscreen'=>'Visualizza a schermo intero', 'editor:exit_fullscreen'=>'Esci dalla visualizzazione a schermo intero', 'editor:filename'=>'Nome file', 'editor:font_size'=>'Dimensione carattere', 'editor:hidden'=>'Nascosto', 'editor:hidden_comment'=>'Le pagine nascoste sono accessibili solo dagli utenti collegati al pannello di controllo.', 'editor:highlight_active_line'=>'Evidenzia la linea attiva', 'editor:layout'=>'Layout', 'editor:markup'=>'Markup', 'editor:menu_description'=>'Personalizza le impostazioni dell\'editor, come la dimensione del carattere e lo schema di colori.', 'editor:menu_label'=>'Preferenze editor di codice', 'editor:meta'=>'Metadati', 'editor:meta_description'=>'Meta Descrizione', 'editor:meta_title'=>'Meta Titolo', 'editor:new_title'=>'Titolo nuova pagina', 'editor:preview'=>'Anteprima', 'editor:settings'=>'Impostazioni', 'editor:show_gutter'=>'Visualizza numeri di linea', 'editor:show_invisibles'=>'Mostra caratteri invisibili', 'editor:tab_size'=>'Dimensione Tab', 'editor:theme'=>'Schema di colori', 'editor:title'=>'Titolo', 'editor:url'=>'URL', 'editor:use_hard_tabs'=>'Indenta utilizzando i Tab', 'editor:word_wrap'=>'A capo automatico', 'event_log:created_at'=>'Data e ora', 'event_log:empty_link'=>'Svuota il registro eventi', 'event_log:empty_loading'=>'Svuotamento del registro eventi in corso...', 'event_log:empty_success'=>'Il registro eventi è stato svuotato con successo.', 'event_log:hint'=>'Questo registro visualizza un elenco dei potenziali errori occorsi nell\'applicazione, come eccezioni e informazioni di debug.', 'event_log:id'=>'ID', 'event_log:id_label'=>'ID evento', 'event_log:level'=>'Livello', 'event_log:menu_description'=>'VIsualizza i messaggi del registro di sistema con i relativi orari di registrazione e dettagli.', 'event_log:menu_label'=>'Registro eventi', 'event_log:message'=>'Messaggio', 'event_log:return_link'=>'Ritorna al registro eventi', 'field:invalid_type'=>'Il tipo di campo :type non è valido.', 'field:options_method_not_exists'=>'La classe :model deve definire un metodo :method() che ritorni le opzioni per il campo \":field\".', 'file:create_fail'=>'Impossibile creare il file: :name', 'fileupload:attachment'=>'Allegato', 'fileupload:attachment_url'=>'URL Allegato', 'fileupload:default_prompt'=>'Fai clic su %s o trascina un file qui per eseguire il caricamento', 'fileupload:description_label'=>'Descrizione', 'fileupload:help'=>'Aggiungi un titolo e una descrizione per questo allegato.', 'fileupload:remove_confirm'=>'Sei sicuro?', 'fileupload:remove_file'=>'Rimuovi file', 'fileupload:title_label'=>'Titolo', 'fileupload:upload_error'=>'Errore nel caricamento', 'fileupload:upload_file'=>'Carica file', 'filter:all'=>'tutto', 'form:action_confirm'=>'Sei sicuro?', 'form:add'=>'Aggiungi', 'form:apply'=>'Applica', 'form:behavior_not_ready'=>'Il form non è stato inizializzato, verifica di aver chiamato il metodo initForm() nel controller.', 'form:cancel'=>'Annulla', 'form:close'=>'Chiudi', 'form:complete'=>'Completo', 'form:concurrency_file_changed_description'=>'Il file che stavi modificando è stato cambiato da un altro utente. Puoi ricaricare il file e perdere le tue modifiche oppure sovrascrivere il file sul disco.', 'form:concurrency_file_changed_title'=>'Il file è stato cambiato', 'form:confirm'=>'Conferma', 'form:confirm_tab_close'=>'Vuoi davvero chiudere il tab? Le modifiche non salvate andranno perse.', 'form:create'=>'Crea', 'form:create_and_close'=>'Crea e chiudi', 'form:create_success'=>':name creato con successo', 'form:create_title'=>'Crea :name', 'form:creating'=>'Creazione in corso...', 'form:creating_name'=>'Creazione :name in corso...', 'form:delete'=>'Elimina', 'form:delete_row'=>'Elimina riga', 'form:delete_success'=>':name eliminato con successo', 'form:deleting'=>'Eliminazione in corso...', 'form:deleting_name'=>'Eliminazione :name in corso...', 'form:field_off'=>'Off', 'form:field_on'=>'On', 'form:insert_row'=>'Inserisci riga', 'form:missing_definition'=>'Il form non contiene il campo \':field\'.', 'form:missing_id'=>'L\'ID del record non è stato specificato.', 'form:missing_model'=>'Il form utilizzato nella classe :class non ha un modello definito.', 'form:not_found'=>'Nessun record con ID :id è stato trovato.', 'form:ok'=>'OK', 'form:or'=>'o', 'form:preview_no_files_message'=>'Non ci sono file caricati.', 'form:preview_no_record_message'=>'Nessun record selezionato.', 'form:preview_title'=>'Anteprima :name', 'form:reload'=>'Ricarica', 'form:reset_default'=>'Ripristina predefiniti', 'form:resetting'=>'Ripristino in corso', 'form:resetting_name'=>'Ripristino :name in corso', 'form:save'=>'Salva', 'form:save_and_close'=>'Salva e chiudi', 'form:saving'=>'Salvataggio in corso...', 'form:saving_name'=>'Salvataggio :name in corso...', 'form:select'=>'Seleziona', 'form:select_all'=>'tutti', 'form:select_none'=>'nessuno', 'form:select_placeholder'=>'seleziona', 'form:undefined_tab'=>'Varie', 'form:update_success'=>':name modificato con successo', 'form:update_title'=>'Modifica :name', 'install:install_completing'=>'Sto terminando il processo di installazione', 'install:install_success'=>'Il plugin è stato installato con successo.', 'install:missing_plugin_name'=>'Specifica il nome del plugin da installare.', 'install:missing_theme_name'=>'Specifica il nome del tema da installare.', 'install:plugin_label'=>'Installa plugin', 'install:project_label'=>'Collega al progetto', 'install:theme_label'=>'Installa tema', 'layout:delete_confirm_multiple'=>'Sei sicuro di voler eliminare i layouts selezionati?', 'layout:delete_confirm_single'=>'Sei sicuro di voler eliminare questo layout?', 'layout:menu_label'=>'Layout', 'layout:new'=>'Nuovo layout', 'layout:no_list_records'=>'Nessun layout trovato', 'layout:not_found_name'=>'Il layout \':name\' non è stato trovato', 'layout:unsaved_label'=>'Layout non salvati', 'list:behavior_not_ready'=>'L\'elenco non è stato inizializzato, controlla di aver chiamato il metodo makeLists() nel controller.', 'list:default_title'=>'Elenco', 'list:delete_selected'=>'Elimina selezionati', 'list:delete_selected_confirm'=>'Elimina i record selezionati?', 'list:delete_selected_empty'=>'Non hai selezionato nessun record da eliminare.', 'list:delete_selected_success'=>'I record selezionati sono stati eliminati con successo.', 'list:invalid_column_datetime'=>'Il valore della colonna \':column\' non è un oggetto di tipo DateTime, hai dimenticato un riferimento a $dates nel modello?', 'list:loading'=>'Caricamento...', 'list:missing_column'=>'Non ci sono colonne definite per :columns.', 'list:missing_columns'=>'L\'elenco utilizzato nella classe :class non ha un elenco di colonne definito.', 'list:missing_definition'=>'L\'elenco non contiene una colonna per il campo \':field\'.', 'list:missing_model'=>'L\'elenco utilizzato nella classe :class non ha un modello definito.', 'list:next_page'=>'Pagina successiva', 'list:no_records'=>'Nessun risultato trovato.', 'list:pagination'=>'Record visualizzati: :from-:to di :total', 'list:prev_page'=>'Pagina precedente', 'list:records_per_page'=>'Record per pagina', 'list:records_per_page_help'=>'Seleziona il numero di record da visualizzare su ogni pagina. Ricorda che un numero elevato di record in una singola pagina può ridurre le prestazioni.', 'list:search_prompt'=>'Cerca...', 'list:setup_help'=>'Utilizza le checkbox per selezionare le colonne che vuoi visualizzare nell\'elenco. Puoi cambiare la posizione delle colonne trascinandole verso l\'alto o il basso.', 'list:setup_title'=>'Configura elenco', 'locale:cs'=>'Ceco', 'locale:de'=>'Tedesco', 'locale:el'=>'Greco', 'locale:en'=>'Inglese', 'locale:es'=>'Spagnolo', 'locale:es-ar'=>'Spagnolo (Argentina)', 'locale:fa'=>'Persiano', 'locale:fr'=>'Francese', 'locale:hu'=>'Ungherese', 'locale:id'=>'Indonesiano', 'locale:it'=>'Italiano', 'locale:ja'=>'Giapponese', 'locale:lv'=>'Lettone', 'locale:nb-no'=>'Norvegese (Bokmål)', 'locale:nl'=>'Olandese', 'locale:pl'=>'Polacco', 'locale:pt-br'=>'Portoghese (Brasile)', 'locale:ro'=>'Romeno', 'locale:ru'=>'Russo', 'locale:sk'=>'Slovacco (Slovacchia)', 'locale:sv'=>'Svedese', 'locale:tr'=>'Turco', 'locale:zh-cn'=>'Cinese (Cina)', 'mail:drivers_hint_content'=>'Questa modalità di invio richiede che il plugin \":plugin\" sia installato prima che tu possa inviare messaggi.', 'mail:drivers_hint_header'=>'Driver non installati', 'mail:general'=>'Generale', 'mail:log_file'=>'File di log', 'mail:mailgun'=>'Mailgun', 'mail:mailgun_domain'=>'Dominio Mailgun', 'mail:mailgun_domain_comment'=>'Inserisci il nome dominio Mailgun.', 'mail:mailgun_secret'=>'Chiave Mailgun', 'mail:mailgun_secret_comment'=>'Inserisci la tua chiave per l\'utilizzo delle API Mailgun.', 'mail:mandrill'=>'Mandrill', 'mail:mandrill_secret'=>'Chiave Mandrill', 'mail:mandrill_secret_comment'=>'Inserisci la tua chiave per l\'utilizzo delle API Mandrill.', 'mail:menu_description'=>'Gestisci la configurazione delle e-mail.', 'mail:menu_label'=>'Configurazione e-mail', 'mail:method'=>'Metodo di invio', 'mail:php_mail'=>'PHP mail', 'mail:sender_email'=>'Indirizzo e-mail del mittente', 'mail:sender_name'=>'Nome del mittente', 'mail:sendmail'=>'Sendmail', 'mail:sendmail_path'=>'Percorso Sendmail', 'mail:sendmail_path_comment'=>'Inserisci il percorso al servizio sendmail.', 'mail:smtp'=>'SMTP', 'mail:smtp_address'=>'Indirizzo SMTP', 'mail:smtp_authorization'=>'Il server SMTP richiede l\'autenticazione', 'mail:smtp_authorization_comment'=>'Seleziona se il tuo server SMTP richieste l\'autenticazione.', 'mail:smtp_password'=>'Password', 'mail:smtp_port'=>'Porta SMTP', 'mail:smtp_ssl'=>'Connessione SSL richiesta', 'mail:smtp_username'=>'Username', 'mail_templates:code'=>'Codice', 'mail_templates:code_comment'=>'Codice univoco utilizzato come riferimento a questo modello', 'mail_templates:content_css'=>'CSS', 'mail_templates:content_html'=>'HTML', 'mail_templates:content_text'=>'Testo piano', 'mail_templates:description'=>'Descrizione', 'mail_templates:layout'=>'Layout', 'mail_templates:layouts'=>'Layouts', 'mail_templates:menu_description'=>'Modifica i modelli di e-mail inviati agli utenti ed amministratori, gestisci il layout delle e-mail.', 'mail_templates:menu_label'=>'Modelli di e-mail', 'mail_templates:menu_layouts_label'=>'Layouts delle e-mail', 'mail_templates:name'=>'Nome', 'mail_templates:name_comment'=>'Nome univoco utilizzato come riferimento a questo modello.', 'mail_templates:new_layout'=>'Nuovo layout', 'mail_templates:new_template'=>'Nuovo modello', 'mail_templates:return'=>'Ritorna all\'elenco dei modelli', 'mail_templates:subject'=>'Oggetto', 'mail_templates:subject_comment'=>'Oggetto del messaggio di posta', 'mail_templates:template'=>'Modello', 'mail_templates:templates'=>'Modelli', 'mail_templates:test_send'=>'Invia un messaggio di prova', 'mail_templates:test_success'=>'Il messaggio di prova è stato inviato con successo.', 'maintenance:is_enabled'=>'Abilita modalità di manutenzione', 'maintenance:is_enabled_comment'=>'Se attivo i visitatori del sito vedranno la pagina selezionata sotto.', 'maintenance:settings_menu'=>'Modalità di manutenzione', 'maintenance:settings_menu_description'=>'Configura la pagina da visualizzare in modalità di manutenzione e cambia l\'impostazione.', 'media:add_folder'=>'Aggiungi cartella', 'media:click_here'=>'Fai clic qui', 'media:crop_and_insert'=>'Ritaglia e inserisci', 'media:delete'=>'Elimina', 'media:delete_confirm'=>'Vuoi davvero eliminare gli elementi selezionati?', 'media:delete_empty'=>'Seleziona elementi da eliminare.', 'media:display'=>'Visualizza', 'media:empty_library'=>'La libreria è vuota. Carica dei files o crea delle cartelle per iniziare.', 'media:error_creating_folder'=>'Errore durante la creazione della cartella', 'media:error_renaming_file'=>'Errore durante la rinominazione dell\'elemento', 'media:filter_audio'=>'Audio', 'media:filter_documents'=>'Documenti', 'media:filter_everything'=>'Tutto', 'media:filter_images'=>'Immagini', 'media:filter_video'=>'Video', 'media:folder'=>'Cartella', 'media:folder_name'=>'Nome della cartella', 'media:folder_or_file_exist'=>'Una cartella o un file con il nome specificato è già esistente.', 'media:folder_size_items'=>'elementi', 'media:height'=>'Altezza', 'media:image_size'=>'Dimensione immagine:', 'media:insert'=>'Inserisci', 'media:invalid_path'=>'Percorso del file non valido: \':path\'.', 'media:last_modified'=>'Ultima modifica', 'media:library'=>'Libreria', 'media:menu_label'=>'Elementi multimediali', 'media:move'=>'Sposta', 'media:move_dest_src_match'=>'Seleziona un\'altra cartella di destinazione.', 'media:move_destination'=>'Cartella di destinazione', 'media:move_empty'=>'Selezione elementi da spostare.', 'media:move_popup_title'=>'Sposta file o cartelle', 'media:multiple_selected'=>'Elementi multipli selezionati.', 'media:new_folder_title'=>'Nuova cartella', 'media:no_files_found'=>'Nessun file corrisponde alla tua richiesta.', 'media:nothing_selected'=>'Nessun elemento selezionato.', 'media:order_by'=>'Ordina per', 'media:please_select_move_dest'=>'Seleziona una cartella di destinazione.', 'media:public_url'=>'URL pubblico', 'media:resize'=>'Ridimensiona...', 'media:resize_image'=>'Ridimensiona immagine', 'media:restore'=>'Annulla tutte le modifiche', 'media:return_to_parent'=>'Ritorna alla cartella superiore', 'media:return_to_parent_label'=>'Torna su ..', 'media:search'=>'Cerca', 'media:select_single_image'=>'Seleziona una singola immagine.', 'media:selected_size'=>'Selezionati:', 'media:selection_mode'=>'Metodo di selezione', 'media:selection_mode_fixed_ratio'=>'Rapporto fisso', 'media:selection_mode_fixed_size'=>'Dimensione fissa', 'media:selection_mode_normal'=>'Normale', 'media:selection_not_image'=>'L\'elemento selezionato non è un\'immagine.', 'media:size'=>'Dimensione', 'media:thumbnail_error'=>'Errore durante la generazione dell\'anteprima.', 'media:title'=>'Titolo', 'media:upload'=>'Carica', 'media:uploading_complete'=>'Caricamento completato', 'media:uploading_file_num'=>'Caricamento in corso di :number file(s)...', 'media:width'=>'Larghezza', 'mediafinder:default_prompt'=>'Fai clic sul pulsante %s per trovare un elemento multimediale', 'model:invalid_class'=>'Il modello :model utilizzato nella classe :class non è valido, deve ereditare la classe \\Model.', 'model:mass_assignment_failed'=>'Assegnazione massiva fallita per l\'attributo \':attribute\' del modello.', 'model:missing_id'=>'Nessun ID specificato per la ricerca.', 'model:missing_method'=>'Il modello \':class\' non contiene un metodo \':method\'.', 'model:missing_relation'=>'Il modello \':class\' non contiene una definizione per la relazione \':relation\'.', 'model:name'=>'Modello', 'model:not_found'=>'Nessun modello \':class\' con ID :id trovato.', 'myaccount:menu_description'=>'Aggiorna i dettagli del tuo account, come il nome, l\'indirizzo e-mail e la password.', 'myaccount:menu_keywords'=>'sicurezza login', 'myaccount:menu_label'=>'Il mio account', 'mysettings:menu_description'=>'Impostazioni legate al tuo account amministratore', 'mysettings:menu_label'=>'Impostazioni personali', 'page:access_denied:cms_link'=>'Ritorna al pannello di controllo', 'page:access_denied:help'=>'Non hai le autorizzazioni necessarie per accedere a questa pagina.', 'page:access_denied:label'=>'Accesso negato', 'page:custom_error:help'=>'Siamo spiacenti, ma qualcosa è andato storto e la pagina non può essere visualizzata.', 'page:custom_error:label'=>'Errore nella pagina', 'page:delete_confirm_multiple'=>'Sei sicuro di voler eliminare le pagine selezionate?', 'page:delete_confirm_single'=>'Sei sicuro di voler eliminare questa pagina?', 'page:invalid_token:label'=>'Token di protezione non valido', 'page:invalid_url'=>'Formato URL non valido. L\'URL deve iniziare con una barra e può contenere numeri, lettere latine e i seguenti simboli: ._-[]:?|/+*^$', 'page:menu_label'=>'Pagine', 'page:new'=>'Nuova pagina', 'page:no_layout'=>'-- nessun layout --', 'page:no_list_records'=>'Pagine non trovate', 'page:not_found:help'=>'La pagina richiesta non è stata trovata.', 'page:not_found:label'=>'Pagina non trovata', 'page:not_found_name'=>'Pagina \':name\' non trovata', 'page:unsaved_label'=>'Pagina/e non salvate', 'page:untitled'=>'Senza titolo', 'partial:delete_confirm_multiple'=>'Sei sicuro di voler eliminare le viste parziali selezionate?', 'partial:delete_confirm_single'=>'Sei sicuro di voler eliminare questa vista parziale?', 'partial:invalid_name'=>'Nome della vista parziale non valido: :name.', 'partial:menu_label'=>'Viste parziali', 'partial:new'=>'Nuova vista parziale', 'partial:no_list_records'=>'Nessuna vista parziale trovata', 'partial:not_found_name'=>'La vista parziale \':name\' non è stata trovata.', 'partial:unsaved_label'=>'Viste parziali non salvate', 'permissions:access_logs'=>'Visualizza registri di sistema', 'permissions:manage_assets'=>'Gestisci assets', 'permissions:manage_branding'=>'Personalizza il pannello di controllo', 'permissions:manage_content'=>'Gestisci contenuti', 'permissions:manage_layouts'=>'Gesstisci layouts', 'permissions:manage_mail_settings'=>'Gestisci impostazioni e-mail', 'permissions:manage_mail_templates'=>'Gestisci i modelli e-mail', 'permissions:manage_media'=>'Gestisci elementi multimediali', 'permissions:manage_other_administrators'=>'Gestisci altri amministratori', 'permissions:manage_pages'=>'Gestisci pagine', 'permissions:manage_partials'=>'Gestisci viste parziali', 'permissions:manage_software_updates'=>'Gestisci aggiornamenti del software', 'permissions:manage_system_settings'=>'Gestisci impostazioni di sistema', 'permissions:manage_themes'=>'Gestisci temi', 'permissions:name'=>'Cms', 'permissions:view_the_dashboard'=>'Visualizza la dashboard', 'plugin:label'=>'Plugin', 'plugin:name:help'=>'Cerca il plugin tramite il suo codice univoco. Ad esempio, RainLab.Blog', 'plugin:name:label'=>'Nome del plugin', 'plugin:unnamed'=>'Plugin senza nome', 'plugins:disable_confirm'=>'Sei sicuro?', 'plugins:disable_success'=>'Disabilitazione dei plugin eseguita con successo.', 'plugins:disabled_help'=>'I plugin disabilitati sono ignorati dall\'applicazione.', 'plugins:disabled_label'=>'Disabilitato', 'plugins:enable_or_disable'=>'Abilita o disabilita', 'plugins:enable_or_disable_title'=>'Abilita o disabilita plugin', 'plugins:enable_success'=>'Abilitazione dei plugin eseguita con successo.', 'plugins:frozen_help'=>'I plugin congelati verranno ignorati nel processo di aggiornamento.', 'plugins:frozen_label'=>'Congela aggiornamenti', 'plugins:install'=>'Installa plugin', 'plugins:install_products'=>'Installa prodotti', 'plugins:installed'=>'Plugin installati', 'plugins:manage'=>'Gestisci plugin', 'plugins:no_plugins'=>'Non ci sono temi installati dal marketplace.', 'plugins:recommended'=>'Raccomandati', 'plugins:refresh'=>'Reinstalla', 'plugins:refresh_confirm'=>'Sei sicuro?', 'plugins:refresh_success'=>'Reinstallazione dei plugin nel sistema eseguita con successo.', 'plugins:remove'=>'Rimuovi', 'plugins:remove_confirm'=>'Sei sicuro di voler rimuovere questo plugin?', 'plugins:remove_success'=>'Rimozione dei plugin dal sistema eseguita con successo.', 'plugins:search'=>'cerca plugin da installare...', 'plugins:selected_amount'=>'Plugin selezionati: :amount', 'plugins:unknown_plugin'=>'Il plugin è stato rimosso dal file system.', 'project:attach'=>'Collega progetto', 'project:detach'=>'Scollega progetto', 'project:detach_confirm'=>'Sei sicuro di voler scollegare questo progetto?', 'project:id:help'=>'Come trovare l\'ID del tuo progetto', 'project:id:label'=>'ID del progetto', 'project:id:missing'=>'Inserisci un ID di progetto da utilizzare.', 'project:name'=>'Progetto', 'project:none'=>'Nessuno', 'project:owner_label'=>'Proprietario', 'project:unbind_success'=>'Il progetto è stato scollegato con successo.', 'relation:add'=>'Aggiungi', 'relation:add_a_new'=>'Aggiungi nuovo :name', 'relation:add_name'=>'Aggiungi :name', 'relation:add_selected'=>'Aggiungi selezionati', 'relation:cancel'=>'Annulla', 'relation:close'=>'Chiudi', 'relation:create'=>'Crea', 'relation:create_name'=>'Crea :name', 'relation:delete'=>'Elimina', 'relation:delete_confirm'=>'Sei sicuro?', 'relation:delete_name'=>'Elimina :name', 'relation:help'=>'Fai clic su un elemento per aggiungere', 'relation:invalid_action_multi'=>'L\'azione non può essere eseguita su una relazione multipla.', 'relation:invalid_action_single'=>'L\'azione non può essere eseguita su una relazione singola.', 'relation:link'=>'Collega', 'relation:link_a_new'=>'Collega nuovo :name', 'relation:link_name'=>'Collega :name', 'relation:link_selected'=>'Collega selezionati', 'relation:missing_config'=>'La relazione non ha nessuna configurazione per \':config\'.', 'relation:missing_definition'=>'La relazione non contiene una definizione per il campo \':field\'.', 'relation:missing_model'=>'La relazione utilizzata nella classe :class non ha un modello definito.', 'relation:preview'=>'Visualizza', 'relation:preview_name'=>'Visualizza :name', 'relation:related_data'=>'Dati :name correlati', 'relation:remove'=>'Rimuovi', 'relation:remove_name'=>'Rimuovi :name', 'relation:unlink'=>'Scollega', 'relation:unlink_confirm'=>'Sei sicuro?', 'relation:unlink_name'=>'Scollega :name', 'relation:update'=>'Aggiorna', 'relation:update_name'=>'Aggiorna :name', 'request_log:count'=>'Contatore', 'request_log:empty_link'=>'Svuota il registro richieste', 'request_log:empty_loading'=>'Svuotamento del registro richieste in corso...', 'request_log:empty_success'=>'Il registro richieste è stato svuotato con successo.', 'request_log:hint'=>'Questo registro visualizza un elenco delle richieste del browser che possono richiedere attenzione. Ad esempio, se un visitatore apre una pagina del CMS che non può essere trovata, viene creato un record con il codice di errore 404.', 'request_log:id'=>'ID', 'request_log:id_label'=>'ID Registro', 'request_log:menu_description'=>'Visualizza richieste errate o reindirizzate, come Pagina non trovata (404).', 'request_log:menu_label'=>'Registro richieste', 'request_log:referer'=>'Provenienza', 'request_log:return_link'=>'Ritorna al registro richieste', 'request_log:status_code'=>'Codice di stato', 'request_log:url'=>'URL', 'server:connect_error'=>'Errore durante la connessione al server.', 'server:file_corrupt'=>'Il file è corrotto.', 'server:file_error'=>'Il server non è riuscito a consegnare il pacchetto.', 'server:response_empty'=>'Il server ha fornito una risposta vuota.', 'server:response_invalid'=>'Il server ha fornito una risposta non valida.', 'server:response_not_found'=>'Il server degli aggiornamento non è stato trovato.', 'settings:menu_label'=>'Impostazioni', 'settings:missing_model'=>'La pagine delle impostazioni non ha nessun modello associato.', 'settings:not_found'=>'Impossibile trovare le impostazioni specificate.', 'settings:return'=>'Ritorna alle impostazioni di sistema', 'settings:search'=>'Cerca', 'settings:update_success'=>'Le impostazioni per :name sono state aggiornate con successo.', 'sidebar:add'=>'Aggiungi', 'sidebar:search'=>'Cerca...', 'system:categories:cms'=>'CMS', 'system:categories:customers'=>'Clienti', 'system:categories:events'=>'Eventi', 'system:categories:logs'=>'Log', 'system:categories:mail'=>'Mail', 'system:categories:misc'=>'Varie', 'system:categories:my_settings'=>'Impostazioni personali', 'system:categories:shop'=>'Negozio', 'system:categories:social'=>'Social', 'system:categories:system'=>'Sistema', 'system:categories:team'=>'Team', 'system:categories:users'=>'Utenti', 'system:menu_label'=>'Sistema', 'system:name'=>'Sistema', 'template:invalid_type'=>'Tipo di template sconosciuto.', 'template:not_found'=>'Il template richiesto non è stato trovato.', 'template:saved'=>'Il template è stato salvato con successo', 'theme:activate_button'=>'Attiva', 'theme:active:not_found'=>'Il tema attivo non è stato trovato.', 'theme:active:not_set'=>'Il tema attivo non è impostato.', 'theme:active_button'=>'Attivo', 'theme:author_label'=>'Autore', 'theme:author_placeholder'=>'Nome della persona o della società', 'theme:code_label'=>'Codice', 'theme:code_placeholder'=>'Un codice univoco per questo tema, utilizzato per la distribuzione', 'theme:create_button'=>'Crea', 'theme:create_new_blank_theme'=>'Crea un nuovo tema vuoto', 'theme:create_theme_required_name'=>'Specifica un nome per il tema.', 'theme:create_theme_success'=>'Tema creato con successo!', 'theme:create_title'=>'Crea tema', 'theme:customize_button'=>'Personalizza', 'theme:customize_theme'=>'Personalizza tema', 'theme:default_tab'=>'Proprietà', 'theme:delete_active_theme_failed'=>'Impossibile eliminare il tema attivo, prova prima ad attivare un altro tema.', 'theme:delete_button'=>'Elimina', 'theme:delete_confirm'=>'Sei sicuro di voler cancellare questo tema? L\'operazione non può essere annullata!', 'theme:delete_theme_success'=>'Tema eliminato con successo!', 'theme:description_label'=>'Descrizione', 'theme:description_placeholder'=>'Descrizione del tema', 'theme:dir_name_create_label'=>'La cartella di destinazione del tema', 'theme:dir_name_invalid'=>'Il nome della cartella può contenere solo numeri, lettere latine e i seguenti simboli: _-', 'theme:dir_name_label'=>'Nome della cartella', 'theme:dir_name_taken'=>'Cartelle di destinazione del tema già esistente.', 'theme:duplicate_button'=>'Duplica', 'theme:duplicate_theme_success'=>'Tema duplicato con successo!', 'theme:duplicate_title'=>'Duplica tema', 'theme:edit:not_found'=>'Il tema modificato non è stato trovato.', 'theme:edit:not_match'=>'L\'oggetto a cui stai cercando di accedere non appartiene al tema che stai modificando. Si prega di ricaricare la pagina.', 'theme:edit:not_set'=>'Il tema modificato non è impostato.', 'theme:edit_properties_button'=>'Modifica proprietà', 'theme:edit_properties_title'=>'Tema', 'theme:export_button'=>'Esporta', 'theme:export_folders_comment'=>'Seleziona le cartelle del tema che vuoi esportare', 'theme:export_folders_label'=>'Cartelle', 'theme:export_title'=>'Esporta tema', 'theme:find_more_themes'=>'Trova nuovi temi', 'theme:homepage_label'=>'Homepage', 'theme:homepage_placeholder'=>'URL Sito web', 'theme:import_button'=>'Importa', 'theme:import_folders_comment'=>'Seleziona le cartelle del tema che vuoi importare', 'theme:import_folders_label'=>'Cartelle', 'theme:import_overwrite_comment'=>'Deseleziona per importare solamente i nuovi file', 'theme:import_overwrite_label'=>'Sovrascrivi file esistenti', 'theme:import_theme_success'=>'Tema importato con successo!', 'theme:import_title'=>'Importa tema', 'theme:import_uploaded_file'=>'File di archivio del tema', 'theme:label'=>'Tema', 'theme:manage_button'=>'Gestisci', 'theme:manage_title'=>'Gestisci tema', 'theme:name:help'=>'Cerca il tema tramite il suo codice univoco. Ad esempio, RainLab.Vanilla', 'theme:name:label'=>'Nome tema', 'theme:name_create_placeholder'=>'Nome del nuovo tema', 'theme:name_label'=>'Nome', 'theme:new_directory_name_comment'=>'Inserisci una nuova cartella per il tema duplicato.', 'theme:new_directory_name_label'=>'Cartella di destinazione del tema', 'theme:not_found_name'=>'Tema \':name\' non trovato.', 'theme:return'=>'Ritorna all\'elenco del temi', 'theme:save_properties'=>'Salva proprietà', 'theme:saving'=>'Salvataggio tema in corso...', 'theme:settings_menu'=>'Tema del sito', 'theme:settings_menu_description'=>'Visualizza l\'anteprima dei temi installati e seleziona un tema attivo.', 'theme:theme_label'=>'Tema', 'theme:theme_title'=>'Temi', 'theme:unnamed'=>'Tema senza nome', 'themes:install'=>'Installa temi', 'themes:installed'=>'Temi installati', 'themes:no_themes'=>'Non ci sono temi installati dal marketplace.', 'themes:recommended'=>'Raccomandati', 'themes:remove_confirm'=>'Sei sicuro di voler rimuovere questo tema?', 'themes:search'=>'cerca temi da installare...', 'tooltips:preview_website'=>'Anteprima del sito web', 'updates:check_label'=>'Verifica gli aggiornamenti', 'updates:core_build'=>'Build :build', 'updates:core_build_help'=>'Disponibile l\'ultima build.', 'updates:core_current_build'=>'Build corrente', 'updates:core_downloading'=>'Scaricamento dei file in corso', 'updates:core_extracting'=>'Estrazione dei file in corso', 'updates:details_author'=>'Autore', 'updates:details_current_version'=>'Versione attuale', 'updates:details_readme'=>'Documentazione', 'updates:details_readme_missing'=>'Nessuna documentazione fornita.', 'updates:details_title'=>'Dettagli plugin', 'updates:details_upgrades'=>'Guida all\'aggiornamento', 'updates:details_upgrades_missing'=>'Nessuna guida all\'aggiornamento fornita.', 'updates:details_view_homepage'=>'Visualizza homepage', 'updates:disabled'=>'Disabilitati', 'updates:force_label'=>'Forza aggiornamento', 'updates:found:help'=>'Clicca Aggiorna il software per iniziare il processo di aggiornamento.', 'updates:found:label'=>'Trovati nuovi aggiornamenti!', 'updates:important_action:confirm'=>'Conferma aggiornamento', 'updates:important_action:empty'=>'Seleziona azione', 'updates:important_action:ignore'=>'Salta questo plugin (sempre)', 'updates:important_action:skip'=>'Salta questo plugin (solo questa volta)', 'updates:important_action_required'=>'Azione richiesta', 'updates:important_alert_text'=>'Alcuni aggiornamenti necessitano della tua attenzione.', 'updates:important_view_guide'=>'Visualizza la guida per l\'aggiornamento', 'updates:menu_description'=>'Aggiorna il sistema, gestisci ed installa plugin e temi.', 'updates:menu_label'=>'Aggiornamenti', 'updates:name'=>'Aggiornamento del software', 'updates:none:help'=>'Nessun aggiornamento trovato.', 'updates:none:label'=>'Nessun aggiornamento', 'updates:plugin_author'=>'Autore', 'updates:plugin_code'=>'Codice', 'updates:plugin_current_version'=>'Versione attuale', 'updates:plugin_description'=>'Descrizione', 'updates:plugin_downloading'=>'Scaricamento plugin: :name', 'updates:plugin_extracting'=>'Estrazione plugin: :name', 'updates:plugin_name'=>'Nome', 'updates:plugin_version'=>'Versione', 'updates:plugin_version_none'=>'Nuovo plugin', 'updates:plugins'=>'Plugin', 'updates:retry_label'=>'Riprova', 'updates:return_link'=>'Ritorna agli aggiornamenti di sistema', 'updates:theme_downloading'=>'Scaricamento tema: :name', 'updates:theme_extracting'=>'Estrazione tema: :name', 'updates:theme_new_install'=>'Installa nuovo tema.', 'updates:themes'=>'Themi', 'updates:title'=>'Gestisci aggiornamenti', 'updates:update_completing'=>'Completamento del processo di aggiornamento', 'updates:update_failed_label'=>'Aggiornamento fallito', 'updates:update_label'=>'Aggiorna il software', 'updates:update_loading'=>'Caricamento degli aggiornamenti disponibili...', 'updates:update_success'=>'L\'aggiornamento è stato eseguito con successo.', 'user:account'=>'Account', 'user:allow'=>'Consenti', 'user:avatar'=>'Avatar', 'user:delete_confirm'=>'Vuoi davvero eliminare questo amministratore?', 'user:deny'=>'Nega', 'user:email'=>'Indirizzo e-mail', 'user:first_name'=>'Nome', 'user:full_name'=>'Nome completo', 'user:group:code_comment'=>'Inserisci un codice univoco se vuoi accedere a questo elementro tramite API.', 'user:group:code_field'=>'Codice', 'user:group:delete_confirm'=>'Vuoi davvero eliminare questo gruppo amministratore?', 'user:group:description_field'=>'Descrizione', 'user:group:is_new_user_default_field'=>'Aggiungi i nuovi amministratori a questo gruppo per impostazione predefinita.', 'user:group:list_title'=>'Gestisci gruppi', 'user:group:menu_label'=>'Gruppi', 'user:group:name'=>'Gruppo', 'user:group:name_field'=>'Nome', 'user:group:new'=>'Nuovo gruppo', 'user:group:return'=>'Ritorna alla lista dei gruppi', 'user:group:users_count'=>'Utenti', 'user:groups'=>'Gruppi', 'user:groups_comment'=>'Seleziona i gruppi a cui appartiene l\'utente.', 'user:inherit'=>'Eredita', 'user:last_name'=>'Cognome', 'user:list_title'=>'Gestisci amministratori', 'user:login'=>'Login', 'user:menu_description'=>'Gestisci gli utenti amministratori, i gruppi e le autorizzazioni.', 'user:menu_label'=>'Amministratori', 'user:name'=>'Amministratore', 'user:new'=>'Nuovo amministratore', 'user:password'=>'Password', 'user:password_confirmation'=>'Conferma password', 'user:permissions'=>'Autorizzazioni', 'user:preferences:not_authenticated'=>'Non c\'è nessun utente autenticato per cui caricare o salvare le preferenze.', 'user:return'=>'Ritorna alla lista degli amministratori', 'user:send_invite'=>'Invia invito tramite e-mail', 'user:send_invite_comment'=>'Invia un messaggio di benvenuto contenente le credenziali per l\'accesso.', 'user:superuser'=>'Super User', 'user:superuser_comment'=>'Seleziona per consentire all\'utente di accedere a tutte le aree.', 'validation:accepted'=>':attribute deve essere accettato.', 'validation:active_url'=>':attribute non è un URL valido.', 'validation:after'=>':attribute deve essere una data maggiore di :date.', 'validation:alpha'=>':attribute può contenere solo lettere.', 'validation:alpha_dash'=>':attribute può contenere solo lettere, numeri e trattini.', 'validation:alpha_num'=>':attribute può contenere solo lettere e numeri.', 'validation:array'=>':attribute deve essere un array.', 'validation:before'=>':attribute deve essere una data minore di :date.', 'validation:between:array'=>':attribute deve avere tra :min e :max elementi.', 'validation:between:file'=>':attribute deve essere compreso tra :min e :max kilobytes.', 'validation:between:numeric'=>':attribute deve essere compreso tra :min e :max.', 'validation:between:string'=>':attribute deve essere compreso tra :min e :max caratteri.', 'validation:confirmed'=>'La conferma :attribute non corrisponde.', 'validation:date'=>':attribute non è una data valida.', 'validation:date_format'=>':attribute non corrisponde al formato :format.', 'validation:different'=>':attribute e :other devono essere diversi.', 'validation:digits'=>':attribute deve essere di :digits cifre.', 'validation:digits_between'=>':attribute deve essere tra :min e :max cifre.', 'validation:email'=>'Il formato di :attribute non è valido.', 'validation:exists'=>'Il valore di :attribute non è valido.', 'validation:extensions'=>':attribute deve avere un estensione: :values.', 'validation:image'=>':attribute deve essere un\'immagine.', 'validation:in'=>'Il valore di :attribute non è valido.', 'validation:integer'=>':attribute deve essere un numero interno.', 'validation:ip'=>':attribute deve essere un indirizzo IP valido.', 'validation:max:array'=>':attribute non può avere più di :max elementi.', 'validation:max:file'=>':attribute non può essere maggiore di :max kilobytes.', 'validation:max:numeric'=>':attribute non può essere maggiore di :max.', 'validation:max:string'=>':attribute non può essere maggiore di :max caratteri.', 'validation:mimes'=>':attribute deve essere un file di tipo: :values.', 'validation:min:array'=>':attribute deve avere almeno :min elementi.', 'validation:min:file'=>':attribute deve essere almeno :min kilobytes.', 'validation:min:numeric'=>':attribute deve essere almeno :min.', 'validation:min:string'=>':attribute deve essere almeno :min caratteri.', 'validation:not_in'=>'Il valore di :attribute non è valido.', 'validation:numeric'=>':attribute deve essere un numero.', 'validation:regex'=>'Il formato di :attribute non è valido.', 'validation:required'=>'Il campo :attribute è obbligatorio.', 'validation:required_if'=>'Il campo :attribute è obbligatorio quando :other è :value.', 'validation:required_with'=>'Il campo :attribute è obbligatorio quando :values è presente.', 'validation:required_without'=>'Il campo :attribute è obbligatorio quando :values non è presente.', 'validation:same'=>':attribute e :other devono corrispondere.', 'validation:size:array'=>':attribute deve contenere :size elementi.', 'validation:size:file'=>':attribute deve essere :size kilobytes.', 'validation:size:numeric'=>':attribute deve essere :size.', 'validation:size:string'=>':attribute deve essere :size caratteri.', 'validation:unique'=>':attribute è già presente.', 'validation:url'=>'Il formato di :attribute non è valido.', 'warnings:extension'=>'L\'estensione di PHP :name non è installata. Installa questa libreria ed attiva l\'estensione.', 'warnings:permissions'=>'La cartella :name o le sue sottocartelle non sono scrivibili da PHP. Imposta le corrette autorizzazioni per il server web su questa cartella.', 'warnings:tips'=>'Suggerimenti per la configurazione del sistema', 'warnings:tips_description'=>'Ci sono elementi a cui è necessario prestare attenzione al fine di configurare il sistema in maniera corretta.', 'widget:not_bound'=>'Nessun widget \':name\' è stato legato al controller', 'widget:not_registered'=>'Nessun widget \':name\' è stato registrato', 'zip:extract_failed'=>'Estrazione del file sistema \':file\' non riuscita.', ]);
{ "content_hash": "3d886c51253b27dbb505b45f14ee8c22", "timestamp": "", "source": "github", "line_count": 874, "max_line_length": 259, "avg_line_length": 57.06178489702517, "alnum_prop": 0.6966634584536413, "repo_name": "Dev-Lucid/lucid", "id": "385c6fb138973a2bb6db20eb02c71a71e9dafa7c", "size": "49979", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dictionaries/it.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "402" }, { "name": "JavaScript", "bytes": "13591" }, { "name": "PHP", "bytes": "1284808" }, { "name": "Shell", "bytes": "831" } ], "symlink_target": "" }
using Swagger.Codegen.Models; using System; using System.Linq; namespace Swagger.Codegen.Processors.CSharp { public static class CSharpExtensions { public static string NormalizeLineEndings(this string val) { if (string.IsNullOrEmpty(val)) { return null; } return val.Replace("\r\n", Environment.NewLine) .Replace("\n", Environment.NewLine); } public static string ToCSharpComment(this string comment, int? indent = null) { if (string.IsNullOrEmpty(comment)) { return null; } return "/// " + comment.NormalizeLineEndings() .Replace( Environment.NewLine, Environment.NewLine + string.Join("", Enumerable.Repeat(" ", indent.GetValueOrDefault())) + "/// "); } } }
{ "content_hash": "8af9af77d13d78a0d61d96f4f8cfd78a", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 140, "avg_line_length": 30, "alnum_prop": 0.501010101010101, "repo_name": "timschlechter/Swagger.Codegen.Net", "id": "df85ee0a7a9d0da027b7d9cf5a4e4ed943b700db", "size": "992", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Swagger.Codegen/Processors/CSharp/CSharpExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "177718" }, { "name": "JavaScript", "bytes": "8034" } ], "symlink_target": "" }
const express = require('express'); const router = express.Router(); router.get('/', function (req, res, next) { console.log('first'); console.log('second'); req.session = null; res.redirect('/'); }); module.exports = router;
{ "content_hash": "2d8be671236414e039525e788afb77bc", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 43, "avg_line_length": 21.454545454545453, "alnum_prop": 0.6440677966101694, "repo_name": "AustinMahan/galvanize-restaurants", "id": "4826aadf8234fbf856f900763061b46b2ed8f04f", "size": "236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/server/routes/logout.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2056" }, { "name": "HTML", "bytes": "29926" }, { "name": "JavaScript", "bytes": "58978" } ], "symlink_target": "" }
namespace NegroniGame.Handlers { using Microsoft.Xna.Framework; using NegroniGame.SystemFunctions; using System; public sealed class SceneryHandler { // Singleton ! private static SceneryHandler instance; private SceneryHandler() { this.ScreenRectangle = new Rectangle(0, 0, GameScreen.ScreenWidth, GameScreen.ScreenHeight); this.ToolbarRectangle = new Rectangle(0, GameScreen.ScreenHeight - 134, 700, 134); this.PlayerPicRectangle = new Rectangle(13, GameScreen.ScreenHeight - 72, 96, 72); this.MarketPosition = new Rectangle(GameScreen.ScreenWidth - 115, 5, 102, 54); //this.DropList = new List<Drop>(); //this.IndexForDeletion = new List<int>(); } public static SceneryHandler Instance { get { if (instance == null) { instance = new SceneryHandler(); } return instance; } } public Rectangle ScreenRectangle { get; private set; } public Rectangle ToolbarRectangle { get; private set; } public Rectangle PlayerPicRectangle { get; private set; } public Rectangle MarketPosition { get; private set; } public Well Well { get; private set; } //public List<Drop> DropList { get; private set; } //public List<int> IndexForDeletion { get; private set; } //public void AddDrop(Drop newDrop) //{ // this.DropList.Add(newDrop); //} //public void Update(GameTime gameTime) //{ // UpdateDrop(gameTime); //} //public void UpdateDrop(GameTime gameTime) //{ // for (int index = 0; index < this.DropList.Count; index++) // { // bool isTimeUp = false; // if (this.DropList[index] != null) // { // isTimeUp = this.DropList[index].Update(gameTime); // } // // deletes the drop if time is up // if (isTimeUp) // { // this.IndexForDeletion.Add(index); // } // } // // picks up drop // for (int index = 0; index < Scenery.Instance.DropList.Count; index++) // { // if (this.DropList[index] != null && Player.Instance.DestinationPosition.Intersects(Scenery.Instance.DropList[index].DropPosition)) // { // if (Scenery.Instance.DropList[index].Name == "Coins") // { // Player.Instance.Coins = new Items.Coins(Player.Instance.Coins.Amount + Scenery.Instance.DropList[index].Amount); // Toolbar.SystemMsg.Instance.AllMessages.Add(new Dictionary<string, Color>() { { String.Format(">> You picked up {0} {1}.", Scenery.Instance.DropList[index].Amount, Scenery.Instance.DropList[index].Name), Color.Beige } }); // this.IndexForDeletion.Add(index); // } // } // } // foreach (int index in IndexForDeletion) // { // this.DropList[index] = null; // } // this.IndexForDeletion = new List<int>(); //} public void Draw() { // backgroundTexture, toolbar, wellGraphic, playerPic, equipmentShopGraphic new Sprite(GameScreen.Instance.AllSceneryTextures[0], this.ScreenRectangle).DrawBox(); new Sprite(GameScreen.Instance.AllSceneryTextures[1], this.ToolbarRectangle).DrawBox(); Well.Instance.Draw(); new Sprite(GameScreen.Instance.AllSceneryTextures[3], this.PlayerPicRectangle).DrawBox(); new Sprite(GameScreen.Instance.AllSceneryTextures[4], this.MarketPosition).DrawBox(); //// drop //foreach (Drop drop in DropList) //{ // if (drop != null) // { // drop.Draw(); // } //} } } }
{ "content_hash": "65f501cb844453927833e222495d7d2b", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 246, "avg_line_length": 35.30508474576271, "alnum_prop": 0.527604416706673, "repo_name": "Galya-IT/negroni-rpg-xna", "id": "5e3127192382f27979094797a513aa7860c7743a", "size": "4168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/NegroniGame/NegroniGame/Handlers/SceneryHandler.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "172099" } ], "symlink_target": "" }
```shell # make image docker build -t ifs-approver . # run image docker run -it --rm -p 5000:80 \ -v $(pwd)/backend/ifsApprover:/ifs-backend/ifsApprover:ro \ -v $(pwd)/backend/static-frontend:/ifs-backend/static-frontend:ro \ -v $(pwd)/backend/cli:/ifs-backend/cli:ro \ -v $(pwd)/backend/cgi:/ifs-backend/cgi:ro \ -v $(pwd)/docker-support/config.py:/ifs-backend/config.py:ro \ -v $(pwd)/docker-support/database.db:/ifs-backend/database.db \ -v $(pwd)/docker-support/approved:/ifs-backend/approved \ ifs-approver /bin/bash ```
{ "content_hash": "4bc636eef29fbeb56523acf81119bc89", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 69, "avg_line_length": 36.266666666666666, "alnum_prop": 0.6838235294117647, "repo_name": "ktt-ol/ifs-approver", "id": "c909d21b0fee460e749dee71bd271269e5e45283", "size": "544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker-support/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1713" }, { "name": "HTML", "bytes": "6753" }, { "name": "JavaScript", "bytes": "21239" }, { "name": "Python", "bytes": "32136" } ], "symlink_target": "" }
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <net/arp.h> #include <linux/init.h> #include <linux/jiffies.h> #include <linux/leds.h> #include "arcdevice.h" #include "com9026.h" /* "do nothing" functions for protocol drivers */ static void null_rx(struct net_device *dev, int bufnum, struct archdr *pkthdr, int length); static int null_build_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, uint8_t daddr); static int null_prepare_tx(struct net_device *dev, struct archdr *pkt, int length, int bufnum); static void arcnet_rx(struct net_device *dev, int bufnum); /* one ArcProto per possible proto ID. None of the elements of * arc_proto_map are allowed to be NULL; they will get set to * arc_proto_default instead. It also must not be NULL; if you would like * to set it to NULL, set it to &arc_proto_null instead. */ struct ArcProto *arc_proto_map[256]; EXPORT_SYMBOL(arc_proto_map); struct ArcProto *arc_proto_default; EXPORT_SYMBOL(arc_proto_default); struct ArcProto *arc_bcast_proto; EXPORT_SYMBOL(arc_bcast_proto); struct ArcProto *arc_raw_proto; EXPORT_SYMBOL(arc_raw_proto); static struct ArcProto arc_proto_null = { .suffix = '?', .mtu = XMTU, .is_ip = 0, .rx = null_rx, .build_header = null_build_header, .prepare_tx = null_prepare_tx, .continue_tx = NULL, .ack_tx = NULL }; /* Exported function prototypes */ int arcnet_debug = ARCNET_DEBUG; EXPORT_SYMBOL(arcnet_debug); /* Internal function prototypes */ static int arcnet_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, const void *daddr, const void *saddr, unsigned len); static int go_tx(struct net_device *dev); static int debug = ARCNET_DEBUG; module_param(debug, int, 0); MODULE_LICENSE("GPL"); static int __init arcnet_init(void) { int count; arcnet_debug = debug; pr_info("arcnet loaded\n"); /* initialize the protocol map */ arc_raw_proto = arc_proto_default = arc_bcast_proto = &arc_proto_null; for (count = 0; count < 256; count++) arc_proto_map[count] = arc_proto_default; if (BUGLVL(D_DURING)) pr_info("struct sizes: %Zd %Zd %Zd %Zd %Zd\n", sizeof(struct arc_hardware), sizeof(struct arc_rfc1201), sizeof(struct arc_rfc1051), sizeof(struct arc_eth_encap), sizeof(struct archdr)); return 0; } static void __exit arcnet_exit(void) { } module_init(arcnet_init); module_exit(arcnet_exit); /* Dump the contents of an sk_buff */ #if ARCNET_DEBUG_MAX & D_SKB void arcnet_dump_skb(struct net_device *dev, struct sk_buff *skb, char *desc) { char hdr[32]; /* dump the packet */ snprintf(hdr, sizeof(hdr), "%6s:%s skb->data:", dev->name, desc); print_hex_dump(KERN_DEBUG, hdr, DUMP_PREFIX_OFFSET, 16, 1, skb->data, skb->len, true); } EXPORT_SYMBOL(arcnet_dump_skb); #endif /* Dump the contents of an ARCnet buffer */ #if (ARCNET_DEBUG_MAX & (D_RX | D_TX)) static void arcnet_dump_packet(struct net_device *dev, int bufnum, char *desc, int take_arcnet_lock) { struct arcnet_local *lp = netdev_priv(dev); int i, length; unsigned long flags = 0; static uint8_t buf[512]; char hdr[32]; /* hw.copy_from_card expects IRQ context so take the IRQ lock * to keep it single threaded */ if (take_arcnet_lock) spin_lock_irqsave(&lp->lock, flags); lp->hw.copy_from_card(dev, bufnum, 0, buf, 512); if (take_arcnet_lock) spin_unlock_irqrestore(&lp->lock, flags); /* if the offset[0] byte is nonzero, this is a 256-byte packet */ length = (buf[2] ? 256 : 512); /* dump the packet */ snprintf(hdr, sizeof(hdr), "%6s:%s packet dump:", dev->name, desc); print_hex_dump(KERN_DEBUG, hdr, DUMP_PREFIX_OFFSET, 16, 1, buf, length, true); } #else #define arcnet_dump_packet(dev, bufnum, desc, take_arcnet_lock) do { } while (0) #endif /* Trigger a LED event in response to a ARCNET device event */ void arcnet_led_event(struct net_device *dev, enum arcnet_led_event event) { struct arcnet_local *lp = netdev_priv(dev); unsigned long led_delay = 350; unsigned long tx_delay = 50; switch (event) { case ARCNET_LED_EVENT_RECON: led_trigger_blink_oneshot(lp->recon_led_trig, &led_delay, &led_delay, 0); break; case ARCNET_LED_EVENT_OPEN: led_trigger_event(lp->tx_led_trig, LED_OFF); led_trigger_event(lp->recon_led_trig, LED_OFF); break; case ARCNET_LED_EVENT_STOP: led_trigger_event(lp->tx_led_trig, LED_OFF); led_trigger_event(lp->recon_led_trig, LED_OFF); break; case ARCNET_LED_EVENT_TX: led_trigger_blink_oneshot(lp->tx_led_trig, &tx_delay, &tx_delay, 0); break; } } EXPORT_SYMBOL_GPL(arcnet_led_event); static void arcnet_led_release(struct device *gendev, void *res) { struct arcnet_local *lp = netdev_priv(to_net_dev(gendev)); led_trigger_unregister_simple(lp->tx_led_trig); led_trigger_unregister_simple(lp->recon_led_trig); } /* Register ARCNET LED triggers for a arcnet device * * This is normally called from a driver's probe function */ void devm_arcnet_led_init(struct net_device *netdev, int index, int subid) { struct arcnet_local *lp = netdev_priv(netdev); void *res; res = devres_alloc(arcnet_led_release, 0, GFP_KERNEL); if (!res) { netdev_err(netdev, "cannot register LED triggers\n"); return; } snprintf(lp->tx_led_trig_name, sizeof(lp->tx_led_trig_name), "arc%d-%d-tx", index, subid); snprintf(lp->recon_led_trig_name, sizeof(lp->recon_led_trig_name), "arc%d-%d-recon", index, subid); led_trigger_register_simple(lp->tx_led_trig_name, &lp->tx_led_trig); led_trigger_register_simple(lp->recon_led_trig_name, &lp->recon_led_trig); devres_add(&netdev->dev, res); } EXPORT_SYMBOL_GPL(devm_arcnet_led_init); /* Unregister a protocol driver from the arc_proto_map. Protocol drivers * are responsible for registering themselves, but the unregister routine * is pretty generic so we'll do it here. */ void arcnet_unregister_proto(struct ArcProto *proto) { int count; if (arc_proto_default == proto) arc_proto_default = &arc_proto_null; if (arc_bcast_proto == proto) arc_bcast_proto = arc_proto_default; if (arc_raw_proto == proto) arc_raw_proto = arc_proto_default; for (count = 0; count < 256; count++) { if (arc_proto_map[count] == proto) arc_proto_map[count] = arc_proto_default; } } EXPORT_SYMBOL(arcnet_unregister_proto); /* Add a buffer to the queue. Only the interrupt handler is allowed to do * this, unless interrupts are disabled. * * Note: we don't check for a full queue, since there aren't enough buffers * to more than fill it. */ static void release_arcbuf(struct net_device *dev, int bufnum) { struct arcnet_local *lp = netdev_priv(dev); int i; lp->buf_queue[lp->first_free_buf++] = bufnum; lp->first_free_buf %= 5; if (BUGLVL(D_DURING)) { arc_printk(D_DURING, dev, "release_arcbuf: freed #%d; buffer queue is now: ", bufnum); for (i = lp->next_buf; i != lp->first_free_buf; i = (i + 1) % 5) arc_cont(D_DURING, "#%d ", lp->buf_queue[i]); arc_cont(D_DURING, "\n"); } } /* Get a buffer from the queue. * If this returns -1, there are no buffers available. */ static int get_arcbuf(struct net_device *dev) { struct arcnet_local *lp = netdev_priv(dev); int buf = -1, i; if (!atomic_dec_and_test(&lp->buf_lock)) { /* already in this function */ arc_printk(D_NORMAL, dev, "get_arcbuf: overlap (%d)!\n", lp->buf_lock.counter); } else { /* we can continue */ if (lp->next_buf >= 5) lp->next_buf -= 5; if (lp->next_buf == lp->first_free_buf) { arc_printk(D_NORMAL, dev, "get_arcbuf: BUG: no buffers are available??\n"); } else { buf = lp->buf_queue[lp->next_buf++]; lp->next_buf %= 5; } } if (BUGLVL(D_DURING)) { arc_printk(D_DURING, dev, "get_arcbuf: got #%d; buffer queue is now: ", buf); for (i = lp->next_buf; i != lp->first_free_buf; i = (i + 1) % 5) arc_cont(D_DURING, "#%d ", lp->buf_queue[i]); arc_cont(D_DURING, "\n"); } atomic_inc(&lp->buf_lock); return buf; } static int choose_mtu(void) { int count, mtu = 65535; /* choose the smallest MTU of all available encaps */ for (count = 0; count < 256; count++) { if (arc_proto_map[count] != &arc_proto_null && arc_proto_map[count]->mtu < mtu) { mtu = arc_proto_map[count]->mtu; } } return mtu == 65535 ? XMTU : mtu; } static const struct header_ops arcnet_header_ops = { .create = arcnet_header, }; static const struct net_device_ops arcnet_netdev_ops = { .ndo_open = arcnet_open, .ndo_stop = arcnet_close, .ndo_start_xmit = arcnet_send_packet, .ndo_tx_timeout = arcnet_timeout, }; /* Setup a struct device for ARCnet. */ static void arcdev_setup(struct net_device *dev) { dev->type = ARPHRD_ARCNET; dev->netdev_ops = &arcnet_netdev_ops; dev->header_ops = &arcnet_header_ops; dev->hard_header_len = sizeof(struct arc_hardware); dev->mtu = choose_mtu(); dev->addr_len = ARCNET_ALEN; dev->tx_queue_len = 100; dev->broadcast[0] = 0x00; /* for us, broadcasts are address 0 */ dev->watchdog_timeo = TX_TIMEOUT; /* New-style flags. */ dev->flags = IFF_BROADCAST; } static void arcnet_timer(unsigned long data) { struct net_device *dev = (struct net_device *)data; if (!netif_carrier_ok(dev)) { netif_carrier_on(dev); netdev_info(dev, "link up\n"); } } struct net_device *alloc_arcdev(const char *name) { struct net_device *dev; dev = alloc_netdev(sizeof(struct arcnet_local), name && *name ? name : "arc%d", NET_NAME_UNKNOWN, arcdev_setup); if (dev) { struct arcnet_local *lp = netdev_priv(dev); spin_lock_init(&lp->lock); init_timer(&lp->timer); lp->timer.data = (unsigned long) dev; lp->timer.function = arcnet_timer; } return dev; } EXPORT_SYMBOL(alloc_arcdev); /* Open/initialize the board. This is called sometime after booting when * the 'ifconfig' program is run. * * This routine should set everything up anew at each open, even registers * that "should" only need to be set once at boot, so that there is * non-reboot way to recover if something goes wrong. */ int arcnet_open(struct net_device *dev) { struct arcnet_local *lp = netdev_priv(dev); int count, newmtu, error; arc_printk(D_INIT, dev, "opened."); if (!try_module_get(lp->hw.owner)) return -ENODEV; if (BUGLVL(D_PROTO)) { arc_printk(D_PROTO, dev, "protocol map (default is '%c'): ", arc_proto_default->suffix); for (count = 0; count < 256; count++) arc_cont(D_PROTO, "%c", arc_proto_map[count]->suffix); arc_cont(D_PROTO, "\n"); } arc_printk(D_INIT, dev, "arcnet_open: resetting card.\n"); /* try to put the card in a defined state - if it fails the first * time, actually reset it. */ error = -ENODEV; if (lp->hw.reset(dev, 0) && lp->hw.reset(dev, 1)) goto out_module_put; newmtu = choose_mtu(); if (newmtu < dev->mtu) dev->mtu = newmtu; arc_printk(D_INIT, dev, "arcnet_open: mtu: %d.\n", dev->mtu); /* autodetect the encapsulation for each host. */ memset(lp->default_proto, 0, sizeof(lp->default_proto)); /* the broadcast address is special - use the 'bcast' protocol */ for (count = 0; count < 256; count++) { if (arc_proto_map[count] == arc_bcast_proto) { lp->default_proto[0] = count; break; } } /* initialize buffers */ atomic_set(&lp->buf_lock, 1); lp->next_buf = lp->first_free_buf = 0; release_arcbuf(dev, 0); release_arcbuf(dev, 1); release_arcbuf(dev, 2); release_arcbuf(dev, 3); lp->cur_tx = lp->next_tx = -1; lp->cur_rx = -1; lp->rfc1201.sequence = 1; /* bring up the hardware driver */ if (lp->hw.open) lp->hw.open(dev); if (dev->dev_addr[0] == 0) arc_printk(D_NORMAL, dev, "WARNING! Station address 00 is reserved for broadcasts!\n"); else if (dev->dev_addr[0] == 255) arc_printk(D_NORMAL, dev, "WARNING! Station address FF may confuse DOS networking programs!\n"); arc_printk(D_DEBUG, dev, "%s: %d: %s\n", __FILE__, __LINE__, __func__); if (lp->hw.status(dev) & RESETflag) { arc_printk(D_DEBUG, dev, "%s: %d: %s\n", __FILE__, __LINE__, __func__); lp->hw.command(dev, CFLAGScmd | RESETclear); } arc_printk(D_DEBUG, dev, "%s: %d: %s\n", __FILE__, __LINE__, __func__); /* make sure we're ready to receive IRQ's. */ lp->hw.intmask(dev, 0); udelay(1); /* give it time to set the mask before * we reset it again. (may not even be * necessary) */ arc_printk(D_DEBUG, dev, "%s: %d: %s\n", __FILE__, __LINE__, __func__); lp->intmask = NORXflag | RECONflag; lp->hw.intmask(dev, lp->intmask); arc_printk(D_DEBUG, dev, "%s: %d: %s\n", __FILE__, __LINE__, __func__); netif_carrier_off(dev); netif_start_queue(dev); mod_timer(&lp->timer, jiffies + msecs_to_jiffies(1000)); arcnet_led_event(dev, ARCNET_LED_EVENT_OPEN); return 0; out_module_put: module_put(lp->hw.owner); return error; } EXPORT_SYMBOL(arcnet_open); /* The inverse routine to arcnet_open - shuts down the card. */ int arcnet_close(struct net_device *dev) { struct arcnet_local *lp = netdev_priv(dev); arcnet_led_event(dev, ARCNET_LED_EVENT_STOP); del_timer_sync(&lp->timer); netif_stop_queue(dev); netif_carrier_off(dev); /* flush TX and disable RX */ lp->hw.intmask(dev, 0); lp->hw.command(dev, NOTXcmd); /* stop transmit */ lp->hw.command(dev, NORXcmd); /* disable receive */ mdelay(1); /* shut down the card */ lp->hw.close(dev); module_put(lp->hw.owner); return 0; } EXPORT_SYMBOL(arcnet_close); static int arcnet_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, const void *daddr, const void *saddr, unsigned len) { const struct arcnet_local *lp = netdev_priv(dev); uint8_t _daddr, proto_num; struct ArcProto *proto; arc_printk(D_DURING, dev, "create header from %d to %d; protocol %d (%Xh); size %u.\n", saddr ? *(uint8_t *)saddr : -1, daddr ? *(uint8_t *)daddr : -1, type, type, len); if (skb->len != 0 && len != skb->len) arc_printk(D_NORMAL, dev, "arcnet_header: Yikes! skb->len(%d) != len(%d)!\n", skb->len, len); /* Type is host order - ? */ if (type == ETH_P_ARCNET) { proto = arc_raw_proto; arc_printk(D_DEBUG, dev, "arc_raw_proto used. proto='%c'\n", proto->suffix); _daddr = daddr ? *(uint8_t *)daddr : 0; } else if (!daddr) { /* if the dest addr isn't provided, we can't choose an * encapsulation! Store the packet type (eg. ETH_P_IP) * for now, and we'll push on a real header when we do * rebuild_header. */ *(uint16_t *)skb_push(skb, 2) = type; /* XXX: Why not use skb->mac_len? */ if (skb->network_header - skb->mac_header != 2) arc_printk(D_NORMAL, dev, "arcnet_header: Yikes! diff (%u) is not 2!\n", skb->network_header - skb->mac_header); return -2; /* return error -- can't transmit yet! */ } else { /* otherwise, we can just add the header as usual. */ _daddr = *(uint8_t *)daddr; proto_num = lp->default_proto[_daddr]; proto = arc_proto_map[proto_num]; arc_printk(D_DURING, dev, "building header for %02Xh using protocol '%c'\n", proto_num, proto->suffix); if (proto == &arc_proto_null && arc_bcast_proto != proto) { arc_printk(D_DURING, dev, "actually, let's use '%c' instead.\n", arc_bcast_proto->suffix); proto = arc_bcast_proto; } } return proto->build_header(skb, dev, type, _daddr); } /* Called by the kernel in order to transmit a packet. */ netdev_tx_t arcnet_send_packet(struct sk_buff *skb, struct net_device *dev) { struct arcnet_local *lp = netdev_priv(dev); struct archdr *pkt; struct arc_rfc1201 *soft; struct ArcProto *proto; int txbuf; unsigned long flags; int retval; arc_printk(D_DURING, dev, "transmit requested (status=%Xh, txbufs=%d/%d, len=%d, protocol %x)\n", lp->hw.status(dev), lp->cur_tx, lp->next_tx, skb->len, skb->protocol); pkt = (struct archdr *)skb->data; soft = &pkt->soft.rfc1201; proto = arc_proto_map[soft->proto]; arc_printk(D_SKB_SIZE, dev, "skb: transmitting %d bytes to %02X\n", skb->len, pkt->hard.dest); if (BUGLVL(D_SKB)) arcnet_dump_skb(dev, skb, "tx"); /* fits in one packet? */ if (skb->len - ARC_HDR_SIZE > XMTU && !proto->continue_tx) { arc_printk(D_NORMAL, dev, "fixme: packet too large: compensating badly!\n"); dev_kfree_skb(skb); return NETDEV_TX_OK; /* don't try again */ } /* We're busy transmitting a packet... */ netif_stop_queue(dev); spin_lock_irqsave(&lp->lock, flags); lp->hw.intmask(dev, 0); if (lp->next_tx == -1) txbuf = get_arcbuf(dev); else txbuf = -1; if (txbuf != -1) { if (proto->prepare_tx(dev, pkt, skb->len, txbuf) && !proto->ack_tx) { /* done right away and we don't want to acknowledge * the package later - forget about it now */ dev->stats.tx_bytes += skb->len; dev_kfree_skb(skb); } else { /* do it the 'split' way */ lp->outgoing.proto = proto; lp->outgoing.skb = skb; lp->outgoing.pkt = pkt; if (proto->continue_tx && proto->continue_tx(dev, txbuf)) { arc_printk(D_NORMAL, dev, "bug! continue_tx finished the first time! (proto='%c')\n", proto->suffix); } } retval = NETDEV_TX_OK; lp->next_tx = txbuf; } else { retval = NETDEV_TX_BUSY; } arc_printk(D_DEBUG, dev, "%s: %d: %s, status: %x\n", __FILE__, __LINE__, __func__, lp->hw.status(dev)); /* make sure we didn't ignore a TX IRQ while we were in here */ lp->hw.intmask(dev, 0); arc_printk(D_DEBUG, dev, "%s: %d: %s\n", __FILE__, __LINE__, __func__); lp->intmask |= TXFREEflag | EXCNAKflag; lp->hw.intmask(dev, lp->intmask); arc_printk(D_DEBUG, dev, "%s: %d: %s, status: %x\n", __FILE__, __LINE__, __func__, lp->hw.status(dev)); arcnet_led_event(dev, ARCNET_LED_EVENT_TX); spin_unlock_irqrestore(&lp->lock, flags); return retval; /* no need to try again */ } EXPORT_SYMBOL(arcnet_send_packet); /* Actually start transmitting a packet that was loaded into a buffer * by prepare_tx. This should _only_ be called by the interrupt handler. */ static int go_tx(struct net_device *dev) { struct arcnet_local *lp = netdev_priv(dev); arc_printk(D_DURING, dev, "go_tx: status=%Xh, intmask=%Xh, next_tx=%d, cur_tx=%d\n", lp->hw.status(dev), lp->intmask, lp->next_tx, lp->cur_tx); if (lp->cur_tx != -1 || lp->next_tx == -1) return 0; if (BUGLVL(D_TX)) arcnet_dump_packet(dev, lp->next_tx, "go_tx", 0); lp->cur_tx = lp->next_tx; lp->next_tx = -1; /* start sending */ lp->hw.command(dev, TXcmd | (lp->cur_tx << 3)); dev->stats.tx_packets++; lp->lasttrans_dest = lp->lastload_dest; lp->lastload_dest = 0; lp->excnak_pending = 0; lp->intmask |= TXFREEflag | EXCNAKflag; return 1; } /* Called by the kernel when transmit times out */ void arcnet_timeout(struct net_device *dev) { unsigned long flags; struct arcnet_local *lp = netdev_priv(dev); int status = lp->hw.status(dev); char *msg; spin_lock_irqsave(&lp->lock, flags); if (status & TXFREEflag) { /* transmit _DID_ finish */ msg = " - missed IRQ?"; } else { msg = ""; dev->stats.tx_aborted_errors++; lp->timed_out = 1; lp->hw.command(dev, NOTXcmd | (lp->cur_tx << 3)); } dev->stats.tx_errors++; /* make sure we didn't miss a TX or a EXC NAK IRQ */ lp->hw.intmask(dev, 0); lp->intmask |= TXFREEflag | EXCNAKflag; lp->hw.intmask(dev, lp->intmask); spin_unlock_irqrestore(&lp->lock, flags); if (time_after(jiffies, lp->last_timeout + 10 * HZ)) { arc_printk(D_EXTRA, dev, "tx timed out%s (status=%Xh, intmask=%Xh, dest=%02Xh)\n", msg, status, lp->intmask, lp->lasttrans_dest); lp->last_timeout = jiffies; } if (lp->cur_tx == -1) netif_wake_queue(dev); } EXPORT_SYMBOL(arcnet_timeout); /* The typical workload of the driver: Handle the network interface * interrupts. Establish which device needs attention, and call the correct * chipset interrupt handler. */ irqreturn_t arcnet_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct arcnet_local *lp; int recbuf, status, diagstatus, didsomething, boguscount; int retval = IRQ_NONE; arc_printk(D_DURING, dev, "\n"); arc_printk(D_DURING, dev, "in arcnet_interrupt\n"); lp = netdev_priv(dev); BUG_ON(!lp); spin_lock(&lp->lock); /* RESET flag was enabled - if device is not running, we must * clear it right away (but nothing else). */ if (!netif_running(dev)) { if (lp->hw.status(dev) & RESETflag) lp->hw.command(dev, CFLAGScmd | RESETclear); lp->hw.intmask(dev, 0); spin_unlock(&lp->lock); return retval; } arc_printk(D_DURING, dev, "in arcnet_inthandler (status=%Xh, intmask=%Xh)\n", lp->hw.status(dev), lp->intmask); boguscount = 5; do { status = lp->hw.status(dev); diagstatus = (status >> 8) & 0xFF; arc_printk(D_DEBUG, dev, "%s: %d: %s: status=%x\n", __FILE__, __LINE__, __func__, status); didsomething = 0; /* RESET flag was enabled - card is resetting and if RX is * disabled, it's NOT because we just got a packet. * * The card is in an undefined state. * Clear it out and start over. */ if (status & RESETflag) { arc_printk(D_NORMAL, dev, "spurious reset (status=%Xh)\n", status); arcnet_close(dev); arcnet_open(dev); /* get out of the interrupt handler! */ break; } /* RX is inhibited - we must have received something. * Prepare to receive into the next buffer. * * We don't actually copy the received packet from the card * until after the transmit handler runs (and possibly * launches the next tx); this should improve latency slightly * if we get both types of interrupts at once. */ recbuf = -1; if (status & lp->intmask & NORXflag) { recbuf = lp->cur_rx; arc_printk(D_DURING, dev, "Buffer #%d: receive irq (status=%Xh)\n", recbuf, status); lp->cur_rx = get_arcbuf(dev); if (lp->cur_rx != -1) { arc_printk(D_DURING, dev, "enabling receive to buffer #%d\n", lp->cur_rx); lp->hw.command(dev, RXcmd | (lp->cur_rx << 3) | RXbcasts); } didsomething++; } if ((diagstatus & EXCNAKflag)) { arc_printk(D_DURING, dev, "EXCNAK IRQ (diagstat=%Xh)\n", diagstatus); lp->hw.command(dev, NOTXcmd); /* disable transmit */ lp->excnak_pending = 1; lp->hw.command(dev, EXCNAKclear); lp->intmask &= ~(EXCNAKflag); didsomething++; } /* a transmit finished, and we're interested in it. */ if ((status & lp->intmask & TXFREEflag) || lp->timed_out) { lp->intmask &= ~(TXFREEflag | EXCNAKflag); arc_printk(D_DURING, dev, "TX IRQ (stat=%Xh)\n", status); if (lp->cur_tx != -1 && !lp->timed_out) { if (!(status & TXACKflag)) { if (lp->lasttrans_dest != 0) { arc_printk(D_EXTRA, dev, "transmit was not acknowledged! (status=%Xh, dest=%02Xh)\n", status, lp->lasttrans_dest); dev->stats.tx_errors++; dev->stats.tx_carrier_errors++; } else { arc_printk(D_DURING, dev, "broadcast was not acknowledged; that's normal (status=%Xh, dest=%02Xh)\n", status, lp->lasttrans_dest); } } if (lp->outgoing.proto && lp->outgoing.proto->ack_tx) { int ackstatus; if (status & TXACKflag) ackstatus = 2; else if (lp->excnak_pending) ackstatus = 1; else ackstatus = 0; lp->outgoing.proto ->ack_tx(dev, ackstatus); } } if (lp->cur_tx != -1) release_arcbuf(dev, lp->cur_tx); lp->cur_tx = -1; lp->timed_out = 0; didsomething++; /* send another packet if there is one */ go_tx(dev); /* continue a split packet, if any */ if (lp->outgoing.proto && lp->outgoing.proto->continue_tx) { int txbuf = get_arcbuf(dev); if (txbuf != -1) { if (lp->outgoing.proto->continue_tx(dev, txbuf)) { /* that was the last segment */ dev->stats.tx_bytes += lp->outgoing.skb->len; if (!lp->outgoing.proto->ack_tx) { dev_kfree_skb_irq(lp->outgoing.skb); lp->outgoing.proto = NULL; } } lp->next_tx = txbuf; } } /* inform upper layers of idleness, if necessary */ if (lp->cur_tx == -1) netif_wake_queue(dev); } /* now process the received packet, if any */ if (recbuf != -1) { if (BUGLVL(D_RX)) arcnet_dump_packet(dev, recbuf, "rx irq", 0); arcnet_rx(dev, recbuf); release_arcbuf(dev, recbuf); didsomething++; } if (status & lp->intmask & RECONflag) { lp->hw.command(dev, CFLAGScmd | CONFIGclear); dev->stats.tx_carrier_errors++; arc_printk(D_RECON, dev, "Network reconfiguration detected (status=%Xh)\n", status); if (netif_carrier_ok(dev)) { netif_carrier_off(dev); netdev_info(dev, "link down\n"); } mod_timer(&lp->timer, jiffies + msecs_to_jiffies(1000)); arcnet_led_event(dev, ARCNET_LED_EVENT_RECON); /* MYRECON bit is at bit 7 of diagstatus */ if (diagstatus & 0x80) arc_printk(D_RECON, dev, "Put out that recon myself\n"); /* is the RECON info empty or old? */ if (!lp->first_recon || !lp->last_recon || time_after(jiffies, lp->last_recon + HZ * 10)) { if (lp->network_down) arc_printk(D_NORMAL, dev, "reconfiguration detected: cabling restored?\n"); lp->first_recon = lp->last_recon = jiffies; lp->num_recons = lp->network_down = 0; arc_printk(D_DURING, dev, "recon: clearing counters.\n"); } else { /* add to current RECON counter */ lp->last_recon = jiffies; lp->num_recons++; arc_printk(D_DURING, dev, "recon: counter=%d, time=%lds, net=%d\n", lp->num_recons, (lp->last_recon - lp->first_recon) / HZ, lp->network_down); /* if network is marked up; * and first_recon and last_recon are 60+ apart; * and the average no. of recons counted is * > RECON_THRESHOLD/min; * then print a warning message. */ if (!lp->network_down && (lp->last_recon - lp->first_recon) <= HZ * 60 && lp->num_recons >= RECON_THRESHOLD) { lp->network_down = 1; arc_printk(D_NORMAL, dev, "many reconfigurations detected: cabling problem?\n"); } else if (!lp->network_down && lp->last_recon - lp->first_recon > HZ * 60) { /* reset counters if we've gone for * over a minute. */ lp->first_recon = lp->last_recon; lp->num_recons = 1; } } } else if (lp->network_down && time_after(jiffies, lp->last_recon + HZ * 10)) { if (lp->network_down) arc_printk(D_NORMAL, dev, "cabling restored?\n"); lp->first_recon = lp->last_recon = 0; lp->num_recons = lp->network_down = 0; arc_printk(D_DURING, dev, "not recon: clearing counters anyway.\n"); netif_carrier_on(dev); } if (didsomething) retval |= IRQ_HANDLED; } while (--boguscount && didsomething); arc_printk(D_DURING, dev, "arcnet_interrupt complete (status=%Xh, count=%d)\n", lp->hw.status(dev), boguscount); arc_printk(D_DURING, dev, "\n"); lp->hw.intmask(dev, 0); udelay(1); lp->hw.intmask(dev, lp->intmask); spin_unlock(&lp->lock); return retval; } EXPORT_SYMBOL(arcnet_interrupt); /* This is a generic packet receiver that calls arcnet??_rx depending on the * protocol ID found. */ static void arcnet_rx(struct net_device *dev, int bufnum) { struct arcnet_local *lp = netdev_priv(dev); struct archdr pkt; struct arc_rfc1201 *soft; int length, ofs; soft = &pkt.soft.rfc1201; lp->hw.copy_from_card(dev, bufnum, 0, &pkt, ARC_HDR_SIZE); if (pkt.hard.offset[0]) { ofs = pkt.hard.offset[0]; length = 256 - ofs; } else { ofs = pkt.hard.offset[1]; length = 512 - ofs; } /* get the full header, if possible */ if (sizeof(pkt.soft) <= length) { lp->hw.copy_from_card(dev, bufnum, ofs, soft, sizeof(pkt.soft)); } else { memset(&pkt.soft, 0, sizeof(pkt.soft)); lp->hw.copy_from_card(dev, bufnum, ofs, soft, length); } arc_printk(D_DURING, dev, "Buffer #%d: received packet from %02Xh to %02Xh (%d+4 bytes)\n", bufnum, pkt.hard.source, pkt.hard.dest, length); dev->stats.rx_packets++; dev->stats.rx_bytes += length + ARC_HDR_SIZE; /* call the right receiver for the protocol */ if (arc_proto_map[soft->proto]->is_ip) { if (BUGLVL(D_PROTO)) { struct ArcProto *oldp = arc_proto_map[lp->default_proto[pkt.hard.source]], *newp = arc_proto_map[soft->proto]; if (oldp != newp) { arc_printk(D_PROTO, dev, "got protocol %02Xh; encap for host %02Xh is now '%c' (was '%c')\n", soft->proto, pkt.hard.source, newp->suffix, oldp->suffix); } } /* broadcasts will always be done with the last-used encap. */ lp->default_proto[0] = soft->proto; /* in striking contrast, the following isn't a hack. */ lp->default_proto[pkt.hard.source] = soft->proto; } /* call the protocol-specific receiver. */ arc_proto_map[soft->proto]->rx(dev, bufnum, &pkt, length); } static void null_rx(struct net_device *dev, int bufnum, struct archdr *pkthdr, int length) { arc_printk(D_PROTO, dev, "rx: don't know how to deal with proto %02Xh from host %02Xh.\n", pkthdr->soft.rfc1201.proto, pkthdr->hard.source); } static int null_build_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, uint8_t daddr) { struct arcnet_local *lp = netdev_priv(dev); arc_printk(D_PROTO, dev, "tx: can't build header for encap %02Xh; load a protocol driver.\n", lp->default_proto[daddr]); /* always fails */ return 0; } /* the "do nothing" prepare_tx function warns that there's nothing to do. */ static int null_prepare_tx(struct net_device *dev, struct archdr *pkt, int length, int bufnum) { struct arcnet_local *lp = netdev_priv(dev); struct arc_hardware newpkt; arc_printk(D_PROTO, dev, "tx: no encap for this host; load a protocol driver.\n"); /* send a packet to myself -- will never get received, of course */ newpkt.source = newpkt.dest = dev->dev_addr[0]; /* only one byte of actual data (and it's random) */ newpkt.offset[0] = 0xFF; lp->hw.copy_to_card(dev, bufnum, 0, &newpkt, ARC_HDR_SIZE); return 1; /* done */ }
{ "content_hash": "b7c20c44ed74f5e2b787d354e3c142c8", "timestamp": "", "source": "github", "line_count": 1064, "max_line_length": 99, "avg_line_length": 28.202067669172934, "alnum_prop": 0.634618588995901, "repo_name": "AlbandeCrevoisier/ldd-athens", "id": "6ea963e3b89a1ab1c78ccb4d63c99a16e1bfbe0b", "size": "31664", "binary": false, "copies": "440", "ref": "refs/heads/master", "path": "linux-socfpga/drivers/net/arcnet/arcnet.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "10184236" }, { "name": "Awk", "bytes": "40418" }, { "name": "Batchfile", "bytes": "81753" }, { "name": "C", "bytes": "566858455" }, { "name": "C++", "bytes": "21399133" }, { "name": "Clojure", "bytes": "971" }, { "name": "Cucumber", "bytes": "5998" }, { "name": "FORTRAN", "bytes": "11832" }, { "name": "GDB", "bytes": "18113" }, { "name": "Groff", "bytes": "2686457" }, { "name": "HTML", "bytes": "34688334" }, { "name": "Lex", "bytes": "56961" }, { "name": "Logos", "bytes": "133810" }, { "name": "M4", "bytes": "3325" }, { "name": "Makefile", "bytes": "1685015" }, { "name": "Objective-C", "bytes": "920162" }, { "name": "Perl", "bytes": "752477" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "533352" }, { "name": "Shell", "bytes": "468244" }, { "name": "SourcePawn", "bytes": "2711" }, { "name": "UnrealScript", "bytes": "12824" }, { "name": "XC", "bytes": "33970" }, { "name": "XS", "bytes": "34909" }, { "name": "Yacc", "bytes": "113516" } ], "symlink_target": "" }
using System; using System.Text; using System.Web; using System.Web.Http.Description; namespace TemplateWebApplication.Areas.HelpPage { public static class ApiDescriptionExtensions { /// <summary> /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" /// </summary> /// <param name="description">The <see cref="ApiDescription"/>.</param> /// <returns>The ID as a string.</returns> public static string GetFriendlyId(this ApiDescription description) { string path = description.RelativePath; string[] urlParts = path.Split('?'); string localPath = urlParts[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; queryKeyString = String.Join("_", queryKeys); } StringBuilder friendlyPath = new StringBuilder(); friendlyPath.AppendFormat("{0}-{1}", description.HttpMethod.Method, localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); if (queryKeyString != null) { friendlyPath.AppendFormat("_{0}", queryKeyString); } return friendlyPath.ToString(); } } }
{ "content_hash": "ef6a509d0f43dc3121550147f33ee625", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 144, "avg_line_length": 38.30769230769231, "alnum_prop": 0.5756358768406962, "repo_name": "razsilev/TelerikAcademy_Homework", "id": "387fc3c746550b4439953520d4d6f92954a5a142", "size": "1494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Web Services and Cloud/WebApiTemplateProject/TemplateWebApplication/Areas/HelpPage/ApiDescriptionExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "1604" }, { "name": "C#", "bytes": "2431431" }, { "name": "CSS", "bytes": "321817" }, { "name": "CoffeeScript", "bytes": "943" }, { "name": "HTML", "bytes": "530569" }, { "name": "JavaScript", "bytes": "1370708" }, { "name": "XSLT", "bytes": "3344" } ], "symlink_target": "" }
from datetime import datetime import logging from django.db import models from django.utils import text from django.utils.encoding import force_unicode, smart_unicode from django.contrib.contenttypes.models import ContentType from django.db.models.query import QuerySet from django.contrib.contenttypes import generic from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User, Group, AnonymousUser from tagging.fields import TagField from djpcms.utils import slugify from djpcms.uploads import uploader, storage_manager from djpcms.template import mark_safe from djpcms.contrib.flowrepo import markups from djpcms.contrib.flowrepo.managers import FlowManager, SlugManager, RepoManager from djpcms.contrib.flowrepo.managers import source_interactive from djpcms.contrib.flowrepo.utils import encrypt, decrypt, nicetimedelta logger = logging.getLogger('flowrepo') report_type = ( (1, 'blog'), (2, 'content'), (3, 'wiki'), (4, 'article') ) visibility_choices = ( (0, _('Hidden')), (1, _('Private')), # In draft, availoable to view only to authors (2, _('Authenticated')), # authenitaced users only (3, _('Public')), ) class FlowItemBase(models.Model): class Meta: abstract = True def flowitem(self): return FlowItem.objects.get_from_instance(self) def update_related(self, qs): item = self.flowitem() if item: item._update_related(qs) class FlowItem(FlowItemBase): '''A general pointer to models. Ultra Denormalised for efficiency. ''' content_type = models.ForeignKey(ContentType, editable = False) object_id = models.TextField(editable = False) object = generic.GenericForeignKey('content_type', 'object_id') authors = models.ManyToManyField(User, blank = True, null = True) groups = models.ManyToManyField(Group, blank = True, null = True) # "Standard" metadata each object provides. last_modified = models.DateTimeField(auto_now = True, editable = False) timestamp = models.DateTimeField() url = models.CharField(blank=True, max_length=1000) visibility = models.IntegerField(choices=visibility_choices, default=3) tags = TagField(max_length=2500, blank = True) allow_comments = models.BooleanField(_('allow comments'), default=False) # Metadata about where the object "came from" source = models.CharField(max_length=100, blank=True, editable = False) source_id = models.TextField(blank=True, editable = False) # Denormalized object for performance in search name = models.CharField(max_length = 255) description = models.TextField(blank=True) object_str = models.TextField(blank=True, editable = False) markup = models.CharField(max_length=3, choices=markups.choices(), default=markups.default(), blank=True) objects = FlowManager() class Meta: ordering = ['-timestamp'] unique_together = [("content_type", "object_id")] get_latest_by = 'timestamp' def __unicode__(self): return self.url or self.name or self.object_str def flowitem(self): return self def can_user_view(self, user = None): if user and user.is_authenticated(): if self.has_author(user): return True else: return self.visibility >= 2 else: return self.visibility >= 3 def relativestamp(self): ''' Get a human redable string representing the posting time Returns: A human readable string representing the posting time ''' return nicetimedelta(datetime.now(),self.timestamp) relativestamp = property(relativestamp, doc='Get a human readable string representing' 'the posting time') def has_author(self, user): return user in self.authors.all() def follow(self, item): re = FlowRelated.objects.filter(related = item) if not re: re = FlowRelated(item = self, related = item) re.save() else: re = re[0] return re def filter_for_model(self, model): ct = ContentType.objects.get_for_model(model) return self.filter(content_type = ct) def create_for_object(self, item, obj): ct = ContentType.objects.get_for_model(obj) m = self.model(content_type = ct, object_id = obj.pk, item = item) m.save() return m def save(self, force_insert=False, force_update=False, source = None, using=None): instance = self.object mkp = markups.get(self.markup) try: repr = instance.representation(mkp) except Exception, e: logger.error('Failed to render {0}. {1}'.format(instance,e)) repr = smart_unicode(instance) try: short_repr = instance.short_representation(mkp) except: short_repr = self.description self.object_str = repr self.name = getattr(instance,'name',self.name) self.description = short_repr self.url = getattr(instance,'url',self.url) timestamp = self.timestamp if not source: self.source = source_interactive else: self.source = source if not timestamp: timestamp = datetime.now() self.timestamp = timestamp super(FlowItem, self).save(force_insert, force_update) def niceauthors(self, sep = ', ', intro = 'by '): authors = self.authors.all() alist = [] for a in authors: fn = a.get_full_name() or a.username alist.append(fn) return '%s%s' % (intro,sep.join(alist)) def _update_related(self, qs): ''' qs must be an iterable ''' for obj in qs: FlowRelated.objects.create_for_object(self, obj) class CategoryType(FlowItemBase): name = models.CharField(unique = True, max_length = 255) def __unicode__(self): return self.name class SlugBase(FlowItemBase): ''' Provides for a name field and a unique slug field ''' name = models.CharField(_('title'),max_length=255) slug = models.SlugField(_('slug'), max_length=260, help_text= _('Unique code. Autogenerated if not provided'), blank = True, unique = True) objects = SlugManager() class Meta: abstract = True def __unicode__(self): return self.name def save(self, **kwargs): ''' In this case implicit is better than explicit. Django is changing in this function ''' model = self.__class__ slug = self.slug if not slug: slug = slugify(self.name) self.slug = model.objects.unique_slug(self.id, slug.lower()) super(SlugBase,self).save(**kwargs) def _tohtml(self, text, mkp): if not text: return u'' if mkp: handler = mkp.get('handler') text = handler(text) return mark_safe(text) class Category(SlugBase): type = models.ForeignKey(CategoryType) body = models.TextField(_('body'),blank=True) class Meta: verbose_name_plural = 'Categories' def tohtml(self): return self._tohtml(self.body) class Report(SlugBase): description = models.TextField(_('abstract'),blank=True) body = models.TextField(_('body'),blank=True) parent = models.ForeignKey('self', null = True, blank = True, related_name = 'children') objects = RepoManager() def get_absolute_url(self): return self.__class__.objects.object_url(self) url = property(get_absolute_url) def representation(self, mkp): return self._tohtml(self.body, mkp) def short_representation(self, mkp): return self._tohtml(self.description, mkp) class Bookmark(SlugBase): ''' A bookmark ''' url = models.URLField(max_length=1000) extended = models.TextField(blank=True) thumbnail = models.ImageField(upload_to = uploader('bookmark'), storage = storage_manager('bookmark'), blank=True) thumbnail_url = models.URLField(blank=True, verify_exists=False, max_length=1000) def representation(self): return self.extended class UploadBase(SlugBase): description = models.TextField(blank = True) elem_url = models.URLField(_('Remote URL'), blank = True, verify_exists=False, max_length=1000) class Meta: abstract = True def mimetype(self): elem = self.elem return 'pdf' def short_representation(self): return self._tohtml(self.description) def __get_absolute_url(self): if self.elem_url: return self.elem_url else: try: return self.elem.url except: return '' url = property(__get_absolute_url) class Image(UploadBase): elem = models.ImageField(_('image'), help_text = _('upload an image. If set remote url is ignored'), blank = True, upload_to = uploader('image'), storage = storage_manager('image')) class Gallery(SlugBase): class Meta: verbose_name_plural = 'Galleries' class GalleryImage(models.Model): image = models.ForeignKey(Image) gallery = models.ForeignKey(Gallery, related_name = 'images') order = models.IntegerField(default = 1) class Meta: ordering = ('order',) def __get_url(self): return self.image.url url = property(__get_url) class Attachment(UploadBase): elem = models.FileField(_('attachment'), help_text = _('upload an attachment. If set remote url is ignored'), blank = True, upload_to = uploader('attachment'), storage = storage_manager('attachment')) class Message(models.Model): """ A message, status update, or "tweet". """ message = models.TextField() url = models.URLField(blank = True) links = models.ManyToManyField('ContentLink',blank=True,null=True) def __unicode__(self): mkp = markups.get('crl') if mkp: handler = mkp.get('handler') try: return handler(smart_unicode(self.message)) except: return self.message else: return self.message class ContentLink(models.Model): url = models.URLField() identifier = models.CharField(max_length=128) def __unicode__(self): return self.identifier class FlowRelated(models.Model): """ Holds the relationship between a a FlowItem and other FlowItems """ item = models.ForeignKey(FlowItem, related_name='following') related = models.ForeignKey(FlowItem, related_name='followers') class Meta: unique_together = ('item','related') def __unicode__(self): return '%s -> %s' % (self.item,self.related) class WebAccount(models.Model): ''' This model can be used to store log-in information for a web-account. The log-in details such as username, password pin number etc... are encrypted and saved into the database as an encrypted string ''' user = models.ForeignKey(User) name = models.CharField(blank = False, max_length = 100) url = models.URLField(max_length=1000) e_data = models.TextField(blank = True, verbose_name = 'encrypted data') tags = TagField(max_length=2500) class Meta: unique_together = ('name','user') def __unicode__(self): return u'%s - %s' % (self.name, self.url) def encrypted_property(name): return property(get_value(name), set_value(name)) def __get_data(self): if self.e_data: return decrypt(self.e_data) else: return u'' def __set_data(self, value): if value: svalue = encrypt(value) else: svalue = u'' self.e_data = svalue data = property(__get_data,__set_data) FlowItem.objects.registerModel(Report,add = 'write') FlowItem.objects.registerModel(Bookmark) FlowItem.objects.registerModel(Message) FlowItem.objects.registerModel(Image, add = 'upload') FlowItem.objects.registerModel(Gallery, add = 'create') FlowItem.objects.registerModel(Attachment, add = 'upload') FlowItem.objects.registerModel(Category) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^tagging\.fields\.TagField"]) except: pass
{ "content_hash": "cfd99f7cce8b2ac3cd34c8a51ffb02c6", "timestamp": "", "source": "github", "line_count": 436, "max_line_length": 103, "avg_line_length": 32.93119266055046, "alnum_prop": 0.5493104889260343, "repo_name": "strogo/djpcms", "id": "8334a78cdf584cc330da4139e4356e814115571c", "size": "14358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "djpcms/contrib/flowrepo/models.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
.. _deploy_nativescript_app: ======================= Deploy NativeScript App ======================= .. note:: The Windows or Debian setup NativeScript must be followed before following this guide. This section describes how to deploy a NativeScript App. Peek is deployed into python virtual environments, a new virtual environment is created for every deployment. To package your own NativeScript App dependencies, see the following document :ref:`package_nativescript_app`. Windows ------- Open a PowerShell window. ---- Download the NativeScript App dependencies deploy script. This is the only step in this section that requires the internet. :: $file = "deploy_nativescript_app_win.ps1" $uri = "https://bitbucket.org/synerty/synerty-peek/raw/master/$file"; Invoke-WebRequest -Uri $uri -UseBasicParsing -OutFile $file; ---- Run the deploy NativeScript App dependencies script. The script will complete with a print out of the environment the NativeScript App dependencies were deployed. Ensure you update the **$ver** variable with the environment version you're deploying. Also update the **$dist** variable with the path to your release. The script will deploy to :file:`C:\\Users\\peek`. :: $ver = "#.#.#" $dist = "C:\Users\peek\Downloads\peek_dist_nativescript_app_win.zip" PowerShell.exe -ExecutionPolicy Bypass -File deploy_nativescript_app_win.ps1 $ver $dist ---- The NativeScript App dependencies are now deployed. Linux ----- **TODO** What Next? ---------- Refer back to the :ref:`how_to_use_peek_documentation` guide to see which document to follow next.
{ "content_hash": "0a15ca44ba704d5a182d02576ab94272", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 95, "avg_line_length": 25.734375, "alnum_prop": 0.7067395264116576, "repo_name": "Synerty/synerty-peek", "id": "f2a2accb737bd72d13fac5d89dc9c727b1416f74", "size": "1647", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/nativescript_app/deploy_nativescript/DeployNativescriptApp.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "797" }, { "name": "PowerShell", "bytes": "14113" }, { "name": "Python", "bytes": "1732" }, { "name": "Shell", "bytes": "35231" } ], "symlink_target": "" }
#include <string> #include <vector> #include <fmt/format.h> #include <lorina/aiger.hpp> #include <mockturtle/algorithms/cleanup.hpp> #include <mockturtle/algorithms/sim_resub.hpp> #include <mockturtle/io/aiger_reader.hpp> #include <mockturtle/networks/aig.hpp> #include <experiments.hpp> int main() { using namespace experiments; using namespace mockturtle; experiment<std::string, uint32_t, uint32_t, float, bool> exp( "sim_resubstitution", "benchmark", "size", "gain", "runtime", "equivalent" ); for ( auto const& benchmark : epfl_benchmarks() ) { fmt::print( "[i] processing {}\n", benchmark ); aig_network aig; if ( lorina::read_aiger( benchmark_path( benchmark ), aiger_reader( aig ) ) != lorina::return_code::success ) { continue; } resubstitution_params ps; resubstitution_stats st; // ps.pattern_filename = "1024sa1/" + benchmark + ".pat"; ps.max_inserts = 1; const uint32_t size_before = aig.num_gates(); sim_resubstitution( aig, ps, &st ); aig = cleanup_dangling( aig ); const auto cec = benchmark == "hyp" ? true : abc_cec( aig, benchmark ); exp( benchmark, size_before, size_before - aig.num_gates(), to_seconds( st.time_total ), cec ); } exp.save(); exp.table(); return 0; }
{ "content_hash": "dffa06c3b975d7fb66f4f98d0abc56d5", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 141, "avg_line_length": 25.62, "alnum_prop": 0.6565183450429352, "repo_name": "lsils/mockturtle", "id": "78bf4ee99ec7f59b532bf47c1b1d5543022c354b", "size": "2442", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "experiments/sim_resubstitution.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2799495" }, { "name": "C++", "bytes": "10178870" }, { "name": "CMake", "bytes": "9254" }, { "name": "CodeQL", "bytes": "688" }, { "name": "Dockerfile", "bytes": "363" }, { "name": "M4", "bytes": "13258" }, { "name": "Makefile", "bytes": "20916" }, { "name": "Python", "bytes": "8004" }, { "name": "Shell", "bytes": "3144" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ccbc6ab6763c3f5d1c9d66869b1e7432", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "f38675a9f8f77dd911322a2ccad39c658a932d1e", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Theaceae/Balthasaria/Balthasaria schliebenii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import * as React from 'react'; import Table from '@mui/material/Table'; import TableCell from '@mui/material/TableCell'; import { createTheme } from '@mui/material/styles'; declare module '@mui/material/Table' { interface TablePropsSizeOverrides { large: true; } } declare module '@mui/material/TableCell' { interface TableCellPropsSizeOverrides { large: true; } interface TableCellPropsVariantOverrides { tableBody: true; } } // theme typings should work as expected const theme = createTheme({ components: { MuiTableCell: { styleOverrides: { root: ({ ownerState }) => ({ ...(ownerState.size === 'large' && { paddingBlock: '1rem', }), }), }, variants: [ { props: { variant: 'tableBody' }, style: { fontSize: '1.2em', color: '#C1D3FF', }, }, ], }, }, }); <Table size="large"> <TableCell size="large" /> </Table>; <Table size="large"> <TableCell variant="tableBody">Foo</TableCell>; </Table>; <Table size="large"> {/* @ts-expect-error unknown variant */} <TableCell variant="tableHeading">Bar</TableCell>; </Table>;
{ "content_hash": "6cfda817107d74a9f9bdf8c45d5863e8", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 52, "avg_line_length": 21.571428571428573, "alnum_prop": 0.5827814569536424, "repo_name": "mui-org/material-ui", "id": "8b4c52e2f1ef754d192d08fd6a18a34ea68b894c", "size": "1208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/mui-material/test/typescript/moduleAugmentation/tableCellCustomProps.spec.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2126" }, { "name": "JavaScript", "bytes": "4120512" }, { "name": "TypeScript", "bytes": "3263233" } ], "symlink_target": "" }
package checks import ( "fmt" "github.com/CiscoCloud/distributive/chkutil" "github.com/CiscoCloud/distributive/errutil" "github.com/CiscoCloud/distributive/fsstatus" "github.com/CiscoCloud/distributive/memstatus" log "github.com/Sirupsen/logrus" "io/ioutil" "os" "strconv" "strings" "syscall" "time" ) /* #### MemoryUsage Description: Is system memory usage below this threshold? Parameters: - Percent (int8 percentage): Maximum acceptable percentage memory used Example parameters: - 95%, 90%, 87% */ // TODO use a uint type MemoryUsage struct{ maxPercentUsed uint8 } func init() { chkutil.Register("MemoryUsage", func() chkutil.Check { return &MemoryUsage{} }) chkutil.Register("SwapUsage", func() chkutil.Check { return &SwapUsage{} }) chkutil.Register("FreeMemory", func() chkutil.Check { return &FreeMemory{} }) chkutil.Register("FreeSwap", func() chkutil.Check { return &FreeSwap{} }) chkutil.Register("CPUUsage", func() chkutil.Check { return &CPUUsage{} }) chkutil.Register("DiskUsage", func() chkutil.Check { return &DiskUsage{} }) chkutil.Register("InodeUsage", func() chkutil.Check { return &InodeUsage{} }) } func (chk MemoryUsage) New(params []string) (chkutil.Check, error) { if len(params) != 1 { return chk, errutil.ParameterLengthError{1, params} } per, err := strconv.ParseInt(strings.Replace(params[0], "%", "", -1), 10, 8) if strings.HasPrefix(params[0], "-") || err != nil { return chk, errutil.ParameterTypeError{params[0], "uint8"} } chk.maxPercentUsed = uint8(per) return chk, nil } func (chk MemoryUsage) Status() (int, string, error) { actualPercentUsed, err := memstatus.FreeMemory("percent") if err != nil { return 1, "", err } if actualPercentUsed < int(chk.maxPercentUsed) { return errutil.Success() } msg := "Memory usage above defined maximum" slc := []string{fmt.Sprint(actualPercentUsed)} return errutil.GenericError(msg, fmt.Sprint(chk.maxPercentUsed), slc) } /* #### SwapUsage Description: Like MemoryUsage, but with swap */ // TODO use a uint type SwapUsage struct{ maxPercentUsed int8 } func (chk SwapUsage) ID() string { return "SwapUsage" } func (chk SwapUsage) New(params []string) (chkutil.Check, error) { if len(params) != 1 { return chk, errutil.ParameterLengthError{1, params} } per, err := strconv.ParseInt(strings.Replace(params[0], "%", "", -1), 10, 8) if err != nil { return chk, errutil.ParameterTypeError{params[0], "positive int8"} } if per < 0 { return chk, errutil.ParameterTypeError{params[0], "positive int8"} } chk.maxPercentUsed = int8(per) return chk, nil } func (chk SwapUsage) Status() (int, string, error) { actualPercentUsed, err := memstatus.UsedSwap("percent") if err != nil { return 1, "", err } if actualPercentUsed < int(chk.maxPercentUsed) { return errutil.Success() } msg := "Swap usage above defined maximum" slc := []string{fmt.Sprint(actualPercentUsed)} return errutil.GenericError(msg, fmt.Sprint(chk.maxPercentUsed), slc) } // freeMemOrSwap is an abstraction of FreeMemory and FreeSwap, which measures // if the desired resource has a quantity free above the amount specified func freeMemOrSwap(input string, swapOrMem string) (int, string, error) { amount, units, err := chkutil.SeparateByteUnits(input) if err != nil { log.WithFields(log.Fields{ "err": err.Error(), }).Fatal("Couldn't separate string into a scalar and units") } var actualAmount int switch strings.ToLower(swapOrMem) { case "memory": actualAmount, err = memstatus.FreeMemory(units) case "swap": actualAmount, err = memstatus.FreeSwap(units) default: log.Fatalf("Invalid option passed to freeMemoOrSwap: %s", swapOrMem) } if err != nil { return 1, "", err } else if actualAmount > amount { return errutil.Success() } msg := "Free " + swapOrMem + " lower than defined threshold" actualString := fmt.Sprint(actualAmount) + units return errutil.GenericError(msg, input, []string{actualString}) } /* #### FreeMemory Description: Is at least this amount of memory free? Parameters: - Amount (string with byte unit): minimum acceptable amount of free memory Example parameters: - 100mb, 1gb, 3TB, 20kib */ type FreeMemory struct{ amount string } func (chk FreeMemory) New(params []string) (chkutil.Check, error) { if len(params) != 1 { return chk, errutil.ParameterLengthError{1, params} } _, _, err := chkutil.SeparateByteUnits(params[0]) if err != nil { return chk, errutil.ParameterTypeError{params[0], "amount"} } chk.amount = params[0] return chk, nil } func (chk FreeMemory) Status() (int, string, error) { return freeMemOrSwap(chk.amount, "memory") } /* #### FreeSwap Description: Like FreeMemory, but with swap instead. */ type FreeSwap struct{ amount string } func (chk FreeSwap) New(params []string) (chkutil.Check, error) { if len(params) != 1 { return chk, errutil.ParameterLengthError{1, params} } _, _, err := chkutil.SeparateByteUnits(params[0]) if err != nil { return chk, errutil.ParameterTypeError{params[0], "amount"} } chk.amount = params[0] return chk, nil } func (chk FreeSwap) Status() (int, string, error) { return freeMemOrSwap(chk.amount, "swap") } // getCPUSample helps CPUUsage do its thing. Taken from a stackoverflow: // http://stackoverflow.com/questions/11356330/getting-cpu-usage-with-golang func getCPUSample() (idle, total uint64) { contents, err := ioutil.ReadFile("/proc/stat") if err != nil { return } lines := strings.Split(string(contents), "\n") for _, line := range lines { fields := strings.Fields(line) if fields[0] == "cpu" { numFields := len(fields) for i := 1; i < numFields; i++ { val, err := strconv.ParseUint(fields[i], 10, 64) if err != nil { fmt.Println("Error: ", i, fields[i], err) } total += val // tally up all the numbers to get total ticks if i == 4 { // idle is the 5th field in the cpu line idle = val } } return } } return } /* #### CPUUsage Description: Is the cpu usage below this percentage in a 3 second interval? Parameters: - Percent (int8 percentage): Maximum acceptable percentage used Example parameters: - 95%, 90%, 87% */ // TODO use a uint type CPUUsage struct{ maxPercentUsed int8 } func (chk CPUUsage) New(params []string) (chkutil.Check, error) { if len(params) != 1 { return chk, errutil.ParameterLengthError{1, params} } per, err := strconv.ParseInt(strings.Replace(params[0], "%", "", -1), 10, 8) if err != nil { return chk, errutil.ParameterTypeError{params[0], "int8"} } chk.maxPercentUsed = int8(per) return chk, nil } func (chk CPUUsage) Status() (int, string, error) { // TODO check that parameters are in range 0 < x < 100 cpuPercentUsed := func(sampleTime time.Duration) float32 { idle0, total0 := getCPUSample() time.Sleep(sampleTime) idle1, total1 := getCPUSample() idleTicks := float32(idle1 - idle0) totalTicks := float32(total1 - total0) return (100 * (totalTicks - idleTicks) / totalTicks) } actualPercentUsed := cpuPercentUsed(3 * time.Second) if actualPercentUsed < float32(chk.maxPercentUsed) { return errutil.Success() } msg := "CPU usage above defined maximum" slc := []string{fmt.Sprint(actualPercentUsed)} return errutil.GenericError(msg, fmt.Sprint(chk.maxPercentUsed), slc) } /* #### DiskUsage Description: Is the disk usage below this percentage? Parameters: - Path (filepath): Path to the disk - Percent (int8 percentage): Maximum acceptable percentage used Example parameters: - /dev/sda1, /mnt/my-disk/ - 95%, 90%, 87% */ // TODO use a uint type DiskUsage struct { path string maxPercentUsed int8 } func (chk DiskUsage) New(params []string) (chkutil.Check, error) { if len(params) != 2 { return chk, errutil.ParameterLengthError{2, params} } else if _, err := os.Stat(params[0]); err != nil { return chk, errutil.ParameterTypeError{params[0], "dir"} } per, err := strconv.ParseInt(strings.Replace(params[1], "%", "", -1), 10, 8) if err != nil { return chk, errutil.ParameterTypeError{params[1], "int8"} } chk.path = params[0] chk.maxPercentUsed = int8(per) return chk, nil } func (chk DiskUsage) Status() (int, string, error) { // TODO: migrate to fsstatus // percentFSUsed gets the percent of the filesystem that is occupied percentFSUsed := func(path string) int { // get FS info (*nix systems only!) var stat syscall.Statfs_t syscall.Statfs(path, &stat) // blocks * size of block = available size totalBytes := stat.Blocks * uint64(stat.Bsize) availableBytes := stat.Bavail * uint64(stat.Bsize) usedBytes := totalBytes - availableBytes percentUsed := int((float64(usedBytes) / float64(totalBytes)) * 100) return percentUsed } actualPercentUsed := percentFSUsed(chk.path) if actualPercentUsed < int(chk.maxPercentUsed) { return errutil.Success() } msg := "More disk space used than expected" slc := []string{fmt.Sprint(actualPercentUsed) + "%"} return errutil.GenericError(msg, fmt.Sprint(chk.maxPercentUsed)+"%", slc) } /* #### InodeUsage Description: Is the inode usage below this percentage? Parameters: - Filesystem (string): Filesystem as shown by `df -i` - Percent (int8 percentage): Maximum acceptable percentage used Example parameters: - /dev/sda1, /mnt/my-disk/, tmpfs - 95%, 90%, 87% */ type InodeUsage struct { filesystem string maxPercentUsed uint8 } func (chk InodeUsage) New(params []string) (chkutil.Check, error) { if len(params) != 2 { return chk, errutil.ParameterLengthError{2, params} } per, err := strconv.ParseUint(strings.Replace(params[1], "%", "", -1), 10, 8) if err != nil { return chk, errutil.ParameterTypeError{params[1], "int8"} } chk.filesystem = params[0] chk.maxPercentUsed = uint8(per) return chk, nil } func (chk InodeUsage) Status() (int, string, error) { actualPercentUsed, err := fsstatus.PercentInodesUsed(chk.filesystem) if err != nil { return 1, "Unexpected error", err } if actualPercentUsed < chk.maxPercentUsed { return errutil.Success() } msg := "More disk space used than expected" slc := []string{fmt.Sprint(actualPercentUsed) + "%"} return errutil.GenericError(msg, fmt.Sprint(chk.maxPercentUsed)+"%", slc) }
{ "content_hash": "3066f1f162beea087f5a89448af92c61", "timestamp": "", "source": "github", "line_count": 363, "max_line_length": 78, "avg_line_length": 28.236914600550964, "alnum_prop": 0.6920975609756097, "repo_name": "CiscoCloud/distributive", "id": "809cc1504a2cfa50b4ac63a3b28617fc0b0636b7", "size": "10250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "checks/usage.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "212902" }, { "name": "Shell", "bytes": "1714" } ], "symlink_target": "" }
#import <React/RCTMultilineTextInputViewManager.h> #import <React/RCTMultilineTextInputView.h> @implementation RCTMultilineTextInputViewManager RCT_EXPORT_MODULE() - (UIView *)view { return [[RCTMultilineTextInputView alloc] initWithBridge:self.bridge]; } #pragma mark - Multiline <TextInput> (aka TextView) specific properties RCT_REMAP_VIEW_PROPERTY(dataDetectorTypes, backedTextInputView.dataDetectorTypes, UIDataDetectorTypes) @end
{ "content_hash": "caec147c7ddb80e009c882585897de74", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 102, "avg_line_length": 23.473684210526315, "alnum_prop": 0.8161434977578476, "repo_name": "arthuralee/react-native", "id": "7a661b183fa008b6f8f488a5d3f44cbb9f27c515", "size": "633", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "Libraries/Text/TextInput/Multiline/RCTMultilineTextInputViewManager.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "1167" }, { "name": "C", "bytes": "35996" }, { "name": "CSS", "bytes": "16240" }, { "name": "HTML", "bytes": "4755" }, { "name": "JavaScript", "bytes": "1220707" }, { "name": "Objective-C", "bytes": "939193" }, { "name": "Ruby", "bytes": "4321" }, { "name": "Shell", "bytes": "5721" } ], "symlink_target": "" }
#include "AndroidTimer.h" #include "../../Core/Helper.h" namespace LLGL { std::unique_ptr<Timer> Timer::Create() { return MakeUnique<AndroidTimer>(); } AndroidTimer::AndroidTimer() { } void AndroidTimer::Start() { } std::uint64_t AndroidTimer::Stop() { return 0; } std::uint64_t AndroidTimer::GetFrequency() const { return 0; } bool AndroidTimer::IsRunning() const { return false; } } // /namespace LLGL // ================================================================================
{ "content_hash": "33db2771298afeb04daacf6be6bad0cf", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 83, "avg_line_length": 11.818181818181818, "alnum_prop": 0.5480769230769231, "repo_name": "LukasBanana/LLGL", "id": "300da35ff0322f802569f92e930111ac409106e9", "size": "682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sources/Platform/Android/AndroidTimer.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "8260" }, { "name": "C", "bytes": "38472" }, { "name": "C++", "bytes": "3784633" }, { "name": "CMake", "bytes": "67632" }, { "name": "GLSL", "bytes": "1713" }, { "name": "HLSL", "bytes": "33344" }, { "name": "Metal", "bytes": "1427" }, { "name": "Objective-C", "bytes": "56921" }, { "name": "Objective-C++", "bytes": "254212" }, { "name": "Python", "bytes": "2100" }, { "name": "Shell", "bytes": "10843" }, { "name": "TeX", "bytes": "46822" } ], "symlink_target": "" }
#include "postgres.h" #include "access/hash.h" #include "catalog/pg_collation.h" #include "miscadmin.h" #include "utils/builtins.h" #include "utils/jsonb.h" #include "utils/memutils.h" /* * Maximum number of elements in an array (or key/value pairs in an object). * This is limited by two things: the size of the JEntry array must fit * in MaxAllocSize, and the number of elements (or pairs) must fit in the bits * reserved for that in the JsonbContainer.header field. * * (The total size of an array's or object's elements is also limited by * JENTRY_OFFLENMASK, but we're not concerned about that here.) */ #define JSONB_MAX_ELEMS (Min(MaxAllocSize / sizeof(JsonbValue), JB_CMASK)) #define JSONB_MAX_PAIRS (Min(MaxAllocSize / sizeof(JsonbPair), JB_CMASK)) static void fillJsonbValue(JsonbContainer *container, int index, char *base_addr, uint32 offset, JsonbValue *result); static bool equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b); static int compareJsonbScalarValue(JsonbValue *a, JsonbValue *b); static Jsonb *convertToJsonb(JsonbValue *val); static void convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level); static void convertJsonbArray(StringInfo buffer, JEntry *header, JsonbValue *val, int level); static void convertJsonbObject(StringInfo buffer, JEntry *header, JsonbValue *val, int level); static void convertJsonbScalar(StringInfo buffer, JEntry *header, JsonbValue *scalarVal); static int reserveFromBuffer(StringInfo buffer, int len); static void appendToBuffer(StringInfo buffer, const char *data, int len); static void copyToBuffer(StringInfo buffer, int offset, const char *data, int len); static short padBufferToInt(StringInfo buffer); static JsonbIterator *iteratorFromContainer(JsonbContainer *container, JsonbIterator *parent); static JsonbIterator *freeAndGetParent(JsonbIterator *it); static JsonbParseState *pushState(JsonbParseState **pstate); static void appendKey(JsonbParseState *pstate, JsonbValue *scalarVal); static void appendValue(JsonbParseState *pstate, JsonbValue *scalarVal); static void appendElement(JsonbParseState *pstate, JsonbValue *scalarVal); static int lengthCompareJsonbStringValue(const void *a, const void *b); static int lengthCompareJsonbPair(const void *a, const void *b, void *arg); static void uniqueifyJsonbObject(JsonbValue *object); static JsonbValue *pushJsonbValueScalar(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *scalarVal); /* * Turn an in-memory JsonbValue into a Jsonb for on-disk storage. * * There isn't a JsonbToJsonbValue(), because generally we find it more * convenient to directly iterate through the Jsonb representation and only * really convert nested scalar values. JsonbIteratorNext() does this, so that * clients of the iteration code don't have to directly deal with the binary * representation (JsonbDeepContains() is a notable exception, although all * exceptions are internal to this module). In general, functions that accept * a JsonbValue argument are concerned with the manipulation of scalar values, * or simple containers of scalar values, where it would be inconvenient to * deal with a great amount of other state. */ Jsonb * JsonbValueToJsonb(JsonbValue *val) { Jsonb *out; if (IsAJsonbScalar(val)) { /* Scalar value */ JsonbParseState *pstate = NULL; JsonbValue *res; JsonbValue scalarArray; scalarArray.type = jbvArray; scalarArray.val.array.rawScalar = true; scalarArray.val.array.nElems = 1; pushJsonbValue(&pstate, WJB_BEGIN_ARRAY, &scalarArray); pushJsonbValue(&pstate, WJB_ELEM, val); res = pushJsonbValue(&pstate, WJB_END_ARRAY, NULL); out = convertToJsonb(res); } else if (val->type == jbvObject || val->type == jbvArray) { out = convertToJsonb(val); } else { Assert(val->type == jbvBinary); out = palloc(VARHDRSZ + val->val.binary.len); SET_VARSIZE(out, VARHDRSZ + val->val.binary.len); memcpy(VARDATA(out), val->val.binary.data, val->val.binary.len); } return out; } /* * Get the offset of the variable-length portion of a Jsonb node within * the variable-length-data part of its container. The node is identified * by index within the container's JEntry array. */ uint32 getJsonbOffset(const JsonbContainer *jc, int index) { uint32 offset = 0; int i; /* * Start offset of this entry is equal to the end offset of the previous * entry. Walk backwards to the most recent entry stored as an end * offset, returning that offset plus any lengths in between. */ for (i = index - 1; i >= 0; i--) { offset += JBE_OFFLENFLD(jc->children[i]); if (JBE_HAS_OFF(jc->children[i])) break; } return offset; } /* * Get the length of the variable-length portion of a Jsonb node. * The node is identified by index within the container's JEntry array. */ uint32 getJsonbLength(const JsonbContainer *jc, int index) { uint32 off; uint32 len; /* * If the length is stored directly in the JEntry, just return it. * Otherwise, get the begin offset of the entry, and subtract that from * the stored end+1 offset. */ if (JBE_HAS_OFF(jc->children[index])) { off = getJsonbOffset(jc, index); len = JBE_OFFLENFLD(jc->children[index]) - off; } else len = JBE_OFFLENFLD(jc->children[index]); return len; } /* * BT comparator worker function. Returns an integer less than, equal to, or * greater than zero, indicating whether a is less than, equal to, or greater * than b. Consistent with the requirements for a B-Tree operator class * * Strings are compared lexically, in contrast with other places where we use a * much simpler comparator logic for searching through Strings. Since this is * called from B-Tree support function 1, we're careful about not leaking * memory here. */ int compareJsonbContainers(JsonbContainer *a, JsonbContainer *b) { JsonbIterator *ita, *itb; int res = 0; ita = JsonbIteratorInit(a); itb = JsonbIteratorInit(b); do { JsonbValue va, vb; JsonbIteratorToken ra, rb; ra = JsonbIteratorNext(&ita, &va, false); rb = JsonbIteratorNext(&itb, &vb, false); if (ra == rb) { if (ra == WJB_DONE) { /* Decisively equal */ break; } if (ra == WJB_END_ARRAY || ra == WJB_END_OBJECT) { /* * There is no array or object to compare at this stage of * processing. jbvArray/jbvObject values are compared * initially, at the WJB_BEGIN_ARRAY and WJB_BEGIN_OBJECT * tokens. */ continue; } if (va.type == vb.type) { switch (va.type) { case jbvString: case jbvNull: case jbvNumeric: case jbvBool: res = compareJsonbScalarValue(&va, &vb); break; case jbvArray: /* * This could be a "raw scalar" pseudo array. That's * a special case here though, since we still want the * general type-based comparisons to apply, and as far * as we're concerned a pseudo array is just a scalar. */ if (va.val.array.rawScalar != vb.val.array.rawScalar) res = (va.val.array.rawScalar) ? -1 : 1; if (va.val.array.nElems != vb.val.array.nElems) res = (va.val.array.nElems > vb.val.array.nElems) ? 1 : -1; break; case jbvObject: if (va.val.object.nPairs != vb.val.object.nPairs) res = (va.val.object.nPairs > vb.val.object.nPairs) ? 1 : -1; break; case jbvBinary: elog(ERROR, "unexpected jbvBinary value"); } } else { /* Type-defined order */ res = (va.type > vb.type) ? 1 : -1; } } else { /* * It's safe to assume that the types differed, and that the va * and vb values passed were set. * * If the two values were of the same container type, then there'd * have been a chance to observe the variation in the number of * elements/pairs (when processing WJB_BEGIN_OBJECT, say). They're * either two heterogeneously-typed containers, or a container and * some scalar type. * * We don't have to consider the WJB_END_ARRAY and WJB_END_OBJECT * cases here, because we would have seen the corresponding * WJB_BEGIN_ARRAY and WJB_BEGIN_OBJECT tokens first, and * concluded that they don't match. */ Assert(ra != WJB_END_ARRAY && ra != WJB_END_OBJECT); Assert(rb != WJB_END_ARRAY && rb != WJB_END_OBJECT); Assert(va.type != vb.type); Assert(va.type != jbvBinary); Assert(vb.type != jbvBinary); /* Type-defined order */ res = (va.type > vb.type) ? 1 : -1; } } while (res == 0); while (ita != NULL) { JsonbIterator *i = ita->parent; pfree(ita); ita = i; } while (itb != NULL) { JsonbIterator *i = itb->parent; pfree(itb); itb = i; } return res; } /* * Find value in object (i.e. the "value" part of some key/value pair in an * object), or find a matching element if we're looking through an array. Do * so on the basis of equality of the object keys only, or alternatively * element values only, with a caller-supplied value "key". The "flags" * argument allows the caller to specify which container types are of interest. * * This exported utility function exists to facilitate various cases concerned * with "containment". If asked to look through an object, the caller had * better pass a Jsonb String, because their keys can only be strings. * Otherwise, for an array, any type of JsonbValue will do. * * In order to proceed with the search, it is necessary for callers to have * both specified an interest in exactly one particular container type with an * appropriate flag, as well as having the pointed-to Jsonb container be of * one of those same container types at the top level. (Actually, we just do * whichever makes sense to save callers the trouble of figuring it out - at * most one can make sense, because the container either points to an array * (possibly a "raw scalar" pseudo array) or an object.) * * Note that we can return a jbvBinary JsonbValue if this is called on an * object, but we never do so on an array. If the caller asks to look through * a container type that is not of the type pointed to by the container, * immediately fall through and return NULL. If we cannot find the value, * return NULL. Otherwise, return palloc()'d copy of value. */ JsonbValue * findJsonbValueFromContainer(JsonbContainer *container, uint32 flags, JsonbValue *key) { JEntry *children = container->children; int count = (container->header & JB_CMASK); JsonbValue *result; Assert((flags & ~(JB_FARRAY | JB_FOBJECT)) == 0); /* Quick out without a palloc cycle if object/array is empty */ if (count <= 0) return NULL; result = palloc(sizeof(JsonbValue)); if (flags & JB_FARRAY & container->header) { char *base_addr = (char *) (children + count); uint32 offset = 0; int i; for (i = 0; i < count; i++) { fillJsonbValue(container, i, base_addr, offset, result); if (key->type == result->type) { if (equalsJsonbScalarValue(key, result)) return result; } JBE_ADVANCE_OFFSET(offset, children[i]); } } else if (flags & JB_FOBJECT & container->header) { /* Since this is an object, account for *Pairs* of Jentrys */ char *base_addr = (char *) (children + count * 2); uint32 stopLow = 0, stopHigh = count; /* Object key passed by caller must be a string */ Assert(key->type == jbvString); /* Binary search on object/pair keys *only* */ while (stopLow < stopHigh) { uint32 stopMiddle; int difference; JsonbValue candidate; stopMiddle = stopLow + (stopHigh - stopLow) / 2; candidate.type = jbvString; candidate.val.string.val = base_addr + getJsonbOffset(container, stopMiddle); candidate.val.string.len = getJsonbLength(container, stopMiddle); difference = lengthCompareJsonbStringValue(&candidate, key); if (difference == 0) { /* Found our key, return corresponding value */ int index = stopMiddle + count; fillJsonbValue(container, index, base_addr, getJsonbOffset(container, index), result); return result; } else { if (difference < 0) stopLow = stopMiddle + 1; else stopHigh = stopMiddle; } } } /* Not found */ pfree(result); return NULL; } /* * Get i-th value of a Jsonb array. * * Returns palloc()'d copy of the value, or NULL if it does not exist. */ JsonbValue * getIthJsonbValueFromContainer(JsonbContainer *container, uint32 i) { JsonbValue *result; char *base_addr; uint32 nelements; if ((container->header & JB_FARRAY) == 0) elog(ERROR, "not a jsonb array"); nelements = container->header & JB_CMASK; base_addr = (char *) &container->children[nelements]; if (i >= nelements) return NULL; result = palloc(sizeof(JsonbValue)); fillJsonbValue(container, i, base_addr, getJsonbOffset(container, i), result); return result; } /* * A helper function to fill in a JsonbValue to represent an element of an * array, or a key or value of an object. * * The node's JEntry is at container->children[index], and its variable-length * data is at base_addr + offset. We make the caller determine the offset * since in many cases the caller can amortize that work across multiple * children. When it can't, it can just call getJsonbOffset(). * * A nested array or object will be returned as jbvBinary, ie. it won't be * expanded. */ static void fillJsonbValue(JsonbContainer *container, int index, char *base_addr, uint32 offset, JsonbValue *result) { JEntry entry = container->children[index]; if (JBE_ISNULL(entry)) { result->type = jbvNull; } else if (JBE_ISSTRING(entry)) { result->type = jbvString; result->val.string.val = base_addr + offset; result->val.string.len = getJsonbLength(container, index); Assert(result->val.string.len >= 0); } else if (JBE_ISNUMERIC(entry)) { result->type = jbvNumeric; result->val.numeric = (Numeric) (base_addr + INTALIGN(offset)); } else if (JBE_ISBOOL_TRUE(entry)) { result->type = jbvBool; result->val.boolean = true; } else if (JBE_ISBOOL_FALSE(entry)) { result->type = jbvBool; result->val.boolean = false; } else { Assert(JBE_ISCONTAINER(entry)); result->type = jbvBinary; /* Remove alignment padding from data pointer and length */ result->val.binary.data = (JsonbContainer *) (base_addr + INTALIGN(offset)); result->val.binary.len = getJsonbLength(container, index) - (INTALIGN(offset) - offset); } } /* * Push JsonbValue into JsonbParseState. * * Used when parsing JSON tokens to form Jsonb, or when converting an in-memory * JsonbValue to a Jsonb. * * Initial state of *JsonbParseState is NULL, since it'll be allocated here * originally (caller will get JsonbParseState back by reference). * * Only sequential tokens pertaining to non-container types should pass a * JsonbValue. There is one exception -- WJB_BEGIN_ARRAY callers may pass a * "raw scalar" pseudo array to append it - the actual scalar should be passed * next and it will be added as the only member of the array. * * Values of type jvbBinary, which are rolled up arrays and objects, * are unpacked before being added to the result. */ JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval) { JsonbIterator *it; JsonbValue *res = NULL; JsonbValue v; JsonbIteratorToken tok; if (!jbval || (seq != WJB_ELEM && seq != WJB_VALUE) || jbval->type != jbvBinary) { /* drop through */ return pushJsonbValueScalar(pstate, seq, jbval); } /* unpack the binary and add each piece to the pstate */ it = JsonbIteratorInit(jbval->val.binary.data); while ((tok = JsonbIteratorNext(&it, &v, false)) != WJB_DONE) res = pushJsonbValueScalar(pstate, tok, tok < WJB_BEGIN_ARRAY ? &v : NULL); return res; } /* * Do the actual pushing, with only scalar or pseudo-scalar-array values * accepted. */ static JsonbValue * pushJsonbValueScalar(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *scalarVal) { JsonbValue *result = NULL; switch (seq) { case WJB_BEGIN_ARRAY: Assert(!scalarVal || scalarVal->val.array.rawScalar); *pstate = pushState(pstate); result = &(*pstate)->contVal; (*pstate)->contVal.type = jbvArray; (*pstate)->contVal.val.array.nElems = 0; (*pstate)->contVal.val.array.rawScalar = (scalarVal && scalarVal->val.array.rawScalar); if (scalarVal && scalarVal->val.array.nElems > 0) { /* Assume that this array is still really a scalar */ Assert(scalarVal->type == jbvArray); (*pstate)->size = scalarVal->val.array.nElems; } else { (*pstate)->size = 4; } (*pstate)->contVal.val.array.elems = palloc(sizeof(JsonbValue) * (*pstate)->size); break; case WJB_BEGIN_OBJECT: Assert(!scalarVal); *pstate = pushState(pstate); result = &(*pstate)->contVal; (*pstate)->contVal.type = jbvObject; (*pstate)->contVal.val.object.nPairs = 0; (*pstate)->size = 4; (*pstate)->contVal.val.object.pairs = palloc(sizeof(JsonbPair) * (*pstate)->size); break; case WJB_KEY: Assert(scalarVal->type == jbvString); appendKey(*pstate, scalarVal); break; case WJB_VALUE: Assert(IsAJsonbScalar(scalarVal)); appendValue(*pstate, scalarVal); break; case WJB_ELEM: Assert(IsAJsonbScalar(scalarVal)); appendElement(*pstate, scalarVal); break; case WJB_END_OBJECT: uniqueifyJsonbObject(&(*pstate)->contVal); /* fall through! */ case WJB_END_ARRAY: /* Steps here common to WJB_END_OBJECT case */ Assert(!scalarVal); result = &(*pstate)->contVal; /* * Pop stack and push current array/object as value in parent * array/object */ *pstate = (*pstate)->next; if (*pstate) { switch ((*pstate)->contVal.type) { case jbvArray: appendElement(*pstate, result); break; case jbvObject: appendValue(*pstate, result); break; default: elog(ERROR, "invalid jsonb container type"); } } break; default: elog(ERROR, "unrecognized jsonb sequential processing token"); } return result; } /* * pushJsonbValue() worker: Iteration-like forming of Jsonb */ static JsonbParseState * pushState(JsonbParseState **pstate) { JsonbParseState *ns = palloc(sizeof(JsonbParseState)); ns->next = *pstate; return ns; } /* * pushJsonbValue() worker: Append a pair key to state when generating a Jsonb */ static void appendKey(JsonbParseState *pstate, JsonbValue *string) { JsonbValue *object = &pstate->contVal; Assert(object->type == jbvObject); Assert(string->type == jbvString); if (object->val.object.nPairs >= JSONB_MAX_PAIRS) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("number of jsonb object pairs exceeds the maximum allowed (%zu)", JSONB_MAX_PAIRS))); if (object->val.object.nPairs >= pstate->size) { pstate->size *= 2; object->val.object.pairs = repalloc(object->val.object.pairs, sizeof(JsonbPair) * pstate->size); } object->val.object.pairs[object->val.object.nPairs].key = *string; object->val.object.pairs[object->val.object.nPairs].order = object->val.object.nPairs; } /* * pushJsonbValue() worker: Append a pair value to state when generating a * Jsonb */ static void appendValue(JsonbParseState *pstate, JsonbValue *scalarVal) { JsonbValue *object = &pstate->contVal; Assert(object->type == jbvObject); object->val.object.pairs[object->val.object.nPairs++].value = *scalarVal; } /* * pushJsonbValue() worker: Append an element to state when generating a Jsonb */ static void appendElement(JsonbParseState *pstate, JsonbValue *scalarVal) { JsonbValue *array = &pstate->contVal; Assert(array->type == jbvArray); if (array->val.array.nElems >= JSONB_MAX_ELEMS) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("number of jsonb array elements exceeds the maximum allowed (%zu)", JSONB_MAX_ELEMS))); if (array->val.array.nElems >= pstate->size) { pstate->size *= 2; array->val.array.elems = repalloc(array->val.array.elems, sizeof(JsonbValue) * pstate->size); } array->val.array.elems[array->val.array.nElems++] = *scalarVal; } /* * Given a JsonbContainer, expand to JsonbIterator to iterate over items * fully expanded to in-memory representation for manipulation. * * See JsonbIteratorNext() for notes on memory management. */ JsonbIterator * JsonbIteratorInit(JsonbContainer *container) { return iteratorFromContainer(container, NULL); } /* * Get next JsonbValue while iterating * * Caller should initially pass their own, original iterator. They may get * back a child iterator palloc()'d here instead. The function can be relied * on to free those child iterators, lest the memory allocated for highly * nested objects become unreasonable, but only if callers don't end iteration * early (by breaking upon having found something in a search, for example). * * Callers in such a scenario, that are particularly sensitive to leaking * memory in a long-lived context may walk the ancestral tree from the final * iterator we left them with to its oldest ancestor, pfree()ing as they go. * They do not have to free any other memory previously allocated for iterators * but not accessible as direct ancestors of the iterator they're last passed * back. * * Returns "Jsonb sequential processing" token value. Iterator "state" * reflects the current stage of the process in a less granular fashion, and is * mostly used here to track things internally with respect to particular * iterators. * * Clients of this function should not have to handle any jbvBinary values * (since recursive calls will deal with this), provided skipNested is false. * It is our job to expand the jbvBinary representation without bothering them * with it. However, clients should not take it upon themselves to touch array * or Object element/pair buffers, since their element/pair pointers are * garbage. Also, *val will not be set when returning WJB_END_ARRAY or * WJB_END_OBJECT, on the assumption that it's only useful to access values * when recursing in. */ JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested) { if (*it == NULL) return WJB_DONE; /* * When stepping into a nested container, we jump back here to start * processing the child. We will not recurse further in one call, because * processing the child will always begin in JBI_ARRAY_START or * JBI_OBJECT_START state. */ recurse: switch ((*it)->state) { case JBI_ARRAY_START: /* Set v to array on first array call */ val->type = jbvArray; val->val.array.nElems = (*it)->nElems; /* * v->val.array.elems is not actually set, because we aren't doing * a full conversion */ val->val.array.rawScalar = (*it)->isScalar; (*it)->curIndex = 0; (*it)->curDataOffset = 0; (*it)->curValueOffset = 0; /* not actually used */ /* Set state for next call */ (*it)->state = JBI_ARRAY_ELEM; return WJB_BEGIN_ARRAY; case JBI_ARRAY_ELEM: if ((*it)->curIndex >= (*it)->nElems) { /* * All elements within array already processed. Report this * to caller, and give it back original parent iterator (which * independently tracks iteration progress at its level of * nesting). */ *it = freeAndGetParent(*it); return WJB_END_ARRAY; } fillJsonbValue((*it)->container, (*it)->curIndex, (*it)->dataProper, (*it)->curDataOffset, val); JBE_ADVANCE_OFFSET((*it)->curDataOffset, (*it)->children[(*it)->curIndex]); (*it)->curIndex++; if (!IsAJsonbScalar(val) && !skipNested) { /* Recurse into container. */ *it = iteratorFromContainer(val->val.binary.data, *it); goto recurse; } else { /* * Scalar item in array, or a container and caller didn't want * us to recurse into it. */ return WJB_ELEM; } case JBI_OBJECT_START: /* Set v to object on first object call */ val->type = jbvObject; val->val.object.nPairs = (*it)->nElems; /* * v->val.object.pairs is not actually set, because we aren't * doing a full conversion */ (*it)->curIndex = 0; (*it)->curDataOffset = 0; (*it)->curValueOffset = getJsonbOffset((*it)->container, (*it)->nElems); /* Set state for next call */ (*it)->state = JBI_OBJECT_KEY; return WJB_BEGIN_OBJECT; case JBI_OBJECT_KEY: if ((*it)->curIndex >= (*it)->nElems) { /* * All pairs within object already processed. Report this to * caller, and give it back original containing iterator * (which independently tracks iteration progress at its level * of nesting). */ *it = freeAndGetParent(*it); return WJB_END_OBJECT; } else { /* Return key of a key/value pair. */ fillJsonbValue((*it)->container, (*it)->curIndex, (*it)->dataProper, (*it)->curDataOffset, val); if (val->type != jbvString) elog(ERROR, "unexpected jsonb type as object key"); /* Set state for next call */ (*it)->state = JBI_OBJECT_VALUE; return WJB_KEY; } case JBI_OBJECT_VALUE: /* Set state for next call */ (*it)->state = JBI_OBJECT_KEY; fillJsonbValue((*it)->container, (*it)->curIndex + (*it)->nElems, (*it)->dataProper, (*it)->curValueOffset, val); JBE_ADVANCE_OFFSET((*it)->curDataOffset, (*it)->children[(*it)->curIndex]); JBE_ADVANCE_OFFSET((*it)->curValueOffset, (*it)->children[(*it)->curIndex + (*it)->nElems]); (*it)->curIndex++; /* * Value may be a container, in which case we recurse with new, * child iterator (unless the caller asked not to, by passing * skipNested). */ if (!IsAJsonbScalar(val) && !skipNested) { *it = iteratorFromContainer(val->val.binary.data, *it); goto recurse; } else return WJB_VALUE; } elog(ERROR, "invalid iterator state"); return -1; } /* * Initialize an iterator for iterating all elements in a container. */ static JsonbIterator * iteratorFromContainer(JsonbContainer *container, JsonbIterator *parent) { JsonbIterator *it; it = palloc(sizeof(JsonbIterator)); it->container = container; it->parent = parent; it->nElems = container->header & JB_CMASK; /* Array starts just after header */ it->children = container->children; switch (container->header & (JB_FARRAY | JB_FOBJECT)) { case JB_FARRAY: it->dataProper = (char *) it->children + it->nElems * sizeof(JEntry); it->isScalar = (container->header & JB_FSCALAR) != 0; /* This is either a "raw scalar", or an array */ Assert(!it->isScalar || it->nElems == 1); it->state = JBI_ARRAY_START; break; case JB_FOBJECT: it->dataProper = (char *) it->children + it->nElems * sizeof(JEntry) * 2; it->state = JBI_OBJECT_START; break; default: elog(ERROR, "unknown type of jsonb container"); } return it; } /* * JsonbIteratorNext() worker: Return parent, while freeing memory for current * iterator */ static JsonbIterator * freeAndGetParent(JsonbIterator *it) { JsonbIterator *v = it->parent; pfree(it); return v; } /* * Worker for "contains" operator's function * * Formally speaking, containment is top-down, unordered subtree isomorphism. * * Takes iterators that belong to some container type. These iterators * "belong" to those values in the sense that they've just been initialized in * respect of them by the caller (perhaps in a nested fashion). * * "val" is lhs Jsonb, and mContained is rhs Jsonb when called from top level. * We determine if mContained is contained within val. */ bool JsonbDeepContains(JsonbIterator **val, JsonbIterator **mContained) { JsonbValue vval, vcontained; JsonbIteratorToken rval, rcont; /* * Guard against stack overflow due to overly complex Jsonb. * * Functions called here independently take this precaution, but that * might not be sufficient since this is also a recursive function. */ check_stack_depth(); rval = JsonbIteratorNext(val, &vval, false); rcont = JsonbIteratorNext(mContained, &vcontained, false); if (rval != rcont) { /* * The differing return values can immediately be taken as indicating * two differing container types at this nesting level, which is * sufficient reason to give up entirely (but it should be the case * that they're both some container type). */ Assert(rval == WJB_BEGIN_OBJECT || rval == WJB_BEGIN_ARRAY); Assert(rcont == WJB_BEGIN_OBJECT || rcont == WJB_BEGIN_ARRAY); return false; } else if (rcont == WJB_BEGIN_OBJECT) { Assert(vval.type == jbvObject); Assert(vcontained.type == jbvObject); /* * If the lhs has fewer pairs than the rhs, it can't possibly contain * the rhs. (This conclusion is safe only because we de-duplicate * keys in all Jsonb objects; thus there can be no corresponding * optimization in the array case.) The case probably won't arise * often, but since it's such a cheap check we may as well make it. */ if (vval.val.object.nPairs < vcontained.val.object.nPairs) return false; /* Work through rhs "is it contained within?" object */ for (;;) { JsonbValue *lhsVal; /* lhsVal is from pair in lhs object */ rcont = JsonbIteratorNext(mContained, &vcontained, false); /* * When we get through caller's rhs "is it contained within?" * object without failing to find one of its values, it's * contained. */ if (rcont == WJB_END_OBJECT) return true; Assert(rcont == WJB_KEY); /* First, find value by key... */ lhsVal = findJsonbValueFromContainer((*val)->container, JB_FOBJECT, &vcontained); if (!lhsVal) return false; /* * ...at this stage it is apparent that there is at least a key * match for this rhs pair. */ rcont = JsonbIteratorNext(mContained, &vcontained, true); Assert(rcont == WJB_VALUE); /* * Compare rhs pair's value with lhs pair's value just found using * key */ if (lhsVal->type != vcontained.type) { return false; } else if (IsAJsonbScalar(lhsVal)) { if (!equalsJsonbScalarValue(lhsVal, &vcontained)) return false; } else { /* Nested container value (object or array) */ JsonbIterator *nestval, *nestContained; Assert(lhsVal->type == jbvBinary); Assert(vcontained.type == jbvBinary); nestval = JsonbIteratorInit(lhsVal->val.binary.data); nestContained = JsonbIteratorInit(vcontained.val.binary.data); /* * Match "value" side of rhs datum object's pair recursively. * It's a nested structure. * * Note that nesting still has to "match up" at the right * nesting sub-levels. However, there need only be zero or * more matching pairs (or elements) at each nesting level * (provided the *rhs* pairs/elements *all* match on each * level), which enables searching nested structures for a * single String or other primitive type sub-datum quite * effectively (provided the user constructed the rhs nested * structure such that we "know where to look"). * * In other words, the mapping of container nodes in the rhs * "vcontained" Jsonb to internal nodes on the lhs is * injective, and parent-child edges on the rhs must be mapped * to parent-child edges on the lhs to satisfy the condition * of containment (plus of course the mapped nodes must be * equal). */ if (!JsonbDeepContains(&nestval, &nestContained)) return false; } } } else if (rcont == WJB_BEGIN_ARRAY) { JsonbValue *lhsConts = NULL; uint32 nLhsElems = vval.val.array.nElems; Assert(vval.type == jbvArray); Assert(vcontained.type == jbvArray); /* * Handle distinction between "raw scalar" pseudo arrays, and real * arrays. * * A raw scalar may contain another raw scalar, and an array may * contain a raw scalar, but a raw scalar may not contain an array. We * don't do something like this for the object case, since objects can * only contain pairs, never raw scalars (a pair is represented by an * rhs object argument with a single contained pair). */ if (vval.val.array.rawScalar && !vcontained.val.array.rawScalar) return false; /* Work through rhs "is it contained within?" array */ for (;;) { rcont = JsonbIteratorNext(mContained, &vcontained, true); /* * When we get through caller's rhs "is it contained within?" * array without failing to find one of its values, it's * contained. */ if (rcont == WJB_END_ARRAY) return true; Assert(rcont == WJB_ELEM); if (IsAJsonbScalar(&vcontained)) { if (!findJsonbValueFromContainer((*val)->container, JB_FARRAY, &vcontained)) return false; } else { uint32 i; /* * If this is first container found in rhs array (at this * depth), initialize temp lhs array of containers */ if (lhsConts == NULL) { uint32 j = 0; /* Make room for all possible values */ lhsConts = palloc(sizeof(JsonbValue) * nLhsElems); for (i = 0; i < nLhsElems; i++) { /* Store all lhs elements in temp array */ rcont = JsonbIteratorNext(val, &vval, true); Assert(rcont == WJB_ELEM); if (vval.type == jbvBinary) lhsConts[j++] = vval; } /* No container elements in temp array, so give up now */ if (j == 0) return false; /* We may have only partially filled array */ nLhsElems = j; } /* XXX: Nested array containment is O(N^2) */ for (i = 0; i < nLhsElems; i++) { /* Nested container value (object or array) */ JsonbIterator *nestval, *nestContained; bool contains; nestval = JsonbIteratorInit(lhsConts[i].val.binary.data); nestContained = JsonbIteratorInit(vcontained.val.binary.data); contains = JsonbDeepContains(&nestval, &nestContained); if (nestval) pfree(nestval); if (nestContained) pfree(nestContained); if (contains) break; } /* * Report rhs container value is not contained if couldn't * match rhs container to *some* lhs cont */ if (i == nLhsElems) return false; } } } else { elog(ERROR, "invalid jsonb container type"); } elog(ERROR, "unexpectedly fell off end of jsonb container"); return false; } /* * Hash a JsonbValue scalar value, mixing the hash value into an existing * hash provided by the caller. * * Some callers may wish to independently XOR in JB_FOBJECT and JB_FARRAY * flags. */ void JsonbHashScalarValue(const JsonbValue *scalarVal, uint32 *hash) { uint32 tmp; /* Compute hash value for scalarVal */ switch (scalarVal->type) { case jbvNull: tmp = 0x01; break; case jbvString: tmp = DatumGetUInt32(hash_any((const unsigned char *) scalarVal->val.string.val, scalarVal->val.string.len)); break; case jbvNumeric: /* Must hash equal numerics to equal hash codes */ tmp = DatumGetUInt32(DirectFunctionCall1(hash_numeric, NumericGetDatum(scalarVal->val.numeric))); break; case jbvBool: tmp = scalarVal->val.boolean ? 0x02 : 0x04; break; default: elog(ERROR, "invalid jsonb scalar type"); tmp = 0; /* keep compiler quiet */ break; } /* * Combine hash values of successive keys, values and elements by rotating * the previous value left 1 bit, then XOR'ing in the new * key/value/element's hash value. */ *hash = (*hash << 1) | (*hash >> 31); *hash ^= tmp; } /* * Are two scalar JsonbValues of the same type a and b equal? */ static bool equalsJsonbScalarValue(JsonbValue *aScalar, JsonbValue *bScalar) { if (aScalar->type == bScalar->type) { switch (aScalar->type) { case jbvNull: return true; case jbvString: return lengthCompareJsonbStringValue(aScalar, bScalar) == 0; case jbvNumeric: return DatumGetBool(DirectFunctionCall2(numeric_eq, PointerGetDatum(aScalar->val.numeric), PointerGetDatum(bScalar->val.numeric))); case jbvBool: return aScalar->val.boolean == bScalar->val.boolean; default: elog(ERROR, "invalid jsonb scalar type"); } } elog(ERROR, "jsonb scalar type mismatch"); return -1; } /* * Compare two scalar JsonbValues, returning -1, 0, or 1. * * Strings are compared using the default collation. Used by B-tree * operators, where a lexical sort order is generally expected. */ static int compareJsonbScalarValue(JsonbValue *aScalar, JsonbValue *bScalar) { if (aScalar->type == bScalar->type) { switch (aScalar->type) { case jbvNull: return 0; case jbvString: return varstr_cmp(aScalar->val.string.val, aScalar->val.string.len, bScalar->val.string.val, bScalar->val.string.len, DEFAULT_COLLATION_OID); case jbvNumeric: return DatumGetInt32(DirectFunctionCall2(numeric_cmp, PointerGetDatum(aScalar->val.numeric), PointerGetDatum(bScalar->val.numeric))); case jbvBool: if (aScalar->val.boolean == bScalar->val.boolean) return 0; else if (aScalar->val.boolean > bScalar->val.boolean) return 1; else return -1; default: elog(ERROR, "invalid jsonb scalar type"); } } elog(ERROR, "jsonb scalar type mismatch"); return -1; } /* * Functions for manipulating the resizeable buffer used by convertJsonb and * its subroutines. */ /* * Reserve 'len' bytes, at the end of the buffer, enlarging it if necessary. * Returns the offset to the reserved area. The caller is expected to fill * the reserved area later with copyToBuffer(). */ static int reserveFromBuffer(StringInfo buffer, int len) { int offset; /* Make more room if needed */ enlargeStringInfo(buffer, len); /* remember current offset */ offset = buffer->len; /* reserve the space */ buffer->len += len; /* * Keep a trailing null in place, even though it's not useful for us; it * seems best to preserve the invariants of StringInfos. */ buffer->data[buffer->len] = '\0'; return offset; } /* * Copy 'len' bytes to a previously reserved area in buffer. */ static void copyToBuffer(StringInfo buffer, int offset, const char *data, int len) { memcpy(buffer->data + offset, data, len); } /* * A shorthand for reserveFromBuffer + copyToBuffer. */ static void appendToBuffer(StringInfo buffer, const char *data, int len) { int offset; offset = reserveFromBuffer(buffer, len); copyToBuffer(buffer, offset, data, len); } /* * Append padding, so that the length of the StringInfo is int-aligned. * Returns the number of padding bytes appended. */ static short padBufferToInt(StringInfo buffer) { int padlen, p, offset; padlen = INTALIGN(buffer->len) - buffer->len; offset = reserveFromBuffer(buffer, padlen); /* padlen must be small, so this is probably faster than a memset */ for (p = 0; p < padlen; p++) buffer->data[offset + p] = '\0'; return padlen; } /* * Given a JsonbValue, convert to Jsonb. The result is palloc'd. */ static Jsonb * convertToJsonb(JsonbValue *val) { StringInfoData buffer; JEntry jentry; Jsonb *res; /* Should not already have binary representation */ Assert(val->type != jbvBinary); /* Allocate an output buffer. It will be enlarged as needed */ initStringInfo(&buffer); /* Make room for the varlena header */ reserveFromBuffer(&buffer, VARHDRSZ); convertJsonbValue(&buffer, &jentry, val, 0); /* * Note: the JEntry of the root is discarded. Therefore the root * JsonbContainer struct must contain enough information to tell what kind * of value it is. */ res = (Jsonb *) buffer.data; SET_VARSIZE(res, buffer.len); return res; } /* * Subroutine of convertJsonb: serialize a single JsonbValue into buffer. * * The JEntry header for this node is returned in *header. It is filled in * with the length of this value and appropriate type bits. If we wish to * store an end offset rather than a length, it is the caller's responsibility * to adjust for that. * * If the value is an array or an object, this recurses. 'level' is only used * for debugging purposes. */ static void convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level) { check_stack_depth(); if (!val) return; /* * A JsonbValue passed as val should never have a type of jbvBinary, and * neither should any of its sub-components. Those values will be produced * by convertJsonbArray and convertJsonbObject, the results of which will * not be passed back to this function as an argument. */ if (IsAJsonbScalar(val)) convertJsonbScalar(buffer, header, val); else if (val->type == jbvArray) convertJsonbArray(buffer, header, val, level); else if (val->type == jbvObject) convertJsonbObject(buffer, header, val, level); else elog(ERROR, "unknown type of jsonb container to convert"); } static void convertJsonbArray(StringInfo buffer, JEntry *pheader, JsonbValue *val, int level) { int base_offset; int jentry_offset; int i; int totallen; uint32 header; int nElems = val->val.array.nElems; /* Remember where in the buffer this array starts. */ base_offset = buffer->len; /* Align to 4-byte boundary (any padding counts as part of my data) */ padBufferToInt(buffer); /* * Construct the header Jentry and store it in the beginning of the * variable-length payload. */ header = nElems | JB_FARRAY; if (val->val.array.rawScalar) { Assert(nElems == 1); Assert(level == 0); header |= JB_FSCALAR; } appendToBuffer(buffer, (char *) &header, sizeof(uint32)); /* Reserve space for the JEntries of the elements. */ jentry_offset = reserveFromBuffer(buffer, sizeof(JEntry) * nElems); totallen = 0; for (i = 0; i < nElems; i++) { JsonbValue *elem = &val->val.array.elems[i]; int len; JEntry meta; /* * Convert element, producing a JEntry and appending its * variable-length data to buffer */ convertJsonbValue(buffer, &meta, elem, level + 1); len = JBE_OFFLENFLD(meta); totallen += len; /* * Bail out if total variable-length data exceeds what will fit in a * JEntry length field. We check this in each iteration, not just * once at the end, to forestall possible integer overflow. */ if (totallen > JENTRY_OFFLENMASK) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("total size of jsonb array elements exceeds the maximum of %u bytes", JENTRY_OFFLENMASK))); /* * Convert each JB_OFFSET_STRIDE'th length to an offset. */ if ((i % JB_OFFSET_STRIDE) == 0) meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF; copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry)); jentry_offset += sizeof(JEntry); } /* Total data size is everything we've appended to buffer */ totallen = buffer->len - base_offset; /* Check length again, since we didn't include the metadata above */ if (totallen > JENTRY_OFFLENMASK) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("total size of jsonb array elements exceeds the maximum of %u bytes", JENTRY_OFFLENMASK))); /* Initialize the header of this node in the container's JEntry array */ *pheader = JENTRY_ISCONTAINER | totallen; } static void convertJsonbObject(StringInfo buffer, JEntry *pheader, JsonbValue *val, int level) { int base_offset; int jentry_offset; int i; int totallen; uint32 header; int nPairs = val->val.object.nPairs; /* Remember where in the buffer this object starts. */ base_offset = buffer->len; /* Align to 4-byte boundary (any padding counts as part of my data) */ padBufferToInt(buffer); /* * Construct the header Jentry and store it in the beginning of the * variable-length payload. */ header = nPairs | JB_FOBJECT; appendToBuffer(buffer, (char *) &header, sizeof(uint32)); /* Reserve space for the JEntries of the keys and values. */ jentry_offset = reserveFromBuffer(buffer, sizeof(JEntry) * nPairs * 2); /* * Iterate over the keys, then over the values, since that is the ordering * we want in the on-disk representation. */ totallen = 0; for (i = 0; i < nPairs; i++) { JsonbPair *pair = &val->val.object.pairs[i]; int len; JEntry meta; /* * Convert key, producing a JEntry and appending its variable-length * data to buffer */ convertJsonbScalar(buffer, &meta, &pair->key); len = JBE_OFFLENFLD(meta); totallen += len; /* * Bail out if total variable-length data exceeds what will fit in a * JEntry length field. We check this in each iteration, not just * once at the end, to forestall possible integer overflow. */ if (totallen > JENTRY_OFFLENMASK) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("total size of jsonb object elements exceeds the maximum of %u bytes", JENTRY_OFFLENMASK))); /* * Convert each JB_OFFSET_STRIDE'th length to an offset. */ if ((i % JB_OFFSET_STRIDE) == 0) meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF; copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry)); jentry_offset += sizeof(JEntry); } for (i = 0; i < nPairs; i++) { JsonbPair *pair = &val->val.object.pairs[i]; int len; JEntry meta; /* * Convert value, producing a JEntry and appending its variable-length * data to buffer */ convertJsonbValue(buffer, &meta, &pair->value, level + 1); len = JBE_OFFLENFLD(meta); totallen += len; /* * Bail out if total variable-length data exceeds what will fit in a * JEntry length field. We check this in each iteration, not just * once at the end, to forestall possible integer overflow. */ if (totallen > JENTRY_OFFLENMASK) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("total size of jsonb object elements exceeds the maximum of %u bytes", JENTRY_OFFLENMASK))); /* * Convert each JB_OFFSET_STRIDE'th length to an offset. */ if (((i + nPairs) % JB_OFFSET_STRIDE) == 0) meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF; copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry)); jentry_offset += sizeof(JEntry); } /* Total data size is everything we've appended to buffer */ totallen = buffer->len - base_offset; /* Check length again, since we didn't include the metadata above */ if (totallen > JENTRY_OFFLENMASK) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("total size of jsonb object elements exceeds the maximum of %u bytes", JENTRY_OFFLENMASK))); /* Initialize the header of this node in the container's JEntry array */ *pheader = JENTRY_ISCONTAINER | totallen; } static void convertJsonbScalar(StringInfo buffer, JEntry *jentry, JsonbValue *scalarVal) { int numlen; short padlen; switch (scalarVal->type) { case jbvNull: *jentry = JENTRY_ISNULL; break; case jbvString: appendToBuffer(buffer, scalarVal->val.string.val, scalarVal->val.string.len); *jentry = scalarVal->val.string.len; break; case jbvNumeric: numlen = VARSIZE_ANY(scalarVal->val.numeric); padlen = padBufferToInt(buffer); appendToBuffer(buffer, (char *) scalarVal->val.numeric, numlen); *jentry = JENTRY_ISNUMERIC | (padlen + numlen); break; case jbvBool: *jentry = (scalarVal->val.boolean) ? JENTRY_ISBOOL_TRUE : JENTRY_ISBOOL_FALSE; break; default: elog(ERROR, "invalid jsonb scalar type"); } } /* * Compare two jbvString JsonbValue values, a and b. * * This is a special qsort() comparator used to sort strings in certain * internal contexts where it is sufficient to have a well-defined sort order. * In particular, object pair keys are sorted according to this criteria to * facilitate cheap binary searches where we don't care about lexical sort * order. * * a and b are first sorted based on their length. If a tie-breaker is * required, only then do we consider string binary equality. */ static int lengthCompareJsonbStringValue(const void *a, const void *b) { const JsonbValue *va = (const JsonbValue *) a; const JsonbValue *vb = (const JsonbValue *) b; int res; Assert(va->type == jbvString); Assert(vb->type == jbvString); if (va->val.string.len == vb->val.string.len) { res = memcmp(va->val.string.val, vb->val.string.val, va->val.string.len); } else { res = (va->val.string.len > vb->val.string.len) ? 1 : -1; } return res; } /* * qsort_arg() comparator to compare JsonbPair values. * * Third argument 'binequal' may point to a bool. If it's set, *binequal is set * to true iff a and b have full binary equality, since some callers have an * interest in whether the two values are equal or merely equivalent. * * N.B: String comparisons here are "length-wise" * * Pairs with equals keys are ordered such that the order field is respected. */ static int lengthCompareJsonbPair(const void *a, const void *b, void *binequal) { const JsonbPair *pa = (const JsonbPair *) a; const JsonbPair *pb = (const JsonbPair *) b; int res; res = lengthCompareJsonbStringValue(&pa->key, &pb->key); if (res == 0 && binequal) *((bool *) binequal) = true; /* * Guarantee keeping order of equal pair. Unique algorithm will prefer * first element as value. */ if (res == 0) res = (pa->order > pb->order) ? -1 : 1; return res; } /* * Sort and unique-ify pairs in JsonbValue object */ static void uniqueifyJsonbObject(JsonbValue *object) { bool hasNonUniq = false; Assert(object->type == jbvObject); if (object->val.object.nPairs > 1) qsort_arg(object->val.object.pairs, object->val.object.nPairs, sizeof(JsonbPair), lengthCompareJsonbPair, &hasNonUniq); if (hasNonUniq) { JsonbPair *ptr = object->val.object.pairs + 1, *res = object->val.object.pairs; while (ptr - object->val.object.pairs < object->val.object.nPairs) { /* Avoid copying over duplicate */ if (lengthCompareJsonbStringValue(ptr, res) != 0) { res++; if (ptr != res) memcpy(res, ptr, sizeof(JsonbPair)); } ptr++; } object->val.object.nPairs = res + 1 - object->val.object.pairs; } }
{ "content_hash": "a1b201a81ba71f2edc764b7c14a8c37e", "timestamp": "", "source": "github", "line_count": 1792, "max_line_length": 94, "avg_line_length": 28.108816964285715, "alnum_prop": 0.6770562426793194, "repo_name": "jmcatamney/gpdb", "id": "ddc34ceec7a1c7839031e44e0df9067c8f61ecb9", "size": "50741", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/backend/utils/adt/jsonb_util.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3724" }, { "name": "Awk", "bytes": "836" }, { "name": "Batchfile", "bytes": "12854" }, { "name": "C", "bytes": "42498841" }, { "name": "C++", "bytes": "14366259" }, { "name": "CMake", "bytes": "38452" }, { "name": "Csound Score", "bytes": "223" }, { "name": "DTrace", "bytes": "3873" }, { "name": "Dockerfile", "bytes": "11932" }, { "name": "Emacs Lisp", "bytes": "3488" }, { "name": "Fortran", "bytes": "14863" }, { "name": "GDB", "bytes": "576" }, { "name": "Gherkin", "bytes": "335208" }, { "name": "HTML", "bytes": "53484" }, { "name": "JavaScript", "bytes": "23969" }, { "name": "Lex", "bytes": "229556" }, { "name": "M4", "bytes": "111147" }, { "name": "Makefile", "bytes": "496239" }, { "name": "Objective-C", "bytes": "38376" }, { "name": "PLpgSQL", "bytes": "8009512" }, { "name": "Perl", "bytes": "798767" }, { "name": "PowerShell", "bytes": "422" }, { "name": "Python", "bytes": "3000118" }, { "name": "Raku", "bytes": "698" }, { "name": "Roff", "bytes": "32437" }, { "name": "Ruby", "bytes": "77585" }, { "name": "SCSS", "bytes": "339" }, { "name": "Shell", "bytes": "451713" }, { "name": "XS", "bytes": "6983" }, { "name": "Yacc", "bytes": "674092" }, { "name": "sed", "bytes": "1231" } ], "symlink_target": "" }
namespace enav { class StagePanel; class ToolbarPanel : public ee::ToolbarPanel { public: ToolbarPanel(wxWindow* parent, StagePanel* stage); protected: virtual wxSizer* InitLayout() override; }; // ToolbarPanel } #endif // _EASYNAVMESH_TOOLBAR_PANEL_H_
{ "content_hash": "61629b95db584a7dae3f62df4e10e8be", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 51, "avg_line_length": 14.444444444444445, "alnum_prop": 0.7461538461538462, "repo_name": "xzrunner/easyeditor", "id": "e643076d3ffac70d94c3627bb1b3b5067352c7fa", "size": "367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "easynavmesh/src/easynavmesh/view/ToolbarPanel.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "118661" }, { "name": "C++", "bytes": "5152354" }, { "name": "GLSL", "bytes": "10503" }, { "name": "Lua", "bytes": "127544" }, { "name": "Makefile", "bytes": "210" } ], "symlink_target": "" }
/** * ElectionInstanceController * * @description :: Server-side logic for managing electioninstances * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { };
{ "content_hash": "2506f21b52d7393255e05f290e9cec25", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 79, "avg_line_length": 19.545454545454547, "alnum_prop": 0.6790697674418604, "repo_name": "Goblab/observatorio-electoral", "id": "9538b4c921bc476de3e04a5ed74168ed2c88db2e", "size": "215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/api/controllers/ElectionInstanceController.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "187954" }, { "name": "HTML", "bytes": "388081" }, { "name": "JavaScript", "bytes": "527848" } ], "symlink_target": "" }
extern CGFloat const YALBottomSelectedDotDefaultSize; extern CGFloat const YALBottomSelectedDotOffset; extern CGFloat const YALTabBarViewDefaultHeight; extern CGFloat const YALExtraTabBarItemsDefaultHeight; extern CGFloat const YALForExtraTabBarItemsDefaultOffset; extern UIEdgeInsets const YALTabBarViewHDefaultEdgeInsets; extern UIEdgeInsets const YALTabBarViewItemsDefaultEdgeInsets; extern NSString * const YALCenterButtonExpandAnimation; extern NSString * const YALCenterButtonCollapseAnimation; extern NSString * const YALAdditionalButtonsAnimation; extern NSString * const YALTabBarExpandAnimation; extern NSString * const YALTabBarExpandCollapseAnimation; extern NSString * const YALExtraLeftBarItemAnimation; extern NSString * const YALExtraRightBarItemAnimation; extern CFTimeInterval const kYALExpandAnimationDuration; typedef struct { CFTimeInterval beginTime; CFTimeInterval duration; double fromValue; double toValue; double damping; double velocity; } YALAnimationParameters; typedef struct { YALAnimationParameters scaleX; YALAnimationParameters scaleY; YALAnimationParameters rotation; YALAnimationParameters bounce; } YALAdditionalButtonsAnimationsParameters; typedef struct { YALAnimationParameters rotation; YALAnimationParameters bounce; } YALCenterButtonAnimationsParameters; typedef struct { NSTimeInterval duration; NSTimeInterval delay; CGFloat damping; CGFloat velocity; UIViewAnimationOptions options; } YALExtraTabBarItemViewAnimationParameters; typedef struct { YALAnimationParameters scaleX; YALAnimationParameters scaleY; } YALSelectedDotAnimationsParameters; extern YALAdditionalButtonsAnimationsParameters const kYALAdditionalButtonsAnimationsParameters; extern YALSelectedDotAnimationsParameters const kYALSelectedDotAnimationsParameters; extern YALAnimationParameters const kYALExtraLeftTabBarItemAnimationParameters; extern YALAnimationParameters const kYALExtraRightTabBarItemAnimationParameters; extern YALAnimationParameters const kYALTabBarExpandAnimationParameters; extern YALAnimationParameters const kYALTabBarCollapseAnimationParameters; extern YALCenterButtonAnimationsParameters const kYALCenterButtonExpandAnimationParameters; extern YALCenterButtonAnimationsParameters const kYALCenterButtonCollapseAnimationParameters; extern YALAnimationParameters const kYALBounceAnimationParameters; extern YALExtraTabBarItemViewAnimationParameters const kYALShowExtraTabBarItemViewAnimationParameters; extern YALExtraTabBarItemViewAnimationParameters const kYALHideExtraTabBarItemViewAnimationParameters;
{ "content_hash": "ecf63937ee3bd898c2ffa2f46c84bdf1", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 102, "avg_line_length": 42.32258064516129, "alnum_prop": 0.8765243902439024, "repo_name": "Yalantis/FoldingTabBar.iOS", "id": "f1ba55ea6fb8cbb33592f6113d9712e4016b4672", "size": "2746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FoldingTabBar/Constants/YALAnimatingTabBarConstants.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "79450" }, { "name": "Ruby", "bytes": "713" }, { "name": "Swift", "bytes": "7418" } ], "symlink_target": "" }
package manifest import ( "errors" "fmt" "code.cloudfoundry.org/cli/cf/models" "gopkg.in/yaml.v2" "io" . "code.cloudfoundry.org/cli/cf/i18n" ) //go:generate counterfeiter . App type App interface { BuildpackURL(string, string) DiskQuota(string, int64) Memory(string, int64) Service(string, string) StartCommand(string, string) EnvironmentVars(string, string, string) HealthCheckTimeout(string, int) HealthCheckType(string, string) HealthCheckHTTPEndpoint(string, string) Instances(string, int) Route(string, string, string, string, int) GetContents() []models.Application Stack(string, string) Save(f io.Writer) error } type Application struct { Name string `yaml:"name"` Instances int `yaml:"instances,omitempty"` Memory string `yaml:"memory,omitempty"` DiskQuota string `yaml:"disk_quota,omitempty"` Routes []map[string]string `yaml:"routes,omitempty"` NoRoute bool `yaml:"no-route,omitempty"` Buildpack string `yaml:"buildpack,omitempty"` Command string `yaml:"command,omitempty"` Env map[string]interface{} `yaml:"env,omitempty"` Services []string `yaml:"services,omitempty"` Stack string `yaml:"stack,omitempty"` Timeout int `yaml:"timeout,omitempty"` HealthCheckType string `yaml:"health-check-type,omitempty"` HealthCheckHTTPEndpoint string `yaml:"health-check-http-endpoint,omitempty"` } type Applications struct { Applications []Application `yaml:"applications"` } type appManifest struct { contents []models.Application } func NewGenerator() App { return &appManifest{} } func (m *appManifest) Stack(appName string, stackName string) { i := m.findOrCreateApplication(appName) m.contents[i].Stack = &models.Stack{ Name: stackName, } } func (m *appManifest) Memory(appName string, memory int64) { i := m.findOrCreateApplication(appName) m.contents[i].Memory = memory } func (m *appManifest) DiskQuota(appName string, diskQuota int64) { i := m.findOrCreateApplication(appName) m.contents[i].DiskQuota = diskQuota } func (m *appManifest) StartCommand(appName string, cmd string) { i := m.findOrCreateApplication(appName) m.contents[i].Command = cmd } func (m *appManifest) BuildpackURL(appName string, url string) { i := m.findOrCreateApplication(appName) m.contents[i].BuildpackURL = url } func (m *appManifest) HealthCheckTimeout(appName string, timeout int) { i := m.findOrCreateApplication(appName) m.contents[i].HealthCheckTimeout = timeout } func (m *appManifest) HealthCheckType(appName string, healthCheckType string) { i := m.findOrCreateApplication(appName) m.contents[i].HealthCheckType = healthCheckType } func (m *appManifest) HealthCheckHTTPEndpoint(appName string, healthCheckHTTPEndpoint string) { i := m.findOrCreateApplication(appName) m.contents[i].HealthCheckHTTPEndpoint = healthCheckHTTPEndpoint } func (m *appManifest) Instances(appName string, instances int) { i := m.findOrCreateApplication(appName) m.contents[i].InstanceCount = instances } func (m *appManifest) Service(appName string, name string) { i := m.findOrCreateApplication(appName) m.contents[i].Services = append(m.contents[i].Services, models.ServicePlanSummary{ GUID: "", Name: name, }) } func (m *appManifest) Route(appName, host, domain, path string, port int) { i := m.findOrCreateApplication(appName) m.contents[i].Routes = append(m.contents[i].Routes, models.RouteSummary{ Host: host, Domain: models.DomainFields{ Name: domain, }, Path: path, Port: port, }) } func (m *appManifest) EnvironmentVars(appName string, key, value string) { i := m.findOrCreateApplication(appName) m.contents[i].EnvironmentVars[key] = value } func (m *appManifest) GetContents() []models.Application { return m.contents } func generateAppMap(app models.Application) (Application, error) { if app.Stack == nil { return Application{}, errors.New(T("required attribute 'stack' missing")) } if app.Memory == 0 { return Application{}, errors.New(T("required attribute 'memory' missing")) } if app.DiskQuota == 0 { return Application{}, errors.New(T("required attribute 'disk_quota' missing")) } if app.InstanceCount == 0 { return Application{}, errors.New(T("required attribute 'instances' missing")) } var services []string for _, s := range app.Services { services = append(services, s.Name) } var routes []map[string]string for _, routeSummary := range app.Routes { routes = append(routes, buildRoute(routeSummary)) } m := Application{ Name: app.Name, Services: services, Buildpack: app.BuildpackURL, Memory: fmt.Sprintf("%dM", app.Memory), Command: app.Command, Env: app.EnvironmentVars, Timeout: app.HealthCheckTimeout, Instances: app.InstanceCount, DiskQuota: fmt.Sprintf("%dM", app.DiskQuota), Stack: app.Stack.Name, Routes: routes, HealthCheckType: app.HealthCheckType, HealthCheckHTTPEndpoint: app.HealthCheckHTTPEndpoint, } if len(app.Routes) == 0 { m.NoRoute = true } return m, nil } func (m *appManifest) Save(f io.Writer) error { apps := Applications{} for _, app := range m.contents { appMap, mapErr := generateAppMap(app) if mapErr != nil { return fmt.Errorf(T("Error saving manifest: {{.Error}}", map[string]interface{}{ "Error": mapErr.Error(), })) } apps.Applications = append(apps.Applications, appMap) } contents, err := yaml.Marshal(apps) if err != nil { return err } _, err = f.Write(contents) if err != nil { return err } return nil } func buildRoute(routeSummary models.RouteSummary) map[string]string { var route string if routeSummary.Host != "" { route = fmt.Sprintf("%s.", routeSummary.Host) } route = fmt.Sprintf("%s%s", route, routeSummary.Domain.Name) if routeSummary.Path != "" { route = fmt.Sprintf("%s%s", route, routeSummary.Path) } if routeSummary.Port != 0 { route = fmt.Sprintf("%s:%d", route, routeSummary.Port) } return map[string]string{ "route": route, } } func (m *appManifest) findOrCreateApplication(name string) int { for i, app := range m.contents { if app.Name == name { return i } } m.addApplication(name) return len(m.contents) - 1 } func (m *appManifest) addApplication(name string) { m.contents = append(m.contents, models.Application{ ApplicationFields: models.ApplicationFields{ Name: name, EnvironmentVars: make(map[string]interface{}), }, }) }
{ "content_hash": "8f5df065bac7ba0f00290e4d7d0cdff6", "timestamp": "", "source": "github", "line_count": 255, "max_line_length": 95, "avg_line_length": 27.2078431372549, "alnum_prop": 0.6579705967137504, "repo_name": "orange-cloudfoundry/terraform-provider-cloudfoundry", "id": "4dc408d5d3aaa99e64501bc59a458378909c70ff", "size": "6938", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/code.cloudfoundry.org/cli/cf/manifest/generate_manifest.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "261939" }, { "name": "Shell", "bytes": "3779" } ], "symlink_target": "" }
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import itertools import pytest from tcolorpy import tcolor from typepy import Bool, StrictLevel, Typecode class_under_test = Bool nan = float("nan") inf = float("inf") class Test_Bool_is_type: @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product([True, False], [StrictLevel.MIN, StrictLevel.MAX], [True])) + list( itertools.product([0, 1, "True", "False", "true", "false"], [StrictLevel.MIN], [True]) ) + list( itertools.product( [0, 1, 0.1, "True", "False", "true", "false"], [StrictLevel.MAX], [False] ) ), ) def test_normal(self, value, strict_level, expected): type_checker = class_under_test(value, strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.BOOL @pytest.mark.parametrize( ["value", "strip_ansi_escape", "expected"], [[tcolor("True", "red"), False, False], [tcolor("True", "red"), True, True]], ) def test_normal_ansi(self, value, strip_ansi_escape, expected): type_checker = class_under_test(value, StrictLevel.MIN, strip_ansi_escape=strip_ansi_escape) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.BOOL
{ "content_hash": "4ccb6dbff5d0a52205b33746817a87df", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 100, "avg_line_length": 31.244444444444444, "alnum_prop": 0.6102418207681366, "repo_name": "thombashi/typepy", "id": "6866a2f8fb59060e33791acc941267cfd5ced876", "size": "1406", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/checker/test_checker_bool.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1107" }, { "name": "Python", "bytes": "103291" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "82bf5eb22766b3f4fa27f91f2a3d24dc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "068c4e9e00788a7fc0340cc0b2df23376032b2ba", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium glabriligulatum/Hieracium nigrescens/ Syn. Hieracium nigrescens adspersum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package net.silentchaos512.scalinghealth.utils.config; import com.mojang.datafixers.util.Pair; import com.udojava.evalex.Expression; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3i; import net.minecraft.world.IWorld; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.silentchaos512.lib.util.MCMathUtils; import net.silentchaos512.scalinghealth.capability.DifficultyAffectedCapability; import net.silentchaos512.scalinghealth.capability.DifficultySourceCapability; import net.silentchaos512.scalinghealth.capability.IDifficultyAffected; import net.silentchaos512.scalinghealth.capability.IDifficultySource; import net.silentchaos512.scalinghealth.config.EvalVars; import net.silentchaos512.scalinghealth.resources.mechanics.SHMechanicListener; import net.silentchaos512.scalinghealth.utils.EntityGroup; import net.silentchaos512.scalinghealth.utils.mode.AreaDifficultyMode; import net.silentchaos512.utils.MathUtils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; public final class SHDifficulty { private SHDifficulty() {throw new IllegalAccessError("Utility class");} public static IDifficultyAffected affected(ICapabilityProvider entity) { return entity.getCapability(DifficultyAffectedCapability.INSTANCE) .orElseGet(DifficultyAffectedCapability::new); } public static IDifficultySource source(ICapabilityProvider source) { return source.getCapability(DifficultySourceCapability.INSTANCE) .orElseGet(DifficultySourceCapability::new); } public static void setSourceDifficulty(PlayerEntity player, double difficulty){ IDifficultySource source = SHDifficulty.source(player); if (!MathUtils.doublesEqual(source.getDifficulty(), difficulty)) { source.setDifficulty((float) difficulty); //player diff SHDifficulty.source(player.world).setDifficulty((float) difficulty); //world diff } } @SuppressWarnings("TypeMayBeWeakened") public static double getDifficultyOf(Entity entity) { if (entity instanceof PlayerEntity) return source(entity).getDifficulty(); return affected(entity).affectiveDifficulty(); } public static List<Pair<IDifficultySource, BlockPos>> positionedPlayerSources(IWorld world, Vector3i center, long radius) { return playersInRange(world, center, radius) .map(player -> Pair.of(source(player), player.getPosition())) .collect(Collectors.toList()); } public static Collection<Tuple<BlockPos, IDifficultySource>> allPlayerSources(IWorld world, Vector3i center, long radius) { Collection<Tuple<BlockPos, IDifficultySource>> list = new ArrayList<>(); // Get players playersInRange(world, center, radius).forEach(player -> list.add(new Tuple<>(player.getPosition(), SHDifficulty.source(player)))); return list; } public static Stream<? extends PlayerEntity> playersInRange(IWorld world, Vector3i center, long radius) { if (radius <= 0) return world.getPlayers().stream(); return world.getPlayers().stream() .filter(p -> MCMathUtils.distanceSq(p, center) < (radius * radius)); } public static int groupSearchRadius() { return SHMechanicListener.getDifficultyMechanics().groupBonusRadius; } public static double areaDifficulty(World world, BlockPos pos) { return areaDifficulty(world, pos, true); } public static double areaDifficulty(World world, BlockPos pos, boolean groupBonus) { return clamp(areaMode().getDifficulty(world, pos) * locationMultiplier(world, pos) * lunarMultiplier(world) * (groupBonus ? groupMultiplier(world, pos) : 1)); } public static double locationMultiplier(World world, BlockPos pos) { return SHMechanicListener.getDifficultyMechanics().multipliers.getScale(world, world.getBiome(pos)); } //TODO Can't be checked on the ClientWorld, have to send packet (for debug overlay) public static double lunarMultiplier(World world) { return (world.getDimensionKey() != World.OVERWORLD || world.isDaytime()) ? 1 : SHMechanicListener.getDifficultyMechanics().multipliers .getLunarMultiplier(world.getDimensionType().getMoonPhase(world.func_241851_ab())); } public static double groupMultiplier(World world, BlockPos pos) { return EvalVars.apply(world, pos, null, SHMechanicListener.getDifficultyMechanics().groupBonus.get()); } public static AreaDifficultyMode areaMode() { return SHMechanicListener.getDifficultyMechanics().mode; } public static double clamp(double difficulty) { return MathHelper.clamp(difficulty, minValue(), maxValue()); } public static double minValue() { return SHMechanicListener.getDifficultyMechanics().minValue; } public static double maxValue() { return SHMechanicListener.getDifficultyMechanics().maxValue; } public static double changePerSecond() { return SHMechanicListener.getDifficultyMechanics().changePerSecond; } public static double idleModifier() { return SHMechanicListener.getDifficultyMechanics().idleMultiplier; } public static boolean afkMessage(){ return SHMechanicListener.getDifficultyMechanics().afkMessage; } public static double timeBeforeAfk() { return SHMechanicListener.getDifficultyMechanics().timeBeforeAfk; } public static double getDifficultyAfterDeath(PlayerEntity player) { return EvalVars.apply(player, SHMechanicListener.getDifficultyMechanics().mutators.onPlayerDeath.get()); } public static void applyKillMutator(LivingEntity killed, PlayerEntity killer) { //check if player, if it is, no other mutator can apply if (killed instanceof PlayerEntity) { setSourceDifficulty(killer, EvalVars.apply(killer, SHMechanicListener.getDifficultyMechanics().mutators.onPlayerKilled.get())); return; } //check if blight, continue even if it to apply the base mutator if (affected(killed).isBlight()) setSourceDifficulty(killer, EvalVars.apply(killer, SHMechanicListener.getDifficultyMechanics().mutators.onBlightKilled.get())); //check for entity specific mutators first for (Pair<List<ResourceLocation>, Supplier<Expression>> p : SHMechanicListener.getDifficultyMechanics().mutators.byEntity) { if (p.getFirst().contains(killed.getType().getRegistryName())) { setSourceDifficulty(killer, EvalVars.apply(killer, p.getSecond().get())); return; } } //finally fall back to categorising entity between peaceful and hostile if (EntityGroup.from(killed, true) == EntityGroup.PEACEFUL) { setSourceDifficulty(killer, EvalVars.apply(killer, SHMechanicListener.getDifficultyMechanics().mutators.onPeacefulKilled.get())); } else { setSourceDifficulty(killer, EvalVars.apply(killer, SHMechanicListener.getDifficultyMechanics().mutators.onHostileKilled.get())); } } public static double diffOnPlayerSleep(PlayerEntity entity){ return EvalVars.apply(entity, SHMechanicListener.getDifficultyMechanics().mutators.onPlayerSleep.get()); } public static boolean sleepWarningMessage(){ return SHMechanicListener.getDifficultyMechanics().sleepWarningMessage; } public static List<? extends String> getDamageBlacklistedMods(){ return SHMechanicListener.getDamageScalingMechanics().modBlackList; } }
{ "content_hash": "f95434b26a6b18af042539cf79182ba1", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 141, "avg_line_length": 43.88770053475936, "alnum_prop": 0.7242597782380894, "repo_name": "SilentChaos512/ScalingHealth", "id": "2ee534aa05c45187711a4c42976fa0c867032850", "size": "8207", "binary": false, "copies": "1", "ref": "refs/heads/1.16", "path": "src/main/java/net/silentchaos512/scalinghealth/utils/config/SHDifficulty.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "25" }, { "name": "Java", "bytes": "320561" } ], "symlink_target": "" }
package org.eigenbase.sql; import java.util.*; import org.eigenbase.reltype.*; import org.eigenbase.sql.parser.*; import org.eigenbase.sql.util.*; import org.eigenbase.sql.validate.*; /** * A <code>SqlCall</code> is a call to an {@link SqlOperator operator}. * (Operators can be used to describe any syntactic construct, so in practice, * every non-leaf node in a SQL parse tree is a <code>SqlCall</code> of some * kind.) */ public abstract class SqlCall extends SqlNode { //~ Constructors ----------------------------------------------------------- public SqlCall(SqlParserPos pos) { super(pos); } //~ Methods ---------------------------------------------------------------- /** * Whether this call was created by expanding a parentheses-free call to * what was syntactically an identifier. */ public boolean isExpanded() { return false; } /** * Changes the value of an operand. Allows some rewrite by * {@link SqlValidator}; use sparingly. * * @param i Operand index * @param operand Operand value */ public void setOperand(int i, SqlNode operand) { throw new UnsupportedOperationException(); } public abstract SqlOperator getOperator(); public abstract List<SqlNode> getOperandList(); @SuppressWarnings("unchecked") public <S extends SqlNode> S operand(int i) { return (S) getOperandList().get(i); } public int operandCount() { return getOperandList().size(); } public SqlNode clone(SqlParserPos pos) { return getOperator().createCall(pos, getOperandList()); } public void unparse( SqlWriter writer, int leftPrec, int rightPrec) { final SqlOperator operator = getOperator(); if (leftPrec > operator.getLeftPrec() || (operator.getRightPrec() <= rightPrec && (rightPrec != 0)) || writer.isAlwaysUseParentheses() && isA(SqlKind.EXPRESSION)) { final SqlWriter.Frame frame = writer.startList("(", ")"); operator.unparse(writer, this, 0, 0); writer.endList(frame); } else { operator.unparse(writer, this, leftPrec, rightPrec); } } /** * Validates this call. * * <p>The default implementation delegates the validation to the operator's * {@link SqlOperator#validateCall}. Derived classes may override (as do, * for example {@link SqlSelect} and {@link SqlUpdate}). */ public void validate(SqlValidator validator, SqlValidatorScope scope) { validator.validateCall(this, scope); } public void findValidOptions( SqlValidator validator, SqlValidatorScope scope, SqlParserPos pos, List<SqlMoniker> hintList) { for (SqlNode operand : getOperandList()) { if (operand instanceof SqlIdentifier) { SqlIdentifier id = (SqlIdentifier) operand; SqlParserPos idPos = id.getParserPosition(); if (idPos.toString().equals(pos.toString())) { ((SqlValidatorImpl) validator).lookupNameCompletionHints( scope, id.names, pos, hintList); return; } } } // no valid options } public <R> R accept(SqlVisitor<R> visitor) { return visitor.visit(this); } public boolean equalsDeep(SqlNode node, boolean fail) { if (node == this) { return true; } if (!(node instanceof SqlCall)) { assert !fail : this + "!=" + node; return false; } SqlCall that = (SqlCall) node; // Compare operators by name, not identity, because they may not // have been resolved yet. if (!this.getOperator().getName().equals(that.getOperator().getName())) { assert !fail : this + "!=" + node; return false; } return equalDeep(this.getOperandList(), that.getOperandList(), fail); } /** * Returns a string describing the actual argument types of a call, e.g. * "SUBSTR(VARCHAR(12), NUMBER(3,2), INTEGER)". */ protected String getCallSignature( SqlValidator validator, SqlValidatorScope scope) { List<String> signatureList = new ArrayList<String>(); for (final SqlNode operand : getOperandList()) { final RelDataType argType = validator.deriveType(scope, operand); if (null == argType) { continue; } signatureList.add(argType.toString()); } return SqlUtil.getOperatorSignature(getOperator(), signatureList); } public SqlMonotonicity getMonotonicity(SqlValidatorScope scope) { // Delegate to operator. return getOperator().getMonotonicity(this, scope); } /** * Test to see if it is the function COUNT(*) * * @return boolean true if function call to COUNT(*) */ public boolean isCountStar() { if (getOperator().isName("COUNT") && operandCount() == 1) { final SqlNode parm = operand(0); if (parm instanceof SqlIdentifier) { SqlIdentifier id = (SqlIdentifier) parm; if (id.isStar() && id.names.size() == 1) { return true; } } } return false; } public SqlLiteral getFunctionQuantifier() { return null; } } // End SqlCall.java
{ "content_hash": "8a7d0db24c7c107a8f1742c1f48f3b90", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 78, "avg_line_length": 28.410112359550563, "alnum_prop": 0.6325884912003163, "repo_name": "nvoron23/incubator-calcite", "id": "19cc16148751eb600a074ec898c1d87db4f1864c", "size": "5854", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/org/eigenbase/sql/SqlCall.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package net.beaconcontroller.topology.internal; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.*; import java.util.Collections; import org.junit.Before; import org.junit.Test; import net.beaconcontroller.core.IOFSwitch; import net.beaconcontroller.test.BeaconTestCase; import net.beaconcontroller.topology.LinkTuple; /** * * @author David Erickson (daviderickson@cs.stanford.edu) */ public class TopologyImplTest extends BeaconTestCase { public TopologyImpl getTopology() { return (TopologyImpl) getApplicationContext().getBean("topology"); } public IOFSwitch createMockSwitch(Long id) { IOFSwitch mockSwitch = createMock(IOFSwitch.class); expect(mockSwitch.getId()).andReturn(id).anyTimes(); return mockSwitch; } @Before public void setUp() throws Exception { super.setUp(); getTopology().links.clear(); getTopology().portLinks.clear(); getTopology().switchLinks.clear(); } @Test public void testAddOrUpdateLink() throws Exception { TopologyImpl topology = getTopology(); IOFSwitch sw1 = createMockSwitch(1L); IOFSwitch sw2 = createMockSwitch(2L); replay(sw1, sw2); LinkTuple lt = new LinkTuple(sw1, 2, sw2, 1); topology.addOrUpdateLink(lt); // check invariants hold assertNotNull(topology.switchLinks.get(lt.getSrc().getSw())); assertTrue(topology.switchLinks.get(lt.getSrc().getSw()).contains(lt)); assertNotNull(topology.portLinks.get(lt.getSrc())); assertTrue(topology.portLinks.get(lt.getSrc()).contains(lt)); assertNotNull(topology.portLinks.get(lt.getDst())); assertTrue(topology.portLinks.get(lt.getDst()).contains(lt)); assertTrue(topology.links.containsKey(lt)); } @Test public void testDeleteLink() throws Exception { TopologyImpl topology = getTopology(); IOFSwitch sw1 = createMockSwitch(1L); IOFSwitch sw2 = createMockSwitch(2L); replay(sw1, sw2); LinkTuple lt = new LinkTuple(sw1, 2, sw2, 1); topology.addOrUpdateLink(lt); topology.deleteLinks(Collections.singletonList(lt)); // check invariants hold assertNull(topology.switchLinks.get(lt.getSrc().getSw())); assertNull(topology.switchLinks.get(lt.getDst().getSw())); assertNull(topology.portLinks.get(lt.getSrc())); assertNull(topology.portLinks.get(lt.getDst())); assertTrue(topology.links.isEmpty()); } @Test public void testAddOrUpdateLinkToSelf() throws Exception { TopologyImpl topology = getTopology(); IOFSwitch sw1 = createMockSwitch(1L); IOFSwitch sw2 = createMockSwitch(2L); replay(sw1, sw2); LinkTuple lt = new LinkTuple(sw1, 2, sw1, 3); topology.addOrUpdateLink(lt); // check invariants hold assertNotNull(topology.switchLinks.get(lt.getSrc().getSw())); assertTrue(topology.switchLinks.get(lt.getSrc().getSw()).contains(lt)); assertNotNull(topology.portLinks.get(lt.getSrc())); assertTrue(topology.portLinks.get(lt.getSrc()).contains(lt)); assertNotNull(topology.portLinks.get(lt.getDst())); assertTrue(topology.portLinks.get(lt.getDst()).contains(lt)); assertTrue(topology.links.containsKey(lt)); } @Test public void testDeleteLinkToSelf() throws Exception { TopologyImpl topology = getTopology(); IOFSwitch sw1 = createMockSwitch(1L); replay(sw1); LinkTuple lt = new LinkTuple(sw1, 2, sw1, 3); topology.addOrUpdateLink(lt); topology.deleteLinks(Collections.singletonList(lt)); // check invariants hold assertNull(topology.switchLinks.get(lt.getSrc().getSw())); assertNull(topology.switchLinks.get(lt.getDst().getSw())); assertNull(topology.portLinks.get(lt.getSrc())); assertNull(topology.portLinks.get(lt.getDst())); assertTrue(topology.links.isEmpty()); } @Test public void testRemovedSwitch() { TopologyImpl topology = getTopology(); IOFSwitch sw1 = createMockSwitch(1L); IOFSwitch sw2 = createMockSwitch(2L); replay(sw1, sw2); LinkTuple lt = new LinkTuple(sw1, 2, sw2, 1); topology.addOrUpdateLink(lt); // Mock up our expected behavior topology.removedSwitch(sw1); verify(sw1, sw2); // check invariants hold assertNull(topology.switchLinks.get(lt.getSrc().getSw())); assertNull(topology.switchLinks.get(lt.getDst().getSw())); assertNull(topology.portLinks.get(lt.getSrc())); assertNull(topology.portLinks.get(lt.getDst())); assertTrue(topology.links.isEmpty()); } @Test public void testRemovedSwitchSelf() { TopologyImpl topology = getTopology(); IOFSwitch sw1 = createMockSwitch(1L); replay(sw1); LinkTuple lt = new LinkTuple(sw1, 2, sw1, 3); topology.addOrUpdateLink(lt); // Mock up our expected behavior topology.removedSwitch(sw1); verify(sw1); // check invariants hold assertNull(topology.switchLinks.get(lt.getSrc().getSw())); assertNull(topology.portLinks.get(lt.getSrc())); assertNull(topology.portLinks.get(lt.getDst())); assertTrue(topology.links.isEmpty()); } }
{ "content_hash": "331ec9238e0f018e373cb33561a48b57", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 79, "avg_line_length": 36.333333333333336, "alnum_prop": 0.6621694549379384, "repo_name": "bigswitch/BeaconMirror", "id": "6631d8ab1f920d2add34431c77f207e36ff97bad", "size": "5559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "net.beaconcontroller.topology.tests/src/main/java/net/beaconcontroller/topology/internal/TopologyImplTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "540825" }, { "name": "JavaScript", "bytes": "1578955" }, { "name": "Shell", "bytes": "1858" } ], "symlink_target": "" }
export const Actions = {} export const ActionCreators = {} export function addAction (actionName, action, actionCreator, sandboxName) { // Make sure the name is unique if (sandboxName) { if (typeof Actions[sandboxName] === 'function') { throw new Error(`An action called "${sandboxName}" already exists! Please pick another sandbox name!`) } Actions[sandboxName] = Actions[sandboxName] || {} ActionCreators[sandboxName] = ActionCreators[sandboxName] || {} if (Actions[sandboxName][actionName]) { throw new Error(`An action called "${actionName}" in the ${sandboxName} sandbox already exists! Please pick another action name!`) } Actions[sandboxName][actionName] = payload => action(payload) ActionCreators[sandboxName][actionName] = actionCreator return } // No need to add the action a second time. if (typeof Actions[actionName] === 'object') { throw new Error(`An action called "${actionName}" in the ${sandboxName} sandbox already exists! Please pick another action name!`) } if (Actions[actionName]) { return true } Actions[actionName] = payload => action(payload) ActionCreators[actionName] = actionCreator } export function addEffect (effectName, action, actionCreator) { // Make sure the effect name is unique if (Actions[effectName]) { throw new Error(`An action called "${effectName}" already exists! Please pick another name for this effect!`) } Actions[effectName] = payload => action(payload) ActionCreators[effectName] = actionCreator } export function removeAction (actionName, sandboxName) { if (sandboxName) { delete Actions[sandboxName][actionName] delete ActionCreators[sandboxName][actionName] return } delete Actions[actionName] delete ActionCreators[actionName] } export function reset () { for (var key in Actions) { if (Actions.hasOwnProperty(key)) { delete Actions[key] delete ActionCreators[key] } } }
{ "content_hash": "fa4dd8701ba0a9ebed56d651a4976e63", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 136, "avg_line_length": 33.93103448275862, "alnum_prop": 0.7073170731707317, "repo_name": "jumpsuit/jumpstate", "id": "92af3bfc98076c847fedecb310245a9f9ba142f0", "size": "1968", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/actions.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "18739" } ], "symlink_target": "" }
package multicast import ( "context" "fmt" "github.com/gofrs/uuid" "github.com/jmoiron/sqlx" "github.com/pkg/errors" "github.com/brocaar/lora-app-server/api" "github.com/brocaar/lora-app-server/internal/backend/networkserver" "github.com/brocaar/lora-app-server/internal/storage" "github.com/brocaar/loraserver/api/ns" "github.com/brocaar/lorawan" ) // Enqueue adds the given payload to the multicast-group queue. func Enqueue(ctx context.Context, db sqlx.Ext, multicastGroupID uuid.UUID, fPort uint8, data []byte) (uint32, error) { fCnts, err := EnqueueMultiple(ctx, db, multicastGroupID, fPort, [][]byte{data}) if err != nil { return 0, err } if len(fCnts) != 1 { return 0, fmt.Errorf("expected 1 frame-counter, got: %d", len(fCnts)) } return fCnts[0], nil } // EnqueueMultiple adds the given payloads to the multicast-group queue. func EnqueueMultiple(ctx context.Context, db sqlx.Ext, multicastGroupID uuid.UUID, fPort uint8, payloads [][]byte) ([]uint32, error) { // Get and lock multicast-group, the lock is to make sure there are no // concurrent enqueue actions for the same multicast-group, which would // result in the re-use of the same frame-counter. mg, err := storage.GetMulticastGroup(ctx, db, multicastGroupID, true, false) if err != nil { return nil, errors.Wrap(err, "get multicast-group error") } // get network-server / client n, err := storage.GetNetworkServerForMulticastGroupID(ctx, db, multicastGroupID) if err != nil { return nil, errors.Wrap(err, "get network-server error") } nsClient, err := networkserver.GetPool().Get(n.Server, []byte(n.CACert), []byte(n.TLSCert), []byte(n.TLSKey)) if err != nil { return nil, errors.Wrap(err, "get network-server client error") } var out []uint32 var devAddr lorawan.DevAddr copy(devAddr[:], mg.MulticastGroup.McAddr) fCnt := mg.MulticastGroup.FCnt for _, pl := range payloads { // encrypt payload b, err := lorawan.EncryptFRMPayload(mg.MCAppSKey, false, devAddr, fCnt, pl) if err != nil { return nil, errors.Wrap(err, "encrypt frmpayload error") } _, err = nsClient.EnqueueMulticastQueueItem(ctx, &ns.EnqueueMulticastQueueItemRequest{ MulticastQueueItem: &ns.MulticastQueueItem{ MulticastGroupId: multicastGroupID.Bytes(), FrmPayload: b, FCnt: fCnt, FPort: uint32(fPort), }, }) if err != nil { return nil, errors.Wrap(err, "enqueue multicast-queue item error") } out = append(out, fCnt) fCnt++ } return out, nil } // ListQueue lists the items in the multicast-group queue. func ListQueue(ctx context.Context, db sqlx.Ext, multicastGroupID uuid.UUID) ([]api.MulticastQueueItem, error) { mg, err := storage.GetMulticastGroup(ctx, db, multicastGroupID, false, false) if err != nil { return nil, errors.Wrap(err, "get multicast-group error") } n, err := storage.GetNetworkServerForMulticastGroupID(ctx, db, multicastGroupID) if err != nil { return nil, errors.Wrap(err, "get network-server for multicast-group error") } nsClient, err := networkserver.GetPool().Get(n.Server, []byte(n.CACert), []byte(n.TLSCert), []byte(n.TLSKey)) if err != nil { return nil, errors.Wrap(err, "get network-server client error") } resp, err := nsClient.GetMulticastQueueItemsForMulticastGroup(ctx, &ns.GetMulticastQueueItemsForMulticastGroupRequest{ MulticastGroupId: multicastGroupID.Bytes(), }) if err != nil { return nil, errors.Wrap(err, "get multicast queue-items error") } var out []api.MulticastQueueItem var devAddr lorawan.DevAddr copy(devAddr[:], mg.MulticastGroup.McAddr) for _, qi := range resp.MulticastQueueItems { b, err := lorawan.EncryptFRMPayload(mg.MCAppSKey, false, devAddr, qi.FCnt, qi.FrmPayload) if err != nil { return nil, errors.Wrap(err, "decrypt multicast queue-item error") } out = append(out, api.MulticastQueueItem{ MulticastGroupId: multicastGroupID.String(), FCnt: qi.FCnt, FPort: qi.FPort, Data: b, }) } return out, nil }
{ "content_hash": "f3065bd9d4bd9b0b380dbdb9dcd1e3e1", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 134, "avg_line_length": 31.748031496062993, "alnum_prop": 0.703125, "repo_name": "brocaar/lora-app-server", "id": "bb7a764751d2eab58cfa4c68c65d74a2df73a34d", "size": "4032", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "internal/multicast/multicast.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "63" }, { "name": "Dockerfile", "bytes": "577" }, { "name": "Go", "bytes": "744501" }, { "name": "HTML", "bytes": "5189" }, { "name": "JavaScript", "bytes": "460242" }, { "name": "Makefile", "bytes": "2810" }, { "name": "PLSQL", "bytes": "2188" }, { "name": "Shell", "bytes": "6600" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/murb/social_linker.svg?branch=master)](https://travis-ci.org/murb/social_linker) **SocialLinker solves two problems involving social networks (and search engines): proper meta-headers and proper share links.** SocialLinker is able to generate the most common share links for you, without depending on JavaScript. You should use generated links, instead of the share buttons provided by the platforms themselves, to protect your user's privacy, and this gem makes it easy for you to do so. And when using Rails, SocialLinker also solves the tedious job of getting the meta tags right. Because once you've set the SocialLinker::Subject correctly, you've also got the right ingredients for the perfect meta keywords & description, open graph variables etc. ## Installation Add this line to your application's Gemfile: ```ruby gem 'social_linker' ``` And then execute: $ bundle Or install it yourself as: $ gem install social_linker ## Usage ### Basics Initialize the subject with enough material to generate links from, such as the page's url, maybe the image url (mainly for Pinterest type-shares), a description, tags etc. For example, initialze ```ruby social_linker_subject = SocialLinker::Subject.new(media: "http://example.com/img.jpg", url: "http://example.com/", title: "Example website", description: "Example.com is the typical URL you would want to use in explanations anyway." ``` You'll get the e-mail share url by calling: ```ruby social_linker_subject.share_link(:mail) ``` Which will deliver you the following url: mailto:emailaddress?subject=Example%20website&body=Example.com%20is%20the%20typical%20URL%20you%20would%20want%20to%20use%20in%20explanations%20anyway.%0A%0Ahttp%3A%2F%2Fexample.com%2F ### Setting up the subject The supported options are: * url * media (media url, e.g. an image (shared only for Pinterest, but also used in OpenGraph headers & Twitter Cards)) * summary * description * title * tags And of a more site-global nature: * twitter_username * facebook_app_id * language * site_title_postfix (which can be hidden by setting `render_site_title_postfix` to false) I've tried to map them as good as possible to the different share tools. Sometimes by combining several values. You may also pass along link-specific parameters such as `:hashtags`, so you can control the 2-tag long string that is generated from the list of tags by default. For example: @subject = SocialLinker::Subject.new( title: "title", url: "https://murb.nl/blog", media: "https://murb.nl/image.jpg", media_dimensions: [640, 480], summary: "short summary", tags: ["key1", "key2", "key3"], ) You can also merge details later on. Let's say you want to set the global values: @subject = SocialLinker::Subject.new( site_title_postfix: ":murb:", twitter_username: 'murb', facebook_app_id: '123123123', tags: ['murb', 'ruby'] ) You might to set these defaults in a before action in your (Ruby on Rails-speak) ApplicationController. Later on you can merge details into this subject: @subject.merge!({ title: "title", url: "https://murb.nl/blog", media: "https://murb.nl/image.jpg", media_dimensions: [640, 480], summary: "short summary", tags: ["key1", "key2", "key3"] }) *Hint*, the media_dimensions are 'compatible' with the output of the Dimensions-gem: @subject.merge!({ title: @article.title, url: article_url(@article), media: @article.image.url(:inline), media_dimensions: Dimensions.dimensions(@article.image.path(:inline)), summary: @article.description, tags: @article.tag_list.to_a }) ### Creating share links Currently support is available for the following ways of sharing: :email :facebook :facebook_native :twitter :twitter_native :pinterest :google :linkedin :whatsapp Or to save you the copy-paste: [TestMailLink](mailto:emailaddress?subject=Example%20website&body=Example.com%20is%20the%20typical%20URL%20you%20would%20want%20to%20use%20in%20explanations%20anyway.%0A%0Ahttp%3A%2F%2Fexample.com%2F) #### UTM Campaign parameters By default [utm campaign parameters](https://support.google.com/analytics/answer/1033863?hl=en) are added when they are not present. You can turn this off by passing the option: `utm_parameters: false`. #### Link helper with SVG icons (Rails) Use the following to create a sharelink to Facebook social_link_to @subject, :facebook This results in a simple `<a href>` containing the share link and an svg image. This SVG image may or may not be found depending on your asset initialization, make sure that config/initializers/assets.rb contains the following line: Rails.application.config.assets.precompile += %w( social_linker/icons.svg ) (if you don't it probably will be suggested to you by Rails) If you want to change the content of the link, pass a block, e.g.: social_link_to @subject, :facebook do "Share on Facebook!" end To make sure that the icons align well, make sure to include the styling, include the following line to the head of your application.ccs file: *= require social_linker/icons ### Meta-Headers When using Ruby on Rails a few helpers have been created. Just set the following, which should give you a reasonable default. header_meta_tags(@subject, { site_title_postfix: "your sitename" # optional }) Alternatively you can also set the `site_title_post` in the `Subject` directly, as suggested in an earlier section: header_meta_tags(@subject) ## Advanced ### Reuse the SVG icons elsewhere When integrating social icons into your site, you might also want to include login options for these social networks, or access the icons for other reasons. Below is 'standard' example code of how to access image-assets in the icon <svg class="icon icon-facebook-official"> <use xlink:href="<%=image_path('social_linker/icons.svg')%>#icon-facebook"></use> </svg> *Note:* If you just want the SVG icon standalone, you can also use the `social_link_to_image` view helper: social_link_to_image :facebook Included layers: * icon-email * icon-google * icon-sticky-note-o * icon-share-square-o * icon-search * icon-heart-o * icon-heart * icon-twitter * icon-pinterest * icon-facebook * icon-facebook-unofficial * icon-linkedin * icon-whatsapp * icon-tumblr Icons have been created with the [IcoMoon App](https://icomoon.io/app) and come from the [Font Awesome](http://scripts.sil.org/OFL)-set (OFL licensed). ## Problem solving ### SVG Icons not showing up in older browsers When using SVG and serving your pages to older browsers, make sure you use something like SVG4Everyone. Include in your gemfile: source 'https://rails-assets.org' do gem 'rails-assets-svg4everybody' end and include the following line to the head of your `application.js` file: //= require svg4everybody ## TODO * Idea: maybe improve share helpers with [javascript timeout workarounds](http://stackoverflow.com/questions/7231085/how-to-fall-back-to-marketplace-when-android-custom-url-scheme-not-handled) for native alternatives (although Twitter and facebook work well) * More share methods (pull request welcome) ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/murb/social_linker. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
{ "content_hash": "34b15cb777da84defbe50090c8f61340", "timestamp": "", "source": "github", "line_count": 254, "max_line_length": 324, "avg_line_length": 32.78740157480315, "alnum_prop": 0.7329490874159462, "repo_name": "murb/social_linker", "id": "c8df93f307a04547d218852ee5a61eae6262fd8f", "size": "8344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2088" }, { "name": "Ruby", "bytes": "48978" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
namespace Cik.PP.Web.Data { using System; public class Story { public Guid Id { get; set; } public string Role { get; set; } public string Purpose { get; set; } public string Result { get; set; } public string Note { get; set; } public DateTime Created { get; set; } public DateTime? Modified { get; set; } public string CreatedBy { get; set; } public Guid? GameId { get; set; } public Game Game { get; set; } } }
{ "content_hash": "0593332bae7c264c0223229a617d68fb", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 47, "avg_line_length": 19.296296296296298, "alnum_prop": 0.5431861804222649, "repo_name": "TRex22/magazine-website-mvc-5", "id": "8dae8a4372464bf6c3ac1b59b326fd944d9176e1", "size": "523", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "_oldprojects/planning-poker/Cik.PlanningPoker.WebSolution/Cik.PP.Web/Data/Story.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace Acf\SecurityBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\ResetType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * * @author sasedev <seif.salah@gmail.com> */ class LoginTForm extends AbstractType { /** * Form builder * * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('username', TextType::class, array( 'label' => 'User.username.label' )); $builder->add('password', PasswordType::class, array( 'label' => 'User.password.label' )); $builder->add('remember_me', CheckboxType::class, array( 'label' => 'User.rememberme.label', 'required' => false )); $builder->add('target_path', HiddenType::class, array( 'required' => false )); $builder->add('submit', SubmitType::class, array( 'label' => 'action.btnLogin' )); $builder->add('reset', ResetType::class, array( 'label' => 'action.btnReset' )); } /** */ public function getName() { return 'LoginForm'; } /** * * {@inheritdoc} @see AbstractType::getBlockPrefix() */ public function getBlockPrefix() { return $this->getName(); } /** * get the default options * * @return multitype:string multitype:string */ public function getDefaultOptions() { return array( 'csrf_protection' => false ); } /** * * {@inheritdoc} @see AbstractType::configureOptions() */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults($this->getDefaultOptions()); } }
{ "content_hash": "e691fd741ed733fa141ea4e388471202", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 76, "avg_line_length": 24.87912087912088, "alnum_prop": 0.6086572438162544, "repo_name": "sasedev/acf-expert", "id": "f25299a27bbe2de21afb765ba6f2d37b0e74595a", "size": "2264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Acf/SecurityBundle/Form/LoginTForm.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "690156" }, { "name": "CoffeeScript", "bytes": "50493" }, { "name": "HTML", "bytes": "2095168" }, { "name": "JavaScript", "bytes": "9978754" }, { "name": "Makefile", "bytes": "743" }, { "name": "PHP", "bytes": "4506157" }, { "name": "PLpgSQL", "bytes": "92638" }, { "name": "Shell", "bytes": "960" } ], "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): # Adding model 'UserStar' db.create_table('quotes_userstar', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='stars', to=orm['auth.User'])), ('quote', self.gf('django.db.models.fields.related.ForeignKey')(related_name='starts', to=orm['quotes.Quote'])), )) db.send_create_signal('quotes', ['UserStar']) # Adding field 'Quote.star_count' db.add_column('quotes_quote', 'star_count', self.gf('django.db.models.fields.IntegerField')(default=0), keep_default=False) def backwards(self, orm): # Deleting model 'UserStar' db.delete_table('quotes_userstar') # Deleting field 'Quote.star_count' db.delete_column('quotes_quote', 'star_count') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'quotes.author': { 'Meta': {'object_name': 'Author'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}) }, 'quotes.quote': { 'Meta': {'object_name': 'Quote'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'quotes'", 'null': 'True', 'to': "orm['quotes.Author']"}), 'body': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '5'}), 'metadata': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'published_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'star_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'quotes'", 'null': 'True', 'to': "orm['auth.User']"}) }, 'quotes.userstar': { 'Meta': {'object_name': 'UserStar'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'quote': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'starts'", 'to': "orm['quotes.Quote']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stars'", 'to': "orm['auth.User']"}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) } } complete_apps = ['quotes']
{ "content_hash": "6cba466a55821584b57cd2521060549d", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 182, "avg_line_length": 65.47222222222223, "alnum_prop": 0.5481544336020365, "repo_name": "rollstudio/DjangoDash", "id": "69d845cfa2db1fe6977a5cc938cb5281040383e5", "size": "7095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quotes/quotes/migrations/0006_auto__add_userstar__add_field_quote_star_count.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2587" }, { "name": "Python", "bytes": "43606" } ], "symlink_target": "" }
package com.yevster.spdxtra; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.apache.jena.query.Dataset; import org.apache.jena.query.DatasetFactory; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.StmtIterator; import org.junit.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.yevster.spdxtra.Write.ModelUpdate; import com.yevster.spdxtra.model.Creator; import com.yevster.spdxtra.model.SpdxDocument; public class TestDocumentOperations { @Test public void createDocument() { final String id = "SPDXRef-Wickendess"; final String baseUrl = "http://example.org"; final String name = "Que paso?"; Dataset dataset = DatasetFactory.createTxnMem(); ModelUpdate creation = Write.New.document(baseUrl, id, name, Creator.person("Albert Einstein", Optional.of("aEinstein@princeton.edu")), Creator.tool("SpdXtra"), Creator.organization("Aperture Science, LLC.", Optional.empty())); assertNotNull(creation); Write.applyUpdatesInOneTransaction(dataset, creation, Write.Document.comment(baseUrl, id, "Doc comment"), Write.Document.creationComment(baseUrl, id, "Creation comment")); SpdxDocument document = Read.Document.get(dataset); assertNotNull(document); assertEquals(baseUrl + "#" + id, document.getUri()); assertEquals(id, document.getSpdxId()); assertEquals(name, document.getName()); assertEquals(Constants.DEFAULT_SPDX_VERSION, document.getSpecVersion()); assertEquals(Optional.of("Doc comment"), document.getComment()); assertEquals(Optional.of("Creation comment"), document.getCreationInfo().getComment()); // Verify creation date/time ZonedDateTime creationDateTime = document.getCreationInfo().getCreationDate(); assertNotNull(creationDateTime); assertTrue(creationDateTime.isAfter(ZonedDateTime.now().minusHours(1))); // The data license should have no properties, just the URI; assertEquals("http://spdx.org/licenses/CC0-1.0", document.getPropertyAsResource(SpdxProperties.DATA_LICENSE).get().getURI()); // Verify creation Info Resource creationInfo = document.getPropertyAsResource(SpdxProperties.CREATION_INFO).get(); assertNotNull(creationInfo); StmtIterator creatorStatements = creationInfo.listProperties(SpdxProperties.CREATOR); Set<String> creatorStrings = stmtIteratorToStringSet(creatorStatements); Set<String> expectedCreators = ImmutableSet.of("Person: Albert Einstein (aEinstein@princeton.edu)", "Tool: SpdXtra", "Organization: Aperture Science, LLC. ()"); assertEquals("Unexpected creator info", new HashSet<String>(), Sets.symmetricDifference(expectedCreators, creatorStrings)); //Try the document accessor assertEquals("Unexpected creator info", new HashSet<String>(), Sets.symmetricDifference(expectedCreators, document.getCreationInfo().getCreators())); } @Test public void testModifyCreationDate() { Dataset dataset = TestUtils.getDefaultDataSet(); SpdxDocument document = Read.Document.get(dataset); ZonedDateTime newCreationDate = ZonedDateTime.of(1976, 7, 4, 9, 1, 2, 3, ZoneId.of("America/New_York")); // Expect the date to be stored in UTC, without nanoseconds. ZonedDateTime expectedCreationDate = ZonedDateTime.of(1976, 7, 4, 13, 1, 2, 0, ZoneId.of("UTC")); ModelUpdate update = Write.Document.creationDate(document, newCreationDate); Write.applyUpdatesInOneTransaction(dataset, ImmutableList.of(update)); document = Read.Document.get(dataset); assertEquals(expectedCreationDate, document.getCreationInfo().getCreationDate()); } @Test public void testModifySpecVersion() { Dataset dataset = DatasetFactory.createTxnMem(); final String baseUrl = "http://foo"; final String spdxId = "SPDXRef-bar"; final String name = "foobar"; Write.applyUpdatesInOneTransaction(dataset, Write.New.document(baseUrl, spdxId, name, Creator.person("Myself", Optional.empty())), Write.Document.specVersion(baseUrl, spdxId, "666. Yep, you're doomed. DOOOOOMED!")); SpdxDocument document = Read.Document.get(dataset); assertEquals("666. Yep, you're doomed. DOOOOOMED!", document.getSpecVersion()); } private static Set<String> stmtIteratorToStringSet(StmtIterator it) { Set<String> result = new HashSet<>(); while (it.hasNext()) { result.add(it.next().getString()); } return result; } }
{ "content_hash": "1ae07a076750c0eb2776613505ee22bf", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 151, "avg_line_length": 41.11607142857143, "alnum_prop": 0.7663409337676439, "repo_name": "yevster/spdxtra", "id": "bb21231a43d2a7d7242d11aea1ae504e9ce243ce", "size": "4605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/yevster/spdxtra/TestDocumentOperations.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "94342" } ], "symlink_target": "" }
package com.sun.org.omg.CORBA; /** * com/sun/org/omg/CORBA/_IDLTypeStub.java * Generated by the IDL-to-Java compiler (portable), version "3.0" * from ir.idl * Thursday, May 6, 1999 1:51:45 AM PDT */ // This file has been manually _CHANGED_ // _CHANGED_ //public class _IDLTypeStub extends org.omg.CORBA.portable.ObjectImpl implements com.sun.org.omg.CORBA.IDLType public class _IDLTypeStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.IDLType { // Constructors // NOTE: If the default constructor is used, the // object is useless until _set_delegate (...) // is called. public _IDLTypeStub () { super (); } public _IDLTypeStub (org.omg.CORBA.portable.Delegate delegate) { super (); _set_delegate (delegate); } public org.omg.CORBA.TypeCode type () { org.omg.CORBA.portable.InputStream _in = null; try { org.omg.CORBA.portable.OutputStream _out = _request ("_get_type", true); _in = _invoke (_out); org.omg.CORBA.TypeCode __result = _in.read_TypeCode (); return __result; } catch (org.omg.CORBA.portable.ApplicationException _ex) { _in = _ex.getInputStream (); String _id = _ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException _rm) { return type (); } finally { _releaseReply (_in); } } // type // read interface // _CHANGED_ //public com.sun.org.omg.CORBA.DefinitionKind def_kind () public org.omg.CORBA.DefinitionKind def_kind () { org.omg.CORBA.portable.InputStream _in = null; try { org.omg.CORBA.portable.OutputStream _out = _request ("_get_def_kind", true); _in = _invoke (_out); // _CHANGED_ //com.sun.org.omg.CORBA.DefinitionKind __result = com.sun.org.omg.CORBA.DefinitionKindHelper.read (_in); org.omg.CORBA.DefinitionKind __result = com.sun.org.omg.CORBA.DefinitionKindHelper.read (_in); return __result; } catch (org.omg.CORBA.portable.ApplicationException _ex) { _in = _ex.getInputStream (); String _id = _ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException _rm) { return def_kind (); } finally { _releaseReply (_in); } } // def_kind // write interface public void destroy () { org.omg.CORBA.portable.InputStream _in = null; try { org.omg.CORBA.portable.OutputStream _out = _request ("destroy", true); _in = _invoke (_out); } catch (org.omg.CORBA.portable.ApplicationException _ex) { _in = _ex.getInputStream (); String _id = _ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException _rm) { destroy (); } finally { _releaseReply (_in); } } // destroy // Type-specific CORBA::Object operations private static String[] __ids = { "IDL:omg.org/CORBA/IDLType:1.0", "IDL:omg.org/CORBA/IRObject:1.0"}; public String[] _ids () { return (String[])__ids.clone (); } private void readObject (java.io.ObjectInputStream s) { try { String str = s.readUTF (); org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init ().string_to_object (str); org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); _set_delegate (delegate); } catch (java.io.IOException e) {} } private void writeObject (java.io.ObjectOutputStream s) { try { String str = org.omg.CORBA.ORB.init ().object_to_string (this); s.writeUTF (str); } catch (java.io.IOException e) {} } } // class _IDLTypeStub
{ "content_hash": "603522b218f46e9afa2d6c5d1df5ffc0", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 118, "avg_line_length": 32.96, "alnum_prop": 0.5633495145631068, "repo_name": "rokn/Count_Words_2015", "id": "e1a5b8635f960a8829cc7818ad08d2b9e3ab4eab", "size": "5332", "binary": false, "copies": "65", "ref": "refs/heads/master", "path": "testing/openjdk/corba/src/share/classes/com/sun/org/omg/CORBA/_IDLTypeStub.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
<!-- Licensed to Jasig under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Jasig licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns="http://www.jasig.org/uportal/web/skin" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.jasig.org/uportal/web/skin https://source.jasig.org/schemas/resource-server/skin-configuration/skin-configuration-v1.2.xsd"> <js included="plain" resource="true">/rs/jquery/1.6.4/jquery-1.6.4.js</js> <js included="aggregated" resource="true">/rs/jquery/1.6.4/jquery-1.6.4.min.js</js> <js included="plain" resource="true">/rs/underscore/1.3.3/underscore-1.3.3.js</js> <js included="aggregated" resource="true">/rs/underscore/1.3.3/underscore-1.3.3.min.js</js> <js included="plain" resource="true">/rs/backbone/0.9.2/backbone-0.9.2.js</js> <js included="aggregated" resource="true">/rs/backbone/0.9.2/backbone-0.9.2.min.js</js> <js included="plain" resource="true">/rs/jqueryui/1.8.13/jquery-ui-1.8.13.js</js> <js included="aggregated" resource="true">/rs/jqueryui/1.8.13/jquery-ui-1.8.13.min.js</js> <js included="plain" resource="true">/rs/fluid/1.4.0/js/fluid-all-1.4.0.js</js> <js included="aggregated" resource="true">/rs/fluid/1.4.0/js/fluid-all-1.4.0.min.js</js> <js>scripts/news.js</js> </resources>
{ "content_hash": "95291a4b054806efa9525ffd7d6f71b0", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 159, "avg_line_length": 47.42857142857143, "alnum_prop": 0.7073293172690763, "repo_name": "chomman/uPortal", "id": "4be388ef5f70e568e1d0e101377e915ff5543956", "size": "1992", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apache-tomcat-6.0.35/webapps/NewsReaderPortlet/skin.xml", "mode": "33188", "license": "apache-2.0", "language": [], "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.4"/> <title>Requirements on range concept</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="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!-- end header part --> <!-- Generated by Doxygen 1.8.4 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="index.html">Main Page</a></li><li class="navelem"><a class="el" href="a00007.html">TBB concepts</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Requirements on range concept </div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><p>Class <code>R</code> implementing the concept of range must define:</p> <ul> <li><div class="fragment"><div class="line">R::R( <span class="keyword">const</span> R&amp; ); </div> </div><!-- fragment --> Copy constructor</li> <li><div class="fragment"><div class="line">R::~R(); </div> </div><!-- fragment --> Destructor</li> <li><div class="fragment"><div class="line"><span class="keywordtype">bool</span> R::is_divisible() <span class="keyword">const</span>; </div> </div><!-- fragment --> True if range can be partitioned into two subranges</li> <li><div class="fragment"><div class="line"><span class="keywordtype">bool</span> R::empty() <span class="keyword">const</span>; </div> </div><!-- fragment --> True if range is empty</li> <li><div class="fragment"><div class="line">R::R( R&amp; r, split ); </div> </div><!-- fragment --> Split range <code>r</code> into two subranges. </li> </ul> </div></div><!-- contents --> <hr> <p></p> Copyright &copy; 2005-2018 Intel Corporation. All Rights Reserved. <p></p> Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are registered trademarks or trademarks of Intel Corporation or its subsidiaries in the United States and other countries. <p></p> * Other names and brands may be claimed as the property of others.
{ "content_hash": "307efb3e041fc3aa70bc3166cc1ca6e7", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 151, "avg_line_length": 49.813559322033896, "alnum_prop": 0.6549846886696156, "repo_name": "gallenmu/MoonGen", "id": "aefe391cbf3971b3cad6d6124aba8c98dbb901f7", "size": "2939", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libmoon/deps/tbb/doc/html/a00001.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "40297" }, { "name": "Batchfile", "bytes": "37719" }, { "name": "C", "bytes": "33365116" }, { "name": "C++", "bytes": "7379414" }, { "name": "CMake", "bytes": "40367" }, { "name": "CSS", "bytes": "29761" }, { "name": "HTML", "bytes": "438911" }, { "name": "Java", "bytes": "14386" }, { "name": "JavaScript", "bytes": "17535" }, { "name": "Lua", "bytes": "3003403" }, { "name": "Makefile", "bytes": "784844" }, { "name": "NASL", "bytes": "76961" }, { "name": "Objective-C", "bytes": "9757" }, { "name": "PHP", "bytes": "21273" }, { "name": "Pascal", "bytes": "15199" }, { "name": "Python", "bytes": "234766" }, { "name": "Roff", "bytes": "5795" }, { "name": "SWIG", "bytes": "5546" }, { "name": "Shell", "bytes": "143025" }, { "name": "SmPL", "bytes": "1798" } ], "symlink_target": "" }
<?php ?> <div class="container"> <h3><?php echo lang('PER_CHARTS'); ?></h3><hr> <button type="submit" class="btn btn-primry" id="coinsupply"><?php echo lang('COIN_SUPPLY'); ?> <i class="fa fa-caret-down"></i></button> <div id="coinsupply_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#coinsupply_container').hide(); coinsupply=0; $( "#coinsupply" ).click(function() { if (coinsupply==0) { $('#coinsupply_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#coinsupply').html('<?php echo lang('COIN_SUPPLY'); ?> <i class="fa fa-caret-up"></i>'); $('#coinsupply_container').show(); get_coinsupply(); coinsupply=1; } else { $('#coinsupply').html('<?php echo lang('COIN_SUPPLY'); ?> <i class="fa fa-caret-down"></i>'); $('#coinsupply_container').hide(500); $('#coinsupply_container').html(''); coinsupply=0; } }); function get_coinsupply() { $.getJSON('/charts/get_coinsupply.php?callback=?', function (data) { // Create the chart $('#coinsupply_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('COIN_SUPPLY'); ?>' }, series : [{ name : 'EMC', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="powdifficulty"><?php echo lang('POW_DIFFICULTY'); ?> <i class="fa fa-caret-down"></i></button> <div id="powdifficulty_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#powdifficulty_container').hide(); powdifficulty=0; $( "#powdifficulty" ).click(function() { if (powdifficulty==0) { $('#powdifficulty_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#powdifficulty').html('<?php echo lang('POW_DIFFICULTY'); ?> <i class="fa fa-caret-up"></i>'); $('#powdifficulty_container').show(); get_powdifficulty(); powdifficulty=1; } else { $('#powdifficulty').html('<?php echo lang('POW_DIFFICULTY'); ?> <i class="fa fa-caret-down"></i>'); $('#powdifficulty_container').hide(500); $('#powdifficulty_container').html(''); powdifficulty=0; } }); function get_powdifficulty() { $.getJSON('/charts/get_powdifficulty.php?callback=?', function (data) { // Create the chart $('#powdifficulty_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('POW_DIFFICULTY'); ?>' }, series : [{ name : '<?php echo lang('POW_DIFF'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="powhashrate">PoW Hashrate <i class="fa fa-caret-down"></i></button> <div id="powhashrate_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#powhashrate_container').hide(); powhashrate=0; $( "#powhashrate" ).click(function() { if (powhashrate==0) { $('#powhashrate_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#powhashrate').html('PoW Hashrate <i class="fa fa-caret-up"></i>'); $('#powhashrate_container').show(); get_powhashrate(); powhashrate=1; } else { $('#powhashrate').html('PoW Hashrate <i class="fa fa-caret-down"></i>'); $('#powhashrate_container').hide(500); $('#powhashrate_container').html(''); powhashrate=0; } }); function get_powhashrate() { $.getJSON('/charts/get_powhashrate.php?callback=?', function (data) { // Create the chart $('#powhashrate_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : 'PoW Hashrate' }, series : [{ name : 'TH/s', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="posdifficulty"><?php echo lang('POS_DIFFICULTY'); ?> <i class="fa fa-caret-down"></i></button> <div id="posdifficulty_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#posdifficulty_container').hide(); posdifficulty=0; $( "#posdifficulty" ).click(function() { if (posdifficulty==0) { $('#posdifficulty_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#posdifficulty').html('<?php echo lang('POS_DIFFICULTY'); ?> <i class="fa fa-caret-up"></i>'); $('#posdifficulty_container').show(); get_posdifficulty(); posdifficulty=1; } else { $('#posdifficulty').html('<?php echo lang('POS_DIFFICULTY'); ?> <i class="fa fa-caret-down"></i>'); $('#posdifficulty_container').hide(500); $('#posdifficulty_container').html(''); posdifficulty=0; } }); function get_posdifficulty() { $.getJSON('/charts/get_posdifficulty.php?callback=?', function (data) { // Create the chart $('#posdifficulty_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('POS_DIFFICULTY'); ?>' }, series : [{ name : '<?php echo lang('POS_DIFF'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="avgcoinage"><?php echo lang('AVG_AGE'); ?> <i class="fa fa-caret-down"></i></button> <div id="avgcoinage_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#avgcoinage_container').hide(); avgcoinage=0; $( "#avgcoinage" ).click(function() { if (avgcoinage==0) { $('#avgcoinage_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#avgcoinage').html('<?php echo lang('AVG_AGE'); ?> <i class="fa fa-caret-up"></i>'); $('#avgcoinage_container').show(); get_avgcoinage(); avgcoinage=1; } else { $('#avgcoinage').html('<?php echo lang('AVG_AGE'); ?> <i class="fa fa-caret-down"></i>'); $('#avgcoinage_container').hide(500); $('#avgcoinage_container').html(''); avgcoinage=0; } }); function get_avgcoinage() { $.getJSON('/charts/get_avgcoinage.php?callback=?', function (data) { // Create the chart $('#avgcoinage_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('AVG_AGE'); ?>' }, series : [{ name : '<?php echo lang('COIN_AGE'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="coinage"><?php echo lang('TOTAL_AGE'); ?> <i class="fa fa-caret-down"></i></button> <div id="coinage_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#coinage_container').hide(); coinage=0; $( "#coinage" ).click(function() { if (coinage==0) { $('#coinage_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#coinage').html('<?php echo lang('TOTAL_AGE'); ?> <i class="fa fa-caret-up"></i>'); $('#coinage_container').show(); get_coinage(); coinage=1; } else { $('#coinage').html('<?php echo lang('TOTAL_AGE'); ?> <i class="fa fa-caret-down"></i>'); $('#coinage_container').hide(500); $('#coinage_container').html(''); coinage=0; } }); function get_coinage() { $.getJSON('/charts/get_totalcoinage.php?callback=?', function (data) { // Create the chart $('#coinage_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('TOTAL_AGE'); ?>' }, series : [{ name : '<?php echo lang('COIN_AGE'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="addressinuse"><?php echo lang('USED_ADDRESSES'); ?> <i class="fa fa-caret-down"></i></button> <div id="addressinuse_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#addressinuse_container').hide(); addressinuse=0; $( "#addressinuse" ).click(function() { if (addressinuse==0) { $('#addressinuse_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#addressinuse').html('<?php echo lang('USED_ADDRESSES'); ?> <i class="fa fa-caret-up"></i>'); $('#addressinuse_container').show(); get_addressinuse(); addressinuse=1; } else { $('#addressinuse').html('<?php echo lang('USED_ADDRESSES'); ?> <i class="fa fa-caret-down"></i>'); $('#addressinuse_container').hide(500); $('#addressinuse_container').html(''); addressinuse=0; } }); function get_addressinuse() { $.getJSON('/charts/get_usedaddresses.php?callback=?', function (data) { // Create the chart $('#addressinuse_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('USED_ADDRESSES'); ?>' }, series : [{ name : '<?php echo lang('USED_ADDRESSES'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 0 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="addressunused"><?php echo lang('UNUSED_ADDRESSES'); ?> <i class="fa fa-caret-down"></i></button> <div id="addressunused_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#addressunused_container').hide(); addressunused=0; $( "#addressunused" ).click(function() { if (addressunused==0) { $('#addressunused_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#addressunused').html('<?php echo lang('UNUSED_ADDRESSES'); ?> <i class="fa fa-caret-up"></i>'); $('#addressunused_container').show(); get_addressunused(); addressunused=1; } else { $('#addressunused').html('<?php echo lang('UNUSED_ADDRESSES'); ?> <i class="fa fa-caret-down"></i>'); $('#addressunused_container').hide(500); $('#addressunused_container').html(''); addressunused=0; } }); function get_addressunused() { $.getJSON('/charts/get_unusedaddresses.php?callback=?', function (data) { // Create the chart $('#addressunused_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('UNUSED_ADDRESSES'); ?>' }, series : [{ name : '<?php echo lang('UNUSED_ADDRESSES'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 0 } }], credits: { enabled: false }, }); }); }; </script> <h3><?php echo lang('AVERAGE_CHARTS'); ?> <small><?php echo lang('DAILY_SUMMARY'); ?></small></h3><hr> <button type="submit" class="btn btn-primry" id="transactions"><?php echo lang('TRANSACTIONS_TRANSACTIONS'); ?> <i class="fa fa-caret-down"></i></button> <i class="text-muted"><sub><?php echo lang('TX_ONLY'); ?></sub></i> <div id="transactions_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#transactions_container').hide(); transactions=0; $( "#transactions" ).click(function() { if (transactions==0) { $('#transactions_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#transactions').html('<?php echo lang('TRANSACTIONS_TRANSACTIONS'); ?> <i class="fa fa-caret-up"></i>'); $('#transactions_container').show(); get_transactions(); transactions=1; } else { $('#transactions').html('<?php echo lang('TRANSACTIONS_TRANSACTIONS'); ?> <i class="fa fa-caret-down"></i>'); $('#transactions_container').hide(500); $('#transactions_container').html(''); transactions=0; } }); function get_transactions() { $.getJSON('/charts/get_transactions.php?callback=?', function (data) { // Create the chart $('#transactions_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('TRANSACTIONS_TRANSACTIONS'); ?>' }, series : [{ name : 'Tx', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 0 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="dailycoindays"><?php echo lang('COIN_DESTROYED'); ?> <i class="fa fa-caret-down"></i></button> <i class="text-muted"><sub><?php echo lang('TX_ONLY'); ?></sub></i> <div id="dailycoindays_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#dailycoindays_container').hide(); dailycoindays=0; $( "#dailycoindays" ).click(function() { if (dailycoindays==0) { $('#dailycoindays_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#dailycoindays').html('<?php echo lang('COIN_DESTROYED'); ?> <i class="fa fa-caret-up"></i>'); $('#dailycoindays_container').show(); get_dailycoindays(); dailycoindays=1; } else { $('#dailycoindays').html('<?php echo lang('COIN_DESTROYED'); ?> <i class="fa fa-caret-down"></i>'); $('#dailycoindays_container').hide(500); $('#dailycoindays_container').html(''); dailycoindays=0; } }); function get_dailycoindays() { $.getJSON('/charts/get_dailycoindays.php?callback=?', function (data) { // Create the chart $('#dailycoindays_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('COIN_DESTROYED'); ?>' }, series : [{ name : '<?php echo lang('DAYS_DAYS'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="timebetweenblocks"><?php echo lang('MINUTES_BLOCKS'); ?> <i class="fa fa-caret-down"></i></button> <div id="timebetweenblocks_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#timebetweenblocks_container').hide(); timebetweenblocks=0; $( "#timebetweenblocks" ).click(function() { if (timebetweenblocks==0) { $('#timebetweenblocks_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#timebetweenblocks').html('<?php echo lang('MINUTES_BLOCKS'); ?> <i class="fa fa-caret-up"></i>'); $('#timebetweenblocks_container').show(); get_timebetweenblocks(); timebetweenblocks=1; } else { $('#timebetweenblocks').html('<?php echo lang('MINUTES_BLOCKS'); ?> <i class="fa fa-caret-down"></i>'); $('#timebetweenblocks_container').hide(500); $('#timebetweenblocks_container').html(''); timebetweenblocks=0; } }); function get_timebetweenblocks() { $.getJSON('/charts/get_timebetweenblocks.php?callback=?', function (data) { // Create the chart $('#timebetweenblocks_container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : '<?php echo lang('MINUTES_BLOCKS'); ?>' }, series : [{ name : '<?php echo lang('MINUTES_MINUTES'); ?>', color: '#8d2d9e', data : data, tooltip: { valueDecimals: 2 } }], credits: { enabled: false }, }); }); }; </script> <button type="submit" class="btn btn-primry" id="powposblocks"><?php echo lang('POW_BLOCKS'); ?> <i class="fa fa-caret-down"></i></button> <div id="powposblocks_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#powposblocks_container').hide(); powposblocks=0; $( "#powposblocks" ).click(function() { if (powposblocks==0) { $('#powposblocks_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#powposblocks').html('<?php echo lang('POW_BLOCKS'); ?> <i class="fa fa-caret-up"></i>'); $('#powposblocks_container').show(); get_powposblocks(); powposblocks=1; } else { $('#powposblocks').html('<?php echo lang('POW_BLOCKS'); ?> <i class="fa fa-caret-down"></i>'); $('#powposblocks_container').hide(500); $('#powposblocks_container').html(''); powposblocks=0; } }); function get_powposblocks() { var seriesOptions = [], seriesCounter = 0, names = ['PoW', 'PoS'], // create the chart when all data is loaded createChart = function () { $('#powposblocks_container').highcharts('StockChart', { colors: ['#FA5858', '#01DF01'], rangeSelector: { selected: 1 }, title : { text : '<?php echo lang('POW_BLOCKS'); ?>' }, yAxis: { floor:0 }, tooltip: { pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', valueDecimals: 2 }, series: seriesOptions }); }; $.each(names, function (i, name) { $.getJSON('/charts/get_powposblocks.php?filename=' + name.toLowerCase() + '&callback=?', function (data) { seriesOptions[i] = { name: name, data: data }; seriesCounter += 1; if (seriesCounter === names.length) { createChart(); } }); }); }; </script> <button type="submit" class="btn btn-primry" id="powposmint"><?php echo lang('POW_MINTED'); ?> <i class="fa fa-caret-down"></i></button> <div id="powposmint_container" style="width:100%; height:375px; text-align:center;"></div><br><hr> <script type="text/javascript"> $('#powposmint_container').hide(); powposmint=0; $( "#powposmint" ).click(function() { if (powposmint==0) { $('#powposmint_container').html('<i class="fa fa-spinner fa-3x fa-pulse"></i>'); $('#powposmint').html('<?php echo lang('POW_MINTED'); ?> <i class="fa fa-caret-up"></i>'); $('#powposmint_container').show(); get_powposmint(); powposmint=1; } else { $('#powposmint').html('<?php echo lang('POW_MINTED'); ?> <i class="fa fa-caret-down"></i>'); $('#powposmint_container').hide(500); $('#powposmint_container').html(''); powposmint=0; } }); function get_powposmint() { var seriesOptions = [], seriesCounter = 0, names = ['PoW', 'PoS'], // create the chart when all data is loaded createChart = function () { $('#powposmint_container').highcharts('StockChart', { colors: ['#FA5858', '#01DF01'], rangeSelector: { selected: 1 }, title : { text : '<?php echo lang('POW_MINTED'); ?>' }, yAxis: { floor:0 }, tooltip: { pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', valueDecimals: 2 }, series: seriesOptions }); }; $.each(names, function (i, name) { $.getJSON('/charts/get_powposmint.php?filename=' + name.toLowerCase() + '&callback=?', function (data) { seriesOptions[i] = { name: name, data: data }; seriesCounter += 1; if (seriesCounter === names.length) { createChart(); } }); }); }; </script> </div>
{ "content_hash": "d1eac15b25c8c30af8df4fbe45f3dd4a", "timestamp": "", "source": "github", "line_count": 717, "max_line_length": 221, "avg_line_length": 29.86192468619247, "alnum_prop": 0.5362197001541263, "repo_name": "Valermos/emercoin-blockchain-explorer", "id": "40bd3492d72c9322690940205697fe7f927b2cd3", "size": "21411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/chart.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "57641" }, { "name": "HTML", "bytes": "116199" }, { "name": "JavaScript", "bytes": "3017775" }, { "name": "PHP", "bytes": "322193" } ], "symlink_target": "" }
package org.osgi.service.wireadmin; /** * Defines standard names for {@code Wire} properties, wire filter attributes, * Consumer and Producer service properties. * * @noimplement * @author $Id$ */ public interface WireConstants { /** * {@code Wire} property key (named {@code wireadmin.pid}) specifying the * persistent identity (PID) of this {@code Wire} object. * * <p> * Each {@code Wire} object has a PID to allow unique and persistent * identification of a specific {@code Wire} object. The PID must be * generated by the {@link WireAdmin} service when the {@code Wire} object * is created. * * <p> * This wire property is automatically set by the Wire Admin service. The * value of the property must be of type {@code String}. */ public final static String WIREADMIN_PID = "wireadmin.pid"; /** * A service registration property for a Producer service that is composite. * It contains the names of the composite Consumer services it can * interoperate with. Interoperability exists when any name in this array * matches any name in the array set by the Consumer service. The type of * this property must be {@code String[]}. */ public final static String WIREADMIN_PRODUCER_COMPOSITE = "wireadmin.producer.composite"; /** * A service registration property for a Consumer service that is composite. * It contains the names of the composite Producer services it can cooperate * with. Interoperability exists when any name in this array matches any * name in the array set by the Producer service. The type of this property * must be {@code String[]}. */ public final static String WIREADMIN_CONSUMER_COMPOSITE = "wireadmin.consumer.composite"; /** * Service registration property key (named {@code wireadmin.producer.scope} * ) specifying a list of names that may be used to define the scope of this * {@code Wire} object. A Producer service should set this service property * when it can produce more than one kind of value. This property is only * used during registration, modifying the property must not have any effect * of the {@code Wire} object's scope. Each name in the given list mist have * {@code WirePermission[name,PRODUCE]} or else is ignored. The type of this * service registration property must be {@code String[]}. * * @see Wire#getScope() * @see #WIREADMIN_CONSUMER_SCOPE */ public final static String WIREADMIN_PRODUCER_SCOPE = "wireadmin.producer.scope"; /** * Service registration property key (named {@code wireadmin.consumer.scope} * ) specifying a list of names that may be used to define the scope of this * {@code Wire} object. A {@code Consumer} service should set this service * property when it can produce more than one kind of value. This property * is only used during registration, modifying the property must not have * any effect of the {@code Wire} object's scope. Each name in the given * list mist have {@code WirePermission[name,CONSUME]} or else is ignored. * The type of this service registration property must be {@code String[]}. * * @see Wire#getScope() * @see #WIREADMIN_PRODUCER_SCOPE */ public final static String WIREADMIN_CONSUMER_SCOPE = "wireadmin.consumer.scope"; /** * Matches all scope names. */ public final static String WIREADMIN_SCOPE_ALL[] = {"*"}; /** * {@code Wire} property key (named {@code wireadmin.producer.pid}) * specifying the {@code service.pid} of the associated Producer service. * * <p> * This wire property is automatically set by the WireAdmin service. The * value of the property must be of type {@code String}. */ public final static String WIREADMIN_PRODUCER_PID = "wireadmin.producer.pid"; /** * {@code Wire} property key (named {@code wireadmin.consumer.pid}) * specifying the {@code service.pid} of the associated Consumer service. * * <p> * This wire property is automatically set by the Wire Admin service. The * value of the property must be of type {@code String}. */ public final static String WIREADMIN_CONSUMER_PID = "wireadmin.consumer.pid"; /** * {@code Wire} property key (named {@code wireadmin.filter}) specifying a * filter used to control the delivery rate of data between the Producer and * the Consumer service. * * <p> * This property should contain a filter as described in the {@code Filter} * class. The filter can be used to specify when an updated value from the * Producer service should be delivered to the Consumer service. In many * cases the Consumer service does not need to receive the data with the * same rate that the Producer service can generate data. This property can * be used to control the delivery rate. * <p> * The filter can use a number of predefined attributes that can be used to * control the delivery of new data values. If the filter produces a match * upon the wire filter attributes, the Consumer service should be notified * of the updated data value. * <p> * If the Producer service was registered with the * {@link #WIREADMIN_PRODUCER_FILTERS} service property indicating that the * Producer service will perform the data filtering then the {@code Wire} * object will not perform data filtering. Otherwise, the {@code Wire} * object must perform basic filtering. Basic filtering includes supporting * the following standard wire filter attributes: * <ul> * <li>{@link #WIREVALUE_CURRENT} - Current value</li> * <li>{@link #WIREVALUE_PREVIOUS} - Previous value</li> * <li>{@link #WIREVALUE_DELTA_ABSOLUTE} - Absolute delta</li> * <li>{@link #WIREVALUE_DELTA_RELATIVE} - Relative delta</li> * <li>{@link #WIREVALUE_ELAPSED} - Elapsed time</li> * </ul> * * @see org.osgi.framework.Filter */ public final static String WIREADMIN_FILTER = "wireadmin.filter"; /* Wire filter attribute names. */ /** * {@code Wire} object's filter attribute (named {@code wirevalue.current}) * representing the current value. */ public final static String WIREVALUE_CURRENT = "wirevalue.current"; /** * {@code Wire} object's filter attribute (named {@code wirevalue.previous}) * representing the previous value. */ public final static String WIREVALUE_PREVIOUS = "wirevalue.previous"; /** * {@code Wire} object's filter attribute (named * {@code wirevalue.delta.absolute}) representing the absolute delta. The * absolute (always positive) difference between the last update and the * current value (only when numeric). This attribute must not be used when * the values are not numeric. */ public final static String WIREVALUE_DELTA_ABSOLUTE = "wirevalue.delta.absolute"; /** * {@code Wire} object's filter attribute (named * {@code wirevalue.delta.relative}) representing the relative delta. The * relative difference is |{@code previous}-{@code current} |/| * {@code current}| (only when numeric). This attribute must not be used * when the values are not numeric. */ public final static String WIREVALUE_DELTA_RELATIVE = "wirevalue.delta.relative"; /** * {@code Wire} object's filter attribute (named {@code wirevalue.elapsed}) * representing the elapsed time, in ms, between this filter evaluation and * the last update of the {@code Consumer} service. */ public final static String WIREVALUE_ELAPSED = "wirevalue.elapsed"; /* Service registration property key names. */ /** * Service Registration property (named {@code wireadmin.producer.filters}). * A {@code Producer} service registered with this property indicates to the * Wire Admin service that the Producer service implements at least the * filtering as described for the {@link #WIREADMIN_FILTER} property. If the * Producer service is not registered with this property, the {@code Wire} * object must perform the basic filtering as described in * {@link #WIREADMIN_FILTER}. * * <p> * The type of the property value is not relevant. Only its presence is * relevant. */ public final static String WIREADMIN_PRODUCER_FILTERS = "wireadmin.producer.filters"; /** * Service Registration property (named {@code wireadmin.consumer.flavors}) * specifying the list of data types understood by this Consumer service. * * <p> * The Consumer service object must be registered with this service * property. The list must be in the order of preference with the first type * being the most preferred. The value of the property must be of type * {@code Class[]}. */ public final static String WIREADMIN_CONSUMER_FLAVORS = "wireadmin.consumer.flavors"; /** * Service Registration property (named {@code wireadmin.producer.flavors}) * specifying the list of data types available from this Producer service. * * <p> * The Producer service object should be registered with this service * property. * * <p> * The value of the property must be of type {@code Class[]}. */ public final static String WIREADMIN_PRODUCER_FLAVORS = "wireadmin.producer.flavors"; /** * Service Registration property (named {@code wireadmin.events}) specifying * the {@code WireAdminEvent} type of interest to a Wire Admin Listener * service. The value of the property is a bitwise OR of all the * {@code WireAdminEvent} types the Wire Admin Listener service wishes to * receive and must be of type {@code Integer}. * * @see WireAdminEvent */ public final static String WIREADMIN_EVENTS = "wireadmin.events"; }
{ "content_hash": "5039391d08d205a0abff969628a545f2", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 90, "avg_line_length": 45.023809523809526, "alnum_prop": 0.7200423056583818, "repo_name": "osgi/osgi", "id": "e9406b56dedf5f46f76a4640dc3d6231553005cb", "size": "10274", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "org.osgi.service.wireadmin/src/org/osgi/service/wireadmin/WireConstants.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "11308" }, { "name": "C", "bytes": "11077" }, { "name": "CSS", "bytes": "63392" }, { "name": "HTML", "bytes": "1425271" }, { "name": "Java", "bytes": "17327563" }, { "name": "JavaScript", "bytes": "684425" }, { "name": "Makefile", "bytes": "8343" }, { "name": "NewLisp", "bytes": "4473" }, { "name": "Perl", "bytes": "7202" }, { "name": "Python", "bytes": "9377" }, { "name": "Roff", "bytes": "64" }, { "name": "Ruby", "bytes": "10888" }, { "name": "Shell", "bytes": "48677" }, { "name": "SystemVerilog", "bytes": "5465" }, { "name": "XSLT", "bytes": "8082406" } ], "symlink_target": "" }
package searchlink.atr.tasks.service.commands.common; import lombok.Data; import searchlink.atr.tasks.domain.entities.Task; import searchlink.atr.util.validation.Validation; import javax.persistence.EntityNotFoundException; import javax.validation.constraints.NotNull; /** * Base class for all the commands that are to result in object mutation. * <p> * This is to ilustrate that I am familiar with the concepts of CQRS and event sourcing. By using this naming convention we can eventually: * a) Move all comands to the domain and loose the Task table completly, just storing a task mutation "history". * b) Have specialized and optimized flows for reading and writing, (although this may cause 'transactions' to be just 'eventually consistent') * c) Have better vertical slices and single responcibility principle utilization in our application and move it to microservices if needed */ @Data public abstract class BaseMutateTaskCommand implements ICommand { @NotNull long id; @NotNull long version; String name; protected BaseMutateTaskCommand(String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public Validation<Task, String> getValidationErrors(Task task) { return Validation.<Task, String>of(task) .validate(this::optimisticLockingFailed, "Trying to update task:" + task.getId() + "with a stale model"); } private boolean optimisticLockingFailed(Task existingTask) { if (existingTask.getId() != id) { throw new EntityNotFoundException("trying to check command against wrong object toZoned DB ids:" + id + "," + existingTask.getId()); } return this.version != existingTask.getVersion(); } }
{ "content_hash": "3ac22329d54acc2b2f4217cb06dd24f9", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 144, "avg_line_length": 38.416666666666664, "alnum_prop": 0.7017353579175705, "repo_name": "alexTheSwEngineer/Searchlink", "id": "ccb9fc46585ac827dabcc61bf9f09fc53c097f52", "size": "1844", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tech-challenge-atr/src/main/java/searchlink/atr/tasks/service/commands/common/BaseMutateTaskCommand.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "80" }, { "name": "HTML", "bytes": "7618" }, { "name": "Java", "bytes": "53450" }, { "name": "JavaScript", "bytes": "3454285" }, { "name": "Shell", "bytes": "356" }, { "name": "TypeScript", "bytes": "20389" } ], "symlink_target": "" }
using System.ComponentModel; namespace Gallio.Icarus.ControlPanel { internal partial class ShutdownPane { /// <summary> /// Required designer variable. /// </summary> private const IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.autoSave = new System.Windows.Forms.CheckBox(); this.groupBoxGeneral = new System.Windows.Forms.GroupBox(); this.groupBoxGeneral.SuspendLayout(); this.SuspendLayout(); this.Controls.Add(this.groupBoxGeneral); // // autoSave // this.autoSave.AutoSize = true; this.autoSave.Location = new System.Drawing.Point(12, 21); this.autoSave.Name = "autoSave"; this.autoSave.Size = new System.Drawing.Size(147, 17); this.autoSave.TabIndex = 0; this.autoSave.Text = "Auto-Save Project Settings"; this.autoSave.UseVisualStyleBackColor = true; this.autoSave.CheckedChanged += new System.EventHandler(this.autoSave_CheckedChanged); // // groupBoxGeneral // this.groupBoxGeneral.Controls.Add(this.autoSave); this.groupBoxGeneral.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBoxGeneral.Location = new System.Drawing.Point(0, 0); this.groupBoxGeneral.Name = "groupBoxGeneral"; this.groupBoxGeneral.Size = new System.Drawing.Size(450, 350); this.groupBoxGeneral.TabIndex = 3; this.groupBoxGeneral.TabStop = false; this.groupBoxGeneral.Text = "General"; // // ShutdownOptions // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.Name = "ShutdownOptions"; this.groupBoxGeneral.ResumeLayout(false); this.groupBoxGeneral.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.CheckBox autoSave; private System.Windows.Forms.GroupBox groupBoxGeneral; } }
{ "content_hash": "f18b13a907a6a4baab359d4ea5664477", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 107, "avg_line_length": 38.13157894736842, "alnum_prop": 0.567287784679089, "repo_name": "mterwoord/mbunit-v3", "id": "d03e519d0a36400bfa95a8c2d7d12d1633014379", "size": "2900", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/Extensions/Icarus/Gallio.Icarus/ControlPanel/ShutdownPane.Designer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "8718" }, { "name": "Batchfile", "bytes": "31812" }, { "name": "C", "bytes": "1006" }, { "name": "C#", "bytes": "13534505" }, { "name": "C++", "bytes": "136700" }, { "name": "CSS", "bytes": "14400" }, { "name": "HTML", "bytes": "3812671" }, { "name": "JavaScript", "bytes": "6632" }, { "name": "Objective-C", "bytes": "1024" }, { "name": "PowerShell", "bytes": "11691" }, { "name": "Ruby", "bytes": "3597212" }, { "name": "Visual Basic", "bytes": "12688" }, { "name": "XSLT", "bytes": "123017" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us"> <head> <meta charset="utf-8"> <title> {% if page.title %} {{ page.title }} &ndash; {% endif %} {{ site.name }} </title> <meta name="author" content="{{ site.name }}" /> <meta name="description" content="{{ site.description }}" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link rel="alternate" type="application/rss+xml" href="/atom.xml" /> <link rel="stylesheet" href="/css/fontawesome.min.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="/css/base.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="/css/pygments.css" type="text/css" /> <link media="only screen and (max-device-width: 480px)" href="/css/mobile.css" type="text/css" rel="stylesheet" /> <link media="only screen and (device-width: 768px)" href="/css/mobile.css" type="text/css" rel="stylesheet" /> <link href='http://fonts.googleapis.com/css?family=Maven+Pro|Alegreya|Alegreya:400italic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" href="/apple-touch-icon.png" /> <link rel="shortcut icon" href="favicon.ico" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="/js/application.js"></script> </head> <body> <section class="sidebar"> <a href="/"> <img src="{{ site.gravatar_url }}?s=150" height="75" width="75" class="avatar" /> </a> <section class="name"> <a href="/"> <span id="fname">{{ site.name|split:' '|first }}</span> <span id="lname">{{ site.name|split:' '|last }}</span> </a> </section> <section class="meta"> <a href="https://github.com/{{ site.github }}" target="_blank"><i class="icon icon-github"></i></a> <a href="https://twitter.com/{{ site.twitter }}" target="_blank"><i class="icon icon-twitter"></i></a> <a href="/atom.xml"><i class="icon icon-rss"></i></a> </section> <section class="sections"> <ul> <li><a href="/about.html">about</a></li> <li><a href="/">home</a></li> </ul> </section> </section> {{ content }} </body> </html>
{ "content_hash": "330390fa29f93ba533ff4bc258661bdd", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 125, "avg_line_length": 37.17741935483871, "alnum_prop": 0.6073752711496746, "repo_name": "augusto-garcia/augusto-garcia.github.io", "id": "3d9be3e6f313144d3ca60e82b58500faec180fe0", "size": "2305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_layouts/layout.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15363" }, { "name": "HTML", "bytes": "5113" }, { "name": "JavaScript", "bytes": "18" } ], "symlink_target": "" }
package org.apache.derbyTesting.functionTests.tests.jdbcapi; import java.io.IOException; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.JDBC; import org.apache.derbyTesting.junit.TestConfiguration; public class DMDBugsTest extends BaseJDBCTestCase { public DMDBugsTest(String name) { super(name); // TODO Auto-generated constructor stub } public void testDerby3000() throws SQLException, IOException { ResultSet rs; // Derby-3000 make sure we process only valid TableType values and // process them correctly. DatabaseMetaData dmd = getConnection().getMetaData(); Statement s = createStatement(); s.executeUpdate("CREATE TABLE APP.TAB (i int)"); s.executeUpdate("CREATE VIEW APP.V as SELECT * FROM TAB"); s.executeUpdate("CREATE SYNONYM TSYN FOR APP.TAB"); String[] withInvalidTableTypes = {"SYNONYM","TABLE","VIEW", "GLOBAL TEMPORARY"}; // just ignore invalid types rs = dmd.getTables( "%", "%", "%", withInvalidTableTypes); JDBC.assertFullResultSet(rs, new String[][] {{"","APP","TSYN","SYNONYM","",null,null,null,null,null}, {"","APP","TAB","TABLE","",null,null,null,null,null}, {"","APP","V","VIEW","",null,null,null,null,null}}); rs = dmd.getTables("%", "%", "%", new String[] {"GLOBAL TEMPORARY"}); JDBC.assertEmpty(rs); rs = dmd.getTables("%", "%", "%", new String[] {"VIEW"}); JDBC.assertUnorderedResultSet(rs, new String[][] {{"","APP","V","VIEW","",null,null,null,null,null}}); rs = dmd.getTables("%", "%", "%", new String[] {"TABLE"}); JDBC.assertUnorderedResultSet(rs,new String[][] {{"","APP","TAB","TABLE","",null,null,null,null,null}} ); rs = dmd.getTables("%", "%", "%", new String[] {"SYNONYM"}); JDBC.assertUnorderedResultSet(rs, new String[][] {{"","APP","TSYN","SYNONYM","",null,null,null,null,null}}); rs = dmd.getTables( "%", "%", "%", new String[] {"SYSTEM TABLE"}); assertEquals(23, JDBC.assertDrainResults(rs)); s.executeUpdate("DROP VIEW APP.V"); s.executeUpdate("DROP TABLE APP.TAB"); s.executeUpdate("DROP SYNONYM APP.TSYN"); } /* Default suite for running this test. */ public static Test suite() { TestSuite suite = new TestSuite("DMDBugsTest"); suite.addTest( TestConfiguration.defaultSuite(DMDBugsTest.class)); return suite; } }
{ "content_hash": "ef5e0ec3fd5adaee7994b50e72ddf9e8", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 78, "avg_line_length": 32.88461538461539, "alnum_prop": 0.6635477582846004, "repo_name": "viaper/DBPlus", "id": "0a32996cf6ce081ecf1924c9b4b75e3e32e5c68a", "size": "3445", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DerbyHodgepodge/java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/DMDBugsTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "132752" }, { "name": "Gnuplot", "bytes": "3125" }, { "name": "Java", "bytes": "42109386" }, { "name": "JavaScript", "bytes": "1654" }, { "name": "Shell", "bytes": "22196" }, { "name": "XSLT", "bytes": "16712" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe User::Email, type: :model do it { is_expected.to belong_to(:user).inverse_of(:emails) } let!(:instance) { create(:instance) } with_tenant(:instance) do let(:email) { build(:user_email) } it 'rejects invalid email addresses' do email.email = 'wrong' expect(email.valid?).to eq(false) end context 'when a user has multiple emails' do let(:user) { create(:user) } let(:primary_email) { user.emails.first } let!(:non_primary_email) { create(:user_email, user: user, primary: false) } context 'when unset a primary email' do subject { primary_email } before { primary_email.primary = false } it { is_expected.to be_valid } end context 'when set the other email as primary' do subject { non_primary_email } before { non_primary_email.primary = true } it { is_expected.not_to be_valid } end end end end
{ "content_hash": "90844aa1bc171f6a754708cc5bdaddda", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 82, "avg_line_length": 27.771428571428572, "alnum_prop": 0.6183127572016461, "repo_name": "BenMQ/coursemology2", "id": "bf67ddb7475a05f816cfc32a1fc59fb9c768cd69", "size": "972", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/models/user_email_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2801" }, { "name": "HTML", "bytes": "77276" }, { "name": "JavaScript", "bytes": "2921" }, { "name": "Ruby", "bytes": "1040388" } ], "symlink_target": "" }
<?php namespace Benkle\Feeding\Interfaces; interface NodeInterface { }
{ "content_hash": "4988a1189b23d496982dbe79b3dab6f6", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 36, "avg_line_length": 8.333333333333334, "alnum_prop": 0.76, "repo_name": "benkle-libs/feeding", "id": "db7adfca931566f2738f913a0dc6842bb3f4f2ff", "size": "1181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Interfaces/NodeInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "252460" } ], "symlink_target": "" }
'use strict'; function ProfileCtrl(session, $scope, $http, errors) { var messages = {}; var feedback = {}; $scope.messages = messages; $scope.feedback = feedback; $scope.supportsPayments = false; $scope.activePlan = {}; if ($scope.showBackBar) { $scope.showBackBar(); } var plans = []; plans.push({ name: "Supporter", displayName: "Five", displayAmount: "$5", stripeAmount: 500 }); plans.push({ name: "Ten", displayName: "Ten", displayAmount: "$10", stripeAmount: 1000 }); plans.push({ name: "Organizer", displayName: "Twenty", displayAmount: "$20", stripeAmount: 2000 }); var updateCircles = function () { $http.get("/data/circles") .success(function (data) { var rawCircleData = data; var circles = {}; // TODO: Need to change the view to remove duplicates, // as data.length === memberships.length, rather than // circle length. rawCircleData.forEach(function (circle) { circles[circle._id] = circle; }); $scope.circles = circles; }) .error(function (data, status) { errors.log(data, status); }); }; var updateScope = function () { if (session.user) { $scope.name = session.user.name; $scope.email = session.user.email; if (session.user.notifications && session.user.notifications.email) { $scope.notificationEmail = session.user.notifications.email; } else { $scope.notificationEmail = session.user.email; } // Load the saved subscription if there is one if (session.user.subscription) { var savedPlanName = session.user.subscription.planName; angular.forEach(plans, function (plan) { if (plan.name === savedPlanName) { $scope.activePlan = plan; } }); } else { $scope.activePlan = {}; } updateCircles(); } }; var saveUserProperty = function (propName, val, callback) { var data = {}; data.id = session.user.id; data[propName] = val; $http.put('/data/user/' + propName, data) .success(function () { feedback[propName] = "success"; messages[propName] = null; if (callback) { callback(); } }) .error(function (data, status) { feedback[propName] = "error"; messages[propName] = data; var err = { data: data, status: status } if (callback) { callback(err); } }); }; var updateName = function (name) { saveUserProperty("name", name, function (err) { if (err) { return; } session.user.name = name; session.save(); }); }; var updateEmail = function (email) { saveUserProperty("email", email, function (err) { if (err) { return; } session.user.email = email; session.save(); }); }; var updateNotificationEmail = function (address) { if (!address) { feedback.notificationEmail = "error"; messages.notificationEmail = "Sorry, we'd like an email address." return; } saveUserProperty("notificationEmail", address, function (err) { if (err) { return; } session.user.notifications = session.user.notifications || {}; session.user.notifications.email = address; session.save(); }); }; $scope.saveProfile = function (name, email, notificationEmail) { updateName(name); updateEmail(email); updateNotificationEmail(notificationEmail); }; $scope.isCreatingCircle = false; $scope.createCircle = function (circleName) { if (!circleName || $scope.isCreatingCircle) { return; } $scope.isCreatingCircle = true; var finishUp = function () { $scope.newCircleName = undefined; $scope.isCreatingCircle = false; }; var data = {}; data.name = circleName; $http.post("/data/circle/", data) .success(function () { messages.circle = "Circle created."; finishUp(); updateCircles(); }) .error(function (data, status) { finishUp(); if (status === 403) { messages.circle = data; return; } errors.handle(data, status); }); }; $scope.updatePassword = function (pass1, pass2) { if (pass1 !== pass2) { messages.password = "Sorry, your passwords don't match." return; } var data = {}; data.password = pass1; $http.put('/data/user/password', data) .success(function() { messages.password = "Password updated."; }) .error(function (data, status) { errors.handle(data, status); }); }; var stripeKey = session.settings['stripe-public-key'].value; if (stripeKey) { $scope.plans = plans; $scope.supportsPayments = true; var stripeHandler = StripeCheckout.configure({ key: stripeKey, image: '/img/logo-on-black-128px.png', token: function (token, args) { var activePlan = $scope.activePlan; var data = {}; data.stripeTokenId = token.id; data.planName = activePlan.name; $http.post('/payment/subscribe', data) .success(function (data) { session.user.subscription = data; session.save(); }) .error(function (data, status) { errors.handle(data, status); }); } }); $scope.openStripeCheckout = function (e) { var activePlan = $scope.activePlan; if (!activePlan.name) { return; } stripeHandler.open({ name: 'Circle Blvd.', description: activePlan.name + " (" + activePlan.displayAmount + " per month)", amount: activePlan.stripeAmount, panelLabel: "Pay {{amount}} per month", email: session.user.email, allowRememberMe: false }); e.stopPropagation(); }; $scope.setPlan = function (plan) { $scope.activePlan = plan; }; $scope.cancelSubscription = function () { var data = {}; $http.put('/payment/subscribe/cancel', data) .success(function (data) { session.user.subscription = data; session.save(); updateScope(); }) .error(function (data, status) { errors.handle(data, status); }); }; } $scope.isSuccess = function (val) { return val === "success"; }; $scope.isError = function (val) { return val === "failure"; }; // Get our data as a check to see if we should even be here. $http.get('/data/user') .success(function (data) { if (session.user.id !== data.id) { $scope.signOut(); // "Sorry, we thought you were someone else for a second. Please sign in again." } else { updateScope(); } }) .error(function (data, status) { if (status === 401 && session && session.user) { $scope.signOut(); // "The server was restarted. Please sign in again." } }); } ProfileCtrl.$inject = ['session', '$scope', '$http', 'errors'];
{ "content_hash": "d29faa6bb15b8d15e176260afdfce7c7", "timestamp": "", "source": "github", "line_count": 300, "max_line_length": 83, "avg_line_length": 21.523333333333333, "alnum_prop": 0.6230447576273811, "repo_name": "secret-project/circle-blvd", "id": "f8a91a8207aeaebbbab2bf4b3929df5b520dc34a", "size": "6457", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/front-end/public/ui/controllers/profile.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "572" }, { "name": "CSS", "bytes": "49794" }, { "name": "HTML", "bytes": "184810" }, { "name": "JavaScript", "bytes": "373165" }, { "name": "Ruby", "bytes": "503" }, { "name": "Shell", "bytes": "3419" } ], "symlink_target": "" }
using System.Collections.Generic; using Azure; using Azure.Core; using Azure.ResourceManager.Resources.Models; namespace Azure.ResourceManager.Network.Models { /// <summary> Backend address pool settings of an application gateway. </summary> public partial class ApplicationGatewayBackendHttpSettings : NetworkResourceData { /// <summary> Initializes a new instance of ApplicationGatewayBackendHttpSettings. </summary> public ApplicationGatewayBackendHttpSettings() { AuthenticationCertificates = new ChangeTrackingList<WritableSubResource>(); TrustedRootCertificates = new ChangeTrackingList<WritableSubResource>(); } /// <summary> Initializes a new instance of ApplicationGatewayBackendHttpSettings. </summary> /// <param name="id"> Resource ID. </param> /// <param name="name"> Resource name. </param> /// <param name="resourceType"> Resource type. </param> /// <param name="etag"> A unique read-only string that changes whenever the resource is updated. </param> /// <param name="port"> The destination port on the backend. </param> /// <param name="protocol"> The protocol used to communicate with the backend. </param> /// <param name="cookieBasedAffinity"> Cookie based affinity. </param> /// <param name="requestTimeoutInSeconds"> Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400 seconds. </param> /// <param name="probe"> Probe resource of an application gateway. </param> /// <param name="authenticationCertificates"> Array of references to application gateway authentication certificates. </param> /// <param name="trustedRootCertificates"> Array of references to application gateway trusted root certificates. </param> /// <param name="connectionDraining"> Connection draining of the backend http settings resource. </param> /// <param name="hostName"> Host header to be sent to the backend servers. </param> /// <param name="pickHostNameFromBackendAddress"> Whether to pick host header should be picked from the host name of the backend server. Default value is false. </param> /// <param name="affinityCookieName"> Cookie name to use for the affinity cookie. </param> /// <param name="probeEnabled"> Whether the probe is enabled. Default value is false. </param> /// <param name="path"> Path which should be used as a prefix for all HTTP requests. Null means no path will be prefixed. Default value is null. </param> /// <param name="provisioningState"> The provisioning state of the backend HTTP settings resource. </param> internal ApplicationGatewayBackendHttpSettings(ResourceIdentifier id, string name, ResourceType? resourceType, ETag? etag, int? port, ApplicationGatewayProtocol? protocol, ApplicationGatewayCookieBasedAffinity? cookieBasedAffinity, int? requestTimeoutInSeconds, WritableSubResource probe, IList<WritableSubResource> authenticationCertificates, IList<WritableSubResource> trustedRootCertificates, ApplicationGatewayConnectionDraining connectionDraining, string hostName, bool? pickHostNameFromBackendAddress, string affinityCookieName, bool? probeEnabled, string path, NetworkProvisioningState? provisioningState) : base(id, name, resourceType) { ETag = etag; Port = port; Protocol = protocol; CookieBasedAffinity = cookieBasedAffinity; RequestTimeoutInSeconds = requestTimeoutInSeconds; Probe = probe; AuthenticationCertificates = authenticationCertificates; TrustedRootCertificates = trustedRootCertificates; ConnectionDraining = connectionDraining; HostName = hostName; PickHostNameFromBackendAddress = pickHostNameFromBackendAddress; AffinityCookieName = affinityCookieName; ProbeEnabled = probeEnabled; Path = path; ProvisioningState = provisioningState; } /// <summary> A unique read-only string that changes whenever the resource is updated. </summary> public ETag? ETag { get; } /// <summary> The destination port on the backend. </summary> public int? Port { get; set; } /// <summary> The protocol used to communicate with the backend. </summary> public ApplicationGatewayProtocol? Protocol { get; set; } /// <summary> Cookie based affinity. </summary> public ApplicationGatewayCookieBasedAffinity? CookieBasedAffinity { get; set; } /// <summary> Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400 seconds. </summary> public int? RequestTimeoutInSeconds { get; set; } /// <summary> Probe resource of an application gateway. </summary> internal WritableSubResource Probe { get; set; } /// <summary> Gets or sets Id. </summary> public ResourceIdentifier ProbeId { get => Probe is null ? default : Probe.Id; set { if (Probe is null) Probe = new WritableSubResource(); Probe.Id = value; } } /// <summary> Array of references to application gateway authentication certificates. </summary> public IList<WritableSubResource> AuthenticationCertificates { get; } /// <summary> Array of references to application gateway trusted root certificates. </summary> public IList<WritableSubResource> TrustedRootCertificates { get; } /// <summary> Connection draining of the backend http settings resource. </summary> public ApplicationGatewayConnectionDraining ConnectionDraining { get; set; } /// <summary> Host header to be sent to the backend servers. </summary> public string HostName { get; set; } /// <summary> Whether to pick host header should be picked from the host name of the backend server. Default value is false. </summary> public bool? PickHostNameFromBackendAddress { get; set; } /// <summary> Cookie name to use for the affinity cookie. </summary> public string AffinityCookieName { get; set; } /// <summary> Whether the probe is enabled. Default value is false. </summary> public bool? ProbeEnabled { get; set; } /// <summary> Path which should be used as a prefix for all HTTP requests. Null means no path will be prefixed. Default value is null. </summary> public string Path { get; set; } /// <summary> The provisioning state of the backend HTTP settings resource. </summary> public NetworkProvisioningState? ProvisioningState { get; } } }
{ "content_hash": "dd51aa4f0126fa7c92c6ca76f93777a4", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 651, "avg_line_length": 69.97979797979798, "alnum_prop": 0.6926963048498845, "repo_name": "Azure/azure-sdk-for-net", "id": "35985eeb90ab7920eef0c904ba73279c19e121e4", "size": "7066", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/network/Azure.ResourceManager.Network/src/Generated/Models/ApplicationGatewayBackendHttpSettings.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php $runner->addTestsFromDirectory(__DIR__.'/src/M6Web/Bundle/ApcuBundle/Tests');
{ "content_hash": "c96eeca25e1532162d960438a9e2662e", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 77, "avg_line_length": 28, "alnum_prop": 0.7380952380952381, "repo_name": "M6Web/ApcuBundle", "id": "dcea57c9ca1278bdf92bd12d4731a49ac3c90fcb", "size": "84", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".atoum.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "9199" }, { "name": "Shell", "bytes": "170" } ], "symlink_target": "" }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.PmsProductAttributeParam; import com.macro.mall.dto.ProductAttrInfo; import com.macro.mall.model.PmsProductAttribute; import com.macro.mall.service.PmsProductAttributeService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 商品属性管理Controller * Created by macro on 2018/4/26. */ @Controller @Api(tags = "PmsProductAttributeController") @Tag(name = "PmsProductAttributeController", description = "商品属性管理") @RequestMapping("/productAttribute") public class PmsProductAttributeController { @Autowired private PmsProductAttributeService productAttributeService; @ApiOperation("根据分类查询属性列表或参数列表") @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "0表示属性,1表示参数", required = true, paramType = "query", dataType = "integer")}) @RequestMapping(value = "/list/{cid}", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProductAttribute>> getList(@PathVariable Long cid, @RequestParam(value = "type") Integer type, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProductAttribute> productAttributeList = productAttributeService.getList(cid, type, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productAttributeList)); } @ApiOperation("添加商品属性信息") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody PmsProductAttributeParam productAttributeParam) { int count = productAttributeService.create(productAttributeParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改商品属性信息") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody PmsProductAttributeParam productAttributeParam) { int count = productAttributeService.update(id, productAttributeParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("查询单个商品属性") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductAttribute> getItem(@PathVariable Long id) { PmsProductAttribute productAttribute = productAttributeService.getItem(id); return CommonResult.success(productAttribute); } @ApiOperation("批量删除商品属性") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = productAttributeService.delete(ids); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据商品分类的id获取商品属性及属性分类") @RequestMapping(value = "/attrInfo/{productCategoryId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<ProductAttrInfo>> getAttrInfo(@PathVariable Long productCategoryId) { List<ProductAttrInfo> productAttrInfoList = productAttributeService.getProductAttrInfo(productCategoryId); return CommonResult.success(productAttrInfoList); } }
{ "content_hash": "0fe13944621c288df967dffad6273fcc", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 141, "avg_line_length": 43.11578947368421, "alnum_prop": 0.696533203125, "repo_name": "macrozheng/mall", "id": "495cc8fdf3b31a870819927d9b28160393f62fc2", "size": "4268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mall-admin/src/main/java/com/macro/mall/controller/PmsProductAttributeController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "366" }, { "name": "Java", "bytes": "2734172" }, { "name": "Shell", "bytes": "2324" } ], "symlink_target": "" }
<?php /** * Plugin Name: Temperature * Description: Displays current temperature for a given local * Version: 0.1 * Author: João Paulo Figueira * License: MIT */ /** * Usage example: * [temperature country="pt" city="lisbon"] */ include_once('autoload.php'); use Temperature\Temperature; add_action('init', 'temperatureRegisterShortCodes'); function temperatureRegisterShortCodes() { add_shortcode('temperature', 'temperature'); } function temperature($args) { $temperature = new Temperature; return $temperature->setCountry($args['country'])->setCity($args['city'])->fetch(); }
{ "content_hash": "3b2834d181ad186bfd3250f387cef285", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 84, "avg_line_length": 19.6, "alnum_prop": 0.7227891156462585, "repo_name": "joaopfigueira/Wordpress-Temperature", "id": "63e3fe23e11842e2af84442d805263fb6913f117", "size": "589", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wp-plugin.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "2624" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <Content type="xform" name="EditContent"> <model> <instance> <tblContent> <nContentKey/> <nContentPrimaryId/> <nVersion/> <cContentForiegnRef/> <cContentName/> <cContentSchemaName>Module</cContentSchemaName> <cContentXmlBrief> <Content moduleType="LinkListGrid" contentType="Link" box="" title="" link="" linkType="internal" linkText="More information" sortBy="Name" order="ascending" cols="1" stepBy="" stepCount="0" display="all" position=""/> </cContentXmlBrief> <cContentXmlDetail/> <nAuditId/> <nAuditKey/> <dPublishDate/> <dExpireDate/> <dInsertDate/> <nInsertDirId/> <dUpdateDate/> <nUpdateDirId/> <nStatus>1</nStatus> <cDescription/> <bCascade/> </tblContent> </instance> <submission id="EditContent" action="" method="post" event="return form_check(this)"/> <bind id="cModuleTitle" nodeset="tblContent/cContentName" required="false()" type="string"/> <bind nodeset="tblContent/cContentXmlBrief/Content"> <bind id="cPosition" nodeset="@position" required="true()" type="string"/> <bind id="cModuleType" nodeset="@moduleType" required="true()" type="string"/> <bind id="cModuleBox" nodeset="@box" required="false()" type="string"/> <bind id="cModuleTitle" nodeset="@title" required="false()" type="string"/> <bind id="cModuleLink" nodeset="@link" required="false()" type="string"/> <bind id="cLinkType" nodeset="@linkType" required="false()" type="string"/> <bind id="cModuleLinkText" nodeset="@linkText" required="false()" type="string"/> <bind id="nColumns" nodeset="@cols" required="false()" type="string"/> <bind id="carousel" nodeset="@carousel" required="false()" type="string"/> <bind id="carouselBullets" nodeset="@carouselBullets" required="false()" type="string"/> <bind id="carouselHeight" nodeset="@carouselHeight" required="false()" type="string"/> <bind id="nStepCount" nodeset="@stepCount" required="false()" type="string"/> <bind id="cDisplay" nodeset="@display" required="false()" type="string"/> <bind id="cSortBy" nodeset="@sortBy" required="false()" type="string"/> <bind id="cStepBy" nodeset="@stepBy" required="false()" type="string"/> <bind id="cPageOrder" nodeset="@order" required="false()" type="string"/> <bind id="autoPlaySpeed" nodeset="@autoPlaySpeed" required="false()" type="string"/> <bind id="autoplay" nodeset="@autoplay" required="false()" type="string"/> <bind id="cCrop" nodeset="@crop" required="false()" type="string"/> </bind> <bind id="cContentBody" nodeset="tblContent/cContentXmlBrief/Content" required="false()" type="string"/> <ewInclude filePath="/ewcommon/xforms/content/module/genericModule.xml" xPath="descendant-or-self::bind[@nodeset='tblContent/cContentXmlBrief/Content']"/> <ewInclude filePath="/ewcommon/xforms/content/module/genericModule.xml" xPath="descendant-or-self::bind[@id='columnBind']"/> <ewInclude filePath="/ewcommon/xforms/content/module/genericModule.xml" xPath="descendant-or-self::bind[@nodeset='tblContent']"/> </model> <group ref="EditContent" class="2col"> <label>Links List Grid Module</label> <group> <group> <label>Settings</label> <!-- These hidden fields and bindings are required for the component--> <input bind="nContentKey" class="hidden"> <label>ContentId</label> </input> <input bind="cModuleType" class="hidden"> <label>ModuleType</label> </input> <!-- end of hidden fields --> <ewInclude filePath="/ewcommon/xforms/content/module/genericModule.xml" xPath="descendant-or-self::group[@id='presentation']"/> <ewInclude filePath="/ewcommon/xforms/content/module/genericModule.xml" xPath="descendant-or-self::group[@id='publish']"/> </group> </group> <group> <group> <label>Content</label> <input bind="cModuleTitle" class="long"> <label>Title or Name</label> </input> <select1 bind="cDisplay" appearance="full" class="required"> <label>Show Items</label> <item> <label>All items on the current page</label> <value>all</value> <toggle case="cDisplay_1" event="DOMActivate"/> </item> <item> <label>Specific items specified below</label> <value>related</value> <toggle case="cDisplay_2" event="DOMActivate"/> </item> </select1> <switch class="disable"> <case id="cDisplay_1"/> <case id="cDisplay_2"> <relatedContent search="find add" type="Link" relationType="" direction="1way"> <label>Links</label> </relatedContent> </case> </switch> </group> <group class="inline"> <label>Display Settings</label> <ewInclude filePath="/ewcommon/xforms/content/module/genericModule.xml" xPath="descendant-or-self::group[@id='columns']"/> <select1 bind="nStepCount" appearance="full" class="required form-group"> <label>Links per page</label> <item> <label>all</label> <value>0</value> <toggle case="cStepCounter_1" event="DOMActivate"/> </item> <item> <label>3</label> <value>3</value> <toggle case="cStepCounter_2" event="DOMActivate"/> </item> <item> <label>5</label> <value>5</value> <toggle case="cStepCounter_3" event="DOMActivate"/> </item> <item> <label>10</label> <value>10</value> <toggle case="cStepCounter_4" event="DOMActivate"/> </item> <item> <label>25</label> <value>25</value> <toggle case="cStepCounter_5" event="DOMActivate"/> </item> <item bindTo="cStepBy"> <input bind="cStepBy" class="hidden" /> <label>Other</label> <value>Other</value> <toggle case="cStepCounter_6" event="DOMActivate" /> </item> </select1> <switch class="disable"> <case id="cStepCounter_1"/> <case id="cStepCounter_2"/> <case id="cStepCounter_3"/> <case id="cStepCounter_4"/> <case id="cStepCounter_5"/> <case id="cStepCounter_6"> <input bind="nStepCount" class="vshort"> <label>Other Stepper Value</label> </input> </case> </switch> <select1 bind="cSortBy" appearance="full" class="form-group"> <label>Sort By</label> <item> <label>Alphabetical</label> <value>Name</value> <toggle case="cSortBy_1" event="DOMActivate"/> </item> <item> <label>Publish Date</label> <value>publish</value> <toggle case="cSortBy_2" event="DOMActivate"/> </item> <item> <label>Page Position</label> <value>Position</value> <toggle case="cSortBy_3" event="DOMActivate"/> </item> </select1> <switch class="disable"> <case id="cSortBy_1"> <select1 bind="cPageOrder" appearance="minimal" class="form-group"> <label>Order</label> <item> <label>A to Z</label> <value>ascending</value> </item> <item> <label>Z to A</label> <value>descending</value> </item> </select1> </case> <case id="cSortBy_2"> <select1 bind="cPageOrder" appearance="minimal" class="form-group"> <label>Order</label> <item> <label>Newest to Oldest</label> <value>descending</value> </item> <item> <label>Oldest to Newest</label> <value>ascending</value> </item> </select1> </case> <case id="cSortBy_3" /> </switch> <select1 bind="cCrop" appearance="full" class="vshort"> <label>Crop</label> <item> <label>Yes</label> <value>true</value> </item> <item> <label>No</label> <value>false</value> </item> </select1> </group> <group class=""> <select1 bind="carousel" appearance="full" class="form-group"> <label>Add articles to a carousel</label> <item> <label>Yes</label> <value>true</value> <toggle case="Carousel_true" event="DOMActivate"/> </item> <item> <label>No</label> <value>false</value> <toggle case="Carousel_false" event="DOMActivate"/> </item> <help class="inline">If selected this option will display articles in a single horizontal line with arrows to scroll through to the left and right.</help> </select1> <switch class="disable"> <case id="Carousel_true" > <group class="inline"> <select1 bind="autoplay" appearance="full" class="form-group "> <label>Auto play</label> <item> <label>Yes</label> <value>true</value> </item> <item> <label>No</label> <value>false</value> </item> </select1> <input bind="autoPlaySpeed" class="form-group "> <label>autoplay Speed (milliseconds) </label> </input> <select1 bind="carouselBullets" appearance="full" class="form-group"> <label>Show navigation bullets for carousel</label> <item> <label>Yes</label> <value>true</value> </item> <item> <label>No</label> <value>false</value> </item> </select1> <select1 bind="carouselHeight" appearance="full" class="form-group"> <label>Match height of carousel items</label> <item> <label>Yes</label> <value>true</value> </item> <item> <label>No</label> <value>false</value> </item> </select1> </group> </case> <case id="Carousel_false"/> </switch> </group> <!--<group> <label>Module Links</label> <select1 bind="cModuleLink" class="siteTree"> <label>Page for the module title and module footer link</label> </select1> <input bind="cModuleLinkText" class="long"> <label>Module footer link text</label> </input> </group>--> <group> <label>Module Links</label> <select1 bind="cLinkType" appearance="full" class="required"> <label>Type of Link</label> <item> <label>Internal (Going to a page on this site)</label> <value>internal</value> <toggle case="cLinkType_1" event="DOMActivate"/> </item> <item> <label>External (Going to another site)</label> <value>external</value> <toggle case="cLinkType_2" event="DOMActivate"/> </item> </select1> <switch class="disable"> <case id="cLinkType_1"> <select1 bind="cModuleLink" class="siteTree"> <label>Link to page</label> </select1> </case> <case id="cLinkType_2"> <input bind="cModuleLink" class="short"> <label>Link to URL</label> </input> </case> </switch> <input bind="cModuleLinkText" class="long"> <label>Module footer link text</label> </input> </group> </group> </group> <group ref="submit" class="contentSubmit"> <submit submission="" ref="ewSubmit" class="principle"> <label>Save Link List Grid</label> </submit> </group> </Content>
{ "content_hash": "8f772dd2a0e7260b7635ddc557eafdcf", "timestamp": "", "source": "github", "line_count": 318, "max_line_length": 228, "avg_line_length": 39.60377358490566, "alnum_prop": 0.5350960774972209, "repo_name": "Eonic/EonicWeb5", "id": "7fa1c22f29f96d5373c9ac024688e8e563781667", "size": "12594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wwwroot/ewcommon/xForms/Content/Module/LinkListGrid.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "187212" }, { "name": "CSS", "bytes": "1993199" }, { "name": "HTML", "bytes": "704275" }, { "name": "JavaScript", "bytes": "26260325" }, { "name": "PHP", "bytes": "59560" }, { "name": "PLSQL", "bytes": "4128" }, { "name": "PLpgSQL", "bytes": "28590" }, { "name": "SQLPL", "bytes": "14993" }, { "name": "Visual Basic", "bytes": "6944306" }, { "name": "XSLT", "bytes": "3362163" } ], "symlink_target": "" }
package linkedlist // Node represents node of singly linked list type Node struct { Value int Next *Node } // LastKthNode returns last kth node of given List func LastKthNode(node *Node, k int) *Node { slow, fast := node, node for i := 0; i < k; i++ { if fast == nil { return nil } fast = fast.Next } for fast != nil { fast = fast.Next slow = slow.Next } return slow }
{ "content_hash": "3f9f34db937855cda34b52b587cea306", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 50, "avg_line_length": 15.8, "alnum_prop": 0.6379746835443038, "repo_name": "motomux/go-algo", "id": "07dc077d283147be04a7916bca29ca8cb225191f", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cracking_the_coding_interview/2.linked_lists/2.return_kth_to_last/linked_list.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "37687" } ], "symlink_target": "" }
/*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ // .NAME vtkExodusIIReader - Read exodus 2 files .ex2 // .SECTION Description // vtkExodusIIReader is a unstructured grid source object that reads ExodusII // files. Most of the meta data associated with the file is loaded when // UpdateInformation is called. This includes information like Title, number // of blocks, number and names of arrays. This data can be retrieved from // methods in this reader. Separate arrays that are meant to be a single // vector, are combined internally for convenience. To be combined, the array // names have to be identical except for a trailing X,Y and Z (or x,y,z). By // default cell and point arrays are not loaded. However, the user can flag // arrays to load with the methods "SetPointArrayStatus" and // "SetCellArrayStatus". The reader DOES NOT respond to piece requests // #ifndef __vtkExodusIIReader_h #define __vtkExodusIIReader_h #include "vtkMultiBlockDataSetAlgorithm.h" class vtkDataArray; class vtkDataSet; class vtkExodusIICache; class vtkExodusIIReaderPrivate; class vtkExodusModel; class vtkFloatArray; class vtkGraph; class vtkIntArray; class vtkPoints; class vtkUnstructuredGrid; class VTK_HYBRID_EXPORT vtkExodusIIReader : public vtkMultiBlockDataSetAlgorithm { public: static vtkExodusIIReader *New(); vtkTypeMacro(vtkExodusIIReader,vtkMultiBlockDataSetAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Determine if the file can be readed with this reader. int CanReadFile(const char* fname); //virtual void Modified(); // Description: // Return the object's MTime. This is overridden to include the timestamp of its internal class. virtual unsigned long GetMTime(); // Description: // Return the MTime of the internal data structure. // This is really only intended for use by vtkPExodusIIReader in order // to determine if the filename is newer than the metadata. virtual unsigned long GetMetadataMTime(); // Description: // Specify file name of the Exodus file. virtual void SetFileName( const char* fname ); vtkGetStringMacro(FileName); // Description: // Specify file name of the xml file. virtual void SetXMLFileName( const char* fname ); vtkGetStringMacro(XMLFileName); // Description: // Which TimeStep to read. vtkSetMacro(TimeStep, int); vtkGetMacro(TimeStep, int); // Description: // Convenience method to set the mode-shape which is same as // this->SetTimeStep(val-1); void SetModeShape(int val) { this->SetTimeStep(val-1); } // Description: // Returns the available range of valid integer time steps. vtkGetVector2Macro(TimeStepRange,int); vtkSetVector2Macro(TimeStepRange,int); // Description: // Extra cell data array that can be generated. By default, this array // is ON. The value of the array is the integer id found // in the exodus file. The name of the array is returned by // GetBlockIdArrayName(). For cells representing elements from // an Exodus element block, this is set to the element block ID. For // cells representing edges from an Exodus edge block, this is the // edge block ID. Similarly, ths is the face block ID for cells // representing faces from an Exodus face block. The same holds // for cells representing entries of node, edge, face, side, and element sets. virtual void SetGenerateObjectIdCellArray( int g ); int GetGenerateObjectIdCellArray(); vtkBooleanMacro(GenerateObjectIdCellArray, int); static const char *GetObjectIdArrayName() { return "ObjectId"; } virtual void SetGenerateGlobalElementIdArray( int g ); int GetGenerateGlobalElementIdArray(); vtkBooleanMacro(GenerateGlobalElementIdArray, int); virtual void SetGenerateGlobalNodeIdArray( int g ); int GetGenerateGlobalNodeIdArray(); vtkBooleanMacro(GenerateGlobalNodeIdArray, int); virtual void SetGenerateImplicitElementIdArray( int g ); int GetGenerateImplicitElementIdArray(); vtkBooleanMacro(GenerateImplicitElementIdArray, int); virtual void SetGenerateImplicitNodeIdArray( int g ); int GetGenerateImplicitNodeIdArray(); vtkBooleanMacro(GenerateImplicitNodeIdArray, int); virtual void SetGenerateFileIdArray( int f ); int GetGenerateFileIdArray(); vtkBooleanMacro(GenerateFileIdArray, int); virtual void SetFileId( int f ); int GetFileId(); //BTX // Description: // Extra cell data array that can be generated. By default, this array // is off. The value of the array is the integer global id of the cell. // The name of the array is returned by GetGlobalElementIdArrayName() // ***NOTE*** No more "unique" global ID. Instead we have an arbitrary number of maps. enum { SEARCH_TYPE_ELEMENT=0, SEARCH_TYPE_NODE, SEARCH_TYPE_ELEMENT_THEN_NODE, SEARCH_TYPE_NODE_THEN_ELEMENT, ID_NOT_FOUND=-234121312 }; // NOTE: GetNumberOfObjectTypes must be updated whenever you add an entry to enum ObjectType {...} enum ObjectType { // match Exodus macros from exodusII.h and exodusII_ext.h EDGE_BLOCK = 6, FACE_BLOCK = 8, ELEM_BLOCK = 1, NODE_SET = 2, EDGE_SET = 7, FACE_SET = 9, SIDE_SET = 3, ELEM_SET = 10, NODE_MAP = 5, EDGE_MAP = 11, FACE_MAP = 12, ELEM_MAP = 4, GLOBAL = 13, NODAL = 14, // extended values (not in Exodus headers) for use with SetAllArrayStatus: ASSEMBLY = 60, PART = 61, MATERIAL = 62, HIERARCHY = 63, // extended values (not in Exodus headers) for use in cache keys: QA_RECORDS = 103, //!< Exodus II Quality Assurance (QA) string metadata INFO_RECORDS = 104, //!< Exodus II Information Records string metadata GLOBAL_TEMPORAL = 102, //!< global data across timesteps NODAL_TEMPORAL = 101, //!< nodal data across timesteps ELEM_BLOCK_TEMPORAL = 100, //!< element data across timesteps GLOBAL_CONN = 99, //!< connectivity assembled from all blocks+sets to be loaded ELEM_BLOCK_ELEM_CONN = 98, //!< raw element block connectivity for elements (not edges/faces) ELEM_BLOCK_FACE_CONN = 97, //!< raw element block connectivity for faces (references face blocks) ELEM_BLOCK_EDGE_CONN = 96, //!< raw element block connectivity for edges (references edge blocks) FACE_BLOCK_CONN = 95, //!< raw face block connectivity (references nodes) EDGE_BLOCK_CONN = 94, //!< raw edge block connectivity (references nodes) ELEM_SET_CONN = 93, //!< element set connectivity SIDE_SET_CONN = 92, //!< side set connectivity FACE_SET_CONN = 91, //!< face set connectivity EDGE_SET_CONN = 90, //!< edge set connectivity NODE_SET_CONN = 89, //!< node set connectivity NODAL_COORDS = 88, //!< raw nodal coordinates (not the "squeezed" version) OBJECT_ID = 87, //!< object id (old BlockId) array IMPLICIT_ELEMENT_ID = 108, //!< the implicit global index of each element given by exodus IMPLICIT_NODE_ID = 107, //!< the implicit global index of each node given by exodus GLOBAL_ELEMENT_ID = 86, //!< element id array extracted for a particular block (yes, this is a bad name) GLOBAL_NODE_ID = 85, //!< nodal id array extracted for a particular block (yes, this is a bad name) ELEMENT_ID = 84, //!< element id map (old-style elem_num_map or first new-style elem map) array NODE_ID = 83, //!< nodal id map (old-style node_num_map or first new-style node map) array NODAL_SQUEEZEMAP = 82, //!< the integer map use to "squeeze" coordinates and nodal arrays/maps ELEM_BLOCK_ATTRIB = 81, //!< an element block attribute array (time-constant scalar per element) FACE_BLOCK_ATTRIB = 80, //!< a face block attribute array (time-constant scalar per element) EDGE_BLOCK_ATTRIB = 79, //!< an edge block attribute array (time-constant scalar per element) FACE_ID = 105, //!< face id map (old-style face_num_map or first new-style face map) array EDGE_ID = 106, //!< edge id map (old-style edge_num_map or first new-style edge map) array ENTITY_COUNTS = 109 //!< polyhedra per-entity count ex_get_block returns the sum for polyhedra }; //ETX static const char* GetGlobalElementIdArrayName() { return "GlobalElementId"; } static const char* GetPedigreeElementIdArrayName() { return "PedigreeElementId"; } static int GetGlobalElementID( vtkDataSet *data, int localID ); static int GetGlobalElementID ( vtkDataSet *data, int localID, int searchType ); static const char* GetImplicitElementIdArrayName() { return "ImplicitElementId"; } static const char* GetGlobalFaceIdArrayName() { return "GlobalFaceId"; } static const char* GetPedigreeFaceIdArrayName() { return "PedigreeFaceId"; } static int GetGlobalFaceID( vtkDataSet *data, int localID ); static int GetGlobalFaceID ( vtkDataSet *data, int localID, int searchType ); static const char* GetImplicitFaceIdArrayName() { return "ImplicitFaceId"; } static const char* GetGlobalEdgeIdArrayName() { return "GlobalEdgeId"; } static const char* GetPedigreeEdgeIdArrayName() { return "PedigreeEdgeId"; } static int GetGlobalEdgeID( vtkDataSet *data, int localID ); static int GetGlobalEdgeID ( vtkDataSet *data, int localID, int searchType ); static const char* GetImplicitEdgeIdArrayName() { return "ImplicitEdgeId"; } // Description: // Extra point data array that can be generated. By default, this array // is ON. The value of the array is the integer id of the node. // The id is relative to the entire data set. // The name of the array is returned by GlobalNodeIdArrayName(). static const char* GetGlobalNodeIdArrayName() { return "GlobalNodeId"; } static const char* GetPedigreeNodeIdArrayName() { return "PedigreeNodeId"; } static int GetGlobalNodeID( vtkDataSet *data, int localID ); static int GetGlobalNodeID( vtkDataSet *data, int localID, int searchType ); static const char* GetImplicitNodeIdArrayName() { return "ImplicitNodeId"; } // Description: // Geometric locations can include displacements. By default, // this is ON. The nodal positions are 'displaced' by the // standard exodus displacment vector. If displacements // are turned 'off', the user can explicitly add them by // applying a warp filter. virtual void SetApplyDisplacements( int d ); int GetApplyDisplacements(); vtkBooleanMacro(ApplyDisplacements, int); virtual void SetDisplacementMagnitude( float s ); float GetDisplacementMagnitude(); // Description: // Set/Get whether the Exodus sequence number corresponds to time steps or mode shapes. // By default, HasModeShapes is false unless two time values in the Exodus file are identical, // in which case it is true. virtual void SetHasModeShapes( int ms ); int GetHasModeShapes(); vtkBooleanMacro(HasModeShapes,int); // Description: // Set/Get the time used to animate mode shapes. // This is a number between 0 and 1 that is used to scale the \a DisplacementMagnitude // in a sinusoidal pattern. Specifically, the displacement vector for each vertex is scaled by // \f$ \mathrm{DisplacementMagnitude} cos( 2\pi \mathrm{ModeShapeTime} ) \f$ before it is // added to the vertex coordinates. virtual void SetModeShapeTime( double phase ); double GetModeShapeTime(); // Description: // If this flag is on (the default) and HasModeShapes is also on, then this // reader will report a continuous time range [0,1] and animate the // displacements in a periodic sinusoid. If this flag is off and // HasModeShapes is on, this reader ignores time. This flag has no effect if // HasModeShapes is off. virtual void SetAnimateModeShapes(int flag); int GetAnimateModeShapes(); vtkBooleanMacro(AnimateModeShapes, int); // Description: // Access to meta data generated by UpdateInformation. const char* GetTitle(); int GetDimensionality(); int GetNumberOfTimeSteps(); int GetNumberOfNodesInFile(); int GetNumberOfEdgesInFile(); int GetNumberOfFacesInFile(); int GetNumberOfElementsInFile(); int GetObjectTypeFromName( const char* name ); const char* GetObjectTypeName( int ); int GetNumberOfNodes(); int GetNumberOfObjects( int objectType ); int GetNumberOfEntriesInObject( int objectType, int objectIndex ); int GetObjectId( int objectType, int objectIndex ); const char* GetObjectName( int objectType, int objectIndex ); int GetObjectIndex( int objectType, const char* objectName ); int GetObjectIndex( int objectType, int id ); int GetObjectStatus( int objectType, int objectIndex ); int GetObjectStatus( int objectType, const char* objectName ) { return this->GetObjectStatus( objectType, this->GetObjectIndex( objectType, objectName ) ); } void SetObjectStatus( int objectType, int objectIndex, int status ); void SetObjectStatus( int objectType, const char* objectName, int status ); // Descriptions: // By default arrays are not loaded. These methods allow the user to select // which arrays they want to load. You can get information about the arrays // by first caling UpdateInformation, and using GetPointArrayName ... // (Developer Note) This meta data is all accessed through vtkExodusMetadata int GetNumberOfObjectArrays( int objectType ); const char* GetObjectArrayName( int objectType, int arrayIndex ); int GetObjectArrayIndex( int objectType, const char* arrayName ); int GetNumberOfObjectArrayComponents( int objectType, int arrayIndex ); int GetObjectArrayStatus( int objectType, int arrayIndex ); int GetObjectArrayStatus( int objectType, const char* arrayName ) { return this->GetObjectArrayStatus( objectType, this->GetObjectArrayIndex( objectType, arrayName ) ); } void SetObjectArrayStatus( int objectType, int arrayIndex, int status ); void SetObjectArrayStatus( int objectType, const char* arrayName, int status ); // Descriptions: // By default attributes are not loaded. These methods allow the user to select // which attributes they want to load. You can get information about the attributes // by first caling UpdateInformation, and using GetObjectAttributeName ... // (Developer Note) This meta data is all accessed through vtkExodusMetadata int GetNumberOfObjectAttributes( int objectType, int objectIndex ); const char* GetObjectAttributeName( int objectType, int objectIndex, int attribIndex ); int GetObjectAttributeIndex( int objectType, int objectIndex, const char* attribName ); int GetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex ); int GetObjectAttributeStatus( int objectType, int objectIndex, const char* attribName ) { return this->GetObjectAttributeStatus( objectType, objectIndex, this->GetObjectAttributeIndex( objectType, objectIndex, attribName ) ); } void SetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex, int status ); void SetObjectAttributeStatus( int objectType, int objectIndex, const char* attribName, int status ) { this->SetObjectAttributeStatus( objectType, objectIndex, this->GetObjectAttributeIndex( objectType, objectIndex, attribName ), status ); } virtual vtkIdType GetTotalNumberOfNodes(); virtual vtkIdType GetTotalNumberOfEdges(); virtual vtkIdType GetTotalNumberOfFaces(); virtual vtkIdType GetTotalNumberOfElements(); // Descriptions: // By default all parts are loaded. These methods allow the user to select // which parts they want to load. You can get information about the parts // by first caling UpdateInformation, and using GetPartArrayName ... int GetNumberOfPartArrays(); const char* GetPartArrayName(int arrayIdx); int GetPartArrayID( const char *name ); const char* GetPartBlockInfo(int arrayIdx); void SetPartArrayStatus(int index, int flag); void SetPartArrayStatus(const char*, int flag); int GetPartArrayStatus(int index); int GetPartArrayStatus(const char*); // Descriptions: // By default all materials are loaded. These methods allow the user to // select which materials they want to load. You can get information // about the materials by first caling UpdateInformation, and using // GetMaterialArrayName ... int GetNumberOfMaterialArrays(); const char* GetMaterialArrayName(int arrayIdx); int GetMaterialArrayID( const char *name ); void SetMaterialArrayStatus(int index, int flag); void SetMaterialArrayStatus(const char*, int flag); int GetMaterialArrayStatus(int index); int GetMaterialArrayStatus(const char*); // Descriptions: // By default all assemblies are loaded. These methods allow the user to // select which assemblies they want to load. You can get information // about the assemblies by first caling UpdateInformation, and using // GetAssemblyArrayName ... int GetNumberOfAssemblyArrays(); const char* GetAssemblyArrayName(int arrayIdx); int GetAssemblyArrayID( const char *name ); void SetAssemblyArrayStatus(int index, int flag); void SetAssemblyArrayStatus(const char*, int flag); int GetAssemblyArrayStatus(int index); int GetAssemblyArrayStatus(const char*); // Descriptions: // By default all hierarchy entries are loaded. These methods allow //the user to // select which hierarchy entries they want to load. You can get information // about the hierarchy entries by first caling UpdateInformation, and using // GetHierarchyArrayName ... //these methods do not call functions in metaData. They call functions on //the ExodusXMLParser since it seemed silly to duplicate all the information int GetNumberOfHierarchyArrays(); const char* GetHierarchyArrayName(int arrayIdx); void SetHierarchyArrayStatus(int index, int flag); void SetHierarchyArrayStatus(const char*, int flag); int GetHierarchyArrayStatus(int index); int GetHierarchyArrayStatus(const char*); vtkGetMacro(DisplayType,int); virtual void SetDisplayType(int type); // Description: // There is a great deal of model information lost when an Exodus II // file is read in to a vtkMultiBlockDataSet. Turn this option ON // if you want this metadata to be read in to a vtkExodusModel object. // The default is OFF. vtkBooleanMacro(ExodusModelMetadata, int); vtkSetMacro(ExodusModelMetadata, int); vtkGetMacro(ExodusModelMetadata, int); // Description: // Returns the object which encapsulates the model metadata. vtkGetObjectMacro(ExodusModel,vtkExodusModel); // Description: // By default, the ExodusModel metadata (if requested with // ExodusModelMetadataOn()) is also encoded into field arrays // and attached to the output unstructured grid. Set this OFF // if you don't want this to happen. (The vtkExodusIIWriter and // the vtkEnSightWriter can unpack this metadata from the field // arrays and use it when writing out Exodus or EnSight files.) vtkSetMacro(PackExodusModelOntoOutput, int); vtkGetMacro(PackExodusModelOntoOutput, int); vtkBooleanMacro(PackExodusModelOntoOutput, int); // Descriptions: // return boolean indicating whether the type,name is a valid variable int IsValidVariable( const char *type, const char *name ); // Descriptions: // Return the id of the type,name variable int GetVariableID ( const char *type, const char *name ); void SetAllArrayStatus( int otype, int status ); // Helper functions //static int StringsEqual(const char* s1, char* s2); //static void StringUppercase(const char* str, char* upperstr); //static char *StrDupWithNew(const char *s); // time series query functions int GetTimeSeriesData( int ID, const char *vName, const char *vType, vtkFloatArray *result ); int GetNumberOfEdgeBlockArrays() { return this->GetNumberOfObjects(EDGE_BLOCK); } const char* GetEdgeBlockArrayName(int index) { return this->GetObjectName(EDGE_BLOCK, index); } int GetEdgeBlockArrayStatus(const char* name) { return this->GetObjectStatus(EDGE_BLOCK, name); } void SetEdgeBlockArrayStatus(const char* name, int flag) { this->SetObjectStatus(EDGE_BLOCK, name, flag); } int GetNumberOfFaceBlockArrays() { return this->GetNumberOfObjects(FACE_BLOCK); } const char* GetFaceBlockArrayName(int index) { return this->GetObjectName(FACE_BLOCK, index); } int GetFaceBlockArrayStatus(const char* name) { return this->GetObjectStatus(FACE_BLOCK, name); } void SetFaceBlockArrayStatus(const char* name, int flag) { this->SetObjectStatus(FACE_BLOCK, name, flag); } int GetNumberOfElementBlockArrays() { return this->GetNumberOfObjects(ELEM_BLOCK); } const char* GetElementBlockArrayName(int index) { return this->GetObjectName(ELEM_BLOCK, index); } int GetElementBlockArrayStatus(const char* name) { return this->GetObjectStatus(ELEM_BLOCK, name); } void SetElementBlockArrayStatus(const char* name, int flag) { this->SetObjectStatus(ELEM_BLOCK, name, flag); } int GetNumberOfGlobalResultArrays() { return this->GetNumberOfObjectArrays(GLOBAL); } const char* GetGlobalResultArrayName(int index) { return this->GetObjectArrayName(GLOBAL, index); } int GetGlobalResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(GLOBAL, name); } void SetGlobalResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(GLOBAL, name, flag); } int GetNumberOfPointResultArrays() { return this->GetNumberOfObjectArrays(NODAL); } const char* GetPointResultArrayName(int index) { return this->GetObjectArrayName(NODAL, index); } int GetPointResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(NODAL, name); } void SetPointResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(NODAL, name, flag); } int GetNumberOfEdgeResultArrays() { return this->GetNumberOfObjectArrays(EDGE_BLOCK); } const char* GetEdgeResultArrayName(int index) { return this->GetObjectArrayName(EDGE_BLOCK, index); } int GetEdgeResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(EDGE_BLOCK, name); } void SetEdgeResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(EDGE_BLOCK, name, flag); } int GetNumberOfFaceResultArrays() { return this->GetNumberOfObjectArrays(FACE_BLOCK); } const char* GetFaceResultArrayName(int index) { return this->GetObjectArrayName(FACE_BLOCK, index); } int GetFaceResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(FACE_BLOCK, name); } void SetFaceResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(FACE_BLOCK, name, flag); } int GetNumberOfElementResultArrays() { return this->GetNumberOfObjectArrays(ELEM_BLOCK); } const char* GetElementResultArrayName(int index) { return this->GetObjectArrayName(ELEM_BLOCK, index); } int GetElementResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(ELEM_BLOCK, name); } void SetElementResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(ELEM_BLOCK, name, flag); } int GetNumberOfNodeMapArrays() { return this->GetNumberOfObjects(NODE_MAP); } const char* GetNodeMapArrayName(int index) { return this->GetObjectName(NODE_MAP, index); } int GetNodeMapArrayStatus(const char* name) { return this->GetObjectStatus(NODE_MAP, name); } void SetNodeMapArrayStatus(const char* name, int flag) { this->SetObjectStatus(NODE_MAP, name, flag); } int GetNumberOfEdgeMapArrays() { return this->GetNumberOfObjects(EDGE_MAP); } const char* GetEdgeMapArrayName(int index) { return this->GetObjectName(EDGE_MAP, index); } int GetEdgeMapArrayStatus(const char* name) { return this->GetObjectStatus(EDGE_MAP, name); } void SetEdgeMapArrayStatus(const char* name, int flag) { this->SetObjectStatus(EDGE_MAP, name, flag); } int GetNumberOfFaceMapArrays() { return this->GetNumberOfObjects(FACE_MAP); } const char* GetFaceMapArrayName(int index) { return this->GetObjectName(FACE_MAP, index); } int GetFaceMapArrayStatus(const char* name) { return this->GetObjectStatus(FACE_MAP, name); } void SetFaceMapArrayStatus(const char* name, int flag) { this->SetObjectStatus(FACE_MAP, name, flag); } int GetNumberOfElementMapArrays() { return this->GetNumberOfObjects(ELEM_MAP); } const char* GetElementMapArrayName(int index) { return this->GetObjectName(ELEM_MAP, index); } int GetElementMapArrayStatus(const char* name) { return this->GetObjectStatus(ELEM_MAP, name); } void SetElementMapArrayStatus(const char* name, int flag) { this->SetObjectStatus(ELEM_MAP, name, flag); } int GetNumberOfNodeSetArrays() { return this->GetNumberOfObjects(NODE_SET); } const char* GetNodeSetArrayName(int index) { return this->GetObjectName(NODE_SET, index); } int GetNodeSetArrayStatus(const char* name) { return this->GetObjectStatus(NODE_SET, name); } void SetNodeSetArrayStatus(const char* name, int flag) { this->SetObjectStatus(NODE_SET, name, flag); } int GetNumberOfSideSetArrays() { return this->GetNumberOfObjects(SIDE_SET); } const char* GetSideSetArrayName(int index) { return this->GetObjectName(SIDE_SET, index); } int GetSideSetArrayStatus(const char* name) { return this->GetObjectStatus(SIDE_SET, name); } void SetSideSetArrayStatus(const char* name, int flag) { this->SetObjectStatus(SIDE_SET, name, flag); } int GetNumberOfEdgeSetArrays() { return this->GetNumberOfObjects(EDGE_SET); } const char* GetEdgeSetArrayName(int index) { return this->GetObjectName(EDGE_SET, index); } int GetEdgeSetArrayStatus(const char* name) { return this->GetObjectStatus(EDGE_SET, name); } void SetEdgeSetArrayStatus(const char* name, int flag) { this->SetObjectStatus(EDGE_SET, name, flag); } int GetNumberOfFaceSetArrays() { return this->GetNumberOfObjects(FACE_SET); } const char* GetFaceSetArrayName(int index) { return this->GetObjectName(FACE_SET, index); } int GetFaceSetArrayStatus(const char* name) { return this->GetObjectStatus(FACE_SET, name); } void SetFaceSetArrayStatus(const char* name, int flag) { this->SetObjectStatus(FACE_SET, name, flag); } int GetNumberOfElementSetArrays() { return this->GetNumberOfObjects(ELEM_SET); } const char* GetElementSetArrayName(int index) { return this->GetObjectName(ELEM_SET, index); } int GetElementSetArrayStatus(const char* name) { return this->GetObjectStatus(ELEM_SET, name); } void SetElementSetArrayStatus(const char* name, int flag) { this->SetObjectStatus(ELEM_SET, name, flag); } int GetNumberOfNodeSetResultArrays() { return this->GetNumberOfObjectArrays(NODE_SET); } const char* GetNodeSetResultArrayName(int index) { return this->GetObjectArrayName(NODE_SET, index); } int GetNodeSetResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(NODE_SET, name); } void SetNodeSetResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(NODE_SET, name, flag); } int GetNumberOfSideSetResultArrays() { return this->GetNumberOfObjectArrays(SIDE_SET); } const char* GetSideSetResultArrayName(int index) { return this->GetObjectArrayName(SIDE_SET, index); } int GetSideSetResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(SIDE_SET, name); } void SetSideSetResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(SIDE_SET, name, flag); } int GetNumberOfEdgeSetResultArrays() { return this->GetNumberOfObjectArrays(EDGE_SET); } const char* GetEdgeSetResultArrayName(int index) { return this->GetObjectArrayName(EDGE_SET, index); } int GetEdgeSetResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(EDGE_SET, name); } void SetEdgeSetResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(EDGE_SET, name, flag); } int GetNumberOfFaceSetResultArrays() { return this->GetNumberOfObjectArrays(FACE_SET); } const char* GetFaceSetResultArrayName(int index) { return this->GetObjectArrayName(FACE_SET, index); } int GetFaceSetResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(FACE_SET, name); } void SetFaceSetResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(FACE_SET, name, flag); } int GetNumberOfElementSetResultArrays() { return this->GetNumberOfObjectArrays(ELEM_SET); } const char* GetElementSetResultArrayName(int index) { return this->GetObjectArrayName(ELEM_SET, index); } int GetElementSetResultArrayStatus(const char* name) { return this->GetObjectArrayStatus(ELEM_SET, name); } void SetElementSetResultArrayStatus(const char* name, int flag) { this->SetObjectArrayStatus(ELEM_SET, name, flag); } /**!\brief Fast path * * The following are set using the fast-path keys found in * vtkPExodusIIReader's input information. * Fast-path keys are meant to be used by an filter that * works with temporal data. Rather than re-executing the pipeline * for each timestep, since the exodus reader, as part of its API, contains * a faster way to read temporal data, algorithms may use these * keys to request temporal data. * See also: vtkExtractArraysOverTime. */ //@{ // Description: // Set the fast-path keys. All three must be set for the fast-path // option to work. // Possible argument values: "POINT","CELL","EDGE","FACE" void SetFastPathObjectType(const char *type); // Description: // Possible argument values: "INDEX","GLOBAL" // "GLOBAL" means the id refers to a global id // "INDEX" means the id refers to an index into the VTK array void SetFastPathIdType(const char *type); void SetFastPathObjectId(vtkIdType id); //@} // Description: // Reset the user-specified parameters and flush internal arrays // so that the reader state is just as it was after the reader was // instantiated. // // It doesn't make sense to let users reset only the internal state; // both the settings and the state are changed by this call. void Reset(); // Description: // Reset the user-specified parameters to their default values. // The only settings not affected are the filename and/or pattern // because these have no default. // // Resetting the settings but not the state allows users to // keep the active cache but return to initial array selections, etc. void ResetSettings(); // Description: // Clears out the cache entries. void ResetCache(); // Description: // Re-reads time information from the exodus file and updates // TimeStepRange accordingly. virtual void UpdateTimeInformation(); virtual void Dump(); // Description: // SIL describes organization of/relationships between classifications // eg. blocks/materials/hierarchies. vtkGraph* GetSIL(); // Description: // Every time the SIL is updated a this will return a different value. vtkGetMacro(SILUpdateStamp, int); // Description: // HACK: Used by vtkPExodusIIReader to tell is the reader produced a valid // fast path output. vtkGetMacro(ProducedFastPathOutput, bool); protected: vtkExodusIIReader(); ~vtkExodusIIReader(); // Description: // Reset or create an ExodusModel and turn on arrays that must be present for the ExodusIIWriter virtual void NewExodusModel(); // helper for finding IDs static int GetIDHelper ( const char *arrayName, vtkDataSet *data, int localID, int searchType ); static int GetGlobalID( const char *arrayName, vtkDataSet *data, int localID, int searchType ); virtual void SetMetadata( vtkExodusIIReaderPrivate* ); vtkGetObjectMacro(Metadata,vtkExodusIIReaderPrivate); // Description: // Returns true if XMLFileName has already been set. Otherwise, look for the XML // metadata file in the same directory as the data file(s) using the following // possible file names: // DATA_FILE_NAME.xml // DATA_FILE_NAME.dart // artifact.dta // Return true if found, false otherwise bool FindXMLFile(); // Time query function. Called by ExecuteInformation(). // Fills the TimestepValues array. void GetAllTimes(vtkInformationVector*); // Description: // Populates the TIME_STEPS and TIME_RANGE keys based on file metadata. void AdvertiseTimeSteps( vtkInformation* outputInfo ); virtual void SetExodusModel( vtkExodusModel* em ); int ProcessRequest( vtkInformation *, vtkInformationVector **, vtkInformationVector *); int RequestInformation( vtkInformation *, vtkInformationVector **, vtkInformationVector *); int RequestData( vtkInformation *, vtkInformationVector **, vtkInformationVector *); //int RequestDataOverTime( vtkInformation *, vtkInformationVector **, vtkInformationVector *); // Parameters for controlling what is read in. char* FileName; char* XMLFileName; int TimeStep; int TimeStepRange[2]; vtkTimeStamp FileNameMTime; vtkTimeStamp XMLFileNameMTime; // Information specific for exodus files. //1=display Block names //2=display Part names //3=display Material names int DisplayType; // Metadata containing a description of the currently open file. vtkExodusIIReaderPrivate* Metadata; vtkExodusModel *ExodusModel; int PackExodusModelOntoOutput; int ExodusModelMetadata; int SILUpdateStamp; bool ProducedFastPathOutput; private: vtkExodusIIReader(const vtkExodusIIReader&); // Not implemented void operator=(const vtkExodusIIReader&); // Not implemented void AddDisplacements(vtkUnstructuredGrid* output); }; #endif
{ "content_hash": "43901beb971d36e1cfb890b981d871c4", "timestamp": "", "source": "github", "line_count": 774, "max_line_length": 111, "avg_line_length": 43.91860465116279, "alnum_prop": 0.731003441885094, "repo_name": "daviddoria/PointGraphsPhase1", "id": "3cac6e3cda9fefc5280919e22f1c1398f9ce35bc", "size": "34580", "binary": false, "copies": "1", "ref": "refs/heads/PointGraphsPhase1", "path": "Hybrid/vtkExodusIIReader.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "40489" }, { "name": "C", "bytes": "43183331" }, { "name": "C++", "bytes": "52316409" }, { "name": "Java", "bytes": "97436" }, { "name": "Objective-C", "bytes": "105122" }, { "name": "Perl", "bytes": "174808" }, { "name": "Python", "bytes": "1005369" }, { "name": "Shell", "bytes": "22210" }, { "name": "Tcl", "bytes": "1922521" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a2cdbcf4bc20c99cb4692e1c3c039ce6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "8fc0963c2402e1d2ed628a8a330bfb077f13354a", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Woodsiaceae/Athyrium/Athyrium javanicum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package bookshop2.seller.incoming.purchaseBooks; import static javax.ejb.TransactionAttributeType.REQUIRED; import javax.annotation.Resource; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.inject.Inject; import javax.jws.HandlerChain; import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebService; import javax.transaction.TransactionSynchronizationRegistry; import javax.xml.ws.WebServiceContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aries.tx.module.Bootstrapper; import org.aries.util.ExceptionUtil; import bookshop2.ShipmentScheduledMessage; import bookshop2.seller.SellerContext; @Remote(ShipmentScheduled.class) @Stateless(name = "ShipmentScheduled") @WebService(name = "shipmentScheduled", serviceName = "shipmentScheduledService", portName = "shipmentScheduled", targetNamespace = "http://bookshop2/seller") @HandlerChain(file = "/jaxws-handlers-service-oneway.xml") public class ShipmentScheduledListenerForJAXWS implements ShipmentScheduled { private static final Log log = LogFactory.getLog(ShipmentScheduledListenerForJAXWS.class); @Inject private SellerContext sellerContext; @Inject private ShipmentScheduledHandler shipmentScheduledHandler; @Resource private WebServiceContext webServiceContext; @Resource private TransactionSynchronizationRegistry transactionSynchronizationRegistry; @Oneway @Override @WebMethod @TransactionAttribute(REQUIRED) public void shipmentScheduled(ShipmentScheduledMessage shipmentScheduledMessage) { if (!Bootstrapper.isInitialized("bookshop2-seller-service")) return; try { sellerContext.validate(shipmentScheduledMessage); shipmentScheduledHandler.shipmentScheduled(shipmentScheduledMessage); } catch (Throwable e) { log.error(e); throw ExceptionUtil.rewrap(e); } } }
{ "content_hash": "744eac88fbe1979325aead4b3d46d592", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 158, "avg_line_length": 29.476923076923075, "alnum_prop": 0.8178496868475992, "repo_name": "tfisher1226/ARIES", "id": "d8bf3e8d9c1a1a1998cd7537244a3cd0a5befd42", "size": "1916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bookshop2/bookshop2-seller/bookshop2-seller-service/src/main/java/bookshop2/seller/incoming/purchaseBooks/ShipmentScheduledListenerForJAXWS.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1606" }, { "name": "CSS", "bytes": "660469" }, { "name": "Common Lisp", "bytes": "91717" }, { "name": "Emacs Lisp", "bytes": "12403" }, { "name": "GAP", "bytes": "86009" }, { "name": "HTML", "bytes": "9381408" }, { "name": "Java", "bytes": "25671734" }, { "name": "JavaScript", "bytes": "304513" }, { "name": "Shell", "bytes": "51942" } ], "symlink_target": "" }
package MachineLearning;import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Stroke; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.swing.*; @SuppressWarnings("serial") public class DrawGraph extends JPanel { private static final int MAX_SCORE = 20; private static final int PREF_W = 800; private static final int PREF_H = 650; private static final int BORDER_GAP = 30; private static final Color GRAPH_COLOR = Color.green; private static final Color GRAPH_POINT_COLOR = new Color(150, 50, 50, 180); private static final Stroke GRAPH_STROKE = new BasicStroke(3f); private static final int GRAPH_POINT_WIDTH = 12; private static final int Y_HATCH_CNT = 10; private List<Integer> scores; public DrawGraph(List<Integer> scores) { this.scores = scores; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); double xScale = ((double) getWidth() - 2 * BORDER_GAP) / (scores.size() - 1); double yScale = ((double) getHeight() - 2 * BORDER_GAP) / (MAX_SCORE - 1); List<Point> graphPoints = new ArrayList<Point>(); for (int i = 0; i < scores.size(); i++) { int x1 = (int) (i * xScale + BORDER_GAP); int y1 = (int) ((MAX_SCORE - scores.get(i)) * yScale + BORDER_GAP); graphPoints.add(new Point(x1, y1)); } // create x and y axes g2.drawLine(BORDER_GAP, getHeight() - BORDER_GAP, BORDER_GAP, BORDER_GAP); g2.drawLine(BORDER_GAP, getHeight() - BORDER_GAP, getWidth() - BORDER_GAP, getHeight() - BORDER_GAP); // create hatch marks for y axis. for (int i = 0; i < Y_HATCH_CNT; i++) { int x0 = BORDER_GAP; int x1 = GRAPH_POINT_WIDTH + BORDER_GAP; int y0 = getHeight() - (((i + 1) * (getHeight() - BORDER_GAP * 2)) / Y_HATCH_CNT + BORDER_GAP); int y1 = y0; g2.drawLine(x0, y0, x1, y1); } // and for x axis for (int i = 0; i < scores.size() - 1; i++) { int x0 = (i + 1) * (getWidth() - BORDER_GAP * 2) / (scores.size() - 1) + BORDER_GAP; int x1 = x0; int y0 = getHeight() - BORDER_GAP; int y1 = y0 - GRAPH_POINT_WIDTH; g2.drawLine(x0, y0, x1, y1); } Stroke oldStroke = g2.getStroke(); g2.setColor(GRAPH_COLOR); g2.setStroke(GRAPH_STROKE); for (int i = 0; i < graphPoints.size() - 1; i++) { int x1 = graphPoints.get(i).x; int y1 = graphPoints.get(i).y; int x2 = graphPoints.get(i + 1).x; int y2 = graphPoints.get(i + 1).y; g2.drawLine(x1, y1, x2, y2); } g2.setStroke(oldStroke); g2.setColor(GRAPH_POINT_COLOR); for (int i = 0; i < graphPoints.size(); i++) { int x = graphPoints.get(i).x - GRAPH_POINT_WIDTH / 2; int y = graphPoints.get(i).y - GRAPH_POINT_WIDTH / 2;; int ovalW = GRAPH_POINT_WIDTH; int ovalH = GRAPH_POINT_WIDTH; g2.fillOval(x, y, ovalW, ovalH); } } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } private static void createAndShowGui() { List<Integer> scores = new ArrayList<Integer>(); Random random = new Random(); int maxDataPoints = 16; int maxScore = 20; for (int i = 0; i < maxDataPoints ; i++) { scores.add(random.nextInt(maxScore)); } DrawGraph mainPanel = new DrawGraph(scores); JFrame frame = new JFrame("DrawGraph"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } }
{ "content_hash": "90ef47a35b15189382576befcca10944", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 107, "avg_line_length": 34.79338842975206, "alnum_prop": 0.603562945368171, "repo_name": "topangad/MachineLearning", "id": "5f7ce4c5836512330d9f089e11b660db218ae04f", "size": "4210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DrawGraph.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "42705" } ], "symlink_target": "" }
(function($) { "use strict"; // Start of use strict // jQuery for page scrolling feature - requires jQuery Easing plugin $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top - 50) }, 1250, 'easeInOutExpo'); event.preventDefault(); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top', offset: 51 }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function() { $('.navbar-toggle:visible').click(); }); // Offset for Main Navigation $('#mainNav').affix({ offset: { top: 100 } }) // Initialize and Configure Magnific Popup Lightbox Plugin $('.popup-gallery').magnificPopup({ delegate: 'a', type: 'image', tLoading: 'Loading image #%curr%...', mainClass: 'mfp-img-mobile', gallery: { enabled: true, navigateByImgClick: true, preload: [0, 1] // Will preload 0 - before current, and 1 after the current image }, image: { tError: '<a href="%url%">The image #%curr%</a> could not be loaded.' } }); })(jQuery); // End of use strict
{ "content_hash": "37d67bd2fe1ee75b4adbb0568cc38f7a", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 93, "avg_line_length": 28.816326530612244, "alnum_prop": 0.5382436260623229, "repo_name": "codephil2016/codephil2016.github.io", "id": "f39940a35a73fcab6abad104fc5b9b5c0f302e30", "size": "1412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/creative.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18695" }, { "name": "HTML", "bytes": "17409" }, { "name": "JavaScript", "bytes": "5265" } ], "symlink_target": "" }
<html lang="en"> <head> <title>ftell - Untitled</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Untitled"> <meta name="generator" content="makeinfo 4.11"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Stdio.html#Stdio" title="Stdio"> <link rel="prev" href="fsetpos.html#fsetpos" title="fsetpos"> <link rel="next" href="funopen.html#funopen" title="funopen"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="ftell"></a> Next:&nbsp;<a rel="next" accesskey="n" href="funopen.html#funopen">funopen</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="fsetpos.html#fsetpos">fsetpos</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Stdio.html#Stdio">Stdio</a> <hr> </div> <h3 class="section">4.28 <code>ftell</code>, <code>ftello</code>&mdash;return position in a stream or file</h3> <p><a name="index-ftell-204"></a><a name="index-ftello-205"></a><a name="index-g_t_005fftell_005fr-206"></a><a name="index-g_t_005fftello_005fr-207"></a><strong>Synopsis</strong> <pre class="example"> #include &lt;stdio.h&gt; long ftell(FILE *<var>fp</var>); off_t ftello(FILE *<var>fp</var>); long _ftell_r(struct _reent *<var>ptr</var>, FILE *<var>fp</var>); off_t _ftello_r(struct _reent *<var>ptr</var>, FILE *<var>fp</var>); </pre> <p><strong>Description</strong><br> Objects of type <code>FILE</code> can have a &ldquo;position&rdquo; that records how much of the file your program has already read. Many of the <code>stdio</code> functions depend on this position, and many change it as a side effect. <p>The result of <code>ftell</code>/<code>ftello</code> is the current position for a file identified by <var>fp</var>. If you record this result, you can later use it with <code>fseek</code>/<code>fseeko</code> to return the file to this position. The difference between <code>ftell</code> and <code>ftello</code> is that <code>ftell</code> returns <code>long</code> and <code>ftello</code> returns <code>off_t</code>. <p>In the current implementation, <code>ftell</code>/<code>ftello</code> simply uses a character count to represent the file position; this is the same number that would be recorded by <code>fgetpos</code>. <p><br> <strong>Returns</strong><br> <code>ftell</code>/<code>ftello</code> return the file position, if possible. If they cannot do this, they return <code>-1L</code>. Failure occurs on streams that do not support positioning; the global <code>errno</code> indicates this condition with the value <code>ESPIPE</code>. <p><br> <strong>Portability</strong><br> <code>ftell</code> is required by the ANSI C standard, but the meaning of its result (when successful) is not specified beyond requiring that it be acceptable as an argument to <code>fseek</code>. In particular, other conforming C implementations may return a different result from <code>ftell</code> than what <code>fgetpos</code> records. <p><code>ftello</code> is defined by the Single Unix specification. <p>No supporting OS subroutines are required. <p><br> </body></html>
{ "content_hash": "7ab5c45b81313e3c5b82d34e3f2f508c", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 178, "avg_line_length": 45.63414634146341, "alnum_prop": 0.705237840726884, "repo_name": "marduino/stm32Proj", "id": "9ae71e586dff08f9c3640a17825c9628820196eb", "size": "3742", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/armgcc/share/doc/gcc-arm-none-eabi/html/libc/ftell.html", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "23333" }, { "name": "C", "bytes": "4470437" }, { "name": "C++", "bytes": "655791" }, { "name": "HTML", "bytes": "109" }, { "name": "Makefile", "bytes": "10291" } ], "symlink_target": "" }
package com.github.ambry.utils; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; /** * A non-blocking {@link ByteBuffer} based {@link InputStream} extension that materializes the whole content in memory. */ public class ByteBufferInputStream extends InputStream { private ByteBuffer byteBuffer; private int mark; private int readLimit; public ByteBufferInputStream(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; this.mark = -1; this.readLimit = -1; } /** * Reads 'size' amount of bytes from the stream into the buffer. * @param stream The stream from which bytes need to be read. If the underlying stream is SocketInputStream, it needs * to be blocking. * @param size The size that needs to be read from the stream * @throws IOException */ public ByteBufferInputStream(InputStream stream, int size) throws IOException { this.byteBuffer = ByteBuffer.allocate(size); int read = 0; ReadableByteChannel readableByteChannel = Channels.newChannel(stream); while (read < size) { int sizeRead = readableByteChannel.read(byteBuffer); if (sizeRead == 0 || sizeRead == -1) { throw new IOException("Total size read " + read + " is less than the size to be read " + size); } read += sizeRead; } byteBuffer.flip(); this.mark = -1; this.readLimit = -1; } @Override public int read() throws IOException { if (!byteBuffer.hasRemaining()) { return -1; } return byteBuffer.get() & 0xFF; } @Override public int read(byte[] bytes, int offset, int length) throws IOException { if (bytes == null) { throw new NullPointerException(); } else if (offset < 0 || length < 0 || length > bytes.length - offset) { throw new IndexOutOfBoundsException(); } else if (length == 0) { return 0; } int count = Math.min(byteBuffer.remaining(), length); if (count == 0) { return -1; } byteBuffer.get(bytes, offset, count); return count; } @Override public int available() throws IOException { return byteBuffer.remaining(); } @Override public synchronized void reset() throws IOException { if (readLimit == -1 || mark == -1) { throw new IOException("Mark not set before reset invoked."); } if (byteBuffer.position() - mark > readLimit) { throw new IOException("Read limit exceeded before reset invoked."); } byteBuffer.reset(); } @Override public synchronized void mark(int readLimit) { this.mark = byteBuffer.position(); this.readLimit = readLimit; byteBuffer.mark(); } @Override public boolean markSupported() { return true; } public ByteBufferInputStream duplicate() { return new ByteBufferInputStream(byteBuffer.duplicate()); } /** * Return the underlying read-only {@link ByteBuffer} associated with this ByteBufferInputStream. * <br> * Combining the reads from the returned {@link ByteBuffer} and the other read methods of this stream can lead to * unexpected behavior. * @return the underlying read-only {@link ByteBuffer} associated with this ByteBufferInputStream. */ public ByteBuffer getByteBuffer() { return byteBuffer.asReadOnlyBuffer(); } }
{ "content_hash": "af4de2786283c6151059043e079ef198", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 119, "avg_line_length": 29.155172413793103, "alnum_prop": 0.6750443524541692, "repo_name": "pnarayanan/ambry", "id": "5c8712f5ea1b319b715cf24bfdc02198226d002d", "size": "3892", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ambry-utils/src/main/java/com.github.ambry.utils/ByteBufferInputStream.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8137909" }, { "name": "Python", "bytes": "7025" } ], "symlink_target": "" }
.class public Lcom/xiaomi/channel/sdk/Constants; .super Ljava/lang/Object; # static fields .field public static final LOGGING_TAG:Ljava/lang/String; = "miliao_sdk_log" .field public static final RESULT_CODE_OK:I = 0x2711 # direct methods .method public constructor <init>()V .locals 0 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method
{ "content_hash": "f01cabc7bbe5d373cace3bc030ba8e4e", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 76, "avg_line_length": 21, "alnum_prop": 0.7222222222222222, "repo_name": "vishnudevk/MiBandDecompiled", "id": "5d9c1bd6a8ddf08151513a623f095f1380d22195", "size": "378", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Original Files/source/smali/com/xiaomi/channel/sdk/Constants.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "109824" }, { "name": "Java", "bytes": "8906016" }, { "name": "Lua", "bytes": "134432" } ], "symlink_target": "" }
package com.quizbowl.app.question; import com.quizbowl.app.dataStore.MCQstore; public class MCQquestion extends Question { private String[] answer; private String genAnswer; private String keys; public MCQquestion(MCQstore object) { super(object.getQuestion(),"MCQ"); this.keys = object.getAnswer(); this.answer = object.getChoices(); this.converter(); this.setAnswer(this.genAnswer); } @Override protected void converter() { int key_gen = (int)this.keys.charAt(0); this.genAnswer = this.answer[key_gen - 'A']; return; } }
{ "content_hash": "36cdd62e12d2c90197d34d0a02ed9aaf", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 47, "avg_line_length": 21.346153846153847, "alnum_prop": 0.7171171171171171, "repo_name": "shivasurya/QuizBowl", "id": "f87536709ba2de0e37ddd80464d5cade4b4764cc", "size": "555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/quizbowl/app/question/MCQquestion.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "11833" } ], "symlink_target": "" }
import {filterAttr} from './attr'; import {includes, isString, isUndefined, toNodes} from './lang'; export function addClass(element, ...args) { apply(element, args, 'add'); } export function removeClass(element, ...args) { apply(element, args, 'remove'); } export function removeClasses(element, cls) { filterAttr(element, 'class', new RegExp(`(^|\\s)${cls}(?!\\S)`, 'g'), ''); } export function replaceClass(element, ...args) { args[0] && removeClass(element, args[0]); args[1] && addClass(element, args[1]); } export function hasClass(element, cls) { return toNodes(element).some(element => element.classList.contains(cls)); } export function toggleClass(element, ...args) { if (!args.length) { return; } args = getArgs(args); const force = !isString(args[args.length - 1]) ? args.pop() : []; // in iOS 9.3 force === undefined evaluates to false args = args.filter(Boolean); toNodes(element).forEach(({classList}) => { for (let i = 0; i < args.length; i++) { supports.Force ? classList.toggle(...[args[i]].concat(force)) : (classList[(!isUndefined(force) ? force : !classList.contains(args[i])) ? 'add' : 'remove'](args[i])); } }); } function apply(element, args, fn) { args = getArgs(args).filter(Boolean); args.length && toNodes(element).forEach(({classList}) => { supports.Multiple ? classList[fn](...args) : args.forEach(cls => classList[fn](cls)); }); } function getArgs(args) { return args.reduce((args, arg) => args.concat.call(args, isString(arg) && includes(arg, ' ') ? arg.trim().split(' ') : arg) , []); } const supports = {}; // IE 11 (function () { let list = document.createElement('_').classList; if (list) { list.add('a', 'b'); list.toggle('c', false); supports.Multiple = list.contains('b'); supports.Force = !list.contains('c'); } list = null; })();
{ "content_hash": "9d6bfaf023bfe856e90d8440b0c9c468", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 122, "avg_line_length": 26.25974025974026, "alnum_prop": 0.5781404549950544, "repo_name": "aoimedia/uikit", "id": "ccec9c086c9267c9f87c2092ab05ae1a22d84540", "size": "2022", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/js/util/class.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1152409" }, { "name": "HTML", "bytes": "992344" }, { "name": "JavaScript", "bytes": "256296" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\devel\Annotation\DevelDumper. */ namespace Drupal\devel\Annotation; use Drupal\Component\Annotation\Plugin; /** * Defines a DevelDumper annotation object. * * @Annotation * * @see \Drupal\devel\DevelDumperPluginManager * @see \Drupal\devel\DevelDumperInterface * @see \Drupal\devel\DevelDumperBase * @see plugin_api */ class DevelDumper extends Plugin { /** * The plugin ID. * * @var string */ public $id; /** * The human-readable name of the DevelDumper type. * * @ingroup plugin_translatable * * @var \Drupal\Core\Annotation\Translation */ public $label; /** * A short description of the DevelDumper type. * * @ingroup plugin_translatable * * @var \Drupal\Core\Annotation\Translation */ public $description; }
{ "content_hash": "e4a9fb3ca0b3037a64360fd3542b3966", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 53, "avg_line_length": 16.918367346938776, "alnum_prop": 0.6622436670687576, "repo_name": "lammensj/tfs", "id": "f4dbbb56d1c5d685d853094599579f161d137e0c", "size": "829", "binary": false, "copies": "69", "ref": "refs/heads/master", "path": "htdocs/modules/contrib/devel/src/Annotation/DevelDumper.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "685" }, { "name": "CSS", "bytes": "551785" }, { "name": "HTML", "bytes": "619384" }, { "name": "JavaScript", "bytes": "963712" }, { "name": "PHP", "bytes": "33350874" }, { "name": "Ruby", "bytes": "582" }, { "name": "Shell", "bytes": "18417" } ], "symlink_target": "" }
function scale_output() global config mem; % this scaling may not be necessary in the future mem.activations{length(mem.activations)} = mem.activations{length(mem.activations)} .* config.NEW_MEM(config.misc.data_sd) + config.NEW_MEM(config.misc.data_mean); end
{ "content_hash": "21749149cf16e2f907e3edb656aa229b", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 167, "avg_line_length": 34.5, "alnum_prop": 0.7318840579710145, "repo_name": "mgharbi/deaf", "id": "51325464f21ad9023421a8eb9b5585b4c0820c93", "size": "276", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "utils/scale_output.m", "mode": "33188", "license": "mit", "language": [ { "name": "Cuda", "bytes": "3307" }, { "name": "M", "bytes": "931" }, { "name": "Matlab", "bytes": "111164" } ], "symlink_target": "" }
package org.dbmaintain.script.repository.impl; import org.dbmaintain.script.Script; import org.dbmaintain.util.TestUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.File; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.dbmaintain.util.TestUtils.createScript; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Filip Neven * @author Tim Ducheyne * @since 28-dec-2008 */ class FileSystemScriptLocationTest { private FileSystemScriptLocation fileSystemScriptLocation; private File scriptRootLocation; private Script indexed1, repeatable1, preProcessing1, postProcessing1; @BeforeEach void init() throws Exception { indexed1 = createScript("01_indexed1.sql"); repeatable1 = createScript("repeatable1.sql"); preProcessing1 = createScript("preprocessing/01_pre1.sql"); postProcessing1 = createScript("postprocessing/01_post1.sql"); scriptRootLocation = new File(getClass().getResource("testscripts").toURI()); fileSystemScriptLocation = TestUtils.createFileSystemLocation(scriptRootLocation); } @Test void testGetAllFiles() { assertEquals(Stream.of(indexed1, repeatable1, preProcessing1, postProcessing1).collect(Collectors.toSet()), fileSystemScriptLocation.getScripts()); } }
{ "content_hash": "3479c1bb37ceac5ba4edd36c1e96ba3b", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 115, "avg_line_length": 33.627906976744185, "alnum_prop": 0.7247579529737206, "repo_name": "DbMaintain/dbmaintain", "id": "98686f850d35bdf85e5ee9e2655c155a3d2b18d6", "size": "2052", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "dbmaintain/src/test/java/org/dbmaintain/script/repository/impl/FileSystemScriptLocationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6590" }, { "name": "Dockerfile", "bytes": "659" }, { "name": "Java", "bytes": "1190155" }, { "name": "Shell", "bytes": "10155" } ], "symlink_target": "" }