text
stringlengths 2
1.04M
| meta
dict |
---|---|
export default {
// extend the resource
associations: true,
};
| {
"content_hash": "bb5f17b910852c6b3f613cc36f7d6248",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 24,
"avg_line_length": 16.75,
"alnum_prop": 0.6865671641791045,
"repo_name": "petekeller2/Epilogue-Starter-Kit",
"id": "661dfb3d6b1347afc4be154e713581fd77244cfc",
"size": "67",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/resources/Todo/extension.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2797175"
},
{
"name": "JavaScript",
"bytes": "200556"
},
{
"name": "Ruby",
"bytes": "1162"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<bitninja.de.holodatepickerdialog.datepicker.DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:holo="http://schemas.android.com/apk/res-auto"
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
holo:calendarViewShown="false"
holo:spinnersShown="true" /> | {
"content_hash": "a85e1d36be61eef9dc42d7d67bb62069",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 114,
"avg_line_length": 48.77777777777778,
"alnum_prop": 0.7357630979498861,
"repo_name": "dgrigutsch/HoloDatePickerDialog",
"id": "3e8ad6bf79c830ff9db627d4158b0a34d7258a16",
"size": "439",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "holodatepickerdialog/src/main/res/layout/date_picker_dialog.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "291766"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="@color/blue700" />
<corners
android:bottomRightRadius="4dp"
android:bottomLeftRadius="4dp"
android:topLeftRadius="4dp"
android:topRightRadius="4dp"/>
</shape> | {
"content_hash": "72bc72704cbc440ce8d80db3d94b27f5",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 65,
"avg_line_length": 30.416666666666668,
"alnum_prop": 0.6493150684931507,
"repo_name": "tbj128/Raindrops",
"id": "4f2fbc458225481a037738fdd590f5107b06fed0",
"size": "365",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/src/main/res/drawable/bg_stats_box.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14999"
},
{
"name": "Java",
"bytes": "288279"
},
{
"name": "JavaScript",
"bytes": "533852"
},
{
"name": "PHP",
"bytes": "376766"
}
],
"symlink_target": ""
} |
(function() {
'use strict';
angular.element(document).ready(function() {
angular.bootstrap(document, ['app']);
});
function config($stateProvider, $urlRouterProvider, $logProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
$logProvider.debugEnabled(true);
$httpProvider.interceptors.push('httpInterceptor');
$stateProvider
.state('root', {
views: {
'header': {
template: '<div>Header</div>',
},
'footer': {
template: '<div>Footer</div>',
}
}
});
}
function MainCtrl($log) {
$log.debug('MainCtrl laoded!');
}
function run($log) {
$log.debug('App is running!');
}
angular.module('app', [
'ui.router',
'home',
'common.filters.uppercase',
'common.interceptors.http',
'templates'
])
.config(config)
.run(run)
.controller('MainCtrl', MainCtrl)
.value('version', '1.1.0');
})();
| {
"content_hash": "18c9c33e6be8ccf0c590c678e5dad7a1",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 84,
"avg_line_length": 22.204545454545453,
"alnum_prop": 0.548618219037871,
"repo_name": "toby533/adopteunfilm",
"id": "9922d2b68c61362a1db2d59dd051f8e57d8d0355",
"size": "977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/app/app.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4072"
},
{
"name": "HTML",
"bytes": "5714"
},
{
"name": "JavaScript",
"bytes": "13772"
}
],
"symlink_target": ""
} |
require 'test_helper'
class UserobjectTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| {
"content_hash": "be0bd3ff681022ab2f4578cf589328ac",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 46,
"avg_line_length": 17.714285714285715,
"alnum_prop": 0.7016129032258065,
"repo_name": "simnotes/countingthings",
"id": "b91b9d0409890444971185876ebed31ed9a5d6c9",
"size": "124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/models/userobject_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "58313"
},
{
"name": "CoffeeScript",
"bytes": "633"
},
{
"name": "JavaScript",
"bytes": "12842"
},
{
"name": "Ruby",
"bytes": "68431"
}
],
"symlink_target": ""
} |
package com.ghoss.android.rappitest.presentation;
import android.app.Application;
import com.ghoss.android.rappitest.presentation.dagger.component.AppComponent;
import com.ghoss.android.rappitest.presentation.dagger.component.DaggerAppComponent;
/**
* Created by rrtatasciore on 14/10/17.
*/
public class RappiApplication extends Application {
private AppComponent component;
@Override
public void onCreate() {
super.onCreate();
component = DaggerAppComponent.builder().build();
component.inject(this);
}
public AppComponent getComponent() {
return component;
}
}
| {
"content_hash": "1843624618752f7fd1ddde2cb97aae80",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 84,
"avg_line_length": 24.192307692307693,
"alnum_prop": 0.7281399046104928,
"repo_name": "phanghos/rappi-test",
"id": "9767bdef22adafdd54ff612537292813623c3f74",
"size": "629",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/ghoss/android/rappitest/presentation/RappiApplication.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "96733"
}
],
"symlink_target": ""
} |
require 'spec_helper'
module Spree
describe Api::OptionValuesController do
render_views
let(:attributes) { [:id, :name, :presentation, :option_type_name, :option_type_name] }
let!(:option_value) { create(:option_value) }
let!(:option_type) { option_value.option_type }
before do
stub_authentication!
end
def check_option_values(option_values)
option_values.count.should == 1
option_values.first.should have_attributes([:id, :name, :presentation,
:option_type_name, :option_type_id])
end
context "without any option type scoping" do
before do
# Create another option value with a brand new option type
create(:option_value, :option_type => create(:option_type))
end
it "can retreive a list of all option values" do
api_get :index
json_response.count.should == 2
json_response.first.should have_attributes(attributes)
end
end
context "for a particular option type" do
let(:resource_scoping) { { :option_type_id => option_type.id } }
it "can list all option values" do
api_get :index
json_response.count.should == 1
json_response.first.should have_attributes(attributes)
end
it "can search for an option type" do
create(:option_value, :name => "buzz")
api_get :index, :q => { :name_cont => option_value.name }
json_response.count.should == 1
json_response.first.should have_attributes(attributes)
end
it "can retreive a list of option types" do
option_value_1 = create(:option_value, :option_type => option_type)
option_value_2 = create(:option_value, :option_type => option_type)
api_get :index, :ids => [option_value.id, option_value_1.id]
json_response.count.should == 2
end
it "can list a single option value" do
api_get :show, :id => option_value.id
json_response.should have_attributes(attributes)
end
it "cannot create a new option value" do
api_post :create, :option_value => {
:name => "Option Value",
:presentation => "Option Value"
}
assert_unauthorized!
end
it "cannot alter an option value" do
original_name = option_type.name
api_put :update, :id => option_type.id,
:option_value => {
:name => "Option Value"
}
assert_unauthorized!
option_type.reload.name.should == original_name
end
it "cannot delete an option value" do
api_delete :destroy, :id => option_type.id
assert_unauthorized!
lambda { option_type.reload }.should_not raise_error
end
context "as an admin" do
sign_in_as_admin!
it "can create an option value" do
api_post :create, :option_value => {
:name => "Option Value",
:presentation => "Option Value"
}
json_response.should have_attributes(attributes)
response.status.should == 201
end
it "cannot create an option type with invalid attributes" do
api_post :create, :option_value => {}
response.status.should == 422
end
it "can update an option value" do
original_name = option_value.name
api_put :update, :id => option_value.id, :option_value => {
:name => "Option Value",
}
response.status.should == 200
option_value.reload
option_value.name.should == "Option Value"
end
it "cannot update an option value with invalid attributes" do
api_put :update, :id => option_value.id, :option_value => {
:name => ""
}
response.status.should == 422
end
it "can delete an option value" do
api_delete :destroy, :id => option_value.id
response.status.should == 204
end
end
end
end
end
| {
"content_hash": "d69f464267c6e488daa6e1e665037108",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 90,
"avg_line_length": 33.296875,
"alnum_prop": 0.5525574847489442,
"repo_name": "Antdesk/karpal-spree",
"id": "9b901212c49f8696f8fca2a66afcbceaf883a5d5",
"size": "4262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/spec/controllers/spree/api/option_values_controller_spec.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "5492"
},
{
"name": "CoffeeScript",
"bytes": "24475"
},
{
"name": "JavaScript",
"bytes": "55981"
},
{
"name": "Ruby",
"bytes": "1338577"
},
{
"name": "Shell",
"bytes": "1620"
}
],
"symlink_target": ""
} |
import Component from '@ember/component';
import layout from '../templates/components/select-dropdown-option';
export default Component.extend({
layout,
classNames: ['es-option'],
classNameBindings: ['model.isSelected:es-highlight'],
click() {
this.select(this.get('model'));
},
mouseEnter() {
this.hover(this.get('model'));
}
});
| {
"content_hash": "4ce7b746a6ac7d50c2d991fd4edee28a",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 68,
"avg_line_length": 22.25,
"alnum_prop": 0.6769662921348315,
"repo_name": "ladadeedee/ember-select",
"id": "98b0ecaf0588fecb6bf57a0a49e95df1661ab2a8",
"size": "356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addon/components/select-dropdown-option.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3041"
},
{
"name": "HTML",
"bytes": "3699"
},
{
"name": "JavaScript",
"bytes": "26125"
}
],
"symlink_target": ""
} |
import React from 'react';
const Row = ({ children }) => {
return (
<div className="clearfix">
{ children }
</div>
);
};
export default Row;
| {
"content_hash": "df1f6c6f9a4ae5aae281057587ede979",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 31,
"avg_line_length": 14.636363636363637,
"alnum_prop": 0.5527950310559007,
"repo_name": "neilff/react-d3-examples",
"id": "e68ad719546683a0832c794e4fbb107d8ecf049f",
"size": "161",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/components/Row.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "200"
},
{
"name": "JavaScript",
"bytes": "5256"
}
],
"symlink_target": ""
} |
#ifndef opengl_COpenGLStandardObject_H
#define opengl_COpenGLStandardObject_H
#include <mrpt/opengl/CRenderizableDisplayList.h>
#include <mrpt/math/geometry.h>
#include <mrpt/utils/stl_extensions.h>
namespace mrpt {
namespace opengl {
typedef uint32_t _GLENUM;
using namespace mrpt::utils;
using namespace mrpt::math;
class OPENGL_IMPEXP COpenGLStandardObject;
DEFINE_SERIALIZABLE_PRE_CUSTOM_BASE_LINKAGE(COpenGLStandardObject,CRenderizableDisplayList, OPENGL_IMPEXP)
/**
* Objects of this class represent a generic openGL object without specific geometric properties.
* \ingroup mrpt_opengl_grp
*/
class OPENGL_IMPEXP COpenGLStandardObject:public CRenderizableDisplayList {
DEFINE_SERIALIZABLE(COpenGLStandardObject)
protected:
/**
* OpenGL identifier of the object type.
*/
_GLENUM type;
/**
* Set of points in which consists this object.
*/
std::vector<TPoint3D> vertices;
/**
* Granularity of the openGL elements. 3 for GL_TRIANGLES, 4 for GL_QUADS, and so on. Setting it to 0 will generate a single openGL object.
*/
uint32_t chunkSize;
/**
* Set of openGL properties enabled in the rendering of this object.
*/
std::vector<_GLENUM> enabled;
float normal[3];
public:
/**
* Render.
* \sa mrpt::opengl::CRenderizable
*/
virtual void render_dl() const;
/** Evaluates the bounding box of this object (including possible children) in the coordinate frame of the object parent. */
virtual void getBoundingBox(mrpt::math::TPoint3D &bb_min, mrpt::math::TPoint3D &bb_max) const;
/**
* Ray Tracing. Will always return false, since objects of this class are not intended to have geometric properties.
* \sa mrpt::opengl::CRenderizable
*/
virtual bool traceRay(const mrpt::poses::CPose3D &o,double &dist) const;
/**
* Creation of object from type, vertices, chunk size and a list of enabled openGL flags.
* \throw std::logic_error if the number of vertices is not an exact multiple of the chunk size.
*/
static COpenGLStandardObjectPtr Create(_GLENUM t,const std::vector<TPoint3D> &v,uint32_t cs=0,const std::vector<_GLENUM> &en=std::vector<_GLENUM>()) {
if (cs!=0&&v.size()%cs!=0) throw std::logic_error("Vertices vector does not match chunk size");
return COpenGLStandardObjectPtr(new COpenGLStandardObject(t,v,cs,en));
}
/**
* Enable some openGL flag.
*/
inline void enable(_GLENUM flag) {
if (find(enabled.begin(),enabled.end(),flag)==enabled.end()) enabled.push_back(flag);
CRenderizableDisplayList::notifyChange();
}
/**
* Disable some openGL flag.
*/
inline void disable(_GLENUM flag) {
std::remove(enabled.begin(),enabled.end(),flag);
CRenderizableDisplayList::notifyChange();
}
/**
* Check whether an openGL will be enabled during the rendering of this object.
*/
inline bool isEnabled(_GLENUM flag) const {
return find(enabled.begin(),enabled.end(),flag)!=enabled.end();
}
/**
* Get a list of all currently enabled openGL flags.
*/
inline void getEnabledFlags(std::vector<_GLENUM> &v) const {
v=enabled;
}
/**
* Set the list of all openGL flags.
*/
inline void setFlags(const std::vector<_GLENUM> &v) {
enabled=v;
CRenderizableDisplayList::notifyChange();
}
/**
* Set the normal vector to this object.
*/
inline void setNormal(const float (&n)[3]) {
for (size_t i=0;i<3;i++) normal[i]=n[i];
CRenderizableDisplayList::notifyChange();
}
/**
* Gets the normal vector to this object.
*/
inline void getNormal(float (&n)[3]) const {
for (size_t i=0;i<3;i++) n[i]=normal[i];
}
private:
/**
* Constructor with all the information.
*/
COpenGLStandardObject(_GLENUM t,const std::vector<TPoint3D> &v,uint32_t cs,const vector<_GLENUM> &en):type(t),vertices(v),chunkSize(cs),enabled(en) {
for (size_t i=0;i<3;i++) normal[i]=0.0;
}
/**
* Baic empty constructor, initializes to default.
*/
COpenGLStandardObject():type(0),vertices(std::vector<TPoint3D>(0)),chunkSize(0),enabled(std::vector<_GLENUM>()) {
for (size_t i=0;i<3;i++) normal[i]=0.0;
}
/**
* Destructor.
*/
virtual ~COpenGLStandardObject() {}
};
} // end namespace
} // End of namespace
#endif
| {
"content_hash": "d51b9c46c2db0808882bb4b7d16ba8bb",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 153,
"avg_line_length": 34.15625,
"alnum_prop": 0.6642268984446478,
"repo_name": "samuelpfchoi/mrpt",
"id": "5b0ce546f7c8624e3f8308763ab48d14f7f10b08",
"size": "5022",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libs/opengl/include/mrpt/opengl/COpenGLStandardObject.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style lang="css">
body {
background-color: #F4F4F4;
color: #333;
font-family: Segoe UI,Tahoma,Arial,Verdana,sans-serif;
}
p#intro {
font-family: Cambria,serif;
font-size: 1.1em;
color: #444;
}
p#intro a {
color: #444;
}
p#intro a:visited {
color: #444;
}
.block {
background-color: #e0e0e0;
padding: 16px;
margin: 20px;
}
p.case_text_block {
border-radius: 10px;
border: 1px solid #aaa;
padding: 16px;
margin: 4px 20px;
color: #444;
}
p.case_desc {
}
p.case_expect {
}
p.case_outcome {
}
p.case_closing_beh {
}
pre.http_dump {
font-family: Consolas, "Courier New", monospace;
font-size: 0.8em;
color: #333;
border-radius: 10px;
border: 1px solid #aaa;
padding: 16px;
margin: 4px 20px;
}
span.case_pickle {
font-family: Consolas, "Courier New", monospace;
font-size: 0.7em;
color: #000;
}
p#case_result,p#close_result {
border-radius: 10px;
background-color: #e8e2d1;
padding: 20px;
margin: 20px;
}
h1 {
margin-left: 60px;
}
h2 {
margin-left: 30px;
}
h3 {
margin-left: 50px;
}
a.up {
float: right;
border-radius: 16px;
margin-top: 16px;
margin-bottom: 10px;
margin-right: 30px;
padding-left: 10px;
padding-right: 10px;
padding-bottom: 2px;
padding-top: 2px;
background-color: #666;
color: #fff;
text-decoration: none;
font-size: 0.8em;
}
a.up:visited {
}
a.up:hover {
background-color: #028ec9;
}
</style>
<style lang="css">
p.case {
color: #fff;
border-radius: 10px;
padding: 20px;
margin: 12px 20px;
font-size: 1.2em;
}
p.case_ok {
background-color: #0a0;
}
p.case_non_strict, p.case_no_close {
background-color: #9a0;
}
p.case_info {
background-color: #4095BF;
}
p.case_failed {
background-color: #900;
}
table {
border-collapse: collapse;
border-spacing: 0px;
margin-left: 80px;
margin-bottom: 12px;
margin-top: 0px;
}
td
{
margin: 0;
font-size: 0.8em;
border: 1px #fff solid;
padding-top: 6px;
padding-bottom: 6px;
padding-left: 16px;
padding-right: 16px;
text-align: right;
}
td.right {
text-align: right;
}
td.left {
text-align: left;
}
tr.stats_header {
color: #eee;
background-color: #000;
}
tr.stats_row {
color: #000;
background-color: #fc3;
}
tr.stats_total {
color: #fff;
background-color: #888;
}
div#wirelog {
margin-top: 20px;
margin-bottom: 80px;
}
pre.wirelog_rx_octets {color: #aaa; margin: 0; background-color: #060; padding: 2px;}
pre.wirelog_tx_octets {color: #aaa; margin: 0; background-color: #600; padding: 2px;}
pre.wirelog_tx_octets_sync {color: #aaa; margin: 0; background-color: #606; padding: 2px;}
pre.wirelog_rx_frame {color: #fff; margin: 0; background-color: #0a0; padding: 2px;}
pre.wirelog_tx_frame {color: #fff; margin: 0; background-color: #a00; padding: 2px;}
pre.wirelog_tx_frame_sync {color: #fff; margin: 0; background-color: #a0a; padding: 2px;}
pre.wirelog_delay {color: #fff; margin: 0; background-color: #000; padding: 2px;}
pre.wirelog_kill_after {color: #fff; margin: 0; background-color: #000; padding: 2px;}
pre.wirelog_tcp_closed_by_me {color: #fff; margin: 0; background-color: #008; padding: 2px;}
pre.wirelog_tcp_closed_by_peer {color: #fff; margin: 0; background-color: #000; padding: 2px;}
</style>
</head>
<body>
<a name="top"></a>
<br/>
<center><a href="http://autobahn.ws/testsuite" title="Autobahn WebSockets Testsuite"><img src="http://autobahn.ws/static/img/ws_protocol_test_report.png" border="0" width="820" height="46" alt="Autobahn WebSockets Testsuite Report"></img></a></center>
<center><a href="http://autobahn.ws" title="Autobahn WebSockets"> <img src="http://autobahn.ws/static/img/ws_protocol_test_report_autobahn.png" border="0" width="300" height="68" alt="Autobahn WebSockets"> </img></a></center>
<br/>
<p class="case case_ok">Crossbar.io - <span style="font-size: 1.3em;"><b>Case 6.22.12</b></span> : Pass - <span style="font-size: 0.9em;"><b>2</b> ms @ 2015-11-06T15:56:10.663Z</a></p>
<p class="case_text_block case_desc"><b>Case Description</b><br/><br/>Send a text message with payload which is valid UTF-8 in one fragment.<br><br>Payload: 0xf19fbfbf</p>
<p class="case_text_block case_expect"><b>Case Expectation</b><br/><br/>The message is echo'ed back to us.</p>
<p class="case_text_block case_outcome">
<b>Case Outcome</b><br/><br/>Actual events match at least one expected.<br/><br/>
<i>Expected:</i><br/><span class="case_pickle">{'OK': [('message', u'\U0005ffff', False)]}</span><br/><br/>
<i>Observed:</i><br><span class="case_pickle">[('message', u'\U0005ffff', False)]</span>
</p>
<p class="case_text_block case_closing_beh"><b>Case Closing Behavior</b><br/><br/>Connection was properly closed (OK)</p>
<br/><hr/>
<h2>Opening Handshake</h2>
<pre class="http_dump">GET / HTTP/1.1
User-Agent: AutobahnTestSuite/0.7.2-0.10.9
Host: 127.0.0.1:8080
Upgrade: WebSocket
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: TCxa7boMhFhOkBrxzMRSNg==
Sec-WebSocket-Version: 13</pre>
<pre class="http_dump">HTTP/1.1 101 Switching Protocols
Server: Crossbar/0.11.1
X-Powered-By: AutobahnPython/0.11.0
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: G5YyF9gJqHtzNY5Q7yvCgFsW6Cg=</pre>
<br/><hr/>
<h2>Closing Behavior</h2>
<table>
<tr class="stats_header"><td>Key</td><td class="left">Value</td><td class="left">Description</td></tr>
<tr class="stats_row"><td>isServer</td><td class="left">False</td><td class="left">True, iff I (the fuzzer) am a server, and the peer is a client.</td></tr>
<tr class="stats_row"><td>closedByMe</td><td class="left">True</td><td class="left">True, iff I have initiated closing handshake (that is, did send close first).</td></tr>
<tr class="stats_row"><td>failedByMe</td><td class="left">False</td><td class="left">True, iff I have failed the WS connection (i.e. due to protocol error). Failing can be either by initiating closing handshake or brutal drop TCP.</td></tr>
<tr class="stats_row"><td>droppedByMe</td><td class="left">False</td><td class="left">True, iff I dropped the TCP connection.</td></tr>
<tr class="stats_row"><td>wasClean</td><td class="left">True</td><td class="left">True, iff full WebSockets closing handshake was performed (close frame sent and received) _and_ the server dropped the TCP (which is its responsibility).</td></tr>
<tr class="stats_row"><td>wasNotCleanReason</td><td class="left">None</td><td class="left">When wasClean == False, the reason what happened.</td></tr>
<tr class="stats_row"><td>wasServerConnectionDropTimeout</td><td class="left">False</td><td class="left">When we are a client, and we expected the server to drop the TCP, but that didn't happen in time, this gets True.</td></tr>
<tr class="stats_row"><td>wasOpenHandshakeTimeout</td><td class="left">False</td><td class="left">When performing the opening handshake, but the peer did not finish in time, this gets True.</td></tr>
<tr class="stats_row"><td>wasCloseHandshakeTimeout</td><td class="left">False</td><td class="left">When we initiated a closing handshake, but the peer did not respond in time, this gets True.</td></tr>
<tr class="stats_row"><td>localCloseCode</td><td class="left">1000</td><td class="left">The close code I sent in close frame (if any).</td></tr>
<tr class="stats_row"><td>localCloseReason</td><td class="left">None</td><td class="left">The close reason I sent in close frame (if any).</td></tr>
<tr class="stats_row"><td>remoteCloseCode</td><td class="left">1000</td><td class="left">The close code the peer sent me in close frame (if any).</td></tr>
<tr class="stats_row"><td>remoteCloseReason</td><td class="left">None</td><td class="left">The close reason the peer sent me in close frame (if any).</td></tr>
</table> <br/><hr/>
<h2>Wire Statistics</h2>
<h3>Octets Received by Chop Size</h3>
<table>
<tr class="stats_header"><td>Chop Size</td><td>Count</td><td>Octets</td></tr>
<tr class="stats_row"><td>4</td><td>1</td><td>4</td></tr>
<tr class="stats_row"><td>6</td><td>1</td><td>6</td></tr>
<tr class="stats_row"><td>191</td><td>1</td><td>191</td></tr>
<tr class="stats_total"><td>Total</td><td>3</td><td>201</td></tr>
</table>
<h3>Octets Transmitted by Chop Size</h3>
<table>
<tr class="stats_header"><td>Chop Size</td><td>Count</td><td>Octets</td></tr>
<tr class="stats_row"><td>8</td><td>1</td><td>8</td></tr>
<tr class="stats_row"><td>10</td><td>1</td><td>10</td></tr>
<tr class="stats_row"><td>240</td><td>1</td><td>240</td></tr>
<tr class="stats_total"><td>Total</td><td>3</td><td>258</td></tr>
</table>
<h3>Frames Received by Opcode</h3>
<table>
<tr class="stats_header"><td>Opcode</td><td>Count</td></tr>
<tr class="stats_row"><td>1</td><td>1</td></tr>
<tr class="stats_row"><td>8</td><td>1</td></tr>
<tr class="stats_total"><td>Total</td><td>2</td></tr>
</table>
<h3>Frames Transmitted by Opcode</h3>
<table>
<tr class="stats_header"><td>Opcode</td><td>Count</td></tr>
<tr class="stats_row"><td>1</td><td>1</td></tr>
<tr class="stats_row"><td>8</td><td>1</td></tr>
<tr class="stats_total"><td>Total</td><td>2</td></tr>
</table>
<br/><hr/>
<h2>Wire Log</h2>
<div id="wirelog">
<pre class="wirelog_tx_octets">000 TX OCTETS: 474554202f20485454502f312e310d0a557365722d4167656e743a204175746f6261686e5465737453756974652f302e372e</pre>
<pre class="wirelog_tx_octets"> 322d302e31302e390d0a486f7374 ...</pre>
<pre class="wirelog_rx_octets">001 RX OCTETS: 485454502f312e312031303120537769746368696e672050726f746f636f6c730d0a5365727665723a2043726f7373626172</pre>
<pre class="wirelog_rx_octets"> 2f302e31312e310d0a582d506f77 ...</pre>
<pre class="wirelog_tx_frame">002 TX FRAME : OPCODE=1, FIN=True, RSV=0, PAYLOAD-LEN=4, MASK=893c3103, PAYLOAD-REPEAT-LEN=None, CHOPSIZE=None, SYNC=False</pre>
<pre class="wirelog_tx_frame"> </pre>
<pre class="wirelog_tx_octets">003 TX OCTETS: 8184893c310378a38ebc</pre>
<pre class="wirelog_kill_after">004 FAIL CONNECTION AFTER 0.500000 sec</pre>
<pre class="wirelog_rx_octets">005 RX OCTETS: 8104f19fbfbf</pre>
<pre class="wirelog_rx_frame">006 RX FRAME : OPCODE=1, FIN=True, RSV=0, PAYLOAD-LEN=4, MASKED=False, MASK=None</pre>
<pre class="wirelog_rx_frame"> </pre>
<pre class="wirelog_tx_frame">007 TX FRAME : OPCODE=8, FIN=True, RSV=0, PAYLOAD-LEN=2, MASK=8aa4f158, PAYLOAD-REPEAT-LEN=None, CHOPSIZE=None, SYNC=False</pre>
<pre class="wirelog_tx_frame"> 0x03e8</pre>
<pre class="wirelog_tx_octets">008 TX OCTETS: 88828aa4f158894c</pre>
<pre class="wirelog_rx_octets">009 RX OCTETS: 880203e8</pre>
<pre class="wirelog_rx_frame">010 RX FRAME : OPCODE=8, FIN=True, RSV=0, PAYLOAD-LEN=2, MASKED=False, MASK=None</pre>
<pre class="wirelog_rx_frame"> 0x03e8</pre>
<pre class="wirelog_tcp_closed_by_peer">011 TCP DROPPED BY PEER</pre>
</div>
<br/><hr/>
</body>
</html>
| {
"content_hash": "9079087971ae18db50a35dfcebb1c159",
"timestamp": "",
"source": "github",
"line_count": 305,
"max_line_length": 266,
"avg_line_length": 38.33114754098361,
"alnum_prop": 0.6306560602172612,
"repo_name": "meejah/crossbarexamples",
"id": "85a8879a958d9e542e7954d836dc56230e619be2",
"size": "11697",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "work/testee/reports/servers/crossbar_io_case_6_22_12.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5120"
},
{
"name": "C#",
"bytes": "22931"
},
{
"name": "C++",
"bytes": "77209"
},
{
"name": "CSS",
"bytes": "270073"
},
{
"name": "Dockerfile",
"bytes": "1423"
},
{
"name": "Erlang",
"bytes": "16493"
},
{
"name": "HTML",
"bytes": "4683415"
},
{
"name": "Hack",
"bytes": "1691"
},
{
"name": "Java",
"bytes": "20795"
},
{
"name": "JavaScript",
"bytes": "3742210"
},
{
"name": "Jupyter Notebook",
"bytes": "335655"
},
{
"name": "Lua",
"bytes": "1233"
},
{
"name": "Makefile",
"bytes": "47961"
},
{
"name": "PHP",
"bytes": "47991"
},
{
"name": "PLSQL",
"bytes": "363209"
},
{
"name": "PLpgSQL",
"bytes": "7749"
},
{
"name": "Python",
"bytes": "726879"
},
{
"name": "SQLPL",
"bytes": "909"
},
{
"name": "Shell",
"bytes": "19566"
},
{
"name": "TSQL",
"bytes": "2937"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Collections;
namespace Microsoft.Build.Evaluation
{
/// <summary>
/// This interface represents a metadata object.
/// </summary>
internal interface IMetadatum : IKeyed, IValued
{
}
}
| {
"content_hash": "86e2f841f33b4ede6bcf36cc6b39f9b6",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 101,
"avg_line_length": 27.428571428571427,
"alnum_prop": 0.7083333333333334,
"repo_name": "mono/msbuild",
"id": "5521a562ea694f84c4e7e1249385352e3d685f28",
"size": "386",
"binary": false,
"copies": "1",
"ref": "refs/heads/xplat-master",
"path": "src/Build/Evaluation/IMetadatum.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5937"
},
{
"name": "C",
"bytes": "21"
},
{
"name": "C#",
"bytes": "29252188"
},
{
"name": "C++",
"bytes": "6"
},
{
"name": "Groovy",
"bytes": "3193"
},
{
"name": "Makefile",
"bytes": "322"
},
{
"name": "PowerShell",
"bytes": "33189"
},
{
"name": "Roff",
"bytes": "10047"
},
{
"name": "Scilab",
"bytes": "8"
},
{
"name": "Shell",
"bytes": "11978"
},
{
"name": "XML",
"bytes": "505598"
},
{
"name": "XSLT",
"bytes": "69632"
}
],
"symlink_target": ""
} |
<?php
class Airport_test extends CI_Model {
public function getAll()
{
return array(
array('title'=>'airport 1','content'=>'...'),
);
}
}
?> | {
"content_hash": "856442114f615ff1f0b256696302b469",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 51,
"avg_line_length": 18,
"alnum_prop": 0.49444444444444446,
"repo_name": "Usman-Asghar/careaxiom",
"id": "03e584cf3cce246b14a74c3454d889f86adf0661",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/airport_test.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "336"
},
{
"name": "Groff",
"bytes": "111873"
},
{
"name": "HTML",
"bytes": "6157"
},
{
"name": "PHP",
"bytes": "2087655"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<title>org.myrobotlab.cmdline</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../org/myrobotlab/cmdline/package-summary.html" target="classFrame">org.myrobotlab.cmdline</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="CcmdParam.html" title="class in org.myrobotlab.cmdline" target="classFrame">CcmdParam</a></li>
<li><a href="CMDLine.html" title="class in org.myrobotlab.cmdline" target="classFrame">CMDLine</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "76ded5a6b69073b54f3a328546778751",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 130,
"avg_line_length": 42.65,
"alnum_prop": 0.6611957796014069,
"repo_name": "lanchun/myrobotlab",
"id": "ec701cdad41e2addc6bd0368920790e3d40c746a",
"size": "853",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "javadoc/org/myrobotlab/cmdline/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Arduino",
"bytes": "88249"
},
{
"name": "Groff",
"bytes": "7733"
},
{
"name": "HTML",
"bytes": "9173"
},
{
"name": "Java",
"bytes": "3743168"
},
{
"name": "Processing",
"bytes": "9582"
},
{
"name": "Propeller Spin",
"bytes": "14185"
},
{
"name": "Python",
"bytes": "4187"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="de.madvertise.android.sdk">
<uses-sdk android:minSdkVersion="7" />
</manifest> | {
"content_hash": "5c6afba4cd9b74641491eb3dee455059",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 68,
"avg_line_length": 43.666666666666664,
"alnum_prop": 0.6946564885496184,
"repo_name": "FireRider/madvertise-android-sdk",
"id": "4fbdd4c12bc64ff73d4aef9b94a147f3c0b4ebf8",
"size": "262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "madvertiseSDK/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace P01_HospitalDatabase.Data
{
public class Configuration
{
public const string ConnectionString = "Server=(LocalDB)\\MSSQLLocalDB;Database=Hospital;Integrated Security=True";
}
}
| {
"content_hash": "4c1a0fa791eb1f0e072274c98aa7b893",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 123,
"avg_line_length": 25.09090909090909,
"alnum_prop": 0.75,
"repo_name": "CvetelinLozanov/SoftUni-C-",
"id": "5e5527343f3339f49ce60f4e3078c41bf6f434e7",
"size": "278",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DBSQL-Advanced/HospitalDatabase/P01_HospitalDatabase.Data/Configuration.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "906352"
},
{
"name": "CSS",
"bytes": "845"
},
{
"name": "HTML",
"bytes": "17026"
},
{
"name": "JavaScript",
"bytes": "226"
}
],
"symlink_target": ""
} |
import requests
# Create your views here.
from django.views.generic import TemplateView
from intro.models import Staff
from intro.utils import toPersianDigit
class HomeView(TemplateView):
template_name = 'intro/home.html'
def get_context_data(self, *args, **kwargs):
registration_url = "http://ce.sharif.edu/~golezardi/ssc-count/webelopers.php"
content = requests.get(registration_url).text
return {"numberOfTeams":toPersianDigit(content)}
class StaffView(TemplateView):
template_name = 'intro/staff_list.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['staffs'] = Staff.objects.all().order_by('?')
return context
| {
"content_hash": "1e39a370092f41603a2e3b2e8ea7b750",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 85,
"avg_line_length": 29.4,
"alnum_prop": 0.6993197278911565,
"repo_name": "Kianoosh76/webelopers-scoreboard",
"id": "88846b4106c3e03e46d6e111c9e6921f0e0a7591",
"size": "735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "intro/views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24707"
},
{
"name": "HTML",
"bytes": "41939"
},
{
"name": "JavaScript",
"bytes": "688151"
},
{
"name": "Python",
"bytes": "33281"
}
],
"symlink_target": ""
} |
package org.apache.isis.core.metamodel.facets.actions.action.command;
import org.apache.isis.applib.annotation.Command.ExecuteIn;
import org.apache.isis.applib.annotation.Command.Persistence;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.actions.command.CommandFacet;
import org.apache.isis.core.metamodel.facets.actions.command.CommandFacetAbstract;
import org.apache.isis.core.metamodel.services.ServicesInjector;
public class CommandFacetFromConfiguration extends CommandFacetAbstract {
public static CommandFacet create(
final FacetHolder holder,
final ServicesInjector servicesInjector) {
return new CommandFacetFromConfiguration(Persistence.PERSISTED, ExecuteIn.FOREGROUND, holder,
servicesInjector);
}
private CommandFacetFromConfiguration(
final Persistence persistence,
final ExecuteIn executeIn,
final FacetHolder holder,
final ServicesInjector servicesInjector) {
super(persistence, executeIn, Enablement.ENABLED, null,
holder, servicesInjector);
}
}
| {
"content_hash": "f884d47be15692478a42313592074354",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 101,
"avg_line_length": 38.8,
"alnum_prop": 0.7508591065292096,
"repo_name": "incodehq/isis",
"id": "c1b7f713860654cbb322c7b076ffc99718897dfc",
"size": "1989",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/actions/action/command/CommandFacetFromConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "40414"
},
{
"name": "Dockerfile",
"bytes": "1985"
},
{
"name": "Gherkin",
"bytes": "2114"
},
{
"name": "Groovy",
"bytes": "20238"
},
{
"name": "HTML",
"bytes": "299368"
},
{
"name": "Java",
"bytes": "13101254"
},
{
"name": "JavaScript",
"bytes": "11087918"
},
{
"name": "Shell",
"bytes": "18256"
}
],
"symlink_target": ""
} |
package io.github.orionhealth.xbdd.model.common;
import java.util.Date;
public class Build {
String name;
Date publishDate;
boolean isPinned;
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public Date getPublishDate() {
return this.publishDate;
}
public void setPublishDate(final Date publishDate) {
this.publishDate = publishDate;
}
public boolean getIsPinned() {
return this.isPinned;
}
public void setIsPinned(final boolean isPinned) {
this.isPinned = isPinned;
}
}
| {
"content_hash": "118d5dfd906921c803dbe384f1dc9d82",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 53,
"avg_line_length": 17.09090909090909,
"alnum_prop": 0.7269503546099291,
"repo_name": "orionhealth/XBDD",
"id": "8ed0b1eb36fe48ecbe7c6256a81f5c62c23df23a",
"size": "564",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/src/main/java/io/github/orionhealth/xbdd/model/common/Build.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "275"
},
{
"name": "Dockerfile",
"bytes": "327"
},
{
"name": "HTML",
"bytes": "1585"
},
{
"name": "Java",
"bytes": "213902"
},
{
"name": "JavaScript",
"bytes": "7541"
},
{
"name": "Shell",
"bytes": "1106"
},
{
"name": "TypeScript",
"bytes": "127135"
}
],
"symlink_target": ""
} |
// File store for user attachments: images with tumbnails & other files.
// Supports image with thumbnails removal in single call.
//
// DB settings should be in:
//
// - N.config.database.mongo_files (if you need separate db)
// - N.config.database.mongo (fallback to main db)
//
// Web server located in autoload/hooks/server_bin/gridfs.js
//
'use strict';
const _ = require('lodash');
const fs = require('fs');
const mime = require('mime-types').lookup;
const stream = require('stream');
const mongoose = require('mongoose');
const { pipeline } = require('stream/promises');
const ObjectId = mongoose.Types.ObjectId;
function escapeRegexp(source) {
return String(source).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
function tryParseObjectId(string) {
try {
return new ObjectId(string);
} catch (e) {
return false;
}
}
// Convert `src` (filename|buffer|stream) into readable stream
//
function getStream(src) {
if (typeof src === 'string') {
// file name passed
return fs.createReadStream(src);
} else if (Buffer.isBuffer(src)) {
// buffer passed
return stream.Readable.from([ src ], { objectMode: false });
} else if (src.readable) {
return src;
}
return false;
}
module.exports = function (N, collectionName) {
let gfs;
/*
* There are 2 type of files:
*
* - original files (http://mysite.com/files/0acd8213789h4e38a9e67b23)
* - thumbnails (http://mysite.com/files/0acd8213789h4e38a9e67b23_small)
*
* Original files are fetched by _id and have `filename` empty.
* Thumbnails are fetched by `filename`, that contains from
* 'original_id' + '_' + 'preview size'.
*
* That's optimal for possible migration to other KV storages. Also that
* simplifies delete for multiple previews at once.
*
* See full db structures here http://docs.mongodb.org/manual/reference/gridfs/
*
* Schema:
*
* _id
* length
* chunkSize
* uploadDate
* md5
*
* filename (optional) XXX or XXX_size
* contentType
* aliases ???
* metadata:
* origName (optional)
*/
// TODO: (?) add collections root to constructor params
// (fs by default)
//
function File() {}
/*
* Get file info from GridFS.
*
* Params:
*
* - name (String) - `_id` {32 hex} or `filename`
*/
File.getInfo = File.prototype.getInfo = function (name) {
let id = name.toHexString ? name : tryParseObjectId(name);
let condition = id ? { _id: id } : { filename: name };
return gfs.find(condition).next();
};
/*
* Remove file + all previews if exist
*
* Params:
*
* - name (ObjectId|String) - `_id` of root file or `filename` for preview
* - all (Boolean) - true: delete all related files too
*/
File.remove = File.prototype.remove = async function (name, all) {
let id = name.toHexString ? name : tryParseObjectId(name);
// The same as above, but via promise
if (id) {
if (all) {
let files = await gfs.find({ filename: new RegExp('^' + escapeRegexp(String(name))) }).toArray();
for (let file of files) await gfs.delete(file._id);
return;
}
let file = await gfs.find({ _id: id }).next();
if (file) await gfs.delete(id);
return;
}
let file = await gfs.find({ filename: name }).next();
if (file) await gfs.delete(file._id);
};
/*
* put file into gridfs
*
* Params:
*
* - opt (Object) - see schema for details. General:
* - _id (ObjectId|String), optional - _id to store in db
* - filename, optional - file name to store in db, `_id` if not set.
* For example '535860e62490c07f0c2eabe3_xxl' for thumbnail of
* '535860e62490c07f0c2eabe3' image.
* - contentType
* - metadata (Object), optional - file metadata
* - origName (String) - original file name (used in downloads)
*/
File.createWriteStream = File.prototype.createWriteStream = function (opt) {
let options = _.omit(opt, '_id', 'filename');
let _id = opt._id || new ObjectId(null);
if (_id.toHexString) _id = tryParseObjectId(_id);
if (!_id) throw new Error('File.put: invalid _id passed');
// if filename NOT set - that's original file (in other case that's thumbnail)
let filename = opt.filename || _id.toHexString();
// if no contentType - try to guess from original file name
if (!options.contentType) {
let origName = options.metadata?.origName;
if (!origName) {
throw new Error('File.put: ContentType or metadata.origName must be set');
}
options.contentType = mime(origName);
if (!options.contentType) {
throw new Error(`File.put: can't guess ContentType for ${origName}`);
}
}
return gfs.openUploadStreamWithId(_id, filename, options);
};
/*
* put file into gridfs
*
* Params:
*
* - src (Mixed) - (buffer|path|stream) with file data. Required.
* - opt (Object) - see schema for details. General:
* - _id (ObjectId|String), optional - _id to store in db
* - filename, optional - file name to store in db, `_id` if not set.
* For example '535860e62490c07f0c2eabe3_xxl' for thumbnail of
* '535860e62490c07f0c2eabe3' image.
* - contentType
* - metadata (Object), optional - file metadata
* - origName (String) - original file name (used in downloads)
*/
File.put = File.prototype.put = async function (src, opt) {
let input = getStream(src);
if (!input) throw new Error('File.put: unknown source data');
let output = File.createWriteStream(opt);
// workaround for https://github.com/Automattic/mongoose/issues/10107
// TODO: remove this when [email protected] gets released
output.once('finish', () => output.destroy());
await pipeline(input, output);
return output.id;
};
/*
* Get GridFS file as stream, by file (id|name)
*/
// FIXME: replace with native stream and add seek support
// https://gist.github.com/psi-4ward/7099001
//
File.createReadStream = File.prototype.createReadStream = function (name) {
let id = name.toHexString ? name : tryParseObjectId(name);
return id ?
gfs.openDownloadStream(id) :
gfs.openDownloadStreamByName(name);
};
N.wire.on('init:models', function emit_init_File(__, callback) {
// connect to database
let options = {
connectTimeoutMS: 30000
};
let mongoPath = N.config.database.mongo_files || N.config.database.mongo;
let conn = mongoose.createConnection(mongoPath, options);
conn.once('open', function () {
gfs = new mongoose.mongo.GridFSBucket(conn.db);
N.wire.emit('init:models.' + collectionName, File, callback);
});
});
N.wire.on('init:models.' + collectionName, function init_model_File() {
N.models[collectionName] = File;
});
};
| {
"content_hash": "7f86b37278a6a64838767ecdcb947f76",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 105,
"avg_line_length": 27.58565737051793,
"alnum_prop": 0.623627960716349,
"repo_name": "nodeca/nodeca.core",
"id": "e84ec10f649443c3c85fc74b8d92f7265be77060",
"size": "6924",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/core/File.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33447"
},
{
"name": "HTML",
"bytes": "26126"
},
{
"name": "JavaScript",
"bytes": "745276"
},
{
"name": "Makefile",
"bytes": "1417"
},
{
"name": "Pug",
"bytes": "44917"
},
{
"name": "SCSS",
"bytes": "5288"
},
{
"name": "Stylus",
"bytes": "49707"
}
],
"symlink_target": ""
} |
import expect from 'expect';
import { fork } from 'redux-saga/effects';
import sagas from '../sagas';
import watchGetAccountData from 'interactions/user/sagas/watch-get-account-data';
import watchGetAlbumImages from 'interactions/albums/sagas/watch-get-album-images';
import watchGetAlbums from 'interactions/albums/sagas/watch-get-albums';
describe('sagas', () => {
it('should fork saga watchGetAccountData', () => {
const gen = sagas();
const next = gen.next();
expect(next.value[0]).toEqual(fork(watchGetAccountData));
});
it('should fork saga watchGetAlbums', () => {
const gen = sagas();
const next = gen.next();
expect(next.value[1]).toEqual(fork(watchGetAlbums));
});
it('should fork saga watchGetAlbumImages', () => {
const gen = sagas();
const next = gen.next();
expect(next.value[2]).toEqual(fork(watchGetAlbumImages));
});
});
| {
"content_hash": "6671899dc46eb9f355b6260e541ccc5b",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 83,
"avg_line_length": 28.838709677419356,
"alnum_prop": 0.6778523489932886,
"repo_name": "romy/personal-imgur-gallery",
"id": "d97c4cad4e06ba9eae4ad38545c0974e647e25fd",
"size": "894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/tests/sagas.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1526"
},
{
"name": "CSS",
"bytes": "109"
},
{
"name": "HTML",
"bytes": "9036"
},
{
"name": "JavaScript",
"bytes": "96673"
}
],
"symlink_target": ""
} |
'use strict';
/**
* @ngdoc function
* @name flightNodeApp.controller:UserCreateController
* @description
* # UserCreateController
* Controller for the create user page.
*/
angular.module('flightNodeApp')
.controller('UserCreateController',
['$scope', '$log', 'messenger', 'roleProxy', 'authService', '$uibModalInstance', 'userProxy',
function ($scope, $log, messenger, roleProxy, authService, $uibModalInstance, userProxy) {
if (!(authService.isAdministrator() ||
authService.isCoordinator())) {
$log.warn('not authorized to access this path');
$uibModalInstance.dismiss('cancel');
return;
}
$scope.loading = true;
$scope.data = {};
$scope.showRoles = true;
roleProxy.getAll( function (error, response) {
if (error) {
$log.error('Failed to retrieve roles: ', JSON.stringify(error));
} else {
if (response.status === 200) {
$scope.data.roles = response.data;
} else {
messenger.showErrorMessage($scope, 'Unable to load available roles. Please try reloading this page or returning again soon. We apologize for the inconvenience.');
$log.info('Roles: ', response);
}
}
});
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
$scope.submit = userProxy.insert($scope, $uibModalInstance);
$scope.loading = false;
}]); | {
"content_hash": "675695e5a82665051af5ae3ebb798123",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 190,
"avg_line_length": 37.375,
"alnum_prop": 0.49665551839464883,
"repo_name": "kpunjani/FlightNode.Demo",
"id": "a5137b0099d5c0089df91032a843b42e3e973383",
"size": "1794",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/app/controllers/users/create.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "2149"
},
{
"name": "HTML",
"bytes": "92527"
},
{
"name": "JavaScript",
"bytes": "121408"
}
],
"symlink_target": ""
} |
"""Unit tests for the "list_collectors" function."""
import unittest
from unittest import mock
from google.auth.transport import requests
from . import list_collectors
class ListCollectorsTest(unittest.TestCase):
@mock.patch.object(requests, "AuthorizedSession", autospec=True)
@mock.patch.object(requests.requests, "Response", autospec=True)
def test_http_error(self, mock_response, mock_session):
mock_session.request.return_value = mock_response
type(mock_response).status_code = mock.PropertyMock(return_value=400)
mock_response.raise_for_status.side_effect = (
requests.requests.exceptions.HTTPError())
with self.assertRaises(requests.requests.exceptions.HTTPError):
list_collectors.list_collectors(mock_session, "forwarder name")
@mock.patch.object(requests, "AuthorizedSession", autospec=True)
@mock.patch.object(requests.requests, "Response", autospec=True)
def test_happy_path(self, mock_response, mock_session):
mock_session.request.return_value = mock_response
type(mock_response).status_code = mock.PropertyMock(return_value=200)
expected_collectors = {
"collectors": [{
"name": "forwarders/uuid/collectors/uuid",
"displayName": "SplunkCollector",
"config": {
"logType": "WINDOWS_DNS",
"maxSecondsPerBatch": 10,
"maxBytesPerBatch": "1048576",
"splunkSettings": {
"host": "127.0.0.1",
"minimumWindowSize": 10,
"maximumWindowSize": 30,
"queryString": "search index=* sourcetype=dns",
"queryMode": "realtime",
"port": 8089
}
},
"state": "ACTIVE"
}, {
"name": "forwarders/uuid/collectors/uuid",
"displayName": "SyslogCollector",
"config": {
"logType": "PAN_FIREWALL",
"maxSecondsPerBatch": 10,
"maxBytesPerBatch": "1048576",
"syslogSettings": {
"protocol": "TCP",
"address": "0.0.0.0",
"port": 10514,
"bufferSize": "65536",
"connectionTimeout": 60
}
},
"state": "ACTIVE"
}]
}
mock_response.json.return_value = expected_collectors
actual_collectors = list_collectors.list_collectors(mock_session,
"forwarder name")
self.assertEqual(actual_collectors, expected_collectors)
if __name__ == "__main__":
unittest.main()
| {
"content_hash": "6d23d21dd92c69859b0a7098041f0e66",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 73,
"avg_line_length": 36.2972972972973,
"alnum_prop": 0.5662695457930007,
"repo_name": "chronicle/api-samples-python",
"id": "d2d07a7999da9c0f666e1b52eb7a453ed31fb6a2",
"size": "3262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "forwarders/list_collectors_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "556471"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("05_FibonacciNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05_FibonacciNumbers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b7dee9b0-779f-4e7f-9ceb-6208d6f472cf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "26c7041403e22f93044126bcb08517dd",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.19444444444444,
"alnum_prop": 0.7462792345854005,
"repo_name": "nellypeneva/SoftUniProjects",
"id": "d4d54001e682d9213d4565a872722cd15d6b2f4d",
"size": "1414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "01_ProgrFundamentalsMay/14_Methods-Exercises/05_FibonacciNumbers/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "689865"
},
{
"name": "CSS",
"bytes": "154047"
},
{
"name": "HTML",
"bytes": "26587"
}
],
"symlink_target": ""
} |
package com.advocatesOnline.daoImpl;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import javax.persistence.Query;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import com.advocatesOnline.dao.UserDao;
import com.advocatesOnline.entity.User;
/**
*<pre>
* Author : Sanjeev Kulkarni
* Project : AdvocatesOnline
* Package : com.advocatesOnline.dao
* File : UserDaoImpl.java
* Created On : 01-Jun-2013 8:00:45 PM
*
*
*<b>Revision History</b>
*-------------------------------------------------------------------------------------------------------------------------------------------------
*<b> Sl No. | Changed By | Date & Time | Remarks
*-------------------------------------------------------------------------------------------------------------------------------------------------
* 1 | Sanjeev Kulkarni | 01-Jun-2013 8:00:45 PM | Initial Version
*</pre>
*/
public class UserDaoImpl extends AbstractDaoImpl implements UserDao {
Logger logger = Logger.getLogger(UserDaoImpl.class);
String className = UserDaoImpl.class.getName();
/* (non-Javadoc)
* @see com.advocatesOnline.dao.UserDao#changeUserPassword(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public boolean changeUserPassword(String userId, String oldPassword, String newPassword, String confirmNewPassword) {
String methodName = " :: changeUserPassword() ";
logger.info(className + methodName + "enter");
boolean changed = false;
try {
em.getTransaction().begin();
Query query = em.createQuery("select x from User x where x.id = ?1 and x.password = ?2");
query.setParameter(1, userId != "0" ? Integer.parseInt(userId) : 0);
query.setParameter(2, DigestUtils.md5Hex(oldPassword));
if(query.getResultList().size() > 0){
Query query1 = em.createQuery("update User x set x.password =?1, x.updatedBy = ?2, x.updatedOn = ?3, x.updatedTime = ?4 where x.id = ?5 ");
query1.setParameter(1,DigestUtils.md5Hex(newPassword));
query1.setParameter(2, userId != "0" ? Integer.parseInt(userId) : 0);
query1.setParameter(3, new Date());
query1.setParameter(4, new Date());
query1.setParameter(5, userId != "0" ? Integer.parseInt(userId) : 0);
int update = query1.executeUpdate();
System.out.println("executed?? "+update);
if(update > 0)
{
em.getTransaction().commit();
changed = true;
}
}else{
changed = false;
}
} catch (Exception e) {
changed = false;
e.printStackTrace();
logger.info(className + methodName + "Exception ", e);
}
logger.info(className + methodName + "leave");
return changed;
}
/* (non-Javadoc)
* @see com.advocatesOnline.dao.UserDao#viewUserProfile(java.lang.String)
*/
@Override
public User viewUserProfile(int userId) {
String methodName = " : viewUserProfile() :: ";
logger.info(className + methodName + "enter");
Query query = null;
try{
query = em.createQuery("select x from User x where x.id = ?1");
query.setParameter(1, userId);
}catch(Exception e){
e.printStackTrace();
logger.info(className + methodName + "Exception :: ", e);
}
logger.info(className + methodName + "leave");
return (User)query.getSingleResult();
}
/* (non-Javadoc)
* @see com.advocatesOnline.dao.UserDao#logoutUser(com.advocatesOnline.entity.User)
*/
@Override
public void logoutUser(User user) {
String methodName = " :: logoutUser() ";
logger.info(className + methodName + "enter");
Query query = null;
try{
em.getTransaction().begin();
query = em.createQuery("update User x set x.loggedIn = ?1, x.lastLogonDate = ?2, x.lastLogonTime = ?3" +
" where x.id = ?4");
query.setParameter(1, false);
query.setParameter(2, new Date());
query.setParameter(3, new Date());
query.setParameter(4, user.getId());
int updated = query.executeUpdate();
if(updated > 0){
em.getTransaction().commit();
}
}catch(Exception e){
e.printStackTrace();
logger.info(className + methodName + "Exception ", e);
}
logger.info(className + methodName + "leave");
}
/* (non-Javadoc)
* @see com.advocatesOnline.dao.UserDao#uploadImage(com.advocatesOnline.entity.User, java.io.InputStream)
*/
@Override
public void uploadImage(User user, InputStream inputStream) {
String methodName = " : uploadImage() ";
logger.info(className + methodName + "enter");
try{
final byte[] data = IOUtils.toByteArray(inputStream);
em.getTransaction().begin();
Query query = em.createQuery("update User x set x.photo = ?1 where x.id = ?2" );
query.setParameter(1, data);
query.setParameter(2, user.getId());
int updated = query.executeUpdate();
if(updated > 0){
em.getTransaction().commit();
}
}catch(Exception e){
System.out.println(e.toString());
logger.info(className + methodName + " Exception ", e);
}finally{
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info(className + methodName + "leave");
}
/* (non-Javadoc)
* @see com.advocatesOnline.dao.UserDao#displayImage(java.lang.String)
*/
@Override
public User displayImage(String userId) {
String methodName = " : displayImage() ";
logger.info(className + methodName + "enter");
Query query = null;
try{
query = em.createQuery("select x from User x where x.id = ?1");
query.setParameter(1, Integer.parseInt(userId));
}catch(Exception e){
logger.info(className + methodName + "Exception", e);
}
logger.info(className + methodName + "leave");
return (User)query.getSingleResult();
}
}
| {
"content_hash": "1a9e06ab390d306b39c7dd85749e76fd",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 149,
"avg_line_length": 32.44385026737968,
"alnum_prop": 0.5994725564529422,
"repo_name": "tectronics/advocatesonline",
"id": "868c887d2ce854da01be1f957b7474e48cbbc068",
"size": "6259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/advocatesOnline/daoImpl/UserDaoImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "20512"
},
{
"name": "HTML",
"bytes": "12109"
},
{
"name": "Java",
"bytes": "306997"
},
{
"name": "JavaScript",
"bytes": "62073"
}
],
"symlink_target": ""
} |
#include <linux/types.h>
#include <linux/param.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/in.h>
#include <linux/pagemap.h>
#include <linux/sunrpc/clnt.h>
#include <linux/nfs.h>
#include <linux/nfs2.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_page.h>
#include <linux/lockd/bind.h>
#include <linux/freezer.h>
#include "internal.h"
#define NFSDBG_FACILITY NFSDBG_PROC
/*
* Bare-bones access to getattr: this is for nfs_read_super.
*/
static int
nfs_proc_get_root(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
struct nfs_fattr *fattr = info->fattr;
struct nfs2_fsstat fsinfo;
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_GETATTR],
.rpc_argp = fhandle,
.rpc_resp = fattr,
};
int status;
dprintk("%s: call getattr\n", __func__);
nfs_fattr_init(fattr);
status = rpc_call_sync(server->client, &msg, 0);
/* Retry with default authentication if different */
if (status && server->nfs_client->cl_rpcclient != server->client)
status = rpc_call_sync(server->nfs_client->cl_rpcclient, &msg, 0);
dprintk("%s: reply getattr: %d\n", __func__, status);
if (status)
return status;
dprintk("%s: call statfs\n", __func__);
msg.rpc_proc = &nfs_procedures[NFSPROC_STATFS];
msg.rpc_resp = &fsinfo;
status = rpc_call_sync(server->client, &msg, 0);
/* Retry with default authentication if different */
if (status && server->nfs_client->cl_rpcclient != server->client)
status = rpc_call_sync(server->nfs_client->cl_rpcclient, &msg, 0);
dprintk("%s: reply statfs: %d\n", __func__, status);
if (status)
return status;
info->rtmax = NFS_MAXDATA;
info->rtpref = fsinfo.tsize;
info->rtmult = fsinfo.bsize;
info->wtmax = NFS_MAXDATA;
info->wtpref = fsinfo.tsize;
info->wtmult = fsinfo.bsize;
info->dtpref = fsinfo.tsize;
info->maxfilesize = 0x7FFFFFFF;
info->lease_time = 0;
return 0;
}
/*
* One function for each procedure in the NFS protocol.
*/
static int
nfs_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fattr *fattr, struct nfs4_label *label)
{
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_GETATTR],
.rpc_argp = fhandle,
.rpc_resp = fattr,
};
int status;
dprintk("NFS call getattr\n");
nfs_fattr_init(fattr);
status = rpc_call_sync(server->client, &msg, 0);
dprintk("NFS reply getattr: %d\n", status);
return status;
}
static int
nfs_proc_setattr(struct dentry *dentry, struct nfs_fattr *fattr,
struct iattr *sattr)
{
struct inode *inode = d_inode(dentry);
struct nfs_sattrargs arg = {
.fh = NFS_FH(inode),
.sattr = sattr
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_SETATTR],
.rpc_argp = &arg,
.rpc_resp = fattr,
};
int status;
/* Mask out the non-modebit related stuff from attr->ia_mode */
sattr->ia_mode &= S_IALLUGO;
dprintk("NFS call setattr\n");
if (sattr->ia_valid & ATTR_FILE)
msg.rpc_cred = nfs_file_cred(sattr->ia_file);
nfs_fattr_init(fattr);
status = rpc_call_sync(NFS_CLIENT(inode), &msg, 0);
if (status == 0)
nfs_setattr_update_inode(inode, sattr, fattr);
dprintk("NFS reply setattr: %d\n", status);
return status;
}
static int
nfs_proc_lookup(struct inode *dir, struct qstr *name,
struct nfs_fh *fhandle, struct nfs_fattr *fattr,
struct nfs4_label *label)
{
struct nfs_diropargs arg = {
.fh = NFS_FH(dir),
.name = name->name,
.len = name->len
};
struct nfs_diropok res = {
.fh = fhandle,
.fattr = fattr
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_LOOKUP],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status;
dprintk("NFS call lookup %s\n", name->name);
nfs_fattr_init(fattr);
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
dprintk("NFS reply lookup: %d\n", status);
return status;
}
static int nfs_proc_readlink(struct inode *inode, struct page *page,
unsigned int pgbase, unsigned int pglen)
{
struct nfs_readlinkargs args = {
.fh = NFS_FH(inode),
.pgbase = pgbase,
.pglen = pglen,
.pages = &page
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_READLINK],
.rpc_argp = &args,
};
int status;
dprintk("NFS call readlink\n");
status = rpc_call_sync(NFS_CLIENT(inode), &msg, 0);
dprintk("NFS reply readlink: %d\n", status);
return status;
}
struct nfs_createdata {
struct nfs_createargs arg;
struct nfs_diropok res;
struct nfs_fh fhandle;
struct nfs_fattr fattr;
};
static struct nfs_createdata *nfs_alloc_createdata(struct inode *dir,
struct dentry *dentry, struct iattr *sattr)
{
struct nfs_createdata *data;
data = kmalloc(sizeof(*data), GFP_KERNEL);
if (data != NULL) {
data->arg.fh = NFS_FH(dir);
data->arg.name = dentry->d_name.name;
data->arg.len = dentry->d_name.len;
data->arg.sattr = sattr;
nfs_fattr_init(&data->fattr);
data->fhandle.size = 0;
data->res.fh = &data->fhandle;
data->res.fattr = &data->fattr;
}
return data;
};
static void nfs_free_createdata(const struct nfs_createdata *data)
{
kfree(data);
}
static int
nfs_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags)
{
struct nfs_createdata *data;
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_CREATE],
};
int status = -ENOMEM;
dprintk("NFS call create %pd\n", dentry);
data = nfs_alloc_createdata(dir, dentry, sattr);
if (data == NULL)
goto out;
msg.rpc_argp = &data->arg;
msg.rpc_resp = &data->res;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_mark_for_revalidate(dir);
if (status == 0)
status = nfs_instantiate(dentry, data->res.fh, data->res.fattr, NULL);
nfs_free_createdata(data);
out:
dprintk("NFS reply create: %d\n", status);
return status;
}
/*
* In NFSv2, mknod is grafted onto the create call.
*/
static int
nfs_proc_mknod(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
dev_t rdev)
{
struct nfs_createdata *data;
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_CREATE],
};
umode_t mode;
int status = -ENOMEM;
dprintk("NFS call mknod %pd\n", dentry);
mode = sattr->ia_mode;
if (S_ISFIFO(mode)) {
sattr->ia_mode = (mode & ~S_IFMT) | S_IFCHR;
sattr->ia_valid &= ~ATTR_SIZE;
} else if (S_ISCHR(mode) || S_ISBLK(mode)) {
sattr->ia_valid |= ATTR_SIZE;
sattr->ia_size = new_encode_dev(rdev);/* get out your barf bag */
}
data = nfs_alloc_createdata(dir, dentry, sattr);
if (data == NULL)
goto out;
msg.rpc_argp = &data->arg;
msg.rpc_resp = &data->res;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_mark_for_revalidate(dir);
if (status == -EINVAL && S_ISFIFO(mode)) {
sattr->ia_mode = mode;
nfs_fattr_init(data->res.fattr);
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
}
if (status == 0)
status = nfs_instantiate(dentry, data->res.fh, data->res.fattr, NULL);
nfs_free_createdata(data);
out:
dprintk("NFS reply mknod: %d\n", status);
return status;
}
static int
nfs_proc_remove(struct inode *dir, struct qstr *name)
{
struct nfs_removeargs arg = {
.fh = NFS_FH(dir),
.name = *name,
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_REMOVE],
.rpc_argp = &arg,
};
int status;
dprintk("NFS call remove %s\n", name->name);
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_mark_for_revalidate(dir);
dprintk("NFS reply remove: %d\n", status);
return status;
}
static void
nfs_proc_unlink_setup(struct rpc_message *msg, struct inode *dir)
{
msg->rpc_proc = &nfs_procedures[NFSPROC_REMOVE];
}
static void nfs_proc_unlink_rpc_prepare(struct rpc_task *task, struct nfs_unlinkdata *data)
{
rpc_call_start(task);
}
static int nfs_proc_unlink_done(struct rpc_task *task, struct inode *dir)
{
nfs_mark_for_revalidate(dir);
return 1;
}
static void
nfs_proc_rename_setup(struct rpc_message *msg, struct inode *dir)
{
msg->rpc_proc = &nfs_procedures[NFSPROC_RENAME];
}
static void nfs_proc_rename_rpc_prepare(struct rpc_task *task, struct nfs_renamedata *data)
{
rpc_call_start(task);
}
static int
nfs_proc_rename_done(struct rpc_task *task, struct inode *old_dir,
struct inode *new_dir)
{
nfs_mark_for_revalidate(old_dir);
nfs_mark_for_revalidate(new_dir);
return 1;
}
static int
nfs_proc_link(struct inode *inode, struct inode *dir, struct qstr *name)
{
struct nfs_linkargs arg = {
.fromfh = NFS_FH(inode),
.tofh = NFS_FH(dir),
.toname = name->name,
.tolen = name->len
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_LINK],
.rpc_argp = &arg,
};
int status;
dprintk("NFS call link %s\n", name->name);
status = rpc_call_sync(NFS_CLIENT(inode), &msg, 0);
nfs_mark_for_revalidate(inode);
nfs_mark_for_revalidate(dir);
dprintk("NFS reply link: %d\n", status);
return status;
}
static int
nfs_proc_symlink(struct inode *dir, struct dentry *dentry, struct page *page,
unsigned int len, struct iattr *sattr)
{
struct nfs_fh *fh;
struct nfs_fattr *fattr;
struct nfs_symlinkargs arg = {
.fromfh = NFS_FH(dir),
.fromname = dentry->d_name.name,
.fromlen = dentry->d_name.len,
.pages = &page,
.pathlen = len,
.sattr = sattr
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_SYMLINK],
.rpc_argp = &arg,
};
int status = -ENAMETOOLONG;
dprintk("NFS call symlink %pd\n", dentry);
if (len > NFS2_MAXPATHLEN)
goto out;
fh = nfs_alloc_fhandle();
fattr = nfs_alloc_fattr();
status = -ENOMEM;
if (fh == NULL || fattr == NULL)
goto out_free;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_mark_for_revalidate(dir);
/*
* V2 SYMLINK requests don't return any attributes. Setting the
* filehandle size to zero indicates to nfs_instantiate that it
* should fill in the data with a LOOKUP call on the wire.
*/
if (status == 0)
status = nfs_instantiate(dentry, fh, fattr, NULL);
out_free:
nfs_free_fattr(fattr);
nfs_free_fhandle(fh);
out:
dprintk("NFS reply symlink: %d\n", status);
return status;
}
static int
nfs_proc_mkdir(struct inode *dir, struct dentry *dentry, struct iattr *sattr)
{
struct nfs_createdata *data;
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_MKDIR],
};
int status = -ENOMEM;
dprintk("NFS call mkdir %pd\n", dentry);
data = nfs_alloc_createdata(dir, dentry, sattr);
if (data == NULL)
goto out;
msg.rpc_argp = &data->arg;
msg.rpc_resp = &data->res;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_mark_for_revalidate(dir);
if (status == 0)
status = nfs_instantiate(dentry, data->res.fh, data->res.fattr, NULL);
nfs_free_createdata(data);
out:
dprintk("NFS reply mkdir: %d\n", status);
return status;
}
static int
nfs_proc_rmdir(struct inode *dir, struct qstr *name)
{
struct nfs_diropargs arg = {
.fh = NFS_FH(dir),
.name = name->name,
.len = name->len
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_RMDIR],
.rpc_argp = &arg,
};
int status;
dprintk("NFS call rmdir %s\n", name->name);
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_mark_for_revalidate(dir);
dprintk("NFS reply rmdir: %d\n", status);
return status;
}
/*
* The READDIR implementation is somewhat hackish - we pass a temporary
* buffer to the encode function, which installs it in the receive
* the receive iovec. The decode function just parses the reply to make
* sure it is syntactically correct; the entries itself are decoded
* from nfs_readdir by calling the decode_entry function directly.
*/
static int
nfs_proc_readdir(struct dentry *dentry, struct rpc_cred *cred,
u64 cookie, struct page **pages, unsigned int count, int plus)
{
struct inode *dir = d_inode(dentry);
struct nfs_readdirargs arg = {
.fh = NFS_FH(dir),
.cookie = cookie,
.count = count,
.pages = pages,
};
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_READDIR],
.rpc_argp = &arg,
.rpc_cred = cred,
};
int status;
dprintk("NFS call readdir %d\n", (unsigned int)cookie);
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_invalidate_atime(dir);
dprintk("NFS reply readdir: %d\n", status);
return status;
}
static int
nfs_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsstat *stat)
{
struct nfs2_fsstat fsinfo;
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_STATFS],
.rpc_argp = fhandle,
.rpc_resp = &fsinfo,
};
int status;
dprintk("NFS call statfs\n");
nfs_fattr_init(stat->fattr);
status = rpc_call_sync(server->client, &msg, 0);
dprintk("NFS reply statfs: %d\n", status);
if (status)
goto out;
stat->tbytes = (u64)fsinfo.blocks * fsinfo.bsize;
stat->fbytes = (u64)fsinfo.bfree * fsinfo.bsize;
stat->abytes = (u64)fsinfo.bavail * fsinfo.bsize;
stat->tfiles = 0;
stat->ffiles = 0;
stat->afiles = 0;
out:
return status;
}
static int
nfs_proc_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
struct nfs2_fsstat fsinfo;
struct rpc_message msg = {
.rpc_proc = &nfs_procedures[NFSPROC_STATFS],
.rpc_argp = fhandle,
.rpc_resp = &fsinfo,
};
int status;
dprintk("NFS call fsinfo\n");
nfs_fattr_init(info->fattr);
status = rpc_call_sync(server->client, &msg, 0);
dprintk("NFS reply fsinfo: %d\n", status);
if (status)
goto out;
info->rtmax = NFS_MAXDATA;
info->rtpref = fsinfo.tsize;
info->rtmult = fsinfo.bsize;
info->wtmax = NFS_MAXDATA;
info->wtpref = fsinfo.tsize;
info->wtmult = fsinfo.bsize;
info->dtpref = fsinfo.tsize;
info->maxfilesize = 0x7FFFFFFF;
info->lease_time = 0;
out:
return status;
}
static int
nfs_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_pathconf *info)
{
info->max_link = 0;
info->max_namelen = NFS2_MAXNAMLEN;
return 0;
}
static int nfs_read_done(struct rpc_task *task, struct nfs_pgio_header *hdr)
{
struct inode *inode = hdr->inode;
nfs_invalidate_atime(inode);
if (task->tk_status >= 0) {
nfs_refresh_inode(inode, hdr->res.fattr);
/* Emulate the eof flag, which isn't normally needed in NFSv2
* as it is guaranteed to always return the file attributes
*/
if (hdr->args.offset + hdr->res.count >= hdr->res.fattr->size)
hdr->res.eof = 1;
}
return 0;
}
static void nfs_proc_read_setup(struct nfs_pgio_header *hdr,
struct rpc_message *msg)
{
msg->rpc_proc = &nfs_procedures[NFSPROC_READ];
}
static int nfs_proc_pgio_rpc_prepare(struct rpc_task *task,
struct nfs_pgio_header *hdr)
{
rpc_call_start(task);
return 0;
}
static int nfs_write_done(struct rpc_task *task, struct nfs_pgio_header *hdr)
{
if (task->tk_status >= 0)
nfs_writeback_update_inode(hdr);
return 0;
}
static void nfs_proc_write_setup(struct nfs_pgio_header *hdr,
struct rpc_message *msg)
{
/* Note: NFSv2 ignores @stable and always uses NFS_FILE_SYNC */
hdr->args.stable = NFS_FILE_SYNC;
msg->rpc_proc = &nfs_procedures[NFSPROC_WRITE];
}
static void nfs_proc_commit_rpc_prepare(struct rpc_task *task, struct nfs_commit_data *data)
{
BUG();
}
static void
nfs_proc_commit_setup(struct nfs_commit_data *data, struct rpc_message *msg)
{
BUG();
}
static int
nfs_proc_lock(struct file *filp, int cmd, struct file_lock *fl)
{
struct inode *inode = file_inode(filp);
return nlmclnt_proc(NFS_SERVER(inode)->nlm_host, cmd, fl);
}
/* Helper functions for NFS lock bounds checking */
#define NFS_LOCK32_OFFSET_MAX ((__s32)0x7fffffffUL)
static int nfs_lock_check_bounds(const struct file_lock *fl)
{
__s32 start, end;
start = (__s32)fl->fl_start;
if ((loff_t)start != fl->fl_start)
goto out_einval;
if (fl->fl_end != OFFSET_MAX) {
end = (__s32)fl->fl_end;
if ((loff_t)end != fl->fl_end)
goto out_einval;
} else
end = NFS_LOCK32_OFFSET_MAX;
if (start < 0 || start > end)
goto out_einval;
return 0;
out_einval:
return -EINVAL;
}
static int nfs_have_delegation(struct inode *inode, fmode_t flags)
{
return 0;
}
static int nfs_return_delegation(struct inode *inode)
{
nfs_wb_all(inode);
return 0;
}
static const struct inode_operations nfs_dir_inode_operations = {
.create = nfs_create,
.lookup = nfs_lookup,
.link = nfs_link,
.unlink = nfs_unlink,
.symlink = nfs_symlink,
.mkdir = nfs_mkdir,
.rmdir = nfs_rmdir,
.mknod = nfs_mknod,
.rename = nfs_rename,
.permission = nfs_permission,
.getattr = nfs_getattr,
.setattr = nfs_setattr,
};
static const struct inode_operations nfs_file_inode_operations = {
.permission = nfs_permission,
.getattr = nfs_getattr,
.setattr = nfs_setattr,
};
const struct nfs_rpc_ops nfs_v2_clientops = {
.version = 2, /* protocol version */
.dentry_ops = &nfs_dentry_operations,
.dir_inode_ops = &nfs_dir_inode_operations,
.file_inode_ops = &nfs_file_inode_operations,
.file_ops = &nfs_file_operations,
.getroot = nfs_proc_get_root,
.submount = nfs_submount,
.try_mount = nfs_try_mount,
.getattr = nfs_proc_getattr,
.setattr = nfs_proc_setattr,
.lookup = nfs_proc_lookup,
.access = NULL, /* access */
.readlink = nfs_proc_readlink,
.create = nfs_proc_create,
.remove = nfs_proc_remove,
.unlink_setup = nfs_proc_unlink_setup,
.unlink_rpc_prepare = nfs_proc_unlink_rpc_prepare,
.unlink_done = nfs_proc_unlink_done,
.rename_setup = nfs_proc_rename_setup,
.rename_rpc_prepare = nfs_proc_rename_rpc_prepare,
.rename_done = nfs_proc_rename_done,
.link = nfs_proc_link,
.symlink = nfs_proc_symlink,
.mkdir = nfs_proc_mkdir,
.rmdir = nfs_proc_rmdir,
.readdir = nfs_proc_readdir,
.mknod = nfs_proc_mknod,
.statfs = nfs_proc_statfs,
.fsinfo = nfs_proc_fsinfo,
.pathconf = nfs_proc_pathconf,
.decode_dirent = nfs2_decode_dirent,
.pgio_rpc_prepare = nfs_proc_pgio_rpc_prepare,
.read_setup = nfs_proc_read_setup,
.read_done = nfs_read_done,
.write_setup = nfs_proc_write_setup,
.write_done = nfs_write_done,
.commit_setup = nfs_proc_commit_setup,
.commit_rpc_prepare = nfs_proc_commit_rpc_prepare,
.lock = nfs_proc_lock,
.lock_check_bounds = nfs_lock_check_bounds,
.close_context = nfs_close_context,
.have_delegation = nfs_have_delegation,
.return_delegation = nfs_return_delegation,
.alloc_client = nfs_alloc_client,
.init_client = nfs_init_client,
.free_client = nfs_free_client,
.create_server = nfs_create_server,
.clone_server = nfs_clone_server,
};
| {
"content_hash": "dd865a63b36624e6ef822840aad3b81a",
"timestamp": "",
"source": "github",
"line_count": 722,
"max_line_length": 92,
"avg_line_length": 25.222991689750693,
"alnum_prop": 0.6742078963263961,
"repo_name": "KristFoundation/Programs",
"id": "b417bbcd970465069afcd820a414b19e4493e7e7",
"size": "19186",
"binary": false,
"copies": "888",
"ref": "refs/heads/master",
"path": "luaide/fs/nfs/proc.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "10201036"
},
{
"name": "Awk",
"bytes": "30879"
},
{
"name": "C",
"bytes": "539626448"
},
{
"name": "C++",
"bytes": "3413466"
},
{
"name": "Clojure",
"bytes": "1570"
},
{
"name": "Cucumber",
"bytes": "4809"
},
{
"name": "Groff",
"bytes": "46837"
},
{
"name": "Lex",
"bytes": "55541"
},
{
"name": "Lua",
"bytes": "59745"
},
{
"name": "Makefile",
"bytes": "1601043"
},
{
"name": "Objective-C",
"bytes": "521706"
},
{
"name": "Perl",
"bytes": "730609"
},
{
"name": "Perl6",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "296036"
},
{
"name": "Shell",
"bytes": "357961"
},
{
"name": "SourcePawn",
"bytes": "4687"
},
{
"name": "UnrealScript",
"bytes": "12797"
},
{
"name": "XS",
"bytes": "1239"
},
{
"name": "Yacc",
"bytes": "115572"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
namespace Roslyn.Test.Utilities
{
/// <summary>
/// Factory for creating different kinds of <see cref="DiagnosticDescriptor"/>s for use in tests.
/// </summary>
public static class DescriptorFactory
{
/// <summary>
/// Creates a <see cref="DiagnosticDescriptor"/> with specified <see cref="DiagnosticDescriptor.Id"/>.
/// </summary>
/// <remarks>
/// Returned <see cref="DiagnosticDescriptor"/> has
/// - empty <see cref="DiagnosticDescriptor.Title"/> and <see cref="DiagnosticDescriptor.Category"/>
/// - <see cref="DiagnosticDescriptor.MessageFormat"/> set to <paramref name="id"/>
/// - <see cref="DiagnosticDescriptor.DefaultSeverity"/> set to <see cref="DiagnosticSeverity.Hidden"/>
/// - <see cref="WellKnownDiagnosticTags.NotConfigurable"/> custom tag added in <see cref="DiagnosticDescriptor.CustomTags"/>.
/// </remarks>
/// <param name="id">The value for <see cref="DiagnosticDescriptor.Id"/>.</param>
/// <returns>A <see cref="DiagnosticDescriptor"/> with specified <see cref="DiagnosticDescriptor.Id"/>.</returns>
public static DiagnosticDescriptor CreateSimpleDescriptor(string id)
{
return new DiagnosticDescriptor(id, title: "", messageFormat: id, category: "",
defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.NotConfigurable);
}
}
}
| {
"content_hash": "29c045207148b89aabbac8f10e6990e9",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 134,
"avg_line_length": 50,
"alnum_prop": 0.6691428571428572,
"repo_name": "brettfo/roslyn",
"id": "9bb102ef08752eaf0320271ac77514e8245d5dff",
"size": "1752",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Test/Utilities/Portable/Diagnostics/DescriptorFactory.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "8643"
},
{
"name": "C#",
"bytes": "110983902"
},
{
"name": "C++",
"bytes": "5392"
},
{
"name": "Dockerfile",
"bytes": "1905"
},
{
"name": "F#",
"bytes": "508"
},
{
"name": "PowerShell",
"bytes": "105474"
},
{
"name": "Shell",
"bytes": "22163"
},
{
"name": "Smalltalk",
"bytes": "622"
},
{
"name": "Visual Basic",
"bytes": "68586535"
}
],
"symlink_target": ""
} |
totemExecStatus totemArgV(totemExecState *state)
{
if (!state->CallStack->NumArguments)
{
printf("no arguments argv\n");
return totemExecStatus_Break(totemExecStatus_Stop);
}
totemRegister *arg = &state->LocalRegisters[0];
if (!totemRegister_IsInt(arg))
{
printf("expected int argv\n");
return totemExecStatus_Break(totemExecStatus_Stop);
}
totemInt val = totemRegister_GetInt(arg);
if (!state->ArgV || val >= state->ArgC)
{
totemExecState_AssignNull(state, state->CallStack->ReturnRegister);
return totemExecStatus_Continue;
}
else
{
totemString str = TOTEM_STRING_VAL(state->ArgV[val]);
return totemExecState_InternString(state, &str, state->CallStack->ReturnRegister);
}
}
totemExecStatus totemPrint(totemExecState *state)
{
for (uint8_t i = 0; i < state->CallStack->NumArguments; i++)
{
totemRegister *reg = &state->LocalRegisters[i];
totemExecState_PrintRegister(state, stdout, reg);
}
return totemExecStatus_Continue;
}
totemExecStatus totemAssert(totemExecState *state)
{
if (!state->CallStack->NumArguments)
{
printf("no arguments assert\n");
return totemExecStatus_Break(totemExecStatus_Stop);
}
totemRegister *reg = &state->LocalRegisters[0];
if (totemRegister_IsZero(reg))
{
printf("assertion failed\n");
return totemExecStatus_Stop;
}
else
{
return totemExecStatus_Continue;
}
}
totemExecStatus totemSqrt(totemExecState *state)
{
if (!state->CallStack->NumArguments)
{
printf("no arguments sqrt\n");
return totemExecStatus_Break(totemExecStatus_Stop);
}
totemRegister *reg = &state->LocalRegisters[0];
if (totemRegister_IsFloat(reg))
{
totemExecState_AssignNewFloat(state, state->CallStack->ReturnRegister, sqrt(totemRegister_GetFloat(reg)));
}
else if (totemRegister_IsInt(reg))
{
totemExecState_AssignNewFloat(state, state->CallStack->ReturnRegister, sqrt((totemFloat)totemRegister_GetInt(reg)));
}
else
{
return totemExecStatus_Break(totemExecStatus_UnexpectedDataType);
}
return totemExecStatus_Continue;
}
void totemFileDestructor(totemExecState *state, void *data)
{
fclose((FILE*)data);
}
totemExecStatus totemFOpen(totemExecState *state)
{
if (state->CallStack->NumArguments < 2)
{
printf("no arguments fopen\n");
return totemExecStatus_Break(totemExecStatus_Stop);
}
totemRegister *srcReg = &state->LocalRegisters[0];
totemRegister *modeReg = &state->LocalRegisters[1];
if (!totemRegister_IsString(srcReg) || !totemRegister_IsString(modeReg))
{
printf("not string\n");
return totemExecStatus_Break(totemExecStatus_UnexpectedDataType);
}
totemRuntimeStringValue srcVal;
totemRuntimeStringValue modeVal;
totemRegister_GetStringValue(srcReg, &srcVal);
totemRegister_GetStringValue(modeReg, &modeVal);
const char *src = srcVal.Value;
const char *mode = modeVal.Value;
FILE *f = totem_fopen(src, mode);
if (!f)
{
printf("could not open file\n");
return totemExecStatus_Break(totemExecStatus_Stop);
}
totemGCObject *gc = NULL;
totemExecStatus status = totemExecState_CreateUserdata(state, (void*)f, totemFileDestructor, &gc);
if (status != totemExecStatus_Continue)
{
fclose(f);
return status;
}
totemExecState_AssignNewUserdata(state, state->CallStack->ReturnRegister, gc);
return status;
}
totemExecStatus totemGCCollect(totemExecState *state)
{
totemExecState_CollectGarbage(state, state->CallStack->NumArguments ? !totemRegister_IsZero(&state->LocalRegisters[0]) : totemBool_False);
return totemExecStatus_Continue;
}
totemExecStatus totemGCNum(totemExecState *state)
{
totemExecState_AssignNewInt(state, state->CallStack->ReturnRegister, state->GCNum);
return totemExecStatus_Continue;
}
totemLinkStatus totemRuntime_LinkStdLib(totemRuntime *runtime)
{
totemNativeFunctionPrototype funcs[] =
{
{ totemPrint, TOTEM_STRING_VAL("print") },
{ totemAssert, TOTEM_STRING_VAL("assert") },
{ totemFOpen, TOTEM_STRING_VAL("fopen") },
{ totemGCCollect, TOTEM_STRING_VAL("gc_collect") },
{ totemGCNum, TOTEM_STRING_VAL("gc_num") },
{ totemSqrt, TOTEM_STRING_VAL("sqrt") },
{ totemArgV, TOTEM_STRING_VAL("argv") }
};
return totemRuntime_LinkNativeFunctions(runtime, funcs, TOTEM_ARRAY_SIZE(funcs));
} | {
"content_hash": "6e707796cbe0d90a27ca059ac332643c",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 142,
"avg_line_length": 28.742331288343557,
"alnum_prop": 0.664461045891142,
"repo_name": "tdsmale/TotemScript",
"id": "00b287ea4b652cb56bd60da55e070ad130cad053",
"size": "4896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/TotemScript/exec_lib.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "521552"
},
{
"name": "C++",
"bytes": "1988"
},
{
"name": "Makefile",
"bytes": "883"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.causeway.core</groupId>
<artifactId>causeway-core</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath>../../core/pom.xml</relativePath>
</parent>
<groupId>org.apache.causeway.security</groupId>
<artifactId>causeway-security-shiro</artifactId>
<name>Apache Causeway Security - Shiro</name>
<description>
Authentication and Authorization using Apache Shiro.
</description>
<properties>
<!-- apache shiro is not migrated to JPMS yet, so no point in converting ours to JPMS -->
<jar-plugin.automaticModuleName>org.apache.causeway.security.shiro</jar-plugin.automaticModuleName>
<git-plugin.propertiesDir>org/apache/causeway/security/shiro</git-plugin.propertiesDir>
</properties>
<dependencyManagement>
<!-- for benefit of application developers, using scope=import -->
<dependencies>
<dependency>
<groupId>org.apache.causeway.security</groupId>
<artifactId>causeway-security-shiro</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.causeway.core</groupId>
<artifactId>causeway-core-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.apache.causeway.core</groupId>
<artifactId>causeway-core-runtimeservices</artifactId>
</dependency>
<dependency>
<groupId>org.apache.causeway.core</groupId>
<artifactId>causeway-core-webapp</artifactId>
<!-- don't make these transitive, so that we can make headless use
of the causeway-security-shiro module (without bringing in spring-boot-web) -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-thymeleaf
</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- SHIRO -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
</dependency>
<!-- TESTING -->
<dependency>
<groupId>org.apache.causeway.core</groupId>
<artifactId>causeway-core-internaltestsupport</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "eb7882164a43b4d262b1c81716591fa7",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 201,
"avg_line_length": 35.573913043478264,
"alnum_prop": 0.6384747005622097,
"repo_name": "apache/isis",
"id": "ac4ff8b995d2b0044e0f1213c46295fac0b4541b",
"size": "4091",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "security/shiro/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "152495"
},
{
"name": "Clean",
"bytes": "8063"
},
{
"name": "Gherkin",
"bytes": "412"
},
{
"name": "Groovy",
"bytes": "15585"
},
{
"name": "HTML",
"bytes": "268010"
},
{
"name": "Handlebars",
"bytes": "337"
},
{
"name": "Java",
"bytes": "17242597"
},
{
"name": "JavaScript",
"bytes": "271368"
},
{
"name": "Kotlin",
"bytes": "1913258"
},
{
"name": "Rich Text Format",
"bytes": "2150674"
},
{
"name": "Shell",
"bytes": "102821"
},
{
"name": "TypeScript",
"bytes": "275"
}
],
"symlink_target": ""
} |
FROM ubuntu:14.04
ENV ERLANG_VSN 17.3
RUN apt-get update && \
apt-get install -y curl \
build-essential \
libncurses5-dev \
libssl-dev \
unixodbc-dev
RUN curl -O https://raw.githubusercontent.com/yrashk/kerl/master/kerl && \
chmod a+x kerl && \
./kerl build ${ERLANG_VSN} ${ERLANG_VSN} && \
./kerl install ${ERLANG_VSN} /opt/erlang
ENV PATH /opt/erlang/bin:$PATH
| {
"content_hash": "9823237c626786a468a94b9bbb808065",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 74,
"avg_line_length": 27.941176470588236,
"alnum_prop": 0.5389473684210526,
"repo_name": "studzien/erlang",
"id": "46da5ee383fdbc63848829068e87fc182e7366a9",
"size": "475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "17.3/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "211"
},
{
"name": "Shell",
"bytes": "25835"
}
],
"symlink_target": ""
} |
const Sequelize = require('sequelize');
// const MarkerModel = sequelize.define('markers', {
// });
module.exports = {
name: 'articles',
model: {
title: {
type: Sequelize.STRING,
allowNull: false
},
content: {
type: Sequelize.JSON
},
previewSize: {
type: Sequelize.ARRAY(Sequelize.DECIMAL),
allowNull: false,
defaultValue: [1, 1]
},
plainText: {
type: Sequelize.TEXT,
allowNull: false,
defaultValue: ''
},
slug: {
type: Sequelize.STRING(255),
allowNull: false,
defaultValue: ''
},
type: {
type: Sequelize.ENUM,
defaultValue: 'own',
values: ['external', 'own']
},
link: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: ''
},
description: {
type: Sequelize.TEXT,
allowNull: false,
defaultValue: null
}
}
};
| {
"content_hash": "57f5f01a8e1e15457a8c0e177fe98aa8",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 52,
"avg_line_length": 19.020833333333332,
"alnum_prop": 0.5443592552026287,
"repo_name": "ReactPoland/react-community",
"id": "bc07dcad17be0f8025036e7d74f26d3368d34804",
"size": "954",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/db/models/Article.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12458"
},
{
"name": "JavaScript",
"bytes": "321777"
}
],
"symlink_target": ""
} |
package org.jetbrains.jps.builders.java.dependencyView;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import gnu.trove.THashSet;
import org.jetbrains.asm4.Type;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
/**
* @author: db
* Date: 01.02.11
*/
class MethodRepr extends ProtoMember {
interface Predicate {
boolean satisfy(MethodRepr m);
}
public final TypeRepr.AbstractType[] myArgumentTypes;
public final Set<TypeRepr.AbstractType> myExceptions;
public abstract class Diff extends Difference {
public abstract Specifier<TypeRepr.AbstractType> exceptions();
public abstract boolean defaultAdded();
public abstract boolean defaultRemoved();
}
@Override
public Difference difference(final Proto past) {
final Difference diff = super.difference(past);
final Difference.Specifier<TypeRepr.AbstractType> excs = Difference.make(((MethodRepr)past).myExceptions, myExceptions);
return new Diff() {
@Override
public int addedModifiers() {
return diff.addedModifiers();
}
@Override
public int removedModifiers() {
return diff.removedModifiers();
}
@Override
public boolean no() {
return base() == NONE && !defaultAdded() && !defaultRemoved() && excs.unchanged();
}
@Override
public boolean defaultAdded() {
return hasValue() && !((MethodRepr)past).hasValue();
}
@Override
public boolean defaultRemoved() {
return !hasValue() && ((MethodRepr)past).hasValue();
}
@Override
public Specifier<TypeRepr.AbstractType> exceptions() {
return excs;
}
@Override
public int base() {
return diff.base();
}
@Override
public boolean packageLocalOn() {
return diff.packageLocalOn();
}
@Override
public boolean hadValue() {
return ((MethodRepr)past).hasValue();
}
@Override
public boolean weakedAccess() {
return diff.weakedAccess();
}
};
}
public void updateClassUsages(final DependencyContext context, final int owner, final Set<UsageRepr.Usage> s) {
myType.updateClassUsages(context, owner, s);
for (int i = 0; i < myArgumentTypes.length; i++) {
myArgumentTypes[i].updateClassUsages(context, owner, s);
}
if (myExceptions != null) {
for (TypeRepr.AbstractType typ : myExceptions) {
typ.updateClassUsages(context, owner, s);
}
}
}
public MethodRepr(final DependencyContext context,
final int a,
final int n,
final int s,
final String d,
final String[] e,
final Object value) {
super(a, s, n, TypeRepr.getType(context, Type.getReturnType(d)), value);
Set<TypeRepr.AbstractType> typeCollection =
e != null ? new THashSet<TypeRepr.AbstractType>(e.length) : Collections.<TypeRepr.AbstractType>emptySet();
myExceptions = (Set<TypeRepr.AbstractType>)TypeRepr.createClassType(context, e, typeCollection);
myArgumentTypes = TypeRepr.getType(context, Type.getArgumentTypes(d));
}
public MethodRepr(final DependencyContext context, final DataInput in) {
super(context, in);
try {
final DataExternalizer<TypeRepr.AbstractType> externalizer = TypeRepr.externalizer(context);
final int size = DataInputOutputUtil.readINT(in);
myArgumentTypes = RW.read(externalizer, in, new TypeRepr.AbstractType[size]);
myExceptions = (Set<TypeRepr.AbstractType>)RW.read(externalizer, new THashSet<TypeRepr.AbstractType>(0), in);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void save(final DataOutput out) {
super.save(out);
RW.save(myArgumentTypes, out);
RW.save(myExceptions, out);
}
public static DataExternalizer<MethodRepr> externalizer(final DependencyContext context) {
return new DataExternalizer<MethodRepr>() {
@Override
public void save(final DataOutput out, final MethodRepr value) throws IOException {
value.save(out);
}
@Override
public MethodRepr read(DataInput in) throws IOException {
return new MethodRepr(context, in);
}
};
}
static Predicate equalByJavaRules(final MethodRepr me) {
return new Predicate() {
@Override
public boolean satisfy(MethodRepr that) {
if (me == that) return true;
return me.name == that.name && Arrays.equals(me.myArgumentTypes, that.myArgumentTypes);
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MethodRepr that = (MethodRepr)o;
return name == that.name && myType.equals(that.myType) && Arrays.equals(myArgumentTypes, that.myArgumentTypes);
}
@Override
public int hashCode() {
return 31 * (31 * Arrays.hashCode(myArgumentTypes) + myType.hashCode()) + name;
}
private String getDescr(final DependencyContext context) {
final StringBuilder buf = new StringBuilder();
buf.append("(");
for (TypeRepr.AbstractType t : myArgumentTypes) {
buf.append(t.getDescr(context));
}
buf.append(")");
buf.append(myType.getDescr(context));
return buf.toString();
}
public UsageRepr.Usage createUsage(final DependencyContext context, final int owner) {
return UsageRepr.createMethodUsage(context, name, owner, getDescr(context));
}
public UsageRepr.Usage createMetaUsage(final DependencyContext context, final int owner) {
return UsageRepr.createMetaMethodUsage(context, name, owner, getDescr(context));
}
@Override
public void toStream(final DependencyContext context, final PrintStream stream) {
super.toStream(context, stream);
stream.print(" Arguments : ");
for (TypeRepr.AbstractType t : myArgumentTypes) {
stream.print(t.getDescr(context));
stream.print("; ");
}
stream.println();
final TypeRepr.AbstractType[] es = myExceptions.toArray(new TypeRepr.AbstractType[myExceptions.size()]);
Arrays.sort(es, new Comparator<TypeRepr.AbstractType>() {
@Override
public int compare(final TypeRepr.AbstractType o1, final TypeRepr.AbstractType o2) {
return o1.getDescr(context).compareTo(o2.getDescr(context));
}
});
stream.print(" Exceptions : ");
for (final TypeRepr.AbstractType e : es) {
stream.print(e.getDescr(context));
stream.print("; ");
}
stream.println();
}
}
| {
"content_hash": "09b49032ad8f1b68daec58f9995183bc",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 124,
"avg_line_length": 29.797356828193834,
"alnum_prop": 0.6595209934949734,
"repo_name": "romankagan/DDBWorkbench",
"id": "b358e1189b81d6ecab6fb5167fa231cba5b5ffd0",
"size": "7364",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/MethodRepr.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "C",
"bytes": "174330"
},
{
"name": "C#",
"bytes": "390"
},
{
"name": "C++",
"bytes": "85270"
},
{
"name": "CSS",
"bytes": "102018"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "FLUX",
"bytes": "57"
},
{
"name": "Groovy",
"bytes": "1899897"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "128604770"
},
{
"name": "JavaScript",
"bytes": "123045"
},
{
"name": "Objective-C",
"bytes": "19702"
},
{
"name": "Perl",
"bytes": "6549"
},
{
"name": "Python",
"bytes": "17759911"
},
{
"name": "Ruby",
"bytes": "1213"
},
{
"name": "Shell",
"bytes": "45691"
},
{
"name": "TeX",
"bytes": "60798"
},
{
"name": "XSLT",
"bytes": "113531"
}
],
"symlink_target": ""
} |
import java.util.Collection;
import java.util.HashSet;
import org.omg.dds.core.InstanceHandle;
import org.omg.dds.core.ServiceEnvironment;
import org.omg.dds.core.policy.Durability;
import org.omg.dds.core.policy.Partition;
import org.omg.dds.core.policy.PolicyFactory;
import org.omg.dds.core.policy.Reliability;
import org.omg.dds.core.policy.WriterDataLifecycle;
import org.omg.dds.core.status.Status;
import org.omg.dds.domain.DomainParticipant;
import org.omg.dds.domain.DomainParticipantFactory;
import org.omg.dds.pub.DataWriter;
import org.omg.dds.pub.DataWriterQos;
import org.omg.dds.pub.Publisher;
import org.omg.dds.pub.PublisherQos;
import org.omg.dds.topic.Topic;
import org.omg.dds.topic.TopicQos;
import LifecycleData.Msg;
public class LifecycleDataPublisher {
public static void usage() {
System.out.println("*** ERROR");
System.out.println("*** usage : LifecyclePublisher <autodispose_flag> <writer_action>");
System.out.println("*** . autodispose_flag = false | true");
System.out.println("*** . dispose | unregister | stoppub");
System.exit(0);
}
public static void main(String args[]) {
System.out.println("=== args_length=" + args.length);
if (args.length < 2) {
usage();
}
if (!(args[0].equals("false")) && !(args[0].equals("true"))
&& !(args[1].equals("dispose")) && !(args[1].equals("unregister")) && !(args[1].equals("stoppub")))
{
usage();
}
boolean autodispose = (args[0].equals("true"));
String partitionName = "Lifecycle example";
try {
System.setProperty(
ServiceEnvironment.IMPLEMENTATION_CLASS_NAME_PROPERTY,
"org.opensplice.dds.core.OsplServiceEnvironment");
ServiceEnvironment env = ServiceEnvironment
.createInstance(LifecycleDataPublisher.class.getClassLoader());
DomainParticipantFactory dpf = DomainParticipantFactory.getInstance(env);
// create Domain Participant
DomainParticipant participant = dpf.createParticipant();
// create Topic with reliable and transient qos
PolicyFactory policyFactory = env.getSPI().getPolicyFactory();
Reliability reliable = policyFactory.Reliability().withReliable();
Durability durability = policyFactory.Durability().withTransient();
TopicQos topicQos = participant.getDefaultTopicQos().withPolicies(reliable,durability);
Collection<Class<? extends Status>> status = new HashSet<Class<? extends Status>>();
Topic<Msg> topic = participant.createTopic("Lifecycle_Msg", Msg.class,topicQos, null, status);
// create Publisher with partition qos
Partition partition = policyFactory.Partition().withName(partitionName);
PublisherQos pubQos = participant.getDefaultPublisherQos().withPolicy(partition);
Publisher pub = participant.createPublisher(pubQos);
// create DataWriter with autDisposeUnregisteredInstances qos
WriterDataLifecycle wdlq = policyFactory.WriterDataLifecycle().withAutDisposeUnregisteredInstances(autodispose);
DataWriterQos dwQos = pub.copyFromTopicQos(pub.getDefaultDataWriterQos().withPolicy(wdlq),topic.getQos());
DataWriter<Msg> writer = pub.createDataWriter(topic,dwQos);
DataWriter<Msg> writerStopper = pub.createDataWriter(topic,dwQos);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (args[1].equals("dispose")){
// Send Msg (topic to monitor)
Msg msgInstance = new Msg();
msgInstance.userID = 1;
msgInstance.message = "Lifecycle_1";
msgInstance.writerStates = "SAMPLE_SENT -> INSTANCE_DISPOSED -> DATAWRITER_DELETED";
System.out.println("=== [Publisher] :");
System.out.println(" userID : " + msgInstance.userID);
System.out.println(" Message : " + msgInstance.message);
System.out.println(" writerStates : " + msgInstance.writerStates);
writer.write(msgInstance, InstanceHandle.nilHandle(env));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=== [Publisher] : SAMPLE_SENT");
// Dispose instance
writer.dispose(InstanceHandle.nilHandle(env), msgInstance);
System.out.println("=== [Publisher] : INSTANCE_DISPOSED");
}
else if (args[1].equals("unregister")){
// Send Msg (topic to monitor)
Msg msgInstance = new Msg();
msgInstance.userID = 2;
msgInstance.message = "Lifecycle_2";
msgInstance.writerStates = "SAMPLE_SENT -> INSTANCE_UNREGISTERED -> DATAWRITER_DELETED";
System.out.println("=== [Publisher] :");
System.out.println(" userID : " + msgInstance.userID);
System.out.println(" Message : " + msgInstance.message);
System.out.println(" writerStates : " + msgInstance.writerStates);
writer.write(msgInstance, InstanceHandle.nilHandle(env));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=== [Publisher] : SAMPLE_SENT");
// Unregister instance : the auto_dispose_unregisterd_instances flag
// is currently ignored and the instance is never disposed
// automatically
writer.unregisterInstance(InstanceHandle.nilHandle(env), msgInstance);
System.out.println("=== [Publisher] : INSTANCE_UNREGISTERED");
}
else if (args[1].equals("stoppub")){
// Send Msg (topic to monitor)
Msg msgInstance = new Msg();
msgInstance.userID = 3;
msgInstance.message = "Lifecycle_3";
msgInstance.writerStates = "SAMPLE_SENT -> DATAWRITER_DELETED";
System.out.println("=== [Publisher] :");
System.out.println(" userID : " + msgInstance.userID);
System.out.println(" Message : " + msgInstance.message);
System.out.println(" writerStates : " + msgInstance.writerStates);
writer.write(msgInstance, InstanceHandle.nilHandle(env));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=== [Publisher] : SAMPLE_SENT");
}
// let the subscriber treat the previous writer state !!!!
System.out
.println("=== [Publisher] waiting 500ms to let the subscriber treat the previous write state ...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Clean-up the dataWriter
writer.close();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=== [Publisher] : DATAWRITER_DELETED");
// Stop the subscriber
Msg msgInstance = new Msg();
msgInstance.userID = 4;
msgInstance.message = "Lifecycle_4";
msgInstance.writerStates = "STOPPING_SUBSCRIBER";
System.out.println("=== [Publisher] :");
System.out.println(" userID : " + msgInstance.userID);
System.out.println(" Message : " + msgInstance.message);
System.out.println(" writerStates : " + msgInstance.writerStates);
writerStopper.write(msgInstance, InstanceHandle.nilHandle(env));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
participant.close();
} catch(Exception e) {
System.out.println("Error occured: " + e.getMessage());
e.printStackTrace();
}
}
}
| {
"content_hash": "8f64260f4c11650378c2ef3ed2629386",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 124,
"avg_line_length": 41.98941798941799,
"alnum_prop": 0.6280241935483871,
"repo_name": "osrf/opensplice",
"id": "45300a28a1448a9028051780c0d8f0e32427c92a",
"size": "8734",
"binary": false,
"copies": "2",
"ref": "refs/heads/osrf-6.9.0",
"path": "examples/dcps/Lifecycle/java5/pub/src/LifecycleDataPublisher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "16400"
},
{
"name": "Batchfile",
"bytes": "192174"
},
{
"name": "C",
"bytes": "19618578"
},
{
"name": "C#",
"bytes": "2428591"
},
{
"name": "C++",
"bytes": "8036199"
},
{
"name": "CMake",
"bytes": "35186"
},
{
"name": "CSS",
"bytes": "41427"
},
{
"name": "HTML",
"bytes": "457045"
},
{
"name": "Java",
"bytes": "5184488"
},
{
"name": "JavaScript",
"bytes": "540355"
},
{
"name": "LLVM",
"bytes": "13059"
},
{
"name": "Lex",
"bytes": "51476"
},
{
"name": "Makefile",
"bytes": "513684"
},
{
"name": "Objective-C",
"bytes": "38424"
},
{
"name": "Perl",
"bytes": "164028"
},
{
"name": "Python",
"bytes": "915683"
},
{
"name": "Shell",
"bytes": "363583"
},
{
"name": "TeX",
"bytes": "8134"
},
{
"name": "Visual Basic",
"bytes": "290"
},
{
"name": "Yacc",
"bytes": "202848"
}
],
"symlink_target": ""
} |
This project provides a Node.js package that makes it easy to manage Windows Azure Web Site. Right now it supports:
- **Node.js version: 0.6.15 or higher**
- **API version: 2013-08-01**
## Features
- Manage web space
- Manage web site
- Manage web farm
## How to Install
```bash
npm install azure-mgmt-website
```
## How to Use
### Authentication
This library support management certificate authentication. To authenticate the library for the REST API calls, you need to
* Have a management certificate set up in your Windows Azure subscription. You can do this by
* Either uploading a certificate in the [Windows Azure management portal](https://manage.windowsazure.com).
* Or use the [Windows Azure Xplat-CLI](https://github.com/WindowsAzure/azure-sdk-tools-xplat).
* Obtain the .pem file of your certificate. If you used [Windows Azure Xplat-CLI](https://github.com/WindowsAzure/azure-sdk-tools-xplat) to set it up. You can run ``azure account cert export`` to get the .pem file.
### Create the WebSiteManagementClient
```javascript
var fs = require('fs'),
webSiteManagement = require('azure-mgmt-website');
var webSiteManagementClient = webSiteManagement.createWebsiteManagementClient(webSiteManagement.createCertificateCloudCredentials({
subscriptionId: '<your subscription id>',
pem: fs.readFileSync('<your pem file>')
}));
```
### Manage Web Site
```javascript
var webSiteName = "website01";
// Get all the available webspaces under a subscription.
webSiteManagementClient.webSpaces.list(function (err, result) {
if (err) {
console.error(err);
} else {
console.info(result);
}
});
// Create a web site.
webSiteManagementClient.webSites.create("westuswebspace", {
name: webSiteName,
hostNames: [webSiteName + ".azurewebsites.net"],
webSpaceName: "westuswebspace"
}, function (err, result) {
if (err) {
console.error(err);
} else {
console.info(result);
}
});
```
## Related projects
- [Windows Azure SDK for Node.js - All-up](https://github.com/WindowsAzure/azure-sdk-for-node)
| {
"content_hash": "8519b3b1f972c0f6a6c77cf0da63e415",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 214,
"avg_line_length": 30.485714285714284,
"alnum_prop": 0.7000937207122774,
"repo_name": "dudeletslive/LosAlamosFoundation",
"id": "00157ad49486ccb5656d8fcb51645fc9f7d7d0f3",
"size": "2189",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/keystone/node_modules/azure/node_modules/azure-mgmt-website/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "191990"
},
{
"name": "JavaScript",
"bytes": "67555"
},
{
"name": "PHP",
"bytes": "22"
}
],
"symlink_target": ""
} |
require "cli/parser"
require "commands"
module Homebrew
# Helper module for printing help output.
#
# @api private
module Help
# NOTE: Keep the length of vanilla `--help` less than 25 lines!
# This is because the default Terminal height is 25 lines. Scrolling sucks
# and concision is important. If more help is needed we should start
# specialising help like the gem command does.
# NOTE: Keep lines less than 80 characters! Wrapping is just not cricket.
HOMEBREW_HELP = <<~EOS
Example usage:
brew search [TEXT|/REGEX/]
brew info [FORMULA...]
brew install FORMULA...
brew update
brew upgrade [FORMULA...]
brew uninstall FORMULA...
brew list [FORMULA...]
Troubleshooting:
brew config
brew doctor
brew install --verbose --debug FORMULA
Contributing:
brew create [URL [--no-fetch]]
brew edit [FORMULA...]
Further help:
brew commands
brew help [COMMAND]
man brew
https://docs.brew.sh
EOS
private_constant :HOMEBREW_HELP
module_function
def help(cmd = nil, empty_argv: false, usage_error: nil, remaining_args: [])
if cmd.nil?
# Handle `brew` (no arguments).
if empty_argv
$stderr.puts HOMEBREW_HELP
exit 1
end
# Handle `brew (-h|--help|--usage|-?|help)` (no other arguments).
puts HOMEBREW_HELP
exit 0
end
# Resolve command aliases and find file containing the implementation.
path = Commands.path(cmd)
# Display command-specific (or generic) help in response to `UsageError`.
if usage_error
$stderr.puts path ? command_help(cmd, path, remaining_args: remaining_args) : HOMEBREW_HELP
$stderr.puts
onoe usage_error
exit 1
end
# Resume execution in `brew.rb` for unknown commands.
return if path.nil?
# Display help for internal command (or generic help if undocumented).
puts command_help(cmd, path, remaining_args: remaining_args)
exit 0
end
def command_help(cmd, path, remaining_args:)
# Only some types of commands can have a parser.
output = if Commands.valid_internal_cmd?(cmd) ||
Commands.valid_internal_dev_cmd?(cmd) ||
Commands.external_ruby_v2_cmd_path(cmd)
parser_help(path, remaining_args: remaining_args)
end
output ||= comment_help(path)
output ||= if output.blank?
opoo "No help text in: #{path}" if Homebrew::EnvConfig.developer?
HOMEBREW_HELP
end
output
end
private_class_method :command_help
def parser_help(path, remaining_args:)
# Let OptionParser generate help text for commands which have a parser.
cmd_parser = CLI::Parser.from_cmd_path(path)
return unless cmd_parser
# Try parsing arguments here in order to show formula options in help output.
cmd_parser.parse(remaining_args, ignore_invalid_options: true)
cmd_parser.generate_help_text
end
private_class_method :parser_help
def command_help_lines(path)
path.read
.lines
.grep(/^#:/)
.map { |line| line.slice(2..-1).delete_prefix(" ") }
end
private_class_method :command_help_lines
def comment_help(path)
# Otherwise read #: lines from the file.
help_lines = command_help_lines(path)
return if help_lines.blank?
Formatter.wrap(help_lines.join, COMMAND_DESC_WIDTH)
.sub("@hide_from_man_page ", "")
.sub(/^\* /, "#{Tty.bold}Usage: brew#{Tty.reset} ")
.gsub(/`(.*?)`/m, "#{Tty.bold}\\1#{Tty.reset}")
.gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) }
.gsub(/<(.*?)>/m, "#{Tty.underline}\\1#{Tty.reset}")
.gsub(/\*(.*?)\*/m, "#{Tty.underline}\\1#{Tty.reset}")
end
private_class_method :comment_help
end
end
| {
"content_hash": "d5fa605201226db51ad514a51e9809c9",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 99,
"avg_line_length": 31.53125,
"alnum_prop": 0.595639246778989,
"repo_name": "vitorgalvao/brew",
"id": "66e38c35769514c4b275c4095f377e4e48672aec",
"size": "4081",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Library/Homebrew/help.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "1357"
},
{
"name": "HTML",
"bytes": "12353"
},
{
"name": "PostScript",
"bytes": "485"
},
{
"name": "Roff",
"bytes": "68766"
},
{
"name": "Ruby",
"bytes": "2166776"
},
{
"name": "Shell",
"bytes": "122099"
},
{
"name": "Swift",
"bytes": "1788"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en" ng-app="LunchCheck">
<head>
<title>Lunch Checker</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles/bootstrap.min.css">
<style>
.message { font-size: 1.3em; font-weight: bold; }
</style>
</head>
<body>
<div class="container">
<h1>Lunch Checker</h1>
<div ng-controller="LunchCheckController">
<div class="form-group">
<input id="lunch-menu"
ng-model="lunchMenuItems"
type="text"
placeholder="list comma separated dishes you usually have for lunch"
class="form-control">
</div>
<div class="form-group">
<button ng-click="LunchCheck()" class="btn btn-default">Check If Too Much</button>
</div>
<div class="form-group message">
{{lunchMenuMessage}}
</div>
</div>
</div>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
| {
"content_hash": "f044f64881c86e71a8840f11e773085b",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 92,
"avg_line_length": 32.39393939393939,
"alnum_prop": 0.5594013096351731,
"repo_name": "zagallai/Coursera-AngularJS-JHU",
"id": "455fe701df8bcd303d8276f891dadfa40e3f833c",
"size": "1069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module1-solution/index.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1053"
},
{
"name": "HTML",
"bytes": "3478"
},
{
"name": "JavaScript",
"bytes": "3336"
}
],
"symlink_target": ""
} |
package org.onosproject.pcelabelstore.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import org.onlab.util.KryoNamespace;
import org.onosproject.cluster.NodeId;
import org.onosproject.store.Timestamp;
import org.onosproject.store.service.EventuallyConsistentMap;
import org.onosproject.store.service.EventuallyConsistentMapBuilder;
import org.onosproject.store.service.EventuallyConsistentMapEvent;
import org.onosproject.store.service.EventuallyConsistentMapListener;
import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.REMOVE;
/**
* Testing version of an Eventually Consistent Map.
*/
public final class TestEventuallyConsistentMap<K, V> extends EventuallyConsistentMapAdapter<K, V> {
private final HashMap<K, V> map;
private final String mapName;
private final List<EventuallyConsistentMapListener<K, V>> listeners;
private final BiFunction<K, V, Collection<NodeId>> peerUpdateFunction;
private TestEventuallyConsistentMap(String mapName,
BiFunction<K, V, Collection<NodeId>> peerUpdateFunction) {
map = new HashMap<>();
listeners = new LinkedList<>();
this.mapName = mapName;
this.peerUpdateFunction = peerUpdateFunction;
}
/**
* Notify all listeners of an event.
*/
private void notifyListeners(EventuallyConsistentMapEvent<K, V> event) {
listeners.forEach(
listener -> listener.event(event)
);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(K key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(V value) {
return map.containsValue(value);
}
@Override
public V get(K key) {
return map.get(key);
}
@Override
public void put(K key, V value) {
map.put(key, value);
EventuallyConsistentMapEvent<K, V> addEvent =
new EventuallyConsistentMapEvent<>(mapName, PUT, key, value);
notifyListeners(addEvent);
if (peerUpdateFunction != null) {
peerUpdateFunction.apply(key, value);
}
}
@Override
public V remove(K key) {
V result = map.remove(key);
if (result != null) {
EventuallyConsistentMapEvent<K, V> removeEvent =
new EventuallyConsistentMapEvent<>(mapName, REMOVE,
key, map.get(key));
notifyListeners(removeEvent);
}
return result;
}
@Override
public void remove(K key, V value) {
boolean removed = map.remove(key, value);
if (removed) {
EventuallyConsistentMapEvent<K, V> removeEvent =
new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, value);
notifyListeners(removeEvent);
}
}
@Override
public V compute(K key, BiFunction<K, V, V> recomputeFunction) {
return map.compute(key, recomputeFunction);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
map.putAll(m);
}
@Override
public void clear() {
map.clear();
}
@Override
public Set<K> keySet() {
return map.keySet();
}
@Override
public Collection<V> values() {
return map.values();
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
return map.entrySet();
}
public static <K, V> Builder<K, V> builder() {
return new Builder<>();
}
@Override
public void addListener(EventuallyConsistentMapListener<K, V> listener) {
listeners.add(listener);
}
@Override
public void removeListener(EventuallyConsistentMapListener<K, V> listener) {
listeners.remove(listener);
}
public static class Builder<K, V> implements EventuallyConsistentMapBuilder<K, V> {
private String name;
private BiFunction<K, V, Collection<NodeId>> peerUpdateFunction;
@Override
public EventuallyConsistentMapBuilder<K, V> withName(String name) {
this.name = name;
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withSerializer(KryoNamespace.Builder serializerBuilder) {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withSerializer(KryoNamespace serializer) {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V>
withTimestampProvider(BiFunction<K, V, Timestamp> timestampProvider) {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withEventExecutor(ExecutorService executor) {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withCommunicationExecutor(ExecutorService executor) {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withBackgroundExecutor(ScheduledExecutorService executor) {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V>
withPeerUpdateFunction(BiFunction<K, V, Collection<NodeId>> peerUpdateFunction) {
this.peerUpdateFunction = peerUpdateFunction;
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withTombstonesDisabled() {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withAntiEntropyPeriod(long period, TimeUnit unit) {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withFasterConvergence() {
return this;
}
@Override
public EventuallyConsistentMapBuilder<K, V> withPersistence() {
return this;
}
@Override
public EventuallyConsistentMap<K, V> build() {
if (name == null) {
name = "test";
}
return new TestEventuallyConsistentMap<>(name, peerUpdateFunction);
}
}
}
| {
"content_hash": "c7d696f9943cd6c3b09eb28fe17541fd",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 111,
"avg_line_length": 28.495726495726494,
"alnum_prop": 0.6361727654469106,
"repo_name": "donNewtonAlpha/onos",
"id": "05bbb7b4a7c21fc40dc1a4dc2baf558b8c799718",
"size": "7285",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "protocols/pcep/ctl/src/test/java/org/onosproject/pcelabelstore/util/TestEventuallyConsistentMap.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "202557"
},
{
"name": "HTML",
"bytes": "110229"
},
{
"name": "Java",
"bytes": "30599243"
},
{
"name": "JavaScript",
"bytes": "3719133"
},
{
"name": "Protocol Buffer",
"bytes": "8451"
},
{
"name": "Python",
"bytes": "210350"
},
{
"name": "Shell",
"bytes": "843"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_03) on Wed Aug 08 01:09:03 PDT 2012 -->
<title> Class Hierarchy</title>
<meta name="date" content="2012-08-08">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title=" Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package <Unnamed></h1>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle"><a href="Scheduler.html" title="class in <Unnamed>"><span class="strong">Scheduler</span></a> (implements java.lang.Runnable)</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "fec3cc12a12d02042dc3d152f39b2222",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 154,
"avg_line_length": 30.065573770491802,
"alnum_prop": 0.6076881134133042,
"repo_name": "mattb243/AmazonEC2Matlab",
"id": "8697f116ee76b4aadda4b8108a49c5c34069b88d",
"size": "3668",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Scheduling-1.2/doc/doc/package-tree.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "38852"
},
{
"name": "Java",
"bytes": "1878893"
},
{
"name": "Matlab",
"bytes": "28669"
},
{
"name": "Perl",
"bytes": "3736"
},
{
"name": "Python",
"bytes": "2705"
},
{
"name": "Shell",
"bytes": "7194"
}
],
"symlink_target": ""
} |
export interface ImageListItemClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to an `img` element to ensure it covers the item. */
img: string;
/** Styles applied to the root element if `variant="standard"`. */
standard: string;
/** Styles applied to the root element if `variant="woven"`. */
woven: string;
/** Styles applied to the root element if `variant="masonry"`. */
masonry: string;
/** Styles applied to the root element if `variant="quilted"`. */
quilted: string;
}
export declare type ImageListItemClassKey = keyof ImageListItemClasses;
export declare function getImageListItemUtilityClass(slot: string): string;
declare const imageListItemClasses: ImageListItemClasses;
export default imageListItemClasses;
| {
"content_hash": "fb1ff9dd32b62903d8f6133ab41f9f8f",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 75,
"avg_line_length": 44.72222222222222,
"alnum_prop": 0.715527950310559,
"repo_name": "cdnjs/cdnjs",
"id": "e8b93810fb86466648e58d83aa5ed4c967316c13",
"size": "805",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "ajax/libs/material-ui/5.0.0-alpha.37/ImageListItem/imageListItemClasses.d.ts",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
var Thread = {
hostRunning: true,
activeLoops: 0,
_timers: [],
spin: function(ctrl) {
ctrl.startTime = ctrl.startTime || Date.now();
ctrl.timeout = false;
this.activeLoops++;
this._spinInternal(ctrl);
this.activeLoops--;
ctrl.elapsed = Date.now() - ctrl.startTime;
return ctrl.timeout;
},
_spinInternal: function(ctrl) {
var t = ctrl.startTime;
var maxTime = parseInt(ctrl.maxTime);
if (maxTime) {
while(ctrl.running && this.hostRunning) {
this.yield();
if (Date.now() - t > maxTime) {
ctrl.timeout = true;
ctrl.running = false;
break;
}
}
} else while(ctrl.running && this.hostRunning) this.yield();
},
yield: function() {
this.current.processNextEvent(true);
},
yieldAll: function() {
var t = this.current;
while(t.hasPendingEvents()) t.processNextEvent(false);
},
get current() {
delete this.current;
var obj = "@mozilla.org/thread-manager;1" in Cc
? Cc["@mozilla.org/thread-manager;1"].getService()
: Cc["@mozilla.org/thread;1"].createInstance(Ci.nsIThread);
this.__defineGetter__("current", function() { return obj.currentThread; });
return this.current;
},
get currentQueue() {
delete this.currentQueue;
var eqs = null;
const CTRID = "@mozilla.org/event-queue-service;1";
if (CTRID in Cc) {
const IFace = Ci.nsIEventQueueService;
eqs = Cc[CTRID].getService(IFace);
}
this.__defineGetter__("currentQueue", eqs
? function() { return eqs.getSpecialEventQueue(IFace.CURRENT_THREAD_EVENT_QUEUE); }
: this.__lookupGetter__("current")
);
return this.currentQueue;
},
delay: function(callback, time, self, args) {
var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._timers.push(timer);
timer.initWithCallback({
notify: this._delayRunner,
context: { callback: callback, args: args || DUMMY_ARRAY, self: self || null }
}, time || 1, 0);
},
dispatch: function(runnable) {
this.current.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL);
},
asap: function(callback, self, args) {
this.current.dispatch({
run: function() {
callback.apply(self, args || DUMMY_ARRAY);
}
}, Ci.nsIEventTarget.DISPATCH_NORMAL);
},
_delayRunner: function(timer) {
var ctx = this.context;
try {
ctx.callback.apply(ctx.self, ctx.args);
} finally {
this.context = null;
var tt = Thread._timers;
var pos = tt.indexOf(timer);
if (pos > -1) tt.splice(pos, 1);
timer.cancel();
}
}
};
| {
"content_hash": "38e14f20aea61737ecf5b99ad989031d",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 89,
"avg_line_length": 27.78,
"alnum_prop": 0.5795536357091433,
"repo_name": "mikedep333/duckpan-vagrant",
"id": "8c9daf6430074641cbdefc0342f89472f1f6b596",
"size": "2778",
"binary": false,
"copies": "2",
"ref": "refs/heads/duckduckhack-vm",
"path": "cookbooks/duckduckhack-vm/files/default/.mozilla/firefox/7z1z212a.default/extensions/[email protected]/chrome/content/code/Thread.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2658"
},
{
"name": "JavaScript",
"bytes": "336188"
},
{
"name": "Ruby",
"bytes": "22556"
},
{
"name": "Shell",
"bytes": "3120"
},
{
"name": "VimL",
"bytes": "82"
}
],
"symlink_target": ""
} |
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// VisualNovelToolkit /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace ViNoToolkit{
public class SceneEvent : MonoBehaviour {
// TEST...
[HideInInspector] public Material portraitMat1;
//public Material portraitMat2;
// public Vector3 actorPos;
public ActorLibrary actorLib; // attach a ActorLibrary in project view.
public SceneLibrary sceneLib;
[HideInInspector] public bool highlightCurrentSpeaker;
[ Range( -600f , 600f ) ]
public float centerPosX = 0f;
[ Range( -600f , 600f ) ]
public float leftPosX = -180f;
[ Range( -600f , 600f ) ]
public float rightPosX = 180f;
[ Range( -600f , 600f ) ]
public float middleLeftPosX = -150f;
[ Range( -600f , 600f ) ]
public float middleRightPosX = 150f;
// left , mid_left , center , mid_right , right .
public enum ActorPosition{
center=0,
left,
right,
middle_left,
middle_right,
}
private Dictionary<string,ActorInfo> m_ActorMap;
private Dictionary<string,Scene> m_SceneMap;
// private Dictionary<string,GameObject> m_ActorGOMap;
void definescene( Hashtable param ){
string sceneName = param["name"] as string;
string texturePath = param["texture"] as string;
/* if( param.ContainsKey( "size" ) ){
sizeInPercent = float.Parse( param["size"] as string );
}
//*/
Scene info = ScriptableObject.CreateInstance<Scene>();
m_SceneMap[ sceneName ] = info;
string[] texs = new string[ 1 ];
texs[ 0 ] = texturePath;
ViNoSceneUtil.SetUpSceneInfo( info , sceneName , texturePath );
}
// Test Define character.
void defineactor( Hashtable param ){
string actorName = param["name"] as string;
// string textColorStr = param["textColor"] as string;
string texturePath = param["texture"] as string;
float sizeInPercent = 100f;
if( param.ContainsKey( "size" ) ){
sizeInPercent = float.Parse( param["size"] as string );
}
// Color textColor = C
ActorInfo info = ScriptableObject.CreateInstance<ActorInfo>();
m_ActorMap[ actorName ] = info;
string[] texs = new string[ 1 ];
texs[ 0 ] = texturePath;//Resources.Load( texturePath , typeof(Texture2D) ) as Texture2D;
ActorUtility.SetUpActorInfo( info , actorName , sizeInPercent , Color.cyan , texs );
}
void jump( Hashtable param ){
string label = param[ "target"] as string;
label = label.Replace( "*" , "" );
if( param.ContainsKey( "storage" ) ){
string storage = param[ "storage" ] as string;
Debug.Log( "Now , Play scenario:" + storage);
ViNoAPI.PlayScenario( storage );
}
Debug.Log( "label:" + label );
VM.Instance.GoToLabel( label );
}
void if_( Hashtable param ){
string exp = param[ "exp"] as string;
Debug.Log( "exp:" + exp );
}
void endif( Hashtable param ){
Debug.Log( "ENDIF");
}
void eval( Hashtable param ){
string exp = param[ "exp"] as string;
Debug.Log( "exp:" + exp );
#if false
exp = exp.Replace( "\"" , "" );
string varName1 = string.Empty;
string varName2 = string.Empty;
string[] strs = exp.Split( "=="[0] );
bool processed = false;
// == or !=.
if( strs.Length >= 2 ){
processed = true;
varName1 = strs[ 0 ];
varName2 = strs[ 1 ];
}
else{
strs = exp.Split( "!="[0] );
if( strs.Length >= 2 ){
processed = true;
}
}
if( ! processed ){
}
ScenarioNode scenario = ScenarioNode.Instance;
if( scenario != null && scenario.flagTable != null ){
// scenario.flagTable.SetStringValue( );
}
#endif
}
void enterscene( Hashtable param ){
string sceneName = param[ "name" ] as string;
// Attached a sceneLib.
// if( sceneLib != null ){
// Debug.Log( "OnEnterScene :" + sceneName );
// for( int i=0;i<sceneLib.sceneEntries.Length;i++){
// Scene scene = sceneLib.sceneEntries[ i ];
// if( scene.name == sceneName ){
if( m_SceneMap.ContainsKey( sceneName ) ){
Scene scene = m_SceneMap[ sceneName ];
// Debug.Log( "matched Scene Name ," + sceneName + " and Enter this actor." );
LoadSceneNode.Do( scene , param );
// break;
// }
// }
}
// If not attached sceneLib , then Load from Resources folder.
else{
Scene scene = Resources.Load( sceneName , typeof(Scene) ) as Scene;
if( scene != null ){
LoadSceneNode.Do( scene , param );
}
}
}
void showsystemui( Hashtable param ){
SystemUtility.ShowSystemUI( true );
}
void hidesystemui( Hashtable param ){
SystemUtility.ShowSystemUI( false );
}
void trans( Hashtable param ){
string method = "crossfade";
if( param.ContainsKey( "method") ){
method = param["method"] as string;
}
string resourcePath = "";
switch( method ){
case "crossfade":
//TODO !
// resource = "";
break;
case "blind":
resourcePath = "Effects/Blind";
break;
case "tile":
resourcePath = "Effects/TileFade";
break;
}
// float time = float.Parse( param["time"] as string )/1000f;
Object loadedResource = Resources.Load( resourcePath );
if( loadedResource == null ){
Debug.LogError( "Resources.Load Error ! path:" + resourcePath );
return;
}
ViNoSceneManager sm = ViNoSceneManager.Instance;
string parentName = sm.transform.parent.gameObject.name; // It is expected that the "Panels" object or the "Camera" object.
UnityWrapper.InstantiateAsGameObject( loadedResource , parentName );
}
// **************************** Sound Tag ******************************* .
void stopbgm( Hashtable param ){
SimpleSoundPlayer player = ISoundPlayer.Instance as SimpleSoundPlayer;
player.StopMusic( 0f );
}
void fadeoutbgm( Hashtable param ){
float time = 1f;
if( param.ContainsKey("time") ){
time = float.Parse( param["time"] as string )/1000f;
}
SimpleSoundPlayer player = ISoundPlayer.Instance as SimpleSoundPlayer;
player.StopMusic( time );
}
void playbgm( Hashtable param ){
string audioPath = param[ "storage"] as string;
bool loop = true;
if( param.ContainsKey( "loop") ){
loop = ( ( param[ "loop" ] as string ) == "true" ) ? true : false;
}
ISoundPlayer player = ISoundPlayer.Instance;
player.PlayMusic( audioPath , loop , 0f );
}
void playse( Hashtable param ){
string audioPath = param[ "storage"] as string;
bool loop = false;
if( param.ContainsKey( "loop") ){
loop = ( ( param[ "loop" ] as string ) == "true" ) ? true : false;
}
ISoundPlayer player = ISoundPlayer.Instance;
player.PlaySE( audioPath , loop , 0f );
}
void playvoice( Hashtable param ){
ISoundPlayer pl = ISoundPlayer.Instance;
if( pl != null ){
pl.StopVoice();
}
string audioPath = param[ "storage"] as string;
bool loop = false;
if( param.ContainsKey( "loop") ){
loop = ( ( param[ "loop" ] as string ) == "true" ) ? true : false;
}
ISoundPlayer player = ISoundPlayer.Instance;
player.PlayVoice( audioPath , loop , 0f );
VM.Instance.UpdateMessageVoiceData( audioPath , 0 );
}
void xchgbgm( Hashtable param ){
string audioPath = param[ "storage"] as string;
bool loop = true;
if( param.ContainsKey( "loop") ){
loop = ( ( param[ "loop" ] as string ) == "true" ) ? true : false;
}
float time = float.Parse( param[ "time" ] as string )/1000f;
ISoundPlayer player = ISoundPlayer.Instance;
player.PlayMusic( audioPath , loop , time );
}
// Actor Event.
/// <summary>
/// Raises the enter actor event.
/// </summary>
/// <param name='param'>
/// Parameter.
/// </param>
void enteractor( Hashtable param ){
if( actorLib != null ){
bool fadein = false;
if( param.ContainsKey( "fade") ){
string fade = param[ "fade" ] as string;
fadein = ( fade == "true" ) ? true : false;
}
// Fade in Start ?.
ISpriteFactory._FADEIN_AT_CREATE = fadein;
string actorName = param[ "name" ] as string;
string position = param["position"] as string;
ActorPosition pos = ActorUtility.GetActorPosition( position );
// Debug.Log( "OnEnterActor :" + actorName );
OnEnterActor( actorName , pos );
}
}
// Wrapper of exitactor.
void exitscene( Hashtable param ){
bool fadein = false;
if( param.ContainsKey( "fade") ){
string fade = param[ "fade" ] as string;
fadein = ( fade == "true" ) ? true : false;
}
ViNoSceneManager sm = ViNoSceneManager.Instance;
SceneCreator.DestroyScene( sm.theSavedPanel , ! fadein ); // Fade and Destroy Actor.
}
void exitactor( Hashtable param ){
string actorName = param[ "name" ] as string;
bool fadeout = false;
if( param.ContainsKey( "fade") ){
string fade = param[ "fade" ] as string;
fadeout = ( fade == "true" ) ? true : false;
}
OnExitActor( actorName , ! fadeout );
}
void setpropactor( Hashtable param ){
string actorName = param[ "name" ] as string;
Debug.Log( "Set Prop Actor : " + actorName );
// if( m_ActorGOMap.ContainsKey( actorName ) ){
// if( m_ActorGOMap[ actorName ] != null ){
// Is Active or Deactive ?.
if( param.ContainsKey( "color" ) ){
string col = param[ "color" ] as string;
if( col == "active" ){
ViNoSceneManager.Instance.SetActiveColor( actorName );
}
else{
ViNoSceneManager.Instance.SetDeactiveColor( actorName );
}
}
// is Visible ?.
if( param.ContainsKey( "visible" ) ){
string visible = param["visible"] as string;
bool t = ( visible == "true" ) ? true : false;
Debug.Log( "Actor visible" );
GameObject actor = GameObject.Find( actorName );
if( actor != null ){
// m_ActorGOMap[ actorName ].SetActive( t );
actor.SetActive( t );
}
else{
Debug.LogWarning( "Actor name: " + actorName + " not found." );
}
}
// }
// else{
// Debug.LogWarning( "Actor name: " + actorName + " found , but GO not assigned." );
// }
// }
}
void changestate( Hashtable param ){
// Debug.Log( "OnChangeState" );
if( actorLib != null ){
string actorName = param[ "name" ] as string;
string state = param["state"] as string;
bool fadein = false;
if( param.ContainsKey( "fade") ){
string fade = param[ "fade" ] as string;
fadein = ( fade == "true" ) ? true : false;
}
// Fade in Start ?.
ISpriteFactory._FADEIN_AT_CREATE = fadein;
// Fadeout and destroy childs.
if( fadein ){
string destroyRootName = actorName + " will_Destroy";
GameObject _destroyRoot = GameObject.Find( destroyRootName );
if( _destroyRoot == null ){
_destroyRoot = new GameObject( destroyRootName );
}
GameObject actor = GameObject.Find( actorName );
Transform actorTra = actor.transform;
int childNum = actorTra.GetChildCount();
// Rename Actors.
while( childNum > 0 ){
Transform tra = actorTra.GetChild( 0 );
tra.name = tra.name + "_";
// Debug.Log( "Destroy:" + tra.name );
tra.parent = _destroyRoot.transform;
childNum = actorTra.GetChildCount();
}
// _destroyRoot.transform.parent = .transform;
SceneCreator.DestroyScene( _destroyRoot , ! fadein ); // Fade and Destroy Actor.
}
// Debug.Log ( "State:" + state );
if( m_ActorMap.ContainsKey( actorName ) ){
ActorInfo actorInfo = m_ActorMap[ actorName ];
// Debug.Log ( "Actor Matched.:" + actorName );
for(int k=0;k<actorInfo.actorStates.Length;k++){
if( actorInfo.actorStates[ k ].stateName == state ){
ActorInfo.ActorState actorState = actorInfo.actorStates[ k ];
CreateChildLayer( actorInfo , actorState );
break;
}
}
}
}
}
void shake( Hashtable param ){
string objectName = param[ "name" ] as string;
GameObject obj = GameObject.Find( objectName );
if( obj != null ){
iTween.PunchPosition( obj , new Vector3( 0.1f , 0.1f , 0f ) , 2f );
}
}
void OnPlayScenario( Hashtable param ){
string scenarioName = param[ "name" ] as string;
ViNoAPI.PlayScenario( scenarioName );
}
// From Scenario Script.
MessageEventData m_MessageEvtData = new MessageEventData();
void settext( Hashtable param ){
string text = param["text"] as string;
string textBoxName = param["textbox"] as string;
int textBoxID = SystemUIEvent.Instance.GetTextBoxIDBy( textBoxName );
m_MessageEvtData.textBoxID = (byte)textBoxID;
m_MessageEvtData.message = text;
m_MessageEvtData.show = true;
OnSetText( m_MessageEvtData );
}
private string prevSpeakerName;
/// /// <summary>
/// Change the Color of Name Text by Actor Name.
/// </summary>
void OnSetText( MessageEventData data ){
// string actorName = data.message;
SystemUIEvent sys = SystemUIEvent.Instance;
if( m_ActorMap.ContainsKey( data.message ) ){
ActorInfo actorInfo = m_ActorMap[ data.message ];
data.message = sys.GetBeginColorTag( actorInfo.textColor , data.textBoxID ) + data.message + sys.GetEndColorTag( data.textBoxID);
// Test...
if( actorInfo.portrait != null && portraitMat1 != null ){
// Debug.Log( "Actor Portrait : " );
portraitMat1.mainTexture = actorInfo.portrait;
}
else{
// portraitMat1.gameObject.SetActive( false );
}
sys.SetText( data.message , data.textBoxID );
}
else{
sys.SetText( data.message , data.textBoxID );
}
VM.Instance.UpdateMessageEvtData( data );
// Highlight Current Speaker for future update.
#if false
if( highlightCurrentSpeaker ){
if( prevSpeakerName == actorName ){
return;
}
if( ! string.IsNullOrEmpty( prevSpeakerName ) ){
ViNoSceneManager.Instance.SetDeactiveColor( prevSpeakerName );
}
ViNoSceneManager.Instance.SetActiveColor( actorName );
prevSpeakerName = actorName;
}
#endif
}
void OnAnimation( Hashtable param ){
}
void moveactor( Hashtable param ){
// Debug.Log( "OnMoveActor" );
string actorName = param[ "name" ] as string;
string position = param["position"] as string;
#if true
GameObject go = GameObject.Find( actorName );
if( go == null ){
// Debug.LogWarning( "Actor name :" + actorName + " Object not found." );
return;
}
#else
GameObject go = null;
if( m_ActorGOMap.ContainsKey( actorName ) ){
go = m_ActorGOMap[ actorName ];
if( go == null ){
Debug.LogWarning( "Actor name :" + actorName + " Object not found." );
return;
}
}
#endif
Vector3 toPos = go.transform.localPosition;
ActorPosition pos = ActorUtility.GetActorPosition( position );
toPos.x = GetPositionX( pos );
// Debug.Log( "to :" + pos + " , value:" + toPos.x );
AnimationNode.MoveTo( go , toPos , 1f );
// TweenPosition.Begin( go , 1f , toPos );
// iTween.MoveTo( go , toPos , 1f );
}
/* IEnumerator Shake( GameObject obj ){
yield return new WaitForSeconds( );
}
//*/
void EnterActor( ActorInfo info , ActorInfo.ActorState actorState ){
CreateActorRoot( info , actorState );
CreateChildLayer( info , actorState );
}
void CreateChildLayer( ActorInfo info , ActorInfo.ActorState actorState ){
for(int i=0;i<actorState.dataArray.Length;i++){
actorState.dataArray[ i ].parentname = info.actorName;
actorState.dataArray[ i ].sclZ = 1f;
SceneCreator.Create( actorState.dataArray[ i ] );
}
}
void EnterActor( ActorInfo info , ActorInfo.ActorState actorState , float posX ){
CreateActorRoot( info , actorState );
GameObject go = GameObject.Find( info.actorName );//actorState.dataArray[ i ].parentname + "/" + actorState );
if( go != null ){
Vector3 pos = go.transform.localPosition;
pos.x = posX;
go.transform.localPosition = pos;
}
for(int i=0;i<actorState.dataArray.Length;i++){
actorState.dataArray[ i ].parentname = info.actorName;
actorState.dataArray[ i ].sclZ = 1f;
SceneCreator.Create( actorState.dataArray[ i ] );
/*
go = GameObject.Find( actorState.dataArray[ i ].parentname + "/" + actorState.dataArray[ i ].name );
if( go != null ){
Vector3 pos = go.transform.localPosition;
pos.x = posX;
go.transform.localPosition = pos;
}
//*/
}
}
void OnEnterActor( string actorName , ActorPosition actorPos ){
if( actorLib != null ){
// for( int i=0;i<actorLib.actorEntries.Length;i++){
// ActorInfo actorInfo = actorLib.actorEntries[ i ];
// if( actorInfo.actorName == actorName ){
if( m_ActorMap.ContainsKey( actorName ) ){
ActorInfo actorInfo = m_ActorMap[ actorName ];
// Debug.Log( "matched Actor Name ," + actorName + " and Enter this actor." );
ActorInfo.ActorState currentActorState = actorInfo.baseActorState;
float posX = GetPositionX( actorPos );
EnterActor( actorInfo , currentActorState , posX );
return;
}
}
// }
else{
Debug.Log( "ActorLibrary not attached. couldn't enter actor : " + actorName );
}
}
#if false
void OnCreateButton( Hashtable param ){
string targetLabel = param[ "target" ] as string;
string arrangement = param[ "arrangement"] as string;
string background = param[ "background"] as string;
}
#endif
void Awake(){
// Register Actors to Map.
if( actorLib == null ){
Debug.LogWarning( "ActorLibrary not attached. Actor can't enter in scene." );
}
else{
m_ActorMap = new Dictionary<string,ActorInfo>();
// Cache ActorInfo.
for( int i=0;i<actorLib.actorEntries.Length;i++){
string actorName = actorLib.actorEntries[ i ].actorName;
m_ActorMap[ actorName ] = actorLib.actorEntries[ i ];
}
}
// Register Scenes to Map.
if( sceneLib == null ){
Debug.LogWarning( "SceneLibrary not attached. LoadSceneNode Not Working correctly." );
}
else{
m_SceneMap = new Dictionary<string,Scene>();
// Cache SceneInfo.
for( int i=0;i<sceneLib.sceneEntries.Length;i++){
string sceneName = sceneLib.sceneEntries[ i ].name;
m_SceneMap[ sceneName ] = sceneLib.sceneEntries[ i ];
}
}
}
void OnExitActor( string actorName , bool immediate ){
GameObject actor = GameObject.Find( actorName );
SceneCreator.DestroyScene( actor , immediate ); // Fade and Destroy Actor.
}
// Helper .
public float GetPositionX( SceneEvent.ActorPosition actorPos ){
float posX = centerPosX;
switch( actorPos ){
case SceneEvent.ActorPosition.center: posX = centerPosX; break;
case SceneEvent.ActorPosition.left: posX = leftPosX; break;
case SceneEvent.ActorPosition.right: posX = rightPosX; break;
case SceneEvent.ActorPosition.middle_left: posX = middleLeftPosX; break;
case SceneEvent.ActorPosition.middle_right: posX = middleRightPosX; break;
}
return posX;
}
GameObject CreateActorRoot( ActorInfo info , ActorInfo.ActorState actorState ){
float scl = actorState.sizeInPercent / 100f;
SceneData.SceneNodeData actorNodeData = new SceneData.SceneNodeData();
actorNodeData.name = info.actorName;
actorNodeData.parentname = ViNoSceneManager.Instance.theSavedPanel.name;
actorNodeData.sclX = scl;
actorNodeData.sclY = scl;
actorNodeData.sclZ = 1f;
actorNodeData.alpha = 1f;
actorNodeData.show = true;
GameObject actorGO = SceneCreator.Create( actorNodeData );
// m_ActorGOMap[ info.actorName ] = actorGO;
return actorGO;
}
// for testing...
#if false
public bool _CauseEnterActor;
public bool _CauseExitActor;
public string actorName = "Sachi";
public ActorUtility.GetActorPosition actorPos = ActorUtility.GetActorPosition.center;
void Update(){
if( _CauseEnterActor) {
_CauseEnterActor = false;
OnEnterActor( actorName , actorPos );
}
if( _CauseExitActor ){
_CauseExitActor = false;
OnExitActor( actorName );
}
}
#endif
}
}
| {
"content_hash": "eaa686b1c13e37a96eb0ba1c7dd08167",
"timestamp": "",
"source": "github",
"line_count": 676,
"max_line_length": 133,
"avg_line_length": 29.772189349112427,
"alnum_prop": 0.6268011527377522,
"repo_name": "lapius/MusicalCube",
"id": "6c2044fb3cda7f494c35bb684afa6df7f596363b",
"size": "20127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/VisualNovelToolkit/Scripts/ViNo/Event/SceneEvent.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3733"
}
],
"symlink_target": ""
} |
/**
* Brick object
* @constructor
*/
BreakOut.BrickColorOrange = function (settings) {
BreakOut.Brick.call(this, settings);
this.textures = [
'brick-color-orange.png'
];
this.score = 20;
this.dropChance = 50;
};
BreakOut.BrickColorOrange.prototype = Object.create(BreakOut.Brick.prototype); | {
"content_hash": "82de3cbc4b1cf6c9cd91ce51e7880361",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 78,
"avg_line_length": 17.210526315789473,
"alnum_prop": 0.6605504587155964,
"repo_name": "Couchfriends/breakout",
"id": "dc4db30a0d2a73520b2db5d060ef61d09f06d5ef",
"size": "1496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BreakOut.BrickColorOrange.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "206"
},
{
"name": "HTML",
"bytes": "2366"
},
{
"name": "JavaScript",
"bytes": "1084798"
}
],
"symlink_target": ""
} |
#include <hal_ugv/control/Waypoint.h>
// COntroller constants
#define _X 0
#define _Y 1
#define _Z 2
#define _YAW 3
#define _Kxy 0.9 /* position proportional constant */
#define _Kv 0.09 /* velocity proportional constant */
#define _Kiz 0.0008 /* altitude integrative constant */
#define _Kpz 0.03 /* altitude proportional constant */
#define _Kdz 0.04 /* altitude derivative constant */
#define _th_hover 0.59 /* throttle hover offset */
#define _maxtilt 0.34 /* max pitch/roll angle (23deg) */
#define _Kya 6.0 /* yaw proportional constant */
#define _maxyawrate 4.4 /* max allowed yaw rate (200dps) */
#define _maxv 3.0 /* max allowed xy velocity */
#define _goal_dist 2.0 /* distance considered reached */
using namespace hal::ugv;
bool Waypoint::SetGoal(
hal_ugv::Waypoint::Request &req,
hal_ugv::Waypoint::Response &res
) {
// Set the new goal
sp[_X] = req.x;
sp[_Y] = req.y;
sp[_Z] = req.z;
sp[_YAW] = req.yaw;
// Assume we haven't yet reached the desired point
reach = false;
// Success!
res.success = true;
res.status = "Successfully switched to Waypoint controller";
return true;
}
void Waypoint::Update(const hal_ugv::State &state,
double dt, hal_ugv::Control &control)
{
//////////////////////// CHECK IF GOAL REACHED //////////////////////
double dst = sqrt(
(sp[_X]-state.x)*(sp[_X]-state.x)
+ (sp[_Y]-state.y)*(sp[_Y]-state.y)
+ (sp[_Z]-state.z)*(sp[_Z]-state.z)
);
if (!reach && dst < _goal_dist)
reach = true;
// P PITCH AND ROLL CONTROLLERS //////////////////////////////////
// Obtain b-frame velocities
double vel[3] = {sp[_X]-state.x, sp[_Y]-state.y, sp[_Z]-state.z};
double rot[3] = {state.roll, state.pitch, state.yaw};
n2b(rot,vel);
double bx = vel[0];
double by = vel[1];
// Roll controller
double desv = limit(_Kxy*by,-_maxv,_maxv);
double desR = limit(-_Kv*(desv - state.v), -_maxtilt, _maxtilt);
// Pitch controller
double desu = limit(_Kxy*bx,-_maxv,_maxv);
double desP = limit( _Kv*(desu - state.u), -_maxtilt, _maxtilt);
//////////////////////// P YAW CONTROLLER ////////////////////////
double desY = limit(_Kya * (sp[_YAW] - state.yaw), -_maxyawrate, _maxyawrate);
/////////////////// PID THROTTLE CONTROLLER //////////////////////
// Get the (P)roportional component (Changed by Andrew)
double ez_ = sp[_Z] - state.z;
// Get the (I)ntegral component
iz += ez_ * dt;
// Get the (D)erivative component
double de_ = (dt > 0 ? (ez_ - ez) / dt : 0.0);
double desth = _th_hover + _Kpz * ez_ + _Kiz * iz + de_ * _Kdz;
double th = limit(desth,0,1);
// Save (P) contribution for next derivative calculation
ez = ez_;
// Save (I) contribution for next derivative calculation
iz = iz - (desth - th) * 2.0;
//////////////////////// CONTROL PACKAGING /////////////////////////
// This will be returned
control.roll = desR;
control.pitch = desP;
control.yaw = desY;
control.throttle = th;
}
// Goal reach implementations
bool Waypoint::HasGoalBeenReached()
{
return reach;
}
// Reset implementations
void Waypoint::Reset()
{
// Carries for altitude PID
iz = 0.0;
ez = 0.0;
}
| {
"content_hash": "40ead4bc1bf00d860d8e684e829b719a",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 82,
"avg_line_length": 30.517241379310345,
"alnum_prop": 0.5271186440677966,
"repo_name": "jiangchenzhu/crates_zhejiang",
"id": "8be447abbd1c7b6db1e93b824e95289f553d768b",
"size": "3540",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/hal_ugv/src/control/Waypoint.cpp",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "91195"
},
{
"name": "C++",
"bytes": "398461"
},
{
"name": "CMake",
"bytes": "14527"
},
{
"name": "Protocol Buffer",
"bytes": "1645"
},
{
"name": "Shell",
"bytes": "4795"
}
],
"symlink_target": ""
} |
import React from 'react';
import {connect} from 'react-redux';
import {Container, Row, Col} from 'react-bootstrap';
import {updateInvoiceFilters} from '../../../actions/index';
import InvoiceListModel from '../models/InvoiceListModel';
import {GroupedInvoiceTable} from '../invoice-table/GroupedInvoiceTable';
import {NonGroupedInvoiceTable} from '../invoice-table/NonGroupedInvoiceTable';
import {ConfacState} from '../../../reducers/app-state';
import {ConfigModel} from '../../config/models/ConfigModel';
import InvoiceModel from '../models/InvoiceModel';
import {ClientModel} from '../../client/models/ClientModels';
import {InvoiceFilters} from '../../../models';
import {t} from '../../utils';
import {QuotationSearch} from './QuotationSearch';
import {LinkToButton} from '../../controls/form-controls/button/LinkToButton';
import {useDocumentTitle} from '../../hooks/useDocumentTitle';
import {ConsultantModel} from '../../consultant/models/ConsultantModel';
import {Claim} from '../../users/models/UserModel';
type QuotationListProps = {
config: ConfigModel,
invoices: InvoiceModel[],
clients: ClientModel[],
consultants: ConsultantModel[],
updateInvoiceFilters: any,
filters: InvoiceFilters,
}
// eslint-disable-next-line react/prefer-stateless-function
export const QuotationList = (props: QuotationListProps) => {
useDocumentTitle('quotationList');
if (!props.filters) {
return null;
}
const vm = new InvoiceListModel(props.invoices, props.clients, props.consultants, props.filters, true);
const TableComponent = props.filters.groupedByMonth ? GroupedInvoiceTable : NonGroupedInvoiceTable;
return (
<Container className="quotation-list">
<Row>
<Col xs={8}>
<h1>{t('quotation.title')}</h1>
</Col>
<Col xs={4} style={{textAlign: 'right'}}>
<LinkToButton claim={Claim.ViewInvoices} to="/invoices" label="title" />
</Col>
</Row>
<QuotationSearch
onChange={(newFilter: InvoiceFilters) => props.updateInvoiceFilters(newFilter)}
filterOptions={vm.getFilterOptions()}
filters={props.filters}
/>
<TableComponent vm={vm} config={props.config} />
</Container>
);
};
export default connect((state: ConfacState) => ({
invoices: state.invoices.filter(x => x.isQuotation),
clients: state.clients,
filters: state.app.invoiceFilters,
config: state.config,
consultants: state.consultants,
}), {updateInvoiceFilters})(QuotationList);
| {
"content_hash": "ca94715c3431b93653319c224833461d",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 105,
"avg_line_length": 36.60294117647059,
"alnum_prop": 0.7010847730012053,
"repo_name": "be-pongit/confac-front",
"id": "b6715395e589ad9e19611fae275f0c94288c267f",
"size": "2489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/invoice/invoice-list/QuotationList.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1313"
},
{
"name": "JavaScript",
"bytes": "1913"
},
{
"name": "SCSS",
"bytes": "20038"
},
{
"name": "TypeScript",
"bytes": "479769"
}
],
"symlink_target": ""
} |
var adjust_zone = require('../common/adjust_zone');
var tmerc = require('./tmerc');
exports.dependsOn = 'tmerc';
exports.init = function() {
var zone = adjust_zone(this.zone, this.long0);
if (zone === undefined) {
throw new Error('unknown utm zone');
}
this.lat0 = 0;
this.long0 = (zone + 0.5) * Math.PI / 30 - Math.PI;
this.x0 = 500000;
this.y0 = this.utmSouth ? 10000000 : 0;
this.k0 = 0.9996;
tmerc.init.apply(this);
this.forward = tmerc.forward;
this.inverse = tmerc.inverse;
};
exports.names = ["Universal Transverse Mercator System", "utm"];
| {
"content_hash": "fa297d3131c53207e27ebd0ffbda1a88",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 64,
"avg_line_length": 25.17391304347826,
"alnum_prop": 0.6424870466321243,
"repo_name": "Tomella/cossap-3d",
"id": "385cabb083cc091b3aeb9553229e874a6eecf448",
"size": "579",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/cossap3d/bower_components/proj4/lib/projections/utm.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3999"
},
{
"name": "HTML",
"bytes": "5460"
},
{
"name": "JavaScript",
"bytes": "11176"
},
{
"name": "Shell",
"bytes": "758"
},
{
"name": "TypeScript",
"bytes": "77392"
}
],
"symlink_target": ""
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationScope = exports.Environment = exports.OrphanedEventPersistences = exports.LogPersistences = exports.LogLevels = void 0;
/**
* Log level enum
*/
var LogLevels;
(function (LogLevels) {
LogLevels[LogLevels["None"] = 0] = "None";
LogLevels[LogLevels["Error"] = 1] = "Error";
LogLevels[LogLevels["Warn"] = 2] = "Warn";
LogLevels[LogLevels["Debug"] = 3] = "Debug";
})(LogLevels = exports.LogLevels || (exports.LogLevels = {}));
;
/**
* Log persistence enum
*/
var LogPersistences;
(function (LogPersistences) {
LogPersistences[LogPersistences["None"] = 0] = "None";
LogPersistences[LogPersistences["IndexedDB"] = 1] = "IndexedDB";
LogPersistences[LogPersistences["LocalStorage"] = 2] = "LocalStorage";
})(LogPersistences = exports.LogPersistences || (exports.LogPersistences = {}));
;
/**
* Log persistence enum
*/
var OrphanedEventPersistences;
(function (OrphanedEventPersistences) {
OrphanedEventPersistences[OrphanedEventPersistences["None"] = 0] = "None";
OrphanedEventPersistences[OrphanedEventPersistences["IndexedDbIfSupported"] = 1] = "IndexedDbIfSupported";
OrphanedEventPersistences[OrphanedEventPersistences["LocalStorage"] = 2] = "LocalStorage"; // force local storage
})(OrphanedEventPersistences = exports.OrphanedEventPersistences || (exports.OrphanedEventPersistences = {}));
;
;
;
;
/**
* Environment enum
*/
var Environment;
(function (Environment) {
Environment[Environment["development"] = 0] = "development";
Environment[Environment["production"] = 1] = "production";
})(Environment = exports.Environment || (exports.Environment = {}));
;
;
;
;
;
/**
* Log level enum
*/
var ConversationScope;
(function (ConversationScope) {
ConversationScope[ConversationScope["public"] = 0] = "public";
ConversationScope[ConversationScope["participant"] = 1] = "participant";
})(ConversationScope = exports.ConversationScope || (exports.ConversationScope = {}));
;
//# sourceMappingURL=interfaces.js.map | {
"content_hash": "6cc07157f25ff44e1f7f7074f765243b",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 139,
"avg_line_length": 34.46666666666667,
"alnum_prop": 0.7132495164410058,
"repo_name": "comapi/comapi-sdk-js-bower",
"id": "1eea9e0dbe89fd2d1e5de121cf0317c1527b3b24",
"size": "2068",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/interfaces.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
class AddUseUploadedPictureToUser < ActiveRecord::Migration
def change
add_column :users, :use_uploaded_picture, :boolean, default: false
end
end
| {
"content_hash": "f46897998c7e61534961cff2ee1c396d",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 70,
"avg_line_length": 30.8,
"alnum_prop": 0.7727272727272727,
"repo_name": "nnamon/coursemology.org",
"id": "9b4dfedec4b140be706a070bb30a2606d24f494f",
"size": "154",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "db/migrate/20140627064143_add_use_uploaded_picture_to_user.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "72337"
},
{
"name": "CoffeeScript",
"bytes": "4593"
},
{
"name": "HTML",
"bytes": "534981"
},
{
"name": "JavaScript",
"bytes": "162580"
},
{
"name": "Python",
"bytes": "58802"
},
{
"name": "Ruby",
"bytes": "802964"
},
{
"name": "Shell",
"bytes": "1514"
}
],
"symlink_target": ""
} |
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.cpp;
import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration;
import com.google.devtools.build.lib.skylarkbuildapi.cpp.FeatureConfigurationApi;
/**
* Wrapper for {@link FeatureConfiguration}, {@link CppConfiguration}, and {@link BuildOptions}.
*
* <p>Instances are created in Starlark by cc_common.configure_features(ctx, cc_toolchain), and
* passed around pretending to be {@link FeatureConfiguration}. Then when the need arises, we get
* the {@link CppConfiguration} and {@link BuildOptions} from it and use it in times when
* configuration of cc_toolchain is different than configuration of the rule depending on it.
*/
// TODO(b/129045294): Remove once cc_toolchain has target configuration.
public class FeatureConfigurationForStarlark implements FeatureConfigurationApi {
private final FeatureConfiguration featureConfiguration;
private final CppConfiguration cppConfiguration;
private final BuildOptions buildOptions;
public static FeatureConfigurationForStarlark from(
FeatureConfiguration featureConfiguration,
CppConfiguration cppConfiguration,
BuildOptions buildOptions) {
return new FeatureConfigurationForStarlark(
featureConfiguration, cppConfiguration, buildOptions);
}
private FeatureConfigurationForStarlark(
FeatureConfiguration featureConfiguration,
CppConfiguration cppConfiguration,
BuildOptions buildOptions) {
this.featureConfiguration = Preconditions.checkNotNull(featureConfiguration);
this.cppConfiguration = Preconditions.checkNotNull(cppConfiguration);
this.buildOptions = buildOptions;
}
public FeatureConfiguration getFeatureConfiguration() {
return featureConfiguration;
}
/**
* Get {@link CppConfiguration} that is threaded along with {@link FeatureConfiguration}. Do this
* only when you're completely aware of why this method was added and hlopko@ allowed you to.
*
* @deprecated will be removed soon by b/129045294.
*/
@Deprecated
CppConfiguration
getCppConfigurationFromFeatureConfigurationCreatedForStarlark_andIKnowWhatImDoing() {
return cppConfiguration;
}
/**
* Get {@link BuildOptions} that is threaded along with {@link FeatureConfiguration}. Do this only
* when you're completely aware of why this method was added and hlopko@ allowed you to.
*
* @deprecated will be removed soon by b/129045294.
*/
@Deprecated
BuildOptions getBuildOptionsFromFeatureConfigurationCreatedForStarlark_andIKnowWhatImDoing() {
return buildOptions;
}
}
| {
"content_hash": "b953e8571db4d292c63394d6597f676a",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 100,
"avg_line_length": 41.6875,
"alnum_prop": 0.7760119940029985,
"repo_name": "aehlig/bazel",
"id": "7f4f4f0b1686560a236f8a8e0234f1d7c2b6b36b",
"size": "3335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/google/devtools/build/lib/rules/cpp/FeatureConfigurationForStarlark.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1588"
},
{
"name": "C",
"bytes": "27067"
},
{
"name": "C++",
"bytes": "1513394"
},
{
"name": "Dockerfile",
"bytes": "839"
},
{
"name": "HTML",
"bytes": "21053"
},
{
"name": "Java",
"bytes": "35178923"
},
{
"name": "Makefile",
"bytes": "248"
},
{
"name": "Objective-C",
"bytes": "10369"
},
{
"name": "Objective-C++",
"bytes": "1043"
},
{
"name": "PowerShell",
"bytes": "15438"
},
{
"name": "Python",
"bytes": "2519187"
},
{
"name": "Ruby",
"bytes": "639"
},
{
"name": "Shell",
"bytes": "1916092"
},
{
"name": "Smarty",
"bytes": "18683"
}
],
"symlink_target": ""
} |
namespace gameplay
{
static GLuint __maxVertexAttribs = 0;
static std::vector<VertexAttributeBinding*> __vertexAttributeBindingCache;
VertexAttributeBinding::VertexAttributeBinding() :
_handle(0), _attributes(NULL), _mesh(NULL), _effect(NULL)
{
}
VertexAttributeBinding::~VertexAttributeBinding()
{
// Delete from the vertex attribute binding cache.
std::vector<VertexAttributeBinding*>::iterator itr = std::find(__vertexAttributeBindingCache.begin(), __vertexAttributeBindingCache.end(), this);
if (itr != __vertexAttributeBindingCache.end())
{
__vertexAttributeBindingCache.erase(itr);
}
SAFE_RELEASE(_mesh);
SAFE_RELEASE(_effect);
SAFE_DELETE_ARRAY(_attributes);
if (_handle)
{
GL_ASSERT( glDeleteVertexArrays(1, &_handle) );
_handle = 0;
}
}
VertexAttributeBinding* VertexAttributeBinding::create(Mesh* mesh, Effect* effect)
{
GP_ASSERT(mesh);
// Search for an existing vertex attribute binding that can be used.
VertexAttributeBinding* b;
for (size_t i = 0, count = __vertexAttributeBindingCache.size(); i < count; ++i)
{
b = __vertexAttributeBindingCache[i];
GP_ASSERT(b);
if (b->_mesh == mesh && b->_effect == effect)
{
// Found a match!
b->addRef();
return b;
}
}
b = create(mesh, mesh->getVertexFormat(), 0, effect);
// Add the new vertex attribute binding to the cache.
if (b)
{
__vertexAttributeBindingCache.push_back(b);
}
return b;
}
VertexAttributeBinding* VertexAttributeBinding::create(const VertexFormat& vertexFormat, void* vertexPointer, Effect* effect)
{
return create(NULL, vertexFormat, vertexPointer, effect);
}
VertexAttributeBinding* VertexAttributeBinding::create(Mesh* mesh, const VertexFormat& vertexFormat, void* vertexPointer, Effect* effect)
{
GP_ASSERT(effect);
// One-time initialization.
if (__maxVertexAttribs == 0)
{
GLint temp;
GL_ASSERT( glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &temp) );
__maxVertexAttribs = temp;
if (__maxVertexAttribs <= 0)
{
GP_ERROR("The maximum number of vertex attributes supported by OpenGL on the current device is 0 or less.");
return NULL;
}
}
// Create a new VertexAttributeBinding.
VertexAttributeBinding* b = new VertexAttributeBinding();
#ifdef GP_USE_VAO
if (mesh && glGenVertexArrays)
{
GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, 0) );
GL_ASSERT( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
// Use hardware VAOs.
GL_ASSERT( glGenVertexArrays(1, &b->_handle) );
if (b->_handle == 0)
{
GP_ERROR("Failed to create VAO handle.");
SAFE_DELETE(b);
return NULL;
}
// Bind the new VAO.
GL_ASSERT( glBindVertexArray(b->_handle) );
// Bind the Mesh VBO so our glVertexAttribPointer calls use it.
GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, mesh->getVertexBuffer()) );
}
else
#endif
{
// Construct a software representation of a VAO.
VertexAttribute* attribs = new VertexAttribute[__maxVertexAttribs];
for (unsigned int i = 0; i < __maxVertexAttribs; ++i)
{
// Set GL defaults
attribs[i].enabled = GL_FALSE;
attribs[i].size = 4;
attribs[i].stride = 0;
attribs[i].type = GL_FLOAT;
attribs[i].normalized = GL_FALSE;
attribs[i].pointer = 0;
}
b->_attributes = attribs;
}
if (mesh)
{
b->_mesh = mesh;
mesh->addRef();
}
b->_effect = effect;
effect->addRef();
// Call setVertexAttribPointer for each vertex element.
std::string name;
size_t offset = 0;
for (size_t i = 0, count = vertexFormat.getElementCount(); i < count; ++i)
{
const VertexFormat::Element& e = vertexFormat.getElement(i);
gameplay::VertexAttribute attrib;
// Constructor vertex attribute name expected in shader.
switch (e.usage)
{
case VertexFormat::POSITION:
attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_POSITION_NAME);
break;
case VertexFormat::NORMAL:
attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_NORMAL_NAME);
break;
case VertexFormat::COLOR:
attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_COLOR_NAME);
break;
case VertexFormat::TANGENT:
attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_TANGENT_NAME);
break;
case VertexFormat::BINORMAL:
attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_BINORMAL_NAME);
break;
case VertexFormat::BLENDWEIGHTS:
attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_BLENDWEIGHTS_NAME);
break;
case VertexFormat::BLENDINDICES:
attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_BLENDINDICES_NAME);
break;
case VertexFormat::TEXCOORD0:
if ((attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_TEXCOORD_PREFIX_NAME)) != -1)
break;
case VertexFormat::TEXCOORD1:
case VertexFormat::TEXCOORD2:
case VertexFormat::TEXCOORD3:
case VertexFormat::TEXCOORD4:
case VertexFormat::TEXCOORD5:
case VertexFormat::TEXCOORD6:
case VertexFormat::TEXCOORD7:
name = VERTEX_ATTRIBUTE_TEXCOORD_PREFIX_NAME;
name += '0' + (e.usage - VertexFormat::TEXCOORD0);
attrib = effect->getVertexAttribute(name.c_str());
break;
default:
// This happens whenever vertex data contains extra information (not an error).
attrib = -1;
break;
}
if (attrib == -1)
{
//GP_WARN("Warning: Vertex element with usage '%s' in mesh '%s' does not correspond to an attribute in effect '%s'.", VertexFormat::toString(e.usage), mesh->getUrl(), effect->getId());
}
else
{
void* pointer = vertexPointer ? (void*)(((unsigned char*)vertexPointer) + offset) : (void*)offset;
b->setVertexAttribPointer(attrib, (GLint)e.size, GL_FLOAT, GL_FALSE, (GLsizei)vertexFormat.getVertexSize(), pointer);
}
offset += e.size * sizeof(float);
}
if (b->_handle)
{
GL_ASSERT( glBindVertexArray(0) );
}
return b;
}
void VertexAttributeBinding::setVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalize, GLsizei stride, void* pointer)
{
GP_ASSERT(indx < (GLuint)__maxVertexAttribs);
if (_handle)
{
// Hardware mode.
GL_ASSERT( glVertexAttribPointer(indx, size, type, normalize, stride, pointer) );
GL_ASSERT( glEnableVertexAttribArray(indx) );
}
else
{
// Software mode.
GP_ASSERT(_attributes);
_attributes[indx].enabled = true;
_attributes[indx].size = size;
_attributes[indx].type = type;
_attributes[indx].normalized = normalize;
_attributes[indx].stride = stride;
_attributes[indx].pointer = pointer;
}
}
void VertexAttributeBinding::bind()
{
if (_handle)
{
// Hardware mode
GL_ASSERT( glBindVertexArray(_handle) );
}
else
{
// Software mode
if (_mesh)
{
GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, _mesh->getVertexBuffer()) );
}
else
{
GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, 0) );
}
GP_ASSERT(_attributes);
for (unsigned int i = 0; i < __maxVertexAttribs; ++i)
{
VertexAttribute& a = _attributes[i];
if (a.enabled)
{
GL_ASSERT( glVertexAttribPointer(i, a.size, a.type, a.normalized, a.stride, a.pointer) );
GL_ASSERT( glEnableVertexAttribArray(i) );
}
}
}
}
void VertexAttributeBinding::unbind()
{
if (_handle)
{
// Hardware mode
GL_ASSERT( glBindVertexArray(0) );
}
else
{
// Software mode
if (_mesh)
{
GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, 0) );
}
GP_ASSERT(_attributes);
for (unsigned int i = 0; i < __maxVertexAttribs; ++i)
{
if (_attributes[i].enabled)
{
GL_ASSERT( glDisableVertexAttribArray(i) );
}
}
}
}
}
| {
"content_hash": "a9cda51fa851d955508c3ad7ffe52a90",
"timestamp": "",
"source": "github",
"line_count": 291,
"max_line_length": 196,
"avg_line_length": 29.649484536082475,
"alnum_prop": 0.5861149745016226,
"repo_name": "zakki/openhsp",
"id": "09d2201f7509023260310ad126f1388287127453",
"size": "8721",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "hsp3dish/gameplay/src/VertexAttributeBinding.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "150345"
},
{
"name": "AngelScript",
"bytes": "415842"
},
{
"name": "Assembly",
"bytes": "6835762"
},
{
"name": "Awk",
"bytes": "8286"
},
{
"name": "Batchfile",
"bytes": "17416"
},
{
"name": "C",
"bytes": "44323065"
},
{
"name": "C++",
"bytes": "77401621"
},
{
"name": "CMake",
"bytes": "327385"
},
{
"name": "CSS",
"bytes": "65110"
},
{
"name": "DIGITAL Command Language",
"bytes": "74194"
},
{
"name": "Emacs Lisp",
"bytes": "11716"
},
{
"name": "GLSL",
"bytes": "243100"
},
{
"name": "HTML",
"bytes": "15891798"
},
{
"name": "Haskell",
"bytes": "2139250"
},
{
"name": "Java",
"bytes": "101998"
},
{
"name": "JavaScript",
"bytes": "218752"
},
{
"name": "LLVM",
"bytes": "26468545"
},
{
"name": "Lua",
"bytes": "1143"
},
{
"name": "M4",
"bytes": "184884"
},
{
"name": "Makefile",
"bytes": "676117"
},
{
"name": "Mathematica",
"bytes": "20070"
},
{
"name": "Monkey C",
"bytes": "274"
},
{
"name": "NASL",
"bytes": "9831"
},
{
"name": "OCaml",
"bytes": "378127"
},
{
"name": "Objective-C",
"bytes": "18168"
},
{
"name": "Objective-C++",
"bytes": "663471"
},
{
"name": "Perl",
"bytes": "55068"
},
{
"name": "Python",
"bytes": "845989"
},
{
"name": "Roff",
"bytes": "23681"
},
{
"name": "Shell",
"bytes": "842849"
},
{
"name": "Vim Script",
"bytes": "13176"
},
{
"name": "sed",
"bytes": "482"
}
],
"symlink_target": ""
} |
package pl.npe.lpp.preprocessor.source;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.npe.lpp.data.source.TexSource;
import pl.npe.lpp.preprocessor.LppParams;
import pl.npe.lpp.preprocessor.source.ProcessingContext;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
/**
* Created by IntelliJ IDEA.
* User: tomek
* Date: 20.05.14
* Time: 19:22
*/
@RunWith(MockitoJUnitRunner.class)
public class ProcessingContext_BuilderTest {
@Mock
private Path path;
@Mock
private TexSource texSourceMock;
@Test
public void testBuildNew() throws Exception {
ProcessingContext context = new ProcessingContext.Builder(texSourceMock, Charset.defaultCharset()).build();
assertEquals(texSourceMock, context.getTexSource());
assertNotNull(context.getReplacements());
assertNotNull(context.getChain());
assertEquals(Charset.defaultCharset(), context.getCharset());
assertFalse(context.isIncludeText());
assertFalse(context.isInherited());
}
@Test
public void testBuildFromExisting() throws Exception {
ProcessingContext oldContext = new ProcessingContext.Builder(texSourceMock, Charset.defaultCharset()).build();
ProcessingContext context = new ProcessingContext.Builder(oldContext, texSourceMock).build();
assertEquals(texSourceMock, context.getTexSource());
assertEquals(oldContext.getReplacements(), context.getReplacements());
assertEquals(oldContext.getChain(), context.getChain());
assertEquals(oldContext.getFlags(), context.getFlags());
assertEquals(Charset.defaultCharset(), context.getCharset());
assertFalse(context.isIncludeText());
assertTrue(context.isInherited());
}
@Test
public void testBuildFromLppParams() throws Exception {
Charset charset = Charset.forName("us-ascii");
Set<String> flags = new HashSet<>(Arrays.asList("flag1","flag2"));
LppParams params = new LppParams.Builder(texSourceMock, null)
.charset(charset)
.flags(flags)
.build();
ProcessingContext context = new ProcessingContext.Builder(params).build();
assertEquals(charset, context.getCharset());
assertEquals(params.getFlags(), context.getFlags());
assertEquals(params.getTexSource(), context.getTexSource());
assertFalse(context.isIncludeText());
assertFalse(context.isInherited());
assertNotNull(context.getChain());
assertEquals(0, context.getLineNumber());
assertTrue(context.getReplacements().isEmpty());
}
}
| {
"content_hash": "a86bc741cba96858923137679a8b1b09",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 118,
"avg_line_length": 36.688311688311686,
"alnum_prop": 0.704070796460177,
"repo_name": "traczykowski/lpp",
"id": "fd0f98c8478243e0c9a3c0e8dba4f76038bc2491",
"size": "2825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/pl/npe/lpp/preprocessor/source/ProcessingContext_BuilderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "107976"
},
{
"name": "TeX",
"bytes": "9300"
}
],
"symlink_target": ""
} |
layout: post
date: 2011-08-15 16:10:00
title: Thoughts on Independence Day
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
Celebrating one's patriotism is not a matter of flying the flag on one day...it also means not littering, not breaking the rules, being polite and helpful to other Indians...EVERY day. Pride in one's country should be a daily state of mind, not an occasional token statement. That minute of pride in the billowing Tiranga should extend into a lifetime of doing one's best for one's country.
| {
"content_hash": "a596d8b195cf454a9bc536089f333622",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 390,
"avg_line_length": 70.625,
"alnum_prop": 0.7752212389380531,
"repo_name": "deeyum/deeyum.github.io",
"id": "8ba84acc0a426fab885176a5b0c9386307b0b91d",
"size": "569",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/archives/2011-08-15-Thoughts-on-Independence-Day.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "63687"
},
{
"name": "HTML",
"bytes": "9811"
},
{
"name": "Shell",
"bytes": "1339"
}
],
"symlink_target": ""
} |
//// <reference path="../_references.ts"/>
module powerbi.data {
/** Allows generic traversal and type discovery for a SQExpr tree. */
export interface ISQExprVisitorWithArg<T, TArg> {
visitEntity(expr: SQEntityExpr, arg: TArg): T;
visitColumnRef(expr: SQColumnRefExpr, arg: TArg): T;
visitMeasureRef(expr: SQMeasureRefExpr, arg: TArg): T;
visitAggr(expr: SQAggregationExpr, arg: TArg): T;
visitHierarchy(expr: SQHierarchyExpr, arg: TArg): T;
visitHierarchyLevel(expr: SQHierarchyLevelExpr, arg: TArg): T;
visitPropertyVariationSource(expr: SQPropertyVariationSourceExpr, arg: TArg): T;
visitAnd(expr: SQAndExpr, arg: TArg): T;
visitBetween(expr: SQBetweenExpr, arg: TArg): T;
visitIn(expr: SQInExpr, arg: TArg): T;
visitOr(expr: SQOrExpr, arg: TArg): T;
visitCompare(expr: SQCompareExpr, arg: TArg): T;
visitContains(expr: SQContainsExpr, arg: TArg): T;
visitExists(expr: SQExistsExpr, arg: TArg): T;
visitNot(expr: SQNotExpr, arg: TArg): T;
visitStartsWith(expr: SQStartsWithExpr, arg: TArg): T;
visitConstant(expr: SQConstantExpr, arg: TArg): T;
visitDateSpan(expr: SQDateSpanExpr, arg: TArg): T;
visitDateAdd(expr: SQDateAddExpr, arg: TArg): T;
visitNow(expr: SQNowExpr, arg: TArg): T;
visitDefaultValue(expr: SQDefaultValueExpr, arg: TArg): T;
visitAnyValue(expr: SQAnyValueExpr, arg: TArg): T;
}
export interface ISQExprVisitor<T> extends ISQExprVisitorWithArg<T, void> {
}
/** Default IQueryExprVisitorWithArg implementation that others may derive from. */
export class DefaultSQExprVisitorWithArg<T, TArg> implements ISQExprVisitorWithArg<T, TArg> {
public visitEntity(expr: SQEntityExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitColumnRef(expr: SQColumnRefExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitMeasureRef(expr: SQMeasureRefExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitAggr(expr: SQAggregationExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitHierarchy(expr: SQHierarchyExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitHierarchyLevel(expr: SQHierarchyLevelExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitPropertyVariationSource(expr: SQPropertyVariationSourceExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitBetween(expr: SQBetweenExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitIn(expr: SQInExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitAnd(expr: SQAndExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitOr(expr: SQOrExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitCompare(expr: SQCompareExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitContains(expr: SQContainsExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitExists(expr: SQExistsExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitNot(expr: SQNotExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitStartsWith(expr: SQStartsWithExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitConstant(expr: SQConstantExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitDateSpan(expr: SQDateSpanExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitDateAdd(expr: SQDateAddExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitNow(expr: SQNowExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitDefaultValue(expr: SQDefaultValueExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitAnyValue(expr: SQAnyValueExpr, arg: TArg): T {
return this.visitDefault(expr, arg);
}
public visitDefault(expr: SQExpr, arg: TArg): T {
return;
}
}
/** Default ISQExprVisitor implementation that others may derive from. */
export class DefaultSQExprVisitor<T> extends DefaultSQExprVisitorWithArg<T, void> implements ISQExprVisitor<T> {
}
/** Default ISQExprVisitor implementation that implements default traversal and that others may derive from. */
export class DefaultSQExprVisitorWithTraversal implements ISQExprVisitor<void> {
public visitEntity(expr: SQEntityExpr): void {
this.visitDefault(expr);
}
public visitColumnRef(expr: SQColumnRefExpr): void {
expr.source.accept(this);
}
public visitMeasureRef(expr: SQMeasureRefExpr): void {
expr.source.accept(this);
}
public visitAggr(expr: SQAggregationExpr): void {
expr.arg.accept(this);
}
public visitHierarchy(expr: SQHierarchyExpr): void {
expr.arg.accept(this);
}
public visitHierarchyLevel(expr: SQHierarchyLevelExpr): void {
expr.arg.accept(this);
}
public visitPropertyVariationSource(expr: SQPropertyVariationSourceExpr): void {
expr.arg.accept(this);
}
public visitBetween(expr: SQBetweenExpr): void {
expr.arg.accept(this);
expr.lower.accept(this);
expr.upper.accept(this);
}
public visitIn(expr: SQInExpr): void {
let args = expr.args;
for (let i = 0, len = args.length; i < len; i++)
args[i].accept(this);
let values = expr.values;
for (let i = 0, len = values.length; i < len; i++) {
let valueTuple = values[i];
for (let j = 0, jlen = valueTuple.length; j < jlen; j++)
valueTuple[j].accept(this);
}
}
public visitAnd(expr: SQAndExpr): void {
expr.left.accept(this);
expr.right.accept(this);
}
public visitOr(expr: SQOrExpr): void {
expr.left.accept(this);
expr.right.accept(this);
}
public visitCompare(expr: SQCompareExpr): void {
expr.left.accept(this);
expr.right.accept(this);
}
public visitContains(expr: SQContainsExpr): void {
expr.left.accept(this);
expr.right.accept(this);
}
public visitExists(expr: SQExistsExpr): void {
expr.arg.accept(this);
}
public visitNot(expr: SQNotExpr): void {
expr.arg.accept(this);
}
public visitStartsWith(expr: SQStartsWithExpr): void {
expr.left.accept(this);
expr.right.accept(this);
}
public visitConstant(expr: SQConstantExpr): void {
this.visitDefault(expr);
}
public visitDateSpan(expr: SQDateSpanExpr): void {
expr.arg.accept(this);
}
public visitDateAdd(expr: SQDateAddExpr): void {
expr.arg.accept(this);
}
public visitNow(expr: SQNowExpr): void {
this.visitDefault(expr);
}
public visitDefaultValue(expr: SQDefaultValueExpr): void {
this.visitDefault(expr);
}
public visitAnyValue(expr: SQAnyValueExpr): void {
this.visitDefault(expr);
}
public visitDefault(expr: SQExpr): void {
return;
}
}
} | {
"content_hash": "b5db6926e403ef3dfc883dfe4d8533e8",
"timestamp": "",
"source": "github",
"line_count": 245,
"max_line_length": 116,
"avg_line_length": 33.089795918367344,
"alnum_prop": 0.5924509682990009,
"repo_name": "galiya/PowerBI-visuals",
"id": "abe4a94e79f8c5229a73f30df175916e8eb86f67",
"size": "9331",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/Clients/VisualsData/semanticQuery/sqExprVisitor.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "192091"
},
{
"name": "HTML",
"bytes": "1956"
},
{
"name": "JavaScript",
"bytes": "970677"
},
{
"name": "TypeScript",
"bytes": "7951659"
}
],
"symlink_target": ""
} |
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import timeutils
from oslo_utils import units
import taskflow.engines
from taskflow.patterns import linear_flow
from taskflow.types import failure as ft
from cinder import exception
from cinder import flow_utils
from cinder.i18n import _, _LE, _LW
from cinder import objects
from cinder import policy
from cinder import quota
from cinder import utils
from cinder.volume.flows import common
from cinder.volume import volume_types
LOG = logging.getLogger(__name__)
ACTION = 'volume:create'
CONF = cfg.CONF
GB = units.Gi
QUOTAS = quota.QUOTAS
# Only in these 'sources' status can we attempt to create a volume from a
# source volume or a source snapshot, other status states we can not create
# from, 'error' being the common example.
SNAPSHOT_PROCEED_STATUS = ('available',)
SRC_VOL_PROCEED_STATUS = ('available', 'in-use',)
REPLICA_PROCEED_STATUS = ('active', 'active-stopped',)
CG_PROCEED_STATUS = ('available', 'creating',)
CGSNAPSHOT_PROCEED_STATUS = ('available',)
class ExtractVolumeRequestTask(flow_utils.CinderTask):
"""Processes an api request values into a validated set of values.
This tasks responsibility is to take in a set of inputs that will form
a potential volume request and validates those values against a set of
conditions and/or translates those values into a valid set and then returns
the validated/translated values for use by other tasks.
Reversion strategy: N/A
"""
# This task will produce the following outputs (said outputs can be
# saved to durable storage in the future so that the flow can be
# reconstructed elsewhere and continued).
default_provides = set(['availability_zone', 'size', 'snapshot_id',
'source_volid', 'volume_type', 'volume_type_id',
'encryption_key_id', 'source_replicaid',
'consistencygroup_id', 'cgsnapshot_id'])
def __init__(self, image_service, availability_zones, **kwargs):
super(ExtractVolumeRequestTask, self).__init__(addons=[ACTION],
**kwargs)
self.image_service = image_service
self.availability_zones = availability_zones
@staticmethod
def _extract_resource(resource, allowed_vals, exc, resource_name,
props=('status',)):
"""Extracts the resource id from the provided resource.
This method validates the input resource dict and checks that the
properties which names are passed in `props` argument match
corresponding lists in `allowed` argument. In case of mismatch
exception of type exc is raised.
:param resource: Resource dict.
:param allowed_vals: Tuple of allowed values lists.
:param exc: Exception type to raise.
:param resource_name: Name of resource - used to construct log message.
:param props: Tuple of resource properties names to validate.
:return: Id of a resource.
"""
resource_id = None
if resource:
for prop, allowed_states in zip(props, allowed_vals):
if resource[prop] not in allowed_states:
msg = _("Originating %(res)s %(prop)s must be one of"
"'%(vals)s' values")
msg = msg % {'res': resource_name,
'prop': prop,
'vals': ', '.join(allowed_states)}
# TODO(harlowja): what happens if the status changes after
# this initial resource status check occurs??? Seems like
# someone could delete the resource after this check passes
# but before the volume is officially created?
raise exc(reason=msg)
resource_id = resource['id']
return resource_id
def _extract_consistencygroup(self, consistencygroup):
return self._extract_resource(consistencygroup, (CG_PROCEED_STATUS,),
exception.InvalidConsistencyGroup,
'consistencygroup')
def _extract_cgsnapshot(self, cgsnapshot):
return self._extract_resource(cgsnapshot, (CGSNAPSHOT_PROCEED_STATUS,),
exception.InvalidCgSnapshot,
'CGSNAPSHOT')
def _extract_snapshot(self, snapshot):
return self._extract_resource(snapshot, (SNAPSHOT_PROCEED_STATUS,),
exception.InvalidSnapshot, 'snapshot')
def _extract_source_volume(self, source_volume):
return self._extract_resource(source_volume, (SRC_VOL_PROCEED_STATUS,),
exception.InvalidVolume, 'source volume')
def _extract_source_replica(self, source_replica):
return self._extract_resource(source_replica, (SRC_VOL_PROCEED_STATUS,
REPLICA_PROCEED_STATUS),
exception.InvalidVolume,
'replica', ('status',
'replication_status'))
@staticmethod
def _extract_size(size, source_volume, snapshot):
"""Extracts and validates the volume size.
This function will validate or when not provided fill in the provided
size variable from the source_volume or snapshot and then does
validation on the size that is found and returns said validated size.
"""
def validate_snap_size(size):
if snapshot and size < snapshot['volume_size']:
msg = _("Volume size '%(size)s'GB cannot be smaller than"
" the snapshot size %(snap_size)sGB. "
"They must be >= original snapshot size.")
msg = msg % {'size': size,
'snap_size': snapshot['volume_size']}
raise exception.InvalidInput(reason=msg)
def validate_source_size(size):
if source_volume and size < source_volume['size']:
msg = _("Volume size '%(size)s'GB cannot be smaller than "
"original volume size %(source_size)sGB. "
"They must be >= original volume size.")
msg = msg % {'size': size,
'source_size': source_volume['size']}
raise exception.InvalidInput(reason=msg)
def validate_int(size):
if not isinstance(size, int) or size <= 0:
msg = _("Volume size '%(size)s' must be an integer and"
" greater than 0") % {'size': size}
raise exception.InvalidInput(reason=msg)
# Figure out which validation functions we should be applying
# on the size value that we extract.
validator_functors = [validate_int]
if source_volume:
validator_functors.append(validate_source_size)
elif snapshot:
validator_functors.append(validate_snap_size)
# If the size is not provided then try to provide it.
if not size and source_volume:
size = source_volume['size']
elif not size and snapshot:
size = snapshot['volume_size']
size = utils.as_int(size)
LOG.debug("Validating volume '%(size)s' using %(functors)s" %
{'size': size,
'functors': ", ".join([common.make_pretty_name(func)
for func in validator_functors])})
for func in validator_functors:
func(size)
return size
def _check_image_metadata(self, context, image_id, size):
"""Checks image existence and validates that the image metadata."""
# Check image existence
if image_id is None:
return
# NOTE(harlowja): this should raise an error if the image does not
# exist, this is expected as it signals that the image_id is missing.
image_meta = self.image_service.show(context, image_id)
# check whether image is active
if image_meta['status'] != 'active':
msg = _('Image %(image_id)s is not active.')\
% {'image_id': image_id}
raise exception.InvalidInput(reason=msg)
# Check image size is not larger than volume size.
image_size = utils.as_int(image_meta['size'], quiet=False)
image_size_in_gb = (image_size + GB - 1) / GB
if image_size_in_gb > size:
msg = _('Size of specified image %(image_size)sGB'
' is larger than volume size %(volume_size)sGB.')
msg = msg % {'image_size': image_size_in_gb, 'volume_size': size}
raise exception.InvalidInput(reason=msg)
# Check image min_disk requirement is met for the particular volume
min_disk = image_meta.get('min_disk', 0)
if size < min_disk:
msg = _('Volume size %(volume_size)sGB cannot be smaller'
' than the image minDisk size %(min_disk)sGB.')
msg = msg % {'volume_size': size, 'min_disk': min_disk}
raise exception.InvalidInput(reason=msg)
@staticmethod
def _check_metadata_properties(metadata=None):
"""Checks that the volume metadata properties are valid."""
if not metadata:
metadata = {}
for (k, v) in metadata.items():
if len(k) == 0:
msg = _("Metadata property key blank")
LOG.warning(msg)
raise exception.InvalidVolumeMetadata(reason=msg)
if len(k) > 255:
msg = _("Metadata property key %s greater than 255 "
"characters") % k
LOG.warning(msg)
raise exception.InvalidVolumeMetadataSize(reason=msg)
if len(v) > 255:
msg = _("Metadata property key %s value greater than"
" 255 characters") % k
LOG.warning(msg)
raise exception.InvalidVolumeMetadataSize(reason=msg)
def _extract_availability_zone(self, availability_zone, snapshot,
source_volume):
"""Extracts and returns a validated availability zone.
This function will extract the availability zone (if not provided) from
the snapshot or source_volume and then performs a set of validation
checks on the provided or extracted availability zone and then returns
the validated availability zone.
"""
# Try to extract the availability zone from the corresponding snapshot
# or source volume if either is valid so that we can be in the same
# availability zone as the source.
if availability_zone is None:
if snapshot:
try:
availability_zone = snapshot['volume']['availability_zone']
except (TypeError, KeyError):
pass
if source_volume and availability_zone is None:
try:
availability_zone = source_volume['availability_zone']
except (TypeError, KeyError):
pass
if availability_zone is None:
if CONF.default_availability_zone:
availability_zone = CONF.default_availability_zone
else:
# For backwards compatibility use the storage_availability_zone
availability_zone = CONF.storage_availability_zone
if availability_zone not in self.availability_zones:
msg = _("Availability zone '%s' is invalid") % (availability_zone)
LOG.warning(msg)
raise exception.InvalidInput(reason=msg)
# If the configuration only allows cloning to the same availability
# zone then we need to enforce that.
if CONF.cloned_volume_same_az:
snap_az = None
try:
snap_az = snapshot['volume']['availability_zone']
except (TypeError, KeyError):
pass
if snap_az and snap_az != availability_zone:
msg = _("Volume must be in the same "
"availability zone as the snapshot")
raise exception.InvalidInput(reason=msg)
source_vol_az = None
try:
source_vol_az = source_volume['availability_zone']
except (TypeError, KeyError):
pass
if source_vol_az and source_vol_az != availability_zone:
msg = _("Volume must be in the same "
"availability zone as the source volume")
raise exception.InvalidInput(reason=msg)
return availability_zone
def _get_encryption_key_id(self, key_manager, context, volume_type_id,
snapshot, source_volume):
encryption_key_id = None
if volume_types.is_encrypted(context, volume_type_id):
if snapshot is not None: # creating from snapshot
encryption_key_id = snapshot['encryption_key_id']
elif source_volume is not None: # cloning volume
encryption_key_id = source_volume['encryption_key_id']
# NOTE(joel-coffman): References to the encryption key should *not*
# be copied because the key is deleted when the volume is deleted.
# Clone the existing key and associate a separate -- but
# identical -- key with each volume.
if encryption_key_id is not None:
encryption_key_id = key_manager.copy_key(context,
encryption_key_id)
else:
encryption_key_id = key_manager.create_key(context)
return encryption_key_id
def _get_volume_type_id(self, volume_type, source_volume, snapshot):
if not volume_type and source_volume:
return source_volume['volume_type_id']
elif snapshot is not None:
if volume_type:
current_volume_type_id = volume_type.get('id')
if current_volume_type_id != snapshot['volume_type_id']:
msg = _LW("Volume type will be changed to "
"be the same as the source volume.")
LOG.warning(msg)
return snapshot['volume_type_id']
else:
return volume_type.get('id')
def execute(self, context, size, snapshot, image_id, source_volume,
availability_zone, volume_type, metadata, key_manager,
source_replica, consistencygroup, cgsnapshot):
utils.check_exclusive_options(snapshot=snapshot,
imageRef=image_id,
source_volume=source_volume)
policy.enforce_action(context, ACTION)
# TODO(harlowja): what guarantee is there that the snapshot or source
# volume will remain available after we do this initial verification??
snapshot_id = self._extract_snapshot(snapshot)
source_volid = self._extract_source_volume(source_volume)
source_replicaid = self._extract_source_replica(source_replica)
size = self._extract_size(size, source_volume, snapshot)
consistencygroup_id = self._extract_consistencygroup(consistencygroup)
cgsnapshot_id = self._extract_cgsnapshot(cgsnapshot)
self._check_image_metadata(context, image_id, size)
availability_zone = self._extract_availability_zone(availability_zone,
snapshot,
source_volume)
# TODO(joel-coffman): This special handling of snapshots to ensure that
# their volume type matches the source volume is too convoluted. We
# should copy encryption metadata from the encrypted volume type to the
# volume upon creation and propagate that information to each snapshot.
# This strategy avoids any dependency upon the encrypted volume type.
def_vol_type = volume_types.get_default_volume_type()
if not volume_type and not source_volume and not snapshot:
volume_type = def_vol_type
# When creating a clone of a replica (replication test), we can't
# use the volume type of the replica, therefore, we use the default.
# NOTE(ronenkat): this assumes the default type is not replicated.
if source_replicaid:
volume_type = def_vol_type
volume_type_id = self._get_volume_type_id(volume_type,
source_volume, snapshot)
encryption_key_id = self._get_encryption_key_id(key_manager,
context,
volume_type_id,
snapshot,
source_volume)
specs = {}
if volume_type_id:
qos_specs = volume_types.get_volume_type_qos_specs(volume_type_id)
specs = qos_specs['qos_specs']
if not specs:
# to make sure we don't pass empty dict
specs = None
self._check_metadata_properties(metadata)
return {
'size': size,
'snapshot_id': snapshot_id,
'source_volid': source_volid,
'availability_zone': availability_zone,
'volume_type': volume_type,
'volume_type_id': volume_type_id,
'encryption_key_id': encryption_key_id,
'qos_specs': specs,
'source_replicaid': source_replicaid,
'consistencygroup_id': consistencygroup_id,
'cgsnapshot_id': cgsnapshot_id,
}
class EntryCreateTask(flow_utils.CinderTask):
"""Creates an entry for the given volume creation in the database.
Reversion strategy: remove the volume_id created from the database.
"""
default_provides = set(['volume_properties', 'volume_id', 'volume'])
def __init__(self, db):
requires = ['availability_zone', 'description', 'metadata',
'name', 'reservations', 'size', 'snapshot_id',
'source_volid', 'volume_type_id', 'encryption_key_id',
'source_replicaid', 'consistencygroup_id',
'cgsnapshot_id', 'multiattach']
super(EntryCreateTask, self).__init__(addons=[ACTION],
requires=requires)
self.db = db
def execute(self, context, optional_args, **kwargs):
"""Creates a database entry for the given inputs and returns details.
Accesses the database and creates a new entry for the to be created
volume using the given volume properties which are extracted from the
input kwargs (and associated requirements this task needs). These
requirements should be previously satisfied and validated by a
pre-cursor task.
"""
volume_properties = {
'size': kwargs.pop('size'),
'user_id': context.user_id,
'project_id': context.project_id,
'status': 'creating',
'attach_status': 'detached',
'encryption_key_id': kwargs.pop('encryption_key_id'),
# Rename these to the internal name.
'display_description': kwargs.pop('description'),
'display_name': kwargs.pop('name'),
'replication_status': 'disabled',
'multiattach': kwargs.pop('multiattach'),
}
# Merge in the other required arguments which should provide the rest
# of the volume property fields (if applicable).
volume_properties.update(kwargs)
volume = self.db.volume_create(context, volume_properties)
return {
'volume_id': volume['id'],
'volume_properties': volume_properties,
# NOTE(harlowja): it appears like further usage of this volume
# result actually depend on it being a sqlalchemy object and not
# just a plain dictionary so that's why we are storing this here.
#
# In the future where this task results can be serialized and
# restored automatically for continued running we will need to
# resolve the serialization & recreation of this object since raw
# sqlalchemy objects can't be serialized.
'volume': volume,
}
def revert(self, context, result, optional_args, **kwargs):
if isinstance(result, ft.Failure):
# We never produced a result and therefore can't destroy anything.
return
if optional_args['is_quota_committed']:
# If quota got commited we shouldn't rollback as the volume has
# already been created and the quota has already been absorbed.
return
vol_id = result['volume_id']
try:
self.db.volume_destroy(context.elevated(), vol_id)
except exception.CinderException:
# We are already reverting, therefore we should silence this
# exception since a second exception being active will be bad.
#
# NOTE(harlowja): Being unable to destroy a volume is pretty
# bad though!!
LOG.exception(_LE("Failed destroying volume entry %s"), vol_id)
class QuotaReserveTask(flow_utils.CinderTask):
"""Reserves a single volume with the given size & the given volume type.
Reversion strategy: rollback the quota reservation.
Warning Warning: if the process that is running this reserve and commit
process fails (or is killed before the quota is rolled back or committed
it does appear like the quota will never be rolled back). This makes
software upgrades hard (inflight operations will need to be stopped or
allowed to complete before the upgrade can occur). *In the future* when
taskflow has persistence built-in this should be easier to correct via
an automated or manual process.
"""
default_provides = set(['reservations'])
def __init__(self):
super(QuotaReserveTask, self).__init__(addons=[ACTION])
def execute(self, context, size, volume_type_id, optional_args):
try:
values = {'per_volume_gigabytes': size}
QUOTAS.limit_check(context, project_id=context.project_id,
**values)
except exception.OverQuota as e:
quotas = e.kwargs['quotas']
raise exception.VolumeSizeExceedsLimit(
size=size, limit=quotas['per_volume_gigabytes'])
try:
reserve_opts = {'volumes': 1, 'gigabytes': size}
QUOTAS.add_volume_type_opts(context, reserve_opts, volume_type_id)
reservations = QUOTAS.reserve(context, **reserve_opts)
return {
'reservations': reservations,
}
except exception.OverQuota as e:
overs = e.kwargs['overs']
quotas = e.kwargs['quotas']
usages = e.kwargs['usages']
def _consumed(name):
return usages[name]['reserved'] + usages[name]['in_use']
def _get_over(name):
for over in overs:
if name in over:
return over
return None
over_name = _get_over('gigabytes')
if over_name:
msg = _LW("Quota exceeded for %(s_pid)s, tried to create "
"%(s_size)sG volume (%(d_consumed)dG "
"of %(d_quota)dG already consumed)")
LOG.warning(msg, {'s_pid': context.project_id,
's_size': size,
'd_consumed': _consumed(over_name),
'd_quota': quotas[over_name]})
raise exception.VolumeSizeExceedsAvailableQuota(
name=over_name,
requested=size,
consumed=_consumed(over_name),
quota=quotas[over_name])
elif _get_over('volumes'):
msg = _LW("Quota exceeded for %(s_pid)s, tried to create "
"volume (%(d_consumed)d volumes "
"already consumed)")
LOG.warning(msg, {'s_pid': context.project_id,
'd_consumed': _consumed('volumes')})
raise exception.VolumeLimitExceeded(allowed=quotas['volumes'])
else:
# If nothing was reraised, ensure we reraise the initial error
raise
def revert(self, context, result, optional_args, **kwargs):
# We never produced a result and therefore can't destroy anything.
if isinstance(result, ft.Failure):
return
if optional_args['is_quota_committed']:
# The reservations have already been committed and can not be
# rolled back at this point.
return
# We actually produced an output that we can revert so lets attempt
# to use said output to rollback the reservation.
reservations = result['reservations']
try:
QUOTAS.rollback(context, reservations)
except exception.CinderException:
# We are already reverting, therefore we should silence this
# exception since a second exception being active will be bad.
LOG.exception(_LE("Failed rolling back quota for"
" %s reservations"), reservations)
class QuotaCommitTask(flow_utils.CinderTask):
"""Commits the reservation.
Reversion strategy: N/A (the rollback will be handled by the task that did
the initial reservation (see: QuotaReserveTask).
Warning Warning: if the process that is running this reserve and commit
process fails (or is killed before the quota is rolled back or committed
it does appear like the quota will never be rolled back). This makes
software upgrades hard (inflight operations will need to be stopped or
allowed to complete before the upgrade can occur). *In the future* when
taskflow has persistence built-in this should be easier to correct via
an automated or manual process.
"""
def __init__(self):
super(QuotaCommitTask, self).__init__(addons=[ACTION])
def execute(self, context, reservations, volume_properties,
optional_args):
QUOTAS.commit(context, reservations)
# updating is_quota_committed attribute of optional_args dictionary
optional_args['is_quota_committed'] = True
return {'volume_properties': volume_properties}
def revert(self, context, result, **kwargs):
# We never produced a result and therefore can't destroy anything.
if isinstance(result, ft.Failure):
return
volume = result['volume_properties']
try:
reserve_opts = {'volumes': -1, 'gigabytes': -volume['size']}
QUOTAS.add_volume_type_opts(context,
reserve_opts,
volume['volume_type_id'])
reservations = QUOTAS.reserve(context,
project_id=context.project_id,
**reserve_opts)
if reservations:
QUOTAS.commit(context, reservations,
project_id=context.project_id)
except Exception:
LOG.exception(_LE("Failed to update quota for deleting "
"volume: %s"), volume['id'])
class VolumeCastTask(flow_utils.CinderTask):
"""Performs a volume create cast to the scheduler or to the volume manager.
This will signal a transition of the api workflow to another child and/or
related workflow on another component.
Reversion strategy: rollback source volume status and error out newly
created volume.
"""
def __init__(self, scheduler_rpcapi, volume_rpcapi, db):
requires = ['image_id', 'scheduler_hints', 'snapshot_id',
'source_volid', 'volume_id', 'volume_type',
'volume_properties', 'source_replicaid',
'consistencygroup_id', 'cgsnapshot_id', ]
super(VolumeCastTask, self).__init__(addons=[ACTION],
requires=requires)
self.volume_rpcapi = volume_rpcapi
self.scheduler_rpcapi = scheduler_rpcapi
self.db = db
def _cast_create_volume(self, context, request_spec, filter_properties):
source_volid = request_spec['source_volid']
source_replicaid = request_spec['source_replicaid']
volume_id = request_spec['volume_id']
snapshot_id = request_spec['snapshot_id']
image_id = request_spec['image_id']
cgroup_id = request_spec['consistencygroup_id']
host = None
cgsnapshot_id = request_spec['cgsnapshot_id']
if cgroup_id:
cgroup = self.db.consistencygroup_get(context, cgroup_id)
if cgroup:
host = cgroup.get('host', None)
elif snapshot_id and CONF.snapshot_same_host:
# NOTE(Rongze Zhu): A simple solution for bug 1008866.
#
# If snapshot_id is set and CONF.snapshot_same_host is True, make
# the call create volume directly to the volume host where the
# snapshot resides instead of passing it through the scheduler, so
# snapshot can be copied to the new volume.
snapshot = objects.Snapshot.get_by_id(context, snapshot_id)
source_volume_ref = self.db.volume_get(context, snapshot.volume_id)
host = source_volume_ref['host']
elif source_volid:
source_volume_ref = self.db.volume_get(context, source_volid)
host = source_volume_ref['host']
elif source_replicaid:
source_volume_ref = self.db.volume_get(context, source_replicaid)
host = source_volume_ref['host']
if not host:
# Cast to the scheduler and let it handle whatever is needed
# to select the target host for this volume.
self.scheduler_rpcapi.create_volume(
context,
CONF.volume_topic,
volume_id,
snapshot_id=snapshot_id,
image_id=image_id,
request_spec=request_spec,
filter_properties=filter_properties)
else:
# Bypass the scheduler and send the request directly to the volume
# manager.
now = timeutils.utcnow()
values = {'host': host, 'scheduled_at': now}
volume_ref = self.db.volume_update(context, volume_id, values)
if not cgsnapshot_id:
self.volume_rpcapi.create_volume(
context,
volume_ref,
volume_ref['host'],
request_spec,
filter_properties,
allow_reschedule=False)
def execute(self, context, **kwargs):
scheduler_hints = kwargs.pop('scheduler_hints', None)
request_spec = kwargs.copy()
filter_properties = {}
if scheduler_hints:
filter_properties['scheduler_hints'] = scheduler_hints
self._cast_create_volume(context, request_spec, filter_properties)
def revert(self, context, result, flow_failures, **kwargs):
if isinstance(result, ft.Failure):
return
# Restore the source volume status and set the volume to error status.
volume_id = kwargs['volume_id']
common.restore_source_status(context, self.db, kwargs)
common.error_out_volume(context, self.db, volume_id)
LOG.error(_LE("Volume %s: create failed"), volume_id)
exc_info = False
if all(flow_failures[-1].exc_info):
exc_info = flow_failures[-1].exc_info
LOG.error(_LE('Unexpected build error:'), exc_info=exc_info)
def get_flow(db_api, image_service_api, availability_zones, create_what,
scheduler_rpcapi=None, volume_rpcapi=None):
"""Constructs and returns the api entrypoint flow.
This flow will do the following:
1. Inject keys & values for dependent tasks.
2. Extracts and validates the input keys & values.
3. Reserves the quota (reverts quota on any failures).
4. Creates the database entry.
5. Commits the quota.
6. Casts to volume manager or scheduler for further processing.
"""
flow_name = ACTION.replace(":", "_") + "_api"
api_flow = linear_flow.Flow(flow_name)
api_flow.add(ExtractVolumeRequestTask(
image_service_api,
availability_zones,
rebind={'size': 'raw_size',
'availability_zone': 'raw_availability_zone',
'volume_type': 'raw_volume_type'}))
api_flow.add(QuotaReserveTask(),
EntryCreateTask(db_api),
QuotaCommitTask())
if scheduler_rpcapi and volume_rpcapi:
# This will cast it out to either the scheduler or volume manager via
# the rpc apis provided.
api_flow.add(VolumeCastTask(scheduler_rpcapi, volume_rpcapi, db_api))
# Now load (but do not run) the flow using the provided initial data.
return taskflow.engines.load(api_flow, store=create_what)
| {
"content_hash": "2adaeb0e477945e0bd2cc6408adf3517",
"timestamp": "",
"source": "github",
"line_count": 763,
"max_line_length": 79,
"avg_line_length": 44.51376146788991,
"alnum_prop": 0.5818808149805677,
"repo_name": "JioCloud/cinder",
"id": "5f1a4adfcbb5b22d6f107ba73e1194d430a90a39",
"size": "34538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cinder/volume/flows/api/create_volume.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "11977630"
},
{
"name": "Shell",
"bytes": "8111"
}
],
"symlink_target": ""
} |
import { StyleSheet } from 'react-native'
import { Colors, Metrics, Fonts, ApplicationStyles } from '../../themes/'
export default StyleSheet.create({
...ApplicationStyles.screen
})
| {
"content_hash": "a9f0398f0249fa3c7eb4bff37a026f58",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 73,
"avg_line_length": 30.833333333333332,
"alnum_prop": 0.7243243243243244,
"repo_name": "phattranky/react-native-redux-boilerplate",
"id": "057e60c2976f824bf9f0bc92a90e6fa7df4cdefd",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/containers/styles/GalleryScreenStyle.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1331"
},
{
"name": "JavaScript",
"bytes": "53985"
},
{
"name": "Objective-C",
"bytes": "4416"
},
{
"name": "Python",
"bytes": "1653"
}
],
"symlink_target": ""
} |
package de.fuberlin.wiwiss.d2rq.expr;
import java.util.Set;
import de.fuberlin.wiwiss.d2rq.algebra.AliasMap;
import de.fuberlin.wiwiss.d2rq.algebra.Attribute;
import de.fuberlin.wiwiss.d2rq.algebra.ColumnRenamer;
import de.fuberlin.wiwiss.d2rq.sql.ConnectedDB;
/**
* A CASE statement that turns a BOOLEAN (TRUE, FALSE) into an
* INT (1, 0)
*
* @author Richard Cyganiak ([email protected])
*/
public class BooleanToIntegerCaseExpression extends Expression {
private Expression base;
public BooleanToIntegerCaseExpression(Expression base) {
this.base = base;
}
public Expression getBase() {
return base;
}
public Set<Attribute> attributes() {
return base.attributes();
}
public boolean isFalse() {
return base.isFalse();
}
public boolean isTrue() {
return base.isTrue();
}
public Expression renameAttributes(ColumnRenamer columnRenamer) {
return new BooleanToIntegerCaseExpression(base.renameAttributes(columnRenamer));
}
public String toSQL(ConnectedDB database, AliasMap aliases) {
return "(CASE WHEN (" + base.toSQL(database, aliases) + ") THEN 1 ELSE 0 END)";
}
public String toString() {
return "Boolean2Int(" + base + ")";
}
public boolean equals(Object other) {
if (!(other instanceof BooleanToIntegerCaseExpression)) {
return false;
}
BooleanToIntegerCaseExpression otherExpression = (BooleanToIntegerCaseExpression) other;
return this.base.equals(otherExpression.base);
}
public int hashCode() {
return base.hashCode() ^ 2341234;
}
} | {
"content_hash": "d82451cffc26efef9ca94601ac81f102",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 90,
"avg_line_length": 24.451612903225808,
"alnum_prop": 0.7401055408970977,
"repo_name": "vishalkpp/VirtualSPARQLer",
"id": "3eda468c0d51c979c79cd08393a72d2dbf702d46",
"size": "1516",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "d2rq-0.8.1/src/de/fuberlin/wiwiss/d2rq/expr/BooleanToIntegerCaseExpression.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1580"
},
{
"name": "CSS",
"bytes": "4783"
},
{
"name": "HTML",
"bytes": "167862"
},
{
"name": "Java",
"bytes": "1083721"
},
{
"name": "JavaScript",
"bytes": "78293"
},
{
"name": "Shell",
"bytes": "1826"
},
{
"name": "XSLT",
"bytes": "4575"
}
],
"symlink_target": ""
} |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>TypeConverterAttribute Constructor</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache log4net SDK Documentation - Microsoft .NET Framework 4.0</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">TypeConverterAttribute Constructor</h1>
</div>
</div>
<div id="nstext">
<p> Default constructor </p>
<h4 class="dtH4">Overload List</h4>
<p> Default constructor </p>
<blockquote class="dtBlock">
<a href="log4net.Util.TypeConverters.TypeConverterAttributeConstructor1.html">public TypeConverterAttribute();</a>
</blockquote>
<p> Create a new type converter attribute for the specified type name </p>
<blockquote class="dtBlock">
<a href="log4net.Util.TypeConverters.TypeConverterAttributeConstructor2.html">public TypeConverterAttribute(string);</a>
</blockquote>
<p> Create a new type converter attribute for the specified type </p>
<blockquote class="dtBlock">
<a href="log4net.Util.TypeConverters.TypeConverterAttributeConstructor3.html">public TypeConverterAttribute(Type);</a>
</blockquote>
<h4 class="dtH4">See Also</h4>
<p>
<a href="log4net.Util.TypeConverters.TypeConverterAttribute.html">TypeConverterAttribute Class</a> | <a href="log4net.Util.TypeConverters.html">log4net.Util.TypeConverters Namespace</a></p>
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
<param name="Keyword" value="TypeConverterAttribute class, constructors">
</param>
</object>
<hr />
<div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div>
</div>
</body>
</html> | {
"content_hash": "2daf60c028896c40a234d06da1108573",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 222,
"avg_line_length": 48.627450980392155,
"alnum_prop": 0.6451612903225806,
"repo_name": "gersonkurz/manualisator",
"id": "99b122c4ebba5f4342a920612eac6b40876fbf7d",
"size": "2480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "manualisator/log4net-1.2.13/doc/release/sdk/log4net.Util.TypeConverters.TypeConverterAttributeConstructor.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "235121"
},
{
"name": "CSS",
"bytes": "15869"
},
{
"name": "HTML",
"bytes": "9723377"
},
{
"name": "JavaScript",
"bytes": "5685"
},
{
"name": "NSIS",
"bytes": "1916"
},
{
"name": "Shell",
"bytes": "1041"
}
],
"symlink_target": ""
} |
namespace net {
namespace test {
class MockQuicDispatcher : public QuicSimpleDispatcher {
public:
MockQuicDispatcher(
const QuicConfig& config,
const QuicCryptoServerConfig* crypto_config,
QuicVersionManager* version_manager,
std::unique_ptr<QuicConnectionHelperInterface> helper,
std::unique_ptr<QuicCryptoServerStream::Helper> session_helper,
std::unique_ptr<QuicAlarmFactory> alarm_factory);
~MockQuicDispatcher() override;
MOCK_METHOD3(ProcessPacket,
void(const IPEndPoint& server_address,
const IPEndPoint& client_address,
const QuicReceivedPacket& packet));
private:
DISALLOW_COPY_AND_ASSIGN(MockQuicDispatcher);
};
} // namespace test
} // namespace net
#endif // NET_QUIC_TEST_TOOLS_MOCK_QUIC_DISPATCHER_H_
| {
"content_hash": "5197164efa9b357a9d6cb04bca1fe48c",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 69,
"avg_line_length": 29.464285714285715,
"alnum_prop": 0.703030303030303,
"repo_name": "ssaroha/node-webrtc",
"id": "e4c41a649628c9c9f746bd9f983f0bb5cae5b87f",
"size": "1394",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "third_party/webrtc/include/chromium/src/net/quic/test_tools/mock_quic_dispatcher.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "6179"
},
{
"name": "C",
"bytes": "2679"
},
{
"name": "C++",
"bytes": "54327"
},
{
"name": "HTML",
"bytes": "434"
},
{
"name": "JavaScript",
"bytes": "42707"
},
{
"name": "Python",
"bytes": "3835"
}
],
"symlink_target": ""
} |
module.exports = {
getCelsius() {
return Promise.resolve(12.34);
},
setHeating(on) {
// TODO console.log("turned heating " + on);
return Promise.resolve(on);
},
};
| {
"content_hash": "d7c118f41a824a154cbeeddf2d36c02b",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 53,
"avg_line_length": 21,
"alnum_prop": 0.582010582010582,
"repo_name": "Tentoe/laforge",
"id": "6ea50b63c50bfee55b132233fa81dc061104ae11",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/heating/piioDUMMY.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "119"
},
{
"name": "HTML",
"bytes": "4292"
},
{
"name": "JavaScript",
"bytes": "49386"
}
],
"symlink_target": ""
} |
import cp from 'child_process';
export default (command, args, options = {}) => new Promise((resolve, reject) => {
const stdio = process.platform === 'win32'
? 'ignore'
: 'inherit';
const child = cp.spawn(command, args, { stdio, ...options });
child.on('error', (err) => {
reject(err);
});
child.on('exit', (code) => {
resolve(code);
});
return child;
});
| {
"content_hash": "b207ca18e980a4ec8613a0f4c9c23e22",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 82,
"avg_line_length": 18.714285714285715,
"alnum_prop": 0.5648854961832062,
"repo_name": "nimzco/Environment",
"id": "024c53790676dbcf24976e3ecccca11aaebdd95b",
"size": "940",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Sublime/Packages/HTML-CSS-JS Prettify/src/js/shared/spawn.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "332445"
},
{
"name": "Python",
"bytes": "3101171"
},
{
"name": "Shell",
"bytes": "26630"
}
],
"symlink_target": ""
} |
// Runs provided program and returns promise that resolves when it ends
'use strict';
var deferred = require('deferred')
, fork = require('child_process').fork;
module.exports = function (program/*, args, options*/) {
var def = deferred();
var child = def.promise.process = fork.apply(null, arguments);
child.on('exit', function () { def.resolve(); });
child.on('error', def.reject);
return def.promise;
};
| {
"content_hash": "d80b8bd9eb5b9bd2f4a559d82a469f12",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 71,
"avg_line_length": 30.071428571428573,
"alnum_prop": 0.6793349168646081,
"repo_name": "egovernment/eregistrations-demo",
"id": "5044abe48bb7df063dfabc81f7c74160ba20aa74",
"size": "421",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/eregistrations/server/utils/run-program.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "31"
},
{
"name": "CSS",
"bytes": "293"
},
{
"name": "HTML",
"bytes": "7910"
},
{
"name": "JavaScript",
"bytes": "183311"
},
{
"name": "Smarty",
"bytes": "8823"
}
],
"symlink_target": ""
} |
```
$ npm install monpy-db
```
## Example
#### Model
```js
var db = require('monpy-db')('mysql');
function User(){
db.BaseEntity.apply(this, arguments);
}
db.inherits(User, db.BaseEntity);
```
#### Use
```js
var db = require('monpy-db')('mysql'),
co = require('co'),
config = {
pool: 5,
host: 'localhost',
user: 'test',
password: 'password',
database: 'test_db'
};
var model = new User();
var user = {
name: 'monpy',
comment: 'hello',
created_at: new Date()
};
co(function *(){
// DataBase Connect
db.connect(config);
// INSERT
var ret = yield model.insert(user);
// var ret = yield model.save(user);
var userId = ret.insertId;
var user = yield model.getById(userId);
console.log(user);
// UPDATE
user.updated_at = new Date();
var ret = yield model.update(user);
// var ret = yield model.save(user);
// DataBase Disconnect
db.end();
});
```
## Document
作成中・・・ | {
"content_hash": "aece6e75c15a91a5558dadb4f578d91c",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 41,
"avg_line_length": 14.753846153846155,
"alnum_prop": 0.5776850886339937,
"repo_name": "monpoco/monpy-db",
"id": "bd02cebd43fc08e89f55e1041749dc3e1ff82696",
"size": "1206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16823"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block title %}Collected Urls{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<ul class="breadcrumb">
<li><a href="{{ url_for('get_hosts') }}">Hosts</a></li>
<li class="active">{{ host }}</li>
</ul>
<h1>{{ host }}</h1>
<div class="list-group">
<a href="{{ url_for('analyse_paths', host=host) }}" class="list-group-item">
<h4 class="list-group-item-heading">Path Analysis</h4>
<p class="list-group-item-text">www.example.com<b>/test/path</b>?a=parameter.</p>
</a>
<a href="{{ url_for('analyse_parameters', host=host) }}" class="list-group-item">
<h4 class="list-group-item-heading">Parameter Analysis</h4>
<p class="list-group-item-text">www.example.com/test/path?<b>a=parameter</b>.</p>
</a>
<a href="{{ url_for('analyse_forms', host=host) }}" class="list-group-item">
<h4 class="list-group-item-heading">Form Analysis</h4>
<p class="list-group-item-text">Analyse collected forms and parameters</p>
</a>
<a href="{{ url_for('analyse_cookies', host=host) }}" class="list-group-item">
<h4 class="list-group-item-heading">Cookie Analysis</h4>
<p class="list-group-item-text">Track changes in cookies</p>
</a>
</div>
{% endblock %} | {
"content_hash": "e8598d0f4237ee6fd469bacc5f02e708",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 84,
"avg_line_length": 38.39393939393939,
"alnum_prop": 0.6140489344909235,
"repo_name": "Samuirai/nazo",
"id": "e0f778f9c5fc3c52757a846fa3f6ac4e707fe5b4",
"size": "1267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/templates/host_overview.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1557"
},
{
"name": "JavaScript",
"bytes": "15220"
},
{
"name": "Python",
"bytes": "24073"
}
],
"symlink_target": ""
} |
package org.apache.wss4j.policy.builders;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.wss4j.policy.SP11Constants;
import org.apache.wss4j.policy.SP13Constants;
import org.apache.wss4j.policy.SPConstants;
import org.apache.wss4j.policy.SPUtils;
import org.apache.wss4j.policy.model.Attachments;
import org.apache.wss4j.policy.model.EncryptedParts;
import org.apache.wss4j.policy.model.Header;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.util.List;
public class EncryptedPartsBuilder extends SignedPartsBuilder {
@Override
public Assertion build(Element element, AssertionBuilderFactory factory) throws IllegalArgumentException {
final SPConstants.SPVersion spVersion = SPConstants.SPVersion.getSPVersion(element.getNamespaceURI());
boolean body = SPUtils.hasChildElementWithName(element, spVersion.getSPConstants().getBody());
final List<Header> headers = getHeaders(element, true, spVersion);
final Attachments attachments = getAttachments(element, spVersion);
body |= !SPUtils.hasChildElements(element);
EncryptedParts encryptedParts = new EncryptedParts(spVersion, body, attachments, headers);
encryptedParts.setOptional(SPUtils.isOptional(element));
encryptedParts.setIgnorable(SPUtils.isIgnorable(element));
return encryptedParts;
}
@Override
public QName[] getKnownElements() {
return new QName[]{SP13Constants.ENCRYPTED_PARTS, SP11Constants.ENCRYPTED_PARTS};
}
}
| {
"content_hash": "e0a7058d8529239ef056ec14979cfc2c",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 110,
"avg_line_length": 40.282051282051285,
"alnum_prop": 0.7740292807129217,
"repo_name": "apache/wss4j",
"id": "3ca2fc77a6fe2fdabbef59cf3dfe9a1d9c858ab1",
"size": "2373",
"binary": false,
"copies": "5",
"ref": "refs/heads/trunk",
"path": "policy/src/main/java/org/apache/wss4j/policy/builders/EncryptedPartsBuilder.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7415448"
},
{
"name": "Shell",
"bytes": "2519"
},
{
"name": "XSLT",
"bytes": "1265"
}
],
"symlink_target": ""
} |
/**
* Internal STM interface. Contains the interface that an STM has to implement
* for Tanger. The part of the interface that is visible in the application is
* in tanger-stm.h.
*/
#ifndef TANGERSTMINTERNAL_H_
#define TANGERSTMINTERNAL_H_
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/** A transaction descriptor/handle/... */
typedef void tanger_stm_tx_t;
#ifndef TANGER_LOADSTORE_ATTR
/* FIXME: LLVM seems to have a bug when inlining these functions. Check if fixed with newer version. */
//#define TANGER_LOADSTORE_ATTR __attribute__((nothrow,always_inline))
#define TANGER_LOADSTORE_ATTR __attribute__((nothrow,noinline))
#endif
#if defined(__i386__)
/* XXX This is not supported by LLVM yet. */
#define ITM_REGPARM __attribute__((regparm(2)))
#else
#define ITM_REGPARM
#endif
/* Load and store functions access a certain number of bits.
* 1b loads/stores are currently assumed to actually go to full 8 bits.
* Addresses being accessed are not necessarily aligned (e.g., a 16b load
* might target memory address 1). If it is known at compile time that the
* access is aligned, then different functions are called.
*/
uint8_t tanger_stm_load1(tanger_stm_tx_t* tx, uint8_t *addr) TANGER_LOADSTORE_ATTR;
uint8_t tanger_stm_load8(tanger_stm_tx_t* tx, uint8_t *addr) TANGER_LOADSTORE_ATTR;
uint16_t tanger_stm_load16(tanger_stm_tx_t* tx, uint16_t *addr) TANGER_LOADSTORE_ATTR;
uint32_t tanger_stm_load32(tanger_stm_tx_t* tx, uint32_t *addr) TANGER_LOADSTORE_ATTR;
uint64_t tanger_stm_load64(tanger_stm_tx_t* tx, uint64_t *addr) TANGER_LOADSTORE_ATTR;
uint16_t tanger_stm_load16aligned(tanger_stm_tx_t* tx, uint16_t *addr) TANGER_LOADSTORE_ATTR;
uint32_t tanger_stm_load32aligned(tanger_stm_tx_t* tx, uint32_t *addr) TANGER_LOADSTORE_ATTR;
uint64_t tanger_stm_load64aligned(tanger_stm_tx_t* tx, uint64_t *addr) TANGER_LOADSTORE_ATTR;
/** Loads a number of bytes from src and copies them to dest
* src is shared data, dest must point to thread-private data */
void tanger_stm_loadregion(tanger_stm_tx_t* tx, uint8_t *src, uintptr_t bytes, uint8_t *dest);
/** Starts reading a number of bytes from addr.
* Mostly useful for creating wrappers for library functions. Use with care!
* The function returns an address that you can read the data from. Depending
* on the STM algorithm, it might be different from addr or not.
* You must call tanger_stm_loadregionpost after calling this function.
* You must not call any other STM function between the pre and post calls.
* Data read from addr between the two calls is not guaranteed to be a
* consistent snapshot. */
void* tanger_stm_loadregionpre(tanger_stm_tx_t* tx, uint8_t *addr, uintptr_t bytes);
/** See tanger_stm_loadregionpre */
void tanger_stm_loadregionpost(tanger_stm_tx_t* tx, uint8_t *addr, uintptr_t bytes);
/** This is like tanger_stm_loadregionpre() except that it assumes that addr
* points to a zero-terminated string and thus reads all bytes up to and
* including the final zero. It returns the size of the string (including the
* terminating zero) in bytes. The size is guaranteed to be derived from a
* consistent snapshot. If you read the strings' contents, you must call
* tanger_stm_loadregionpost() afterwards.
*/
void* tanger_stm_loadregionstring(tanger_stm_tx_t* tx, char *addr, uintptr_t *bytes);
void tanger_stm_store1(tanger_stm_tx_t* tx, uint8_t *addr, uint8_t value) TANGER_LOADSTORE_ATTR;
void tanger_stm_store8(tanger_stm_tx_t* tx, uint8_t *addr, uint8_t value) TANGER_LOADSTORE_ATTR;
void tanger_stm_store16(tanger_stm_tx_t* tx, uint16_t *addr, uint16_t value) TANGER_LOADSTORE_ATTR;
void tanger_stm_store32(tanger_stm_tx_t* tx, uint32_t *addr, uint32_t value) TANGER_LOADSTORE_ATTR;
void tanger_stm_store64(tanger_stm_tx_t* tx, uint64_t *addr, uint64_t value) TANGER_LOADSTORE_ATTR;
void tanger_stm_store16aligned(tanger_stm_tx_t* tx, uint16_t *addr, uint16_t value) TANGER_LOADSTORE_ATTR;
void tanger_stm_store32aligned(tanger_stm_tx_t* tx, uint32_t *addr, uint32_t value) TANGER_LOADSTORE_ATTR;
void tanger_stm_store64aligned(tanger_stm_tx_t* tx, uint64_t *addr, uint64_t value) TANGER_LOADSTORE_ATTR;
/** Reads a number of bytes from src and writes them to dest
* dest is shared data, src must point to thread-private data */
void tanger_stm_storeregion(tanger_stm_tx_t* tx, uint8_t *src, uintptr_t bytes, uint8_t *dest);
/** Prepares writing a number of bytes to addr.
* The function returns an address that you can write the data to. Depending
* on the STM algorithm, it might be different from addr or not.
* The memory starting at addr does not necessarily contain a consistent
* snapshot or the data previously located at this memory region. */
void* tanger_stm_storeregionpre(tanger_stm_tx_t* tx, uint8_t *addr, uintptr_t bytes);
/** Prepares updating a number of bytes starting at addr.
* The function returns an address that you can write the data to. Depending
* on the STM algorithm, it might be different from addr or not.
* The memory starting at the returned address will contain a consistent
* snapshot of the previous values of the region. */
void* tanger_stm_updateregionpre(tanger_stm_tx_t* tx, uint8_t *addr, uintptr_t bytes);
/**
* Returns the calling thread's transaction descriptor.
* ABI note: Remove this once we have efficient TLS.
*/
tanger_stm_tx_t* tanger_stm_get_tx(void);
/**
* Saves or restores the stack, depending on whether the current txn was
* started or restarted. The STM will save/restore everything in the range
* [low_addr, high_addr). The STM's implementation of this function must be
* marked as no-inline, so it will get a new stack frame that does not
* overlap the [low_addr, high_addr) region.
* To avoid corrupting stack space of rollback functions, the STM should skip
* undoing changes to addresses that are between the current stack pointer
* during execution of the undo function and the [low_addr, high_addr)
* area (i.e., all newer stack frames, including the current one).
*/
void tanger_stm_save_restore_stack(void* low_addr, void* high_addr);
/**
* Replacement function for malloc calls in transactions.
*/
void *tanger_stm_malloc(size_t size);
/**
* Replacement function for free calls in transactions.
*/
void tanger_stm_free(void *ptr);
/**
* Replacement function for calloc calls in transactions.
*/
void *tanger_stm_calloc(size_t nmemb, size_t size);
/**
* Replacement function for realloc calls in transactions.
*/
void *tanger_stm_realloc(void *ptr, size_t size);
/**
* Returns the transactional version of the function passed as argument.
* If no transactional version has been registered, it aborts.
*/
void* tanger_stm_indirect_resolve(void *nontxnal_function);
/**
* Called before transactional versions are registered for nontransactional
* functions.
* The parameter returns the exact number of functions that will be registered.
*/
void tanger_stm_indirect_init(uint32_t number_of_call_targets);
/**
* Registers a transactional versions for a nontransactional function.
*/
void tanger_stm_indirect_register(void* nontxnal, void* txnal);
/* ABI: Additionnal declarations */
void tanger_stm_stack_restorehack();
void tanger_stm_stack_savehack();
//void tanger_stm_threadstack_init();
//void tanger_stm_threadstack_fini();
#ifdef __cplusplus
}
#endif
#endif /*TANGERSTMINTERNAL_H_*/
| {
"content_hash": "e51839089360db046dce67138ba500c8",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 106,
"avg_line_length": 44.951219512195124,
"alnum_prop": 0.7482365708084645,
"repo_name": "nmldiegues/tm-study-pact14",
"id": "9ac406b0a217a81045c53b1590b77309cd6491fb",
"size": "7876",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "TinySTM/abi/dtmc/tanger-stm-internal.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "17408"
},
{
"name": "C",
"bytes": "2876414"
},
{
"name": "C++",
"bytes": "682405"
},
{
"name": "CSS",
"bytes": "21171"
},
{
"name": "HTML",
"bytes": "408497"
},
{
"name": "JavaScript",
"bytes": "2140"
},
{
"name": "Makefile",
"bytes": "51786"
},
{
"name": "Objective-C",
"bytes": "28482"
},
{
"name": "Python",
"bytes": "2533"
},
{
"name": "Shell",
"bytes": "2350"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Mon Nov 28 00:13:26 MST 2016 -->
<title>com.cloudycrew.cloudycar.driversummary</title>
<meta name="date" content="2016-11-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.cloudycrew.cloudycar.driversummary";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/cloudycrew/cloudycar/createrequest/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/cloudycrew/cloudycar/elasticsearch/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/cloudycrew/cloudycar/driversummary/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.cloudycrew.cloudycar.driversummary</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/cloudycrew/cloudycar/driversummary/IDriverSummaryView.html" title="interface in com.cloudycrew.cloudycar.driversummary">IDriverSummaryView</a></td>
<td class="colLast">
<div class="block">Created by George on 2016-11-05.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/cloudycrew/cloudycar/driversummary/DriverSummaryController.html" title="class in com.cloudycrew.cloudycar.driversummary">DriverSummaryController</a></td>
<td class="colLast">
<div class="block">Created by George on 2016-11-05.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/cloudycrew/cloudycar/driversummary/DriverSummaryFragment.html" title="class in com.cloudycrew.cloudycar.driversummary">DriverSummaryFragment</a></td>
<td class="colLast">
<div class="block">Created by George on 2016-11-05.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/cloudycrew/cloudycar/driversummary/DriverSummaryFragment_ViewBinding.html" title="class in com.cloudycrew.cloudycar.driversummary">DriverSummaryFragment_ViewBinding</a><T extends <a href="../../../../com/cloudycrew/cloudycar/driversummary/DriverSummaryFragment.html" title="class in com.cloudycrew.cloudycar.driversummary">DriverSummaryFragment</a>></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/cloudycrew/cloudycar/createrequest/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/cloudycrew/cloudycar/elasticsearch/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/cloudycrew/cloudycar/driversummary/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "991410c6276bb3e4de147131660eb94c",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 406,
"avg_line_length": 38.49112426035503,
"alnum_prop": 0.6564181398923905,
"repo_name": "CMPUT301F16T12/CloudyCar",
"id": "20732428ba0a68f0990e9d62c2ef0fdde2dee8dc",
"size": "6505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/javadoc/com/cloudycrew/cloudycar/driversummary/package-summary.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "323945"
}
],
"symlink_target": ""
} |
# Configurations
Through the `PSFramework` you have a simple method that allows you to ...
- Publish settings
- With onboard documentation
- Input validation
- Scripts that run on change of settings
- That can be discovered and updated by the user
- That can be administrated by policy & DSC
The configuration system is a bit too complex to describe in a help file, you can however visit us at http://psframework.org for detailed guidance.
An example can be seen in the attached ps1 file | {
"content_hash": "9c781fe22a8a0f0644d63cb40599e7ee",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 147,
"avg_line_length": 35.57142857142857,
"alnum_prop": 0.7690763052208835,
"repo_name": "FriedrichWeinmann/PSModuleDevelopment",
"id": "d6c321033be690a9818ea51997e4f6171a758a58",
"size": "500",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "templates/PSFProject/þnameþ/internal/configurations/readme.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "10471"
},
{
"name": "PowerShell",
"bytes": "111772"
}
],
"symlink_target": ""
} |
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef DOCUMENT
#define DOCUMENT
#include "openMVG/cameras/PinholeCamera.hpp"
#include "openMVG/cameras/Camera_IO.hpp"
#include "openMVG/tracks/tracks.hpp"
using namespace openMVG;
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
struct Document
{
std::vector<float> _vec_points;
std::map<size_t, std::vector<size_t> > _map_visibility; //Inth camera see the Inth 3D point
tracks::STLMAPTracks _tracks;
std::map<size_t, PinholeCamera > _map_camera;
std::vector<std::string> _vec_imageNames;
std::map<size_t, std::pair<size_t,size_t> > _map_imageSize;
std::string _sDirectory;
bool load(const std::string & spath)
{
//-- Check if the required file are present.
_sDirectory = spath;
std::string sDirectoryPly = stlplus::folder_append_separator(_sDirectory) + "clouds";
if (stlplus::is_file(stlplus::create_filespec(sDirectoryPly,"visibility","txt"))
&& stlplus::is_file(stlplus::create_filespec(_sDirectory,"views","txt")))
{
// Read visibility file (3Dpoint, NbVisbility, [(imageId, featId); ... )
std::ifstream iFilein(stlplus::create_filespec(sDirectoryPly,"visibility","txt").c_str());
if (iFilein.is_open())
{
size_t trackId = 0;
while (!iFilein.eof())
{
// read one line at a time
std::string temp;
std::getline(iFilein, temp);
std::stringstream sStream(temp);
float pt[3];
sStream >> pt[0] >> pt[1] >> pt[2];
int count;
sStream >> count;
size_t imaId, featId;
for (int i = 0; i < count; ++i)
{
sStream >> imaId >> featId;
_tracks[trackId].insert(std::make_pair(imaId, featId));
_map_visibility[imaId].push_back(trackId); //imaId camera see the point indexed trackId
}
_vec_points.push_back(pt[0]);
_vec_points.push_back(pt[1]);
_vec_points.push_back(pt[2]);
trackId++;
}
}
else
{
std::cerr << "Cannot open the visibility file" << std::endl;
}
}
else
{
std::cerr << "Required file(s) is missing" << std::endl;
}
// Read cameras
const std::string sDirectoryCam = stlplus::folder_append_separator(_sDirectory) + "cameras";
size_t camIndex = 0;
//Read views file
{
std::ifstream iFilein(stlplus::create_filespec(_sDirectory,"views","txt").c_str());
if (iFilein.is_open())
{
std::string temp;
getline(iFilein,temp); //directory name
getline(iFilein,temp); //directory name
size_t nbImages;
iFilein>> nbImages;
while(iFilein.good())
{
getline(iFilein,temp);
if (!temp.empty() && temp.length() > 1)
{
std::stringstream sStream(temp);
std::string sImageName, sCamName;
size_t w,h;
float znear, zfar;
sStream >> sImageName >> w >> h >> sCamName >> znear >> zfar;
// Read the corresponding camera
PinholeCamera cam;
if (!openMVG::load(stlplus::folder_append_separator(sDirectoryCam) + sCamName, cam))
{
std::cerr << "Cannot read camera" << std::endl;
return false;
}
_map_camera[camIndex] = cam;
_vec_imageNames.push_back(sImageName);
_map_imageSize[camIndex] = std::make_pair(w,h);
++camIndex;
}
temp.clear();
}
}
std::cout << "\n Loaded image names : " << std::endl;
std::copy(_vec_imageNames.begin(), _vec_imageNames.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
return !_map_camera.empty();
}
};
#endif //DOCUMENT
| {
"content_hash": "de8f57f931dfd64f90430736a14a9e87",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 117,
"avg_line_length": 32.255639097744364,
"alnum_prop": 0.5634032634032634,
"repo_name": "danylaksono/openMVG",
"id": "cc8a7547e15c9f55da704f3f1411b56d8038dbc4",
"size": "4290",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/software/SfMViewer/document.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "315221"
},
{
"name": "C++",
"bytes": "1650912"
},
{
"name": "CMake",
"bytes": "88473"
},
{
"name": "Objective-C",
"bytes": "3962"
},
{
"name": "Python",
"bytes": "15766"
}
],
"symlink_target": ""
} |
//? include("macros.js");
/**
* Constructs a new ByteBuffer.
* @class The swiss army knife for binary data in JavaScript.
* @exports ByteBuffer
* @constructor
* @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @expose
*/
var ByteBuffer = function(capacity, littleEndian, noAssert) {
if (typeof capacity === 'undefined') capacity = ByteBuffer.DEFAULT_CAPACITY;
if (typeof littleEndian === 'undefined') littleEndian = ByteBuffer.DEFAULT_ENDIAN;
if (typeof noAssert === 'undefined') noAssert = ByteBuffer.DEFAULT_NOASSERT;
if (!noAssert) {
capacity = capacity | 0;
if (capacity < 0)
throw RangeError("Illegal capacity");
littleEndian = !!littleEndian;
noAssert = !!noAssert;
}
//? if (NODE) {
/**
* Backing buffer.
* @type {!Buffer}
* @expose
*/
this.buffer = capacity === 0 ? EMPTY_BUFFER : new Buffer(capacity);
//? } else {
/**
* Backing buffer.
* @type {!ArrayBuffer}
* @expose
*/
this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
//? }
//? if (NODE && BUFFERVIEW) {
/**
* View to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`. This is not
* used internally but may be useful if you need to access its functionality in node as well as the browser.
* @type {?BufferView}
* @expose
* @see https://github.com/dcodeIO/node-BufferView
*/
this.view = capacity === 0 ? null : new BufferView(this.buffer);
//? } else if (!NODE) {
/**
* Data view to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
* @type {?DataView}
* @expose
*/
//? if (DATAVIEW)
this.view = capacity === 0 ? null : new DataView(this.buffer);
//? else
this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
//? }
/**
* Absolute read/write offset.
* @type {number}
* @expose
* @see ByteBuffer#flip
* @see ByteBuffer#clear
*/
this.offset = 0;
/**
* Marked offset.
* @type {number}
* @expose
* @see ByteBuffer#mark
* @see ByteBuffer#reset
*/
this.markedOffset = -1;
/**
* Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
* @type {number}
* @expose
* @see ByteBuffer#flip
* @see ByteBuffer#clear
*/
this.limit = capacity;
/**
* Whether to use little endian byte order, defaults to `false` for big endian.
* @type {boolean}
* @expose
*/
this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : false;
/**
* Whether to skip assertions of offsets and values, defaults to `false`.
* @type {boolean}
* @expose
*/
this.noAssert = !!noAssert;
};
/**
* ByteBuffer version.
* @type {string}
* @const
* @expose
*/
ByteBuffer.VERSION = "/*?= VERSION */";
/**
* Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
* @type {boolean}
* @const
* @expose
*/
ByteBuffer.LITTLE_ENDIAN = true;
/**
* Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
* @type {boolean}
* @const
* @expose
*/
ByteBuffer.BIG_ENDIAN = false;
/**
* Default initial capacity of `16`.
* @type {number}
* @expose
*/
ByteBuffer.DEFAULT_CAPACITY = 16;
/**
* Default endianess of `false` for big endian.
* @type {boolean}
* @expose
*/
ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
/**
* Default no assertions flag of `false`.
* @type {boolean}
* @expose
*/
ByteBuffer.DEFAULT_NOASSERT = false;
//? if (NODE) {
/**
* A `Long` class for representing a 64-bit two's-complement integer value.
* @type {!Long}
* @const
* @see https://npmjs.org/package/long
* @expose
*/
ByteBuffer.Long = Long;
//? } else {
/**
* A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
* and int64 support is not available.
* @type {?Long}
* @const
* @see https://github.com/dcodeIO/Long.js
* @expose
*/
ByteBuffer.Long = Long || null;
//? }
/**
* @alias ByteBuffer.prototype
* @inner
*/
var ByteBufferPrototype = ByteBuffer.prototype;
//? include("helpers.js");
//? include("methods/static/*.js");
//? if (INTS) {
//? include("types/ints/*.js");
//? }
//? if (FLOATS) {
//? include("types/floats/float*.js");
//? }
//? if (VARINTS) {
//? include("types/varints/*.js");
//? }
//? if (UTF8 && STRINGS) {
//? include("types/strings/*.js");
//? }
//? include("methods/*.js");
//? if (ENCODINGS) {
//? include("encodings/*.js");
//? }
| {
"content_hash": "f5afdd004c4c9de8ee56bec06568f489",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 120,
"avg_line_length": 25.818627450980394,
"alnum_prop": 0.5824947788114676,
"repo_name": "allankv/bdq-framework-slides",
"id": "4244f2b106f38ddaac3e569ae3e2321586fdc9c4",
"size": "5267",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "node_modules/bytebuffer/src/ByteBuffer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "198654"
},
{
"name": "HTML",
"bytes": "84799"
},
{
"name": "JavaScript",
"bytes": "415272"
}
],
"symlink_target": ""
} |
export const easings: {
entrance: {
expressive: string;
productive: string;
};
exit: {
expressive: string;
productive: string;
};
standard: {
expressive: string;
productive: string;
};
};
export function motion(name: string, mode: string): string;
export namespace motion {
const prototype: {};
}
| {
"content_hash": "e934bb04471895ca3ccaa92b3018d1a8",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 59,
"avg_line_length": 18.75,
"alnum_prop": 0.5733333333333334,
"repo_name": "georgemarshall/DefinitelyTyped",
"id": "173687d04c08ce74502e25224fb08383f715b8c4",
"size": "626",
"binary": false,
"copies": "63",
"ref": "refs/heads/master",
"path": "types/carbon__motion/index.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16338312"
},
{
"name": "Ruby",
"bytes": "40"
},
{
"name": "Shell",
"bytes": "73"
},
{
"name": "TypeScript",
"bytes": "17728346"
}
],
"symlink_target": ""
} |
package com.canzs.lhjz.util;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
public class BeanUtil {
private static final Logger logger = Logger.getLogger(BeanUtil.class);
public static void copyNotEmptyFields(Object src, Object dest) {
try {
Map<String, String> describe = BeanUtils.describe(src);
for (String name : describe.keySet()) {
try {
if (describe.get(name) != null) {
BeanUtils.setProperty(dest, name, describe.get(name));
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
}
}
}
| {
"content_hash": "f880efa251308833a070cb4c5953508c",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 71,
"avg_line_length": 21.17142857142857,
"alnum_prop": 0.6639676113360324,
"repo_name": "czs/lhjz",
"id": "c0b3a3277100c14082cd62644114bfd16defe082",
"size": "741",
"binary": false,
"copies": "1",
"ref": "refs/heads/ui-new",
"path": "src/main/java/com/canzs/lhjz/util/BeanUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1254803"
},
{
"name": "HTML",
"bytes": "149050"
},
{
"name": "Java",
"bytes": "261941"
},
{
"name": "JavaScript",
"bytes": "1472659"
}
],
"symlink_target": ""
} |
package org.ovirt.engine.api.model;
public enum UsbType {
LEGACY, NATIVE;
public String value() {
return name().toLowerCase();
}
public static UsbType fromValue(String value) {
try {
return valueOf(value.toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
}
| {
"content_hash": "60503aeddeb7d7722d88b84e37576758",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 51,
"avg_line_length": 18.894736842105264,
"alnum_prop": 0.5766016713091922,
"repo_name": "yingyun001/ovirt-engine",
"id": "a545585edd13add736eb7991fd5b5f1b9db2a6ca",
"size": "951",
"binary": false,
"copies": "11",
"ref": "refs/heads/eayunos-4.2",
"path": "backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/model/UsbType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "62308"
},
{
"name": "Groff",
"bytes": "10764"
},
{
"name": "HTML",
"bytes": "16218"
},
{
"name": "Java",
"bytes": "35041045"
},
{
"name": "JavaScript",
"bytes": "70092"
},
{
"name": "Makefile",
"bytes": "24720"
},
{
"name": "PLpgSQL",
"bytes": "795871"
},
{
"name": "Python",
"bytes": "970779"
},
{
"name": "Shell",
"bytes": "163500"
},
{
"name": "XSLT",
"bytes": "54683"
}
],
"symlink_target": ""
} |
SUBDIR= btx boot2 libpc98 loader
.include <bsd.subdir.mk>
| {
"content_hash": "0c992dd6158076c988e6885449d737cb",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 33,
"avg_line_length": 20,
"alnum_prop": 0.75,
"repo_name": "MarginC/kame",
"id": "7c7cf1c796d921382bc5492290468ffd1038a8a4",
"size": "138",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "freebsd4/sys/boot/pc98/Makefile",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arc",
"bytes": "7491"
},
{
"name": "Assembly",
"bytes": "14375563"
},
{
"name": "Awk",
"bytes": "313712"
},
{
"name": "Batchfile",
"bytes": "6819"
},
{
"name": "C",
"bytes": "356715789"
},
{
"name": "C++",
"bytes": "4231647"
},
{
"name": "DIGITAL Command Language",
"bytes": "11155"
},
{
"name": "Emacs Lisp",
"bytes": "790"
},
{
"name": "Forth",
"bytes": "253695"
},
{
"name": "GAP",
"bytes": "9964"
},
{
"name": "Groff",
"bytes": "2220485"
},
{
"name": "Lex",
"bytes": "168376"
},
{
"name": "Logos",
"bytes": "570213"
},
{
"name": "Makefile",
"bytes": "1778847"
},
{
"name": "Mathematica",
"bytes": "16549"
},
{
"name": "Objective-C",
"bytes": "529629"
},
{
"name": "PHP",
"bytes": "11283"
},
{
"name": "Perl",
"bytes": "151251"
},
{
"name": "Perl6",
"bytes": "2572"
},
{
"name": "Ruby",
"bytes": "7283"
},
{
"name": "Scheme",
"bytes": "76872"
},
{
"name": "Shell",
"bytes": "583253"
},
{
"name": "Stata",
"bytes": "408"
},
{
"name": "Yacc",
"bytes": "606054"
}
],
"symlink_target": ""
} |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/* BibSubject.cs --
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using MoonSharp.Interpreter;
#endregion
namespace ManagedIrbis.Metadata.BibFrame
{
class BibSubject
{
}
}
| {
"content_hash": "e69d3996d584fd9307824567c499791e",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 84,
"avg_line_length": 20.551724137931036,
"alnum_prop": 0.6610738255033557,
"repo_name": "amironov73/ManagedIrbis",
"id": "b244d3f477098db1a352b0162aa75987ef379711",
"size": "598",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Classic/Libs/ManagedIrbis/Source/Metadata/BibFrame/BibSubject.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "92910"
},
{
"name": "ASP.NET",
"bytes": "413"
},
{
"name": "Batchfile",
"bytes": "33021"
},
{
"name": "C",
"bytes": "24669"
},
{
"name": "C#",
"bytes": "19567730"
},
{
"name": "CSS",
"bytes": "170"
},
{
"name": "F*",
"bytes": "362819"
},
{
"name": "HTML",
"bytes": "5592"
},
{
"name": "JavaScript",
"bytes": "5342"
},
{
"name": "Pascal",
"bytes": "152697"
},
{
"name": "Shell",
"bytes": "524"
},
{
"name": "Smalltalk",
"bytes": "29356"
},
{
"name": "TeX",
"bytes": "44337"
},
{
"name": "VBA",
"bytes": "46543"
},
{
"name": "Witcher Script",
"bytes": "40165"
}
],
"symlink_target": ""
} |
//// [a.ts]
declare function forwardRef(x: any): any;
declare var Something: any;
@Something({ v: () => Testing123 })
export class Testing123 { }
//// [a.js]
System.register([], function (exports_1, context_1) {
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var Testing123;
var __moduleName = context_1 && context_1.id;
return {
setters: [],
execute: function () {
Testing123 = /** @class */ (() => {
var Testing123_1;
let Testing123 = Testing123_1 = class Testing123 {
};
Testing123 = Testing123_1 = __decorate([
Something({ v: () => Testing123_1 })
], Testing123);
return Testing123;
})();
exports_1("Testing123", Testing123);
}
};
});
| {
"content_hash": "316d83d62416fca4bb1a0fea381237ba",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 154,
"avg_line_length": 43.303030303030305,
"alnum_prop": 0.5157452764170749,
"repo_name": "alexeagle/TypeScript",
"id": "cc26df71f033a9ea38298e283e0de348949b0553",
"size": "1429",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/baselines/reference/decoratedClassExportsSystem2.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3710"
},
{
"name": "JavaScript",
"bytes": "175"
},
{
"name": "PowerShell",
"bytes": "2855"
},
{
"name": "Shell",
"bytes": "47"
},
{
"name": "TypeScript",
"bytes": "91618587"
}
],
"symlink_target": ""
} |
'use strict';
var _ = require('lodash');
var through = require('through2');
var fs = require('fs');
var path = require('path');
var cssTransform = require('./css-transform');
var CleanCSS = require('clean-css');
var defaults = {
'autoInject': true,
'autoInjectOptions': {
'verbose': true
},
'minify': false,
'minifyOptions': {
// Check out a list of CSS minify options at [CleanCSS](https://github.com/jakubpawlowicz/clean-css#how-to-use-clean-css-programmatically).
},
'rebaseUrls': true,
'rootDir': process.cwd()
};
try {
var pkg = JSON.parse(fs.readFileSync(process.cwd() + '/package.json') || '{}');
var options = pkg['browserify-css'] || defaults;
if (typeof options === 'string') {
var base = path.relative(__dirname, process.cwd());
options = require(path.join(base, options)) || defaults;
}
} catch (err) {
options = defaults;
}
options = _.defaults(options, defaults);
module.exports = function(filename, opts) {
if ( ! /\.css$/i.test(filename)) {
return through();
}
var buffer = '';
options = _.extend({}, options, opts);
return through(
function transform(chunk, enc, next) {
buffer += chunk;
next();
},
function flush(done) {
var that = this;
cssTransform.call(this, options, filename, function(data) {
var moduleBody = '';
var rootDir = path.resolve(process.cwd(), options.rootDir);
var relativePath = path.relative(rootDir, path.dirname(filename));
var href = path.join(relativePath, path.basename(filename));
if (options['minify']) {
data = new CleanCSS(options['minifyOptions']).minify(data);
}
if ( ! options['autoInject']) {
moduleBody = 'module.exports = ' + JSON.stringify(data) + ';';
} else {
if (options.autoInjectOptions['verbose']) {
moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify('browserify-css') + ').createStyle(css, { "href": ' + JSON.stringify(href) + '})); module.exports = css;';
} else {
moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify('browserify-css') + ').createStyle(css)); module.exports = css;';
}
}
that.push(moduleBody);
that.push(null);
done();
});
}
);
};
| {
"content_hash": "a8ca03d5e7e85413525c842739a38536",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 212,
"avg_line_length": 33.705128205128204,
"alnum_prop": 0.5290985165462153,
"repo_name": "sufyanAbbasi/gothicVR",
"id": "5b5a5686eab090934ceb90d1b44eb842780fdaf7",
"size": "2629",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "node_modules/browserify-css/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "190"
},
{
"name": "HTML",
"bytes": "863"
},
{
"name": "JavaScript",
"bytes": "8454"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using ZXing.Mobile;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace ZXing.Mobile
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ScanPage : Page, IMobileBarcodeScanner
{
ScanPageNavigationParameters Parameters { get; set; }
public ScanPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// If no parameters were passed, we navigated here for some other reason
// so let's ignore it
if (e.Parameter == null)
return;
Parameters = e.Parameter as ScanPageNavigationParameters;
scannerControl.OnCameraInitialized += ScannerControl_OnCameraInitialized;
scannerControl.OnScannerError += ScannerControl_OnScannerError;
if (Parameters != null)
Parameters.Scanner.ScanPage = this;
scannerControl.TopText = Parameters?.Scanner?.TopText ?? "";
scannerControl.BottomText = Parameters?.Scanner?.BottomText ?? "";
scannerControl.CustomOverlay = Parameters?.Scanner?.CustomOverlay;
scannerControl.UseCustomOverlay = Parameters?.Scanner?.UseCustomOverlay ?? false;
scannerControl.ScanningOptions = Parameters?.Options ?? new MobileBarcodeScanningOptions();
scannerControl.ContinuousScanning = Parameters?.ContinuousScanning ?? false;
scannerControl.StartScanning(Parameters?.ResultHandler, Parameters?.Options);
}
void ScannerControl_OnCameraInitialized()
=> Parameters.CameraInitialized?.Invoke();
void ScannerControl_OnScannerError(IEnumerable<string> errors)
=> Parameters.CameraError?.Invoke(errors);
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
try
{
MobileBarcodeScanner.Log("OnNavigatingFrom, stopping camera...");
await scannerControl.StopScanningAsync();
}
catch (Exception ex)
{
MobileBarcodeScanner.Log("OnNavigatingFrom Error: {0}", ex);
}
base.OnNavigatingFrom(e);
}
#region IMobileBarcodeScanner Implementation
public bool UseCustomOverlay
=> scannerControl.UseCustomOverlay;
public string TopText
{
get => scannerControl.TopText;
set => scannerControl.TopText = value;
}
public string BottomText
{
get => scannerControl.BottomText;
set => scannerControl.BottomText = value;
}
public string CancelButtonText
{
get => string.Empty;
set { }
}
public string FlashButtonText
{
get => string.Empty;
set { }
}
public string CameraUnsupportedMessage
{
get => string.Empty;
set { }
}
public bool IsTorchOn
=> scannerControl.IsTorchOn;
public Task<Result> Scan(MobileBarcodeScanningOptions options)
{
var tcsResult = new TaskCompletionSource<Result>();
scannerControl.ContinuousScanning = false;
scannerControl.StartScanning(r =>
{
scannerControl.StopScanning();
tcsResult.SetResult(r);
}, options ?? Parameters?.Options);
return tcsResult.Task;
}
public Task<Result> Scan()
=> Scan(new MobileBarcodeScanningOptions());
public void ScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler)
{
scannerControl.ContinuousScanning = true;
scannerControl.StartScanning(scanHandler, options ?? Parameters?.Options);
}
public void ScanContinuously(Action<Result> scanHandler)
=> ScanContinuously(new MobileBarcodeScanningOptions(), scanHandler);
public void Cancel()
=> scannerControl?.Cancel();
public void Torch(bool on)
=> scannerControl?.Torch(on);
public void AutoFocus()
=> scannerControl?.AutoFocus();
public void ToggleTorch()
=> scannerControl?.ToggleTorch();
public void PauseAnalysis()
=> scannerControl?.PauseAnalysis();
public void ResumeAnalysis()
=> scannerControl?.ResumeAnalysis();
#endregion
}
public class ScanPageNavigationParameters
{
public MobileBarcodeScanner Scanner { get; set; }
public bool ContinuousScanning { get; set; }
public MobileBarcodeScanningOptions Options { get; set; }
public Action<ZXing.Result> ResultHandler { get; set; }
public Action CameraInitialized { get; set; }
public Action<IEnumerable<string>> CameraError { get; set; }
}
}
| {
"content_hash": "41c6f0cfc9dea65e2ebe22e5782da36e",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 96,
"avg_line_length": 26.62146892655367,
"alnum_prop": 0.7398132427843803,
"repo_name": "Redth/ZXing.Net.Mobile",
"id": "f9f17310d0886d82ae1d7b8b75bb8cc9e3c4e509",
"size": "4714",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ZXing.Net.Mobile/ScanPage.xaml.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "235063"
}
],
"symlink_target": ""
} |
package com.marshalchen.common.uimodule.smoothswitch;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ListView;
/**
*
* @author Dean.Ding
*
*/
public class SwitchAnimationUtil {
private int mOrderIndex = 0;
private int mDelay = 100;
private int mDuration = 300;
public SwitchAnimationUtil() {
}
public void startAnimation(View root, AnimationType type) {
ViewUtils.init(root.getContext());
bindAnimation(root, 0, type);
}
private void bindAnimation(View view, int depth, AnimationType type) {
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
if (type == AnimationType.HORIZON_CROSS) {
/*
* Something wrong with it... Fixing
*/
for (int i = 0; i < group.getChildCount(); i++) {
bindAnimation(group.getChildAt(i), depth + 1,
i % 2 == 0 ? AnimationType.HORIZION_LEFT
: AnimationType.HORIZION_RIGHT);
}
} else {
for (int i = 0; i < group.getChildCount(); i++) {
bindAnimation(group.getChildAt(i), depth + 1, type);
}
}
} else {
runAnimation(view, mDelay * mOrderIndex, type);
mOrderIndex++;
}
}
private void runAnimation(View view, long delay, AnimationType type) {
switch (type) {
case ROTATE:
runRotateAnimation(view, delay);
break;
case ALPHA:
runAlphaAnimation(view, delay);
break;
case HORIZION_LEFT:
runHorizonLeftAnimation(view, delay);
break;
case HORIZION_RIGHT:
runHorizonRightAnimation(view, delay);
break;
case HORIZON_CROSS:
// NOT SUPPORT NOW
// May be something for List
break;
case SCALE:
runScaleAnimation(view, delay);
break;
case FLIP_HORIZON:
runFlipHorizonAnimation(view, delay);
break;
case FLIP_VERTICAL:
runFlipVertialAnimation(view, delay);
break;
default:
break;
}
}
private void runHorizonLeftAnimation(View view, long delay) {
view.setAlpha(0);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view,
"translationX", -ViewUtils.getScreenWidth(), 0);
objectAnimator.setInterpolator(new LinearInterpolator());
ObjectAnimator objectAnimatorAlpha = ObjectAnimator.ofFloat(view,
"alpha", 0f, 1f);
AnimatorSet set = new AnimatorSet();
set.setDuration(mDuration);
set.setStartDelay(delay);
set.playTogether(objectAnimator, objectAnimatorAlpha);
set.start();
}
private void runHorizonRightAnimation(View view, long delay) {
view.setAlpha(0);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view,
"translationX", ViewUtils.getScreenWidth(), 0);
objectAnimator.setInterpolator(new LinearInterpolator());
ObjectAnimator objectAnimatorAlpha = ObjectAnimator.ofFloat(view,
"alpha", 0f, 1f);
AnimatorSet set = new AnimatorSet();
set.setStartDelay(delay);
set.setDuration(mDuration);
set.playTogether(objectAnimator, objectAnimatorAlpha);
set.start();
}
private void runAlphaAnimation(View view, long delay) {
view.setAlpha(0);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "alpha",
0, 1);
objectAnimator.setStartDelay(delay);
objectAnimator.setDuration(mDuration);
objectAnimator.setInterpolator(new LinearInterpolator());
objectAnimator.start();
}
private void runRotateAnimation(View view, long delay) {
view.setAlpha(0);
AnimatorSet set = new AnimatorSet();
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view,
"rotation", 0f, 360f);
ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(view, "scaleX",
0f, 1f);
ObjectAnimator objectAnimator3 = ObjectAnimator.ofFloat(view, "scaleY",
0f, 1f);
ObjectAnimator objectAnimator4 = ObjectAnimator.ofFloat(view, "alpha",
0f, 1f);
objectAnimator2.setInterpolator(new AccelerateInterpolator(1.0f));
objectAnimator3.setInterpolator(new AccelerateInterpolator(1.0f));
set.setDuration(mDuration);
set.playTogether(objectAnimator, objectAnimator2, objectAnimator3,
objectAnimator4);
set.setStartDelay(delay);
set.start();
}
private void runScaleAnimation(View view, long delay) {
view.setAlpha(0);
AnimatorSet set = new AnimatorSet();
ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(view, "scaleX",
0f, 1f);
ObjectAnimator objectAnimator3 = ObjectAnimator.ofFloat(view, "scaleY",
0f, 1f);
ObjectAnimator objectAnimator4 = ObjectAnimator.ofFloat(view, "alpha",
0f, 1f);
set.setDuration(mDuration);
set.playTogether(objectAnimator2, objectAnimator3, objectAnimator4);
set.setStartDelay(delay);
set.start();
}
private void runFlipVertialAnimation(View view, long delay) {
view.setAlpha(0);
AnimatorSet set = new AnimatorSet();
ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(view,
"rotationX", -180f, 0f);
ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(view, "alpha",
0f, 1f);
set.setDuration(mDuration);
set.playTogether(objectAnimator1, objectAnimator2);
set.setStartDelay(delay);
set.start();
}
private void runFlipHorizonAnimation(View view, long delay) {
view.setAlpha(0);
AnimatorSet set = new AnimatorSet();
ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(view,
"rotationY", -180f, 0f);
ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(view, "alpha",
0f, 1f);
set.setDuration(mDuration);
set.playTogether(objectAnimator1, objectAnimator2);
set.setStartDelay(delay);
set.start();
}
public enum AnimationType {
ALPHA, ROTATE, HORIZION_LEFT, HORIZION_RIGHT, HORIZON_CROSS, SCALE, FLIP_HORIZON, FLIP_VERTICAL
}
}
| {
"content_hash": "f3ef713e324626ad076da418c0674319",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 97,
"avg_line_length": 29.412371134020617,
"alnum_prop": 0.7318611987381703,
"repo_name": "apkdemo/UltimateAndroid",
"id": "f4bdd91ef30742f063d986c3b986283dbd68da4a",
"size": "5706",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "UltimateAndroidGradle/ultimateandroidui/src/main/java/com/marshalchen/common/uimodule/smoothswitch/SwitchAnimationUtil.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "14297296"
}
],
"symlink_target": ""
} |
<script src="<?php echo ResURL('ckeditor'); ?>/ckeditor.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
// thay đổi anh theo khi chọn 1 ảnh mới
$('#anh').change(function(event) {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
});
</script>
<style type="text/css">
#img{
height: auto;width: 100%;
max-height:500px;
max-width: 500px;
}
</style>
<div class="row">
<div class="col-md-12 panel">
<div class="panel-heading">
<h2>Thêm Sản Phẩm Mới</h2>
</div>
<div class="panel-body jumbotron">
<?php $this->load->view('errors/msg') ?>
<?php echo form_open_multipart(base_url('sanpham/addsp')); ?>
<div class="col-md-6">
<?php echo form_error('sp_name'); ?>
<div class="input-group">
<span class="input-group-addon">Tên Sản Phẩm :</span>
<input type="text" name="sp_name" class="form-control" required placeholder="Nhập Tên Của Sản Phẩm" value="<?php echo set_value('sp_name'); ?>">
</div>
<?php echo form_error('sp_price'); ?>
<div class="input-group">
<span class="input-group-addon">Giá Sản Phẩm :</span>
<input type="number" name="sp_price" class="form-control" required placeholder="Đơn Giá Sản Phẩm" min="0" value="<?php echo set_value('sp_price'); ?>"> <span class="input-group-addon">VND</span>
</div>
<?php echo form_error('cat_id') ?>
<div class="input-group">
<span class="input-group-addon">Danh Mục : </span>
<select name="cat_id" class="form-control">
<?php
foreach ($catlist as $cat) {
echo '<option value="'.$cat['cat_id'].'"';
if($cat['cat_id'] == set_value('cat_id')){
echo "selected";
}
echo '>'.$cat['cat_name'].'</option>';
}
?>
</select>
</div>
<?php echo form_error('sp_features') ?>
<div class="input-group">
<span class="input-group-addon">Đặc Biệt :</span>
<select name="sp_features" class="form-control">
<option value="1" <?php
if(set_value('sp_features') == 1) echo "selected";
?>>Mới</option>
<option value="2" <?php
if(set_value('sp_features') == 2) echo "selected";
?>>Khuyến Mại</option>
<option value="3" <?php
if(set_value('sp_features') == 3) echo "selected";
?>>Mua Nhiều</option>
<option value="4" <?php
if((set_value('sp_features') == null) OR (set_value('sp_features') == 4) ) echo "selected";
?>>Phổ Biến</option>
</select>
</div>
<?php echo form_error('sp_quality') ?>
<div class="input-group">
<span class="input-group-addon">Số Lượng :</span>
<input type="number" name="sp_quality" class="form-control" placeholder="Số Lượng Sản Phẩm" min="0" value="<?php echo set_value('sp_quality'); ?>">
<span class="input-group-addon"> Sản Phẩm</span>
</div>
<?php echo form_error('sp_title') ?>
<div class="input-group">
<span class="input-group-addon">Slug :</span>
<input type="text" name="sp_title" class="form-control" placeholder="Bỏ Trống nếu để slug mặc định" value="<?php echo set_value('sp_title'); ?>">
</div>
<?php echo form_error('sp_img') ?>
<div class="input-group">
<span class="input-group-addon">Ảnh : </span>
<input type="file" name="sp_img" class="form-control btn btn-info" id="anh"> <span class="input-group-addon text-primary">gif|jpg|png|jpeg</span>
</div>
</div>
<div class="col-md-6">
<div class="img-responsive">
<img src="<?php echo ResURL('upload/').'defaul.jpg'; ?>" alt="Ảnh Mô Tả" class="img img-rounded img-responsive" height="260" id="img" >
</div>
</div>
<div class="col-md-12">
<?php echo form_error('sp_content') ?>
<div class="well well-lg">
<textarea id="editor" name="sp_content"><?php echo set_value('sp_content'); ?></textarea>
<script>
CKEDITOR.replace( 'editor' );
</script>
</div>
</div>
<div class="clearfix"></div>
<input type="submit" name="submit" class="form-control btn btn-primary" value="Thêm Sản Phẩm Mới">
<?php echo form_close(); ?>
</div>
</div>
</div> | {
"content_hash": "6c3acae430c8296d70f3c65ca5221f82",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 199,
"avg_line_length": 38.078947368421055,
"alnum_prop": 0.5765952545496429,
"repo_name": "phamdoanw/web",
"id": "97f70c73c17db70b4ea7ce6e28cd23020460a4a4",
"size": "4448",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/admin/views/SP_add.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "820"
},
{
"name": "CSS",
"bytes": "288444"
},
{
"name": "HTML",
"bytes": "219054"
},
{
"name": "JavaScript",
"bytes": "48156"
},
{
"name": "PHP",
"bytes": "3125334"
}
],
"symlink_target": ""
} |
{% extends "project/base.html" %}
{% set page_title = _("Diff") %}
{% block pnav %}
{% from 'project/macros.html' import nav with context%}
{{ nav('upstream') }}
{% endblock %}
{% block pbody %}
{% from 'project/macros.html' import subnav_git with context%}
{{ subnav_git('diff') }}
<h3>{{ _("Changes between <a href='%(url_left)s'>%(left)s</a> and <a href='%(url_right)s'>%(right)s</a>", url_left=url_for('project.ufiles', project_id = project.id, revision=left), left=left, url_right=url_for('project.ufiles', project_id = project.id, revision=right), right=right) }}</h3>
{% for f in diff.keys() %}
<h4>{{ f }}</h4>
<table class="diff">{{ diff[f]|safe }}</table>
{% endfor %}
{% endblock %}
| {
"content_hash": "a09b0b08cc7400a650a5dd8a33b26862",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 291,
"avg_line_length": 33.333333333333336,
"alnum_prop": 0.6157142857142858,
"repo_name": "vitalyvolkov/fontbakery",
"id": "fd7861705596b898a31ba407ad041a41d40dc793",
"size": "700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bakery/templates/project/diff.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8114"
},
{
"name": "JavaScript",
"bytes": "6468"
},
{
"name": "Python",
"bytes": "312438"
},
{
"name": "Shell",
"bytes": "234"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "cc9558f79e7abc25b9db782ee7809e16",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "4455f680f0b16de7a48ea7a571d7ac03bdfc1f11",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Sommerfeltia spinulosa/ Syn. Conyza spinulosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<resources>
<string name="app_name">Pdfium Demo</string>
<string name="menu_pdf_files">PDF Files</string>
<string name="menu_presentation">Presentation</string>
<string name="menu_taxes">IRS 1040A</string>
<string name="menu_open">Picker</string>
</resources>
| {
"content_hash": "1d01cfe83a06f0ad1199cf6cd6809999",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 56,
"avg_line_length": 38.57142857142857,
"alnum_prop": 0.7185185185185186,
"repo_name": "commonsguy/cw-omnibus",
"id": "95e2d77042b2e8f69d7e4c4358617763abbbae86",
"size": "270",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "PDF/Pdfium/app/src/main/res/values/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54274"
},
{
"name": "Groovy",
"bytes": "4601"
},
{
"name": "HTML",
"bytes": "2293656"
},
{
"name": "Java",
"bytes": "3404604"
},
{
"name": "JavaScript",
"bytes": "646239"
},
{
"name": "Kotlin",
"bytes": "7397"
},
{
"name": "Python",
"bytes": "546"
},
{
"name": "Ruby",
"bytes": "2071"
},
{
"name": "Shell",
"bytes": "1020"
}
],
"symlink_target": ""
} |
This application makes use of the following third party libraries:
## Cache
Licensed under the **MIT** license
> Copyright (c) 2015 Hyper Interaktiv AS
>
> Permission is hereby granted, free of charge, to any person obtaining
> a copy of this software and associated documentation files (the
> "Software"), to deal in the Software without restriction, including
> without limitation the rights to use, copy, modify, merge, publish,
> distribute, sublicense, and/or sell copies of the Software, and to
> permit persons to whom the Software is furnished to do so, subject to
> the following conditions:
>
> The above copyright notice and this permission notice shall be
> included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## MGSwipeTableCell
The MIT License (MIT)
Copyright (c) 2018 Imanol Fernandez @MortimerGoro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## Result
The MIT License (MIT)
Copyright (c) 2014 Rob Rix
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## SugarRecord
Copyright (c) 2016 SugarRecord
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## SwiftyJSON
The MIT License (MIT)
Copyright (c) 2017 Ruoyu Fu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Generated by CocoaPods - https://cocoapods.org
| {
"content_hash": "022444c98fa5d015f315c14fd46650aa",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 78,
"avg_line_length": 43.37692307692308,
"alnum_prop": 0.7949991133179641,
"repo_name": "TonnyTao/Acornote",
"id": "f77ccb4585a3d4440d20ebe96db8078c7e96cd6a",
"size": "5658",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Acornote_iOS/Pods/Target Support Files/Pods-Acornote/Pods-Acornote-acknowledgements.markdown",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "564"
},
{
"name": "Kotlin",
"bytes": "33000"
},
{
"name": "Ruby",
"bytes": "559"
},
{
"name": "Swift",
"bytes": "154834"
}
],
"symlink_target": ""
} |
namespace web_view {
class NavigationControllerDelegate {
public:
virtual ~NavigationControllerDelegate() {}
// Called when the navigation controller starts a navigation.
//
// TODO(erg): This should be removed and most of the PendingWebViewLoad logic
// should be moved to NavigationEntry and/or NavigationController.
virtual void OnNavigate(mojo::URLRequestPtr request) = 0;
// Notification that blink has committed a pending load.
virtual void OnDidNavigate() = 0;
};
} // namespace web_view
#endif // COMPONENTS_WEB_VIEW_NAVIGATION_CONTROLLER_DELEGATE_H_
| {
"content_hash": "44a7fe1ad9c5e146560a3294da397dd0",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 79,
"avg_line_length": 30.68421052631579,
"alnum_prop": 0.7530017152658662,
"repo_name": "joone/chromium-crosswalk",
"id": "51c4662d2182c6aa3402959624b30bb9bd20743c",
"size": "874",
"binary": false,
"copies": "8",
"ref": "refs/heads/2016.04.css-round-display-edtior-draft-1",
"path": "components/web_view/navigation_controller_delegate.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package fsrepo
import (
"fmt"
"path"
ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore"
"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore/flatfs"
levelds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore/leveldb"
"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore/measure"
mount "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore/syncmount"
ldbopts "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt"
repo "github.com/ipfs/go-ipfs/repo"
config "github.com/ipfs/go-ipfs/repo/config"
"github.com/ipfs/go-ipfs/thirdparty/dir"
)
const (
leveldbDirectory = "datastore"
flatfsDirectory = "blocks"
)
func openDefaultDatastore(r *FSRepo) (repo.Datastore, error) {
leveldbPath := path.Join(r.path, leveldbDirectory)
// save leveldb reference so it can be neatly closed afterward
leveldbDS, err := levelds.NewDatastore(leveldbPath, &levelds.Options{
Compression: ldbopts.NoCompression,
})
if err != nil {
return nil, fmt.Errorf("unable to open leveldb datastore: %v", err)
}
// 4TB of 256kB objects ~=17M objects, splitting that 256-way
// leads to ~66k objects per dir, splitting 256*256-way leads to
// only 256.
//
// The keys seen by the block store have predictable prefixes,
// including "/" from datastore.Key and 2 bytes from multihash. To
// reach a uniform 256-way split, we need approximately 4 bytes of
// prefix.
syncfs := !r.config.Datastore.NoSync
blocksDS, err := flatfs.New(path.Join(r.path, flatfsDirectory), 4, syncfs)
if err != nil {
return nil, fmt.Errorf("unable to open flatfs datastore: %v", err)
}
// Add our PeerID to metrics paths to keep them unique
//
// As some tests just pass a zero-value Config to fsrepo.Init,
// cope with missing PeerID.
id := r.config.Identity.PeerID
if id == "" {
// the tests pass in a zero Config; cope with it
id = fmt.Sprintf("uninitialized_%p", r)
}
prefix := "fsrepo." + id + ".datastore."
metricsBlocks := measure.New(prefix+"blocks", blocksDS)
metricsLevelDB := measure.New(prefix+"leveldb", leveldbDS)
mountDS := mount.New([]mount.Mount{
{
Prefix: ds.NewKey("/blocks"),
Datastore: metricsBlocks,
},
{
Prefix: ds.NewKey("/"),
Datastore: metricsLevelDB,
},
})
return mountDS, nil
}
func initDefaultDatastore(repoPath string, conf *config.Config) error {
// The actual datastore contents are initialized lazily when Opened.
// During Init, we merely check that the directory is writeable.
leveldbPath := path.Join(repoPath, leveldbDirectory)
if err := dir.Writable(leveldbPath); err != nil {
return fmt.Errorf("datastore: %s", err)
}
flatfsPath := path.Join(repoPath, flatfsDirectory)
if err := dir.Writable(flatfsPath); err != nil {
return fmt.Errorf("datastore: %s", err)
}
return nil
}
| {
"content_hash": "66283eb9e60c451529ae8cccfaeee2d6",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 96,
"avg_line_length": 33.44827586206897,
"alnum_prop": 0.7171821305841924,
"repo_name": "palkeo/go-ipfs",
"id": "c9fef0f122ab46af07caa7f1b437f6d4f173bf37",
"size": "2910",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "repo/fsrepo/defaultds.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "1253647"
},
{
"name": "Makefile",
"bytes": "10411"
},
{
"name": "Protocol Buffer",
"bytes": "4707"
},
{
"name": "PureBasic",
"bytes": "29"
},
{
"name": "Python",
"bytes": "788"
},
{
"name": "Shell",
"bytes": "161725"
}
],
"symlink_target": ""
} |
package com.switchfly.inputvalidation.sanitizer;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LocaleCodeSanitizerTest {
@Test
public void testExecute() throws Exception {
LocaleCodeSanitizer localeCodeSanitizer = new LocaleCodeSanitizer();
assertEquals("en_US", localeCodeSanitizer.execute("en_US"));
assertEquals("en", localeCodeSanitizer.execute("en"));
assertEquals("fr_FR", localeCodeSanitizer.execute("fr_FR"));
assertEquals("en_US", localeCodeSanitizer.execute("foo"));
assertEquals("en_US", localeCodeSanitizer.execute("<script>"));
assertEquals("", localeCodeSanitizer.execute(""));
assertEquals(" ", localeCodeSanitizer.execute(" "));
assertEquals(null, localeCodeSanitizer.execute(null));
}
}
| {
"content_hash": "4b8433cfd13808ad2e89de377ed49bac",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 76,
"avg_line_length": 34.583333333333336,
"alnum_prop": 0.7012048192771084,
"repo_name": "switchfly/switchfly-java",
"id": "194c5e1fb31e65adcaf7ecbe0f8f2c77b1bf9381",
"size": "1422",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "inputvalidation/src/test/java/com/switchfly/inputvalidation/sanitizer/LocaleCodeSanitizerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "179045"
},
{
"name": "JavaScript",
"bytes": "68280"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>nxt.crypto Class Hierarchy</title>
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="nxt.crypto Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../nxt/package-tree.html">Prev</a></li>
<li><a href="../../nxt/http/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?nxt/crypto/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package nxt.crypto</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">nxt.crypto.<a href="../../nxt/crypto/Crypto.html" title="class in nxt.crypto"><span class="strong">Crypto</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../nxt/package-tree.html">Prev</a></li>
<li><a href="../../nxt/http/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?nxt/crypto/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "e46ae4b4b8b0d11cbfed99e6ae0ab4d7",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 139,
"avg_line_length": 31.653225806451612,
"alnum_prop": 0.6175796178343949,
"repo_name": "stevedoe/nxt-client",
"id": "e2e9828d08fa95feb51c61098e1753a67b9547ce",
"size": "3925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "html/doc/nxt/crypto/package-tree.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "Java",
"bytes": "599969"
},
{
"name": "JavaScript",
"bytes": "6382"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d7094b9986a0e440c477b57213b8c78f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "ed873b6199b9d709289a2a8f76511b62e5a77765",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Phyllanthus/Phyllanthus sauropodoides/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
HDL-xLibCores
=============
HDL x-library of IP Cores
External tools and libraries
----------------------------
* CMake 2.8.10
* Verilator 3.862
* SystemC 2.3.1
* Google C++ Testing Framework gtest-1.7.0
* Doxverilog 2.8 (patched Doxygen 1.8.5 for verilog)
Build
-----
To build all modules in Linux:
mkdir build
cd build
cmake ..
make
To clean workspace:
make clean
Test
----
Library use unit testing and testbenches to valid correct module behavior.
Run all test on Linux after doing build step:
make test
To run particular test e.g. on Fifo module:
./tests/hdl/ipc/test_ipc_fifo
Documentation
-------------
To generate documentation for verilog modules:
doxverilog Doxverilog.cfg
| {
"content_hash": "1c1395c8bd1eda9351e81d7f461b38e7",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 74,
"avg_line_length": 15.869565217391305,
"alnum_prop": 0.6589041095890411,
"repo_name": "tymonx/hdl-xlibcores",
"id": "304c1ff595a4f094842898ac096e178ef49304f4",
"size": "730",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "3547"
},
{
"name": "Verilog",
"bytes": "5219"
}
],
"symlink_target": ""
} |
* Latest features on master...
## v1.1.0 - May 24, 2013 - [view commits](https://github.com/lotaris/REPO_NAME/compare/v1.0.0...v1.1.0)
* **BREAKING!** API no longer does that. (Jane Doe)
* This now does that. (John Smith)
* Added a feature that... (John Doe)
* Fixed a bug where... (John Doe)
## v1.0.0 - March 4, 2013
* First prototype.
| {
"content_hash": "08adb5d207e934422aeb334535e11f95",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 103,
"avg_line_length": 23,
"alnum_prop": 0.6405797101449275,
"repo_name": "lotaris/open-source-template",
"id": "907ecb022bb511be48984d5698de597c5011cde7",
"size": "367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package io.undertow.server.protocol.http;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import io.undertow.UndertowMessages;
import io.undertow.UndertowOptions;
import io.undertow.annotationprocessor.HttpParserConfig;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import io.undertow.util.Protocols;
import io.undertow.util.URLUtils;
import org.xnio.OptionMap;
import static io.undertow.util.Headers.ACCEPT_CHARSET_STRING;
import static io.undertow.util.Headers.ACCEPT_ENCODING_STRING;
import static io.undertow.util.Headers.ACCEPT_LANGUAGE_STRING;
import static io.undertow.util.Headers.ACCEPT_RANGES_STRING;
import static io.undertow.util.Headers.ACCEPT_STRING;
import static io.undertow.util.Headers.AUTHORIZATION_STRING;
import static io.undertow.util.Headers.CACHE_CONTROL_STRING;
import static io.undertow.util.Headers.CONNECTION_STRING;
import static io.undertow.util.Headers.CONTENT_LENGTH_STRING;
import static io.undertow.util.Headers.CONTENT_TYPE_STRING;
import static io.undertow.util.Headers.COOKIE_STRING;
import static io.undertow.util.Headers.EXPECT_STRING;
import static io.undertow.util.Headers.FROM_STRING;
import static io.undertow.util.Headers.HOST_STRING;
import static io.undertow.util.Headers.IF_MATCH_STRING;
import static io.undertow.util.Headers.IF_MODIFIED_SINCE_STRING;
import static io.undertow.util.Headers.IF_NONE_MATCH_STRING;
import static io.undertow.util.Headers.IF_RANGE_STRING;
import static io.undertow.util.Headers.IF_UNMODIFIED_SINCE_STRING;
import static io.undertow.util.Headers.MAX_FORWARDS_STRING;
import static io.undertow.util.Headers.ORIGIN_STRING;
import static io.undertow.util.Headers.PRAGMA_STRING;
import static io.undertow.util.Headers.PROXY_AUTHORIZATION_STRING;
import static io.undertow.util.Headers.RANGE_STRING;
import static io.undertow.util.Headers.REFERER_STRING;
import static io.undertow.util.Headers.REFRESH_STRING;
import static io.undertow.util.Headers.SEC_WEB_SOCKET_KEY_STRING;
import static io.undertow.util.Headers.SEC_WEB_SOCKET_VERSION_STRING;
import static io.undertow.util.Headers.SERVER_STRING;
import static io.undertow.util.Headers.SSL_CIPHER_STRING;
import static io.undertow.util.Headers.SSL_CIPHER_USEKEYSIZE_STRING;
import static io.undertow.util.Headers.SSL_CLIENT_CERT_STRING;
import static io.undertow.util.Headers.SSL_SESSION_ID_STRING;
import static io.undertow.util.Headers.STRICT_TRANSPORT_SECURITY_STRING;
import static io.undertow.util.Headers.TRAILER_STRING;
import static io.undertow.util.Headers.TRANSFER_ENCODING_STRING;
import static io.undertow.util.Headers.UPGRADE_STRING;
import static io.undertow.util.Headers.USER_AGENT_STRING;
import static io.undertow.util.Headers.VIA_STRING;
import static io.undertow.util.Headers.WARNING_STRING;
import static io.undertow.util.Methods.CONNECT_STRING;
import static io.undertow.util.Methods.DELETE_STRING;
import static io.undertow.util.Methods.GET_STRING;
import static io.undertow.util.Methods.HEAD_STRING;
import static io.undertow.util.Methods.OPTIONS_STRING;
import static io.undertow.util.Methods.POST_STRING;
import static io.undertow.util.Methods.PUT_STRING;
import static io.undertow.util.Methods.TRACE_STRING;
import static io.undertow.util.Protocols.HTTP_0_9_STRING;
import static io.undertow.util.Protocols.HTTP_1_0_STRING;
import static io.undertow.util.Protocols.HTTP_1_1_STRING;
import static io.undertow.util.Protocols.HTTP_2_0_STRING;
/**
* The basic HTTP parser. The actual parser is a sub class of this class that is generated as part of
* the build process by the {@link io.undertow.annotationprocessor.AbstractParserGenerator} annotation processor.
* <p>
* The actual processor is a state machine, that means that for common header, method, protocol values
* it will return an interned string, rather than creating a new string for each one.
* <p>
*
* @author Stuart Douglas
*/
@HttpParserConfig(methods = {
OPTIONS_STRING,
GET_STRING,
HEAD_STRING,
POST_STRING,
PUT_STRING,
DELETE_STRING,
TRACE_STRING,
CONNECT_STRING},
protocols = {
HTTP_0_9_STRING, HTTP_1_0_STRING, HTTP_1_1_STRING, HTTP_2_0_STRING
},
headers = {
ACCEPT_STRING,
ACCEPT_CHARSET_STRING,
ACCEPT_ENCODING_STRING,
ACCEPT_LANGUAGE_STRING,
ACCEPT_RANGES_STRING,
AUTHORIZATION_STRING,
CACHE_CONTROL_STRING,
COOKIE_STRING,
CONNECTION_STRING,
CONTENT_LENGTH_STRING,
CONTENT_TYPE_STRING,
EXPECT_STRING,
FROM_STRING,
HOST_STRING,
IF_MATCH_STRING,
IF_MODIFIED_SINCE_STRING,
IF_NONE_MATCH_STRING,
IF_RANGE_STRING,
IF_UNMODIFIED_SINCE_STRING,
MAX_FORWARDS_STRING,
ORIGIN_STRING,
PRAGMA_STRING,
PROXY_AUTHORIZATION_STRING,
RANGE_STRING,
REFERER_STRING,
REFRESH_STRING,
SEC_WEB_SOCKET_KEY_STRING,
SEC_WEB_SOCKET_VERSION_STRING,
SERVER_STRING,
SSL_CLIENT_CERT_STRING,
SSL_CIPHER_STRING,
SSL_SESSION_ID_STRING,
SSL_CIPHER_USEKEYSIZE_STRING,
STRICT_TRANSPORT_SECURITY_STRING,
TRAILER_STRING,
TRANSFER_ENCODING_STRING,
UPGRADE_STRING,
USER_AGENT_STRING,
VIA_STRING,
WARNING_STRING
})
public abstract class HttpRequestParser {
private static final byte[] HTTP;
public static final int HTTP_LENGTH;
private final int maxParameters;
private final int maxHeaders;
private final boolean allowEncodedSlash;
private final boolean decode;
private final String charset;
static {
try {
HTTP = "HTTP/1.".getBytes("ASCII");
HTTP_LENGTH = HTTP.length;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public HttpRequestParser(OptionMap options) {
maxParameters = options.get(UndertowOptions.MAX_PARAMETERS, UndertowOptions.DEFAULT_MAX_PARAMETERS);
maxHeaders = options.get(UndertowOptions.MAX_HEADERS, UndertowOptions.DEFAULT_MAX_HEADERS);
allowEncodedSlash = options.get(UndertowOptions.ALLOW_ENCODED_SLASH, false);
decode = options.get(UndertowOptions.DECODE_URL, true);
charset = options.get(UndertowOptions.URL_CHARSET, StandardCharsets.UTF_8.name());
}
public static final HttpRequestParser instance(final OptionMap options) {
try {
final Class<?> cls = Class.forName(HttpRequestParser.class.getName() + "$$generated", false, HttpRequestParser.class.getClassLoader());
Constructor<?> ctor = cls.getConstructor(OptionMap.class);
return (HttpRequestParser) ctor.newInstance(options);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void handle(ByteBuffer buffer, final ParseState currentState, final HttpServerExchange builder) throws BadRequestException {
if (currentState.state == ParseState.VERB) {
//fast path, we assume that it will parse fully so we avoid all the if statements
//fast path HTTP GET requests, basically just assume all requests are get
//and fall out to the state machine if it is not
final int position = buffer.position();
if (buffer.remaining() > 3
&& buffer.get(position) == 'G'
&& buffer.get(position + 1) == 'E'
&& buffer.get(position + 2) == 'T'
&& buffer.get(position + 3) == ' ') {
buffer.position(position + 4);
builder.setRequestMethod(Methods.GET);
currentState.state = ParseState.PATH;
} else {
handleHttpVerb(buffer, currentState, builder);
}
handlePath(buffer, currentState, builder);
boolean failed = false;
if (buffer.remaining() > HTTP_LENGTH + 3) {
int pos = buffer.position();
for (int i = 0; i < HTTP_LENGTH; ++i) {
if (HTTP[i] != buffer.get(pos + i)) {
failed = true;
break;
}
}
if (!failed) {
final byte b = buffer.get(pos + HTTP_LENGTH);
final byte b2 = buffer.get(pos + HTTP_LENGTH + 1);
final byte b3 = buffer.get(pos + HTTP_LENGTH + 2);
if (b2 == '\r' && b3 == '\n') {
if (b == '1') {
builder.setProtocol(Protocols.HTTP_1_1);
buffer.position(pos + HTTP_LENGTH + 3);
currentState.state = ParseState.HEADER;
} else if (b == '0') {
builder.setProtocol(Protocols.HTTP_1_0);
buffer.position(pos + HTTP_LENGTH + 3);
currentState.state = ParseState.HEADER;
} else {
failed = true;
}
} else {
failed = true;
}
}
} else {
failed = true;
}
if (failed) {
handleHttpVersion(buffer, currentState, builder);
handleAfterVersion(buffer, currentState);
}
while (currentState.state != ParseState.PARSE_COMPLETE && buffer.hasRemaining()) {
handleHeader(buffer, currentState, builder);
if (currentState.state == ParseState.HEADER_VALUE) {
handleHeaderValue(buffer, currentState, builder);
}
}
return;
}
handleStateful(buffer, currentState, builder);
}
private void handleStateful(ByteBuffer buffer, ParseState currentState, HttpServerExchange builder) throws BadRequestException {
if (currentState.state == ParseState.PATH) {
handlePath(buffer, currentState, builder);
if (!buffer.hasRemaining()) {
return;
}
}
if (currentState.state == ParseState.QUERY_PARAMETERS) {
handleQueryParameters(buffer, currentState, builder);
if (!buffer.hasRemaining()) {
return;
}
}
if (currentState.state == ParseState.PATH_PARAMETERS) {
handlePathParameters(buffer, currentState, builder);
if (!buffer.hasRemaining()) {
return;
}
}
if (currentState.state == ParseState.VERSION) {
handleHttpVersion(buffer, currentState, builder);
if (!buffer.hasRemaining()) {
return;
}
}
if (currentState.state == ParseState.AFTER_VERSION) {
handleAfterVersion(buffer, currentState);
if (!buffer.hasRemaining()) {
return;
}
}
while (currentState.state != ParseState.PARSE_COMPLETE) {
if (currentState.state == ParseState.HEADER) {
handleHeader(buffer, currentState, builder);
if (!buffer.hasRemaining()) {
return;
}
}
if (currentState.state == ParseState.HEADER_VALUE) {
handleHeaderValue(buffer, currentState, builder);
if (!buffer.hasRemaining()) {
return;
}
}
}
}
abstract void handleHttpVerb(ByteBuffer buffer, final ParseState currentState, final HttpServerExchange builder);
abstract void handleHttpVersion(ByteBuffer buffer, final ParseState currentState, final HttpServerExchange builder);
abstract void handleHeader(ByteBuffer buffer, final ParseState currentState, final HttpServerExchange builder);
/**
* The parse states for parsing the path.
*/
private static final int START = 0;
private static final int FIRST_COLON = 1;
private static final int FIRST_SLASH = 2;
private static final int SECOND_SLASH = 3;
private static final int IN_PATH = 4;
private static final int HOST_DONE = 5;
/**
* Parses a path value
*
* @param buffer The buffer
* @param state The current state
* @param exchange The exchange builder
* @return The number of bytes remaining
*/
@SuppressWarnings("unused")
final void handlePath(ByteBuffer buffer, ParseState state, HttpServerExchange exchange) {
StringBuilder stringBuilder = state.stringBuilder;
int parseState = state.parseState;
int canonicalPathStart = state.pos;
boolean urlDecodeRequired = state.urlDecodeRequired;
while (buffer.hasRemaining()) {
char next = (char) (buffer.get() & 0xFF);
if (next == ' ' || next == '\t') {
if (stringBuilder.length() != 0) {
final String path = stringBuilder.toString();
if(parseState == SECOND_SLASH) {
exchange.setRequestPath("/");
exchange.setRelativePath("/");
exchange.setRequestURI(path);
} else if (parseState < HOST_DONE) {
String decodedPath = decode(path, urlDecodeRequired, state, allowEncodedSlash);
exchange.setRequestPath(decodedPath);
exchange.setRelativePath(decodedPath);
exchange.setRequestURI(path);
} else {
handleFullUrl(state, exchange, canonicalPathStart, urlDecodeRequired, path);
}
exchange.setQueryString("");
state.state = ParseState.VERSION;
state.stringBuilder.setLength(0);
state.parseState = 0;
state.pos = 0;
state.urlDecodeRequired = false;
return;
}
} else if (next == '\r' || next == '\n') {
throw UndertowMessages.MESSAGES.failedToParsePath();
} else if (next == '?' && (parseState == START || parseState == HOST_DONE || parseState == IN_PATH)) {
beginQueryParameters(buffer, state, exchange, stringBuilder, parseState, canonicalPathStart, urlDecodeRequired);
return;
} else if (next == ';' && (parseState == START || parseState == HOST_DONE || parseState == IN_PATH)) {
beginPathParameters(state, exchange, stringBuilder, parseState, canonicalPathStart, urlDecodeRequired);
handlePathParameters(buffer, state, exchange);
return;
} else {
if (decode && (next == '%' || next > 127)) {
urlDecodeRequired = true;
} else if (next == ':' && parseState == START) {
parseState = FIRST_COLON;
} else if (next == '/' && parseState == FIRST_COLON) {
parseState = FIRST_SLASH;
} else if (next == '/' && parseState == FIRST_SLASH) {
parseState = SECOND_SLASH;
} else if (next == '/' && parseState == SECOND_SLASH) {
parseState = HOST_DONE;
canonicalPathStart = stringBuilder.length();
} else if (parseState == FIRST_COLON || parseState == FIRST_SLASH) {
parseState = IN_PATH;
} else if (next == '/' && parseState != HOST_DONE) {
parseState = IN_PATH;
}
stringBuilder.append(next);
}
}
state.parseState = parseState;
state.pos = canonicalPathStart;
state.urlDecodeRequired = urlDecodeRequired;
}
private void beginPathParameters(ParseState state, HttpServerExchange exchange, StringBuilder stringBuilder, int parseState, int canonicalPathStart, boolean urlDecodeRequired) {
final String path = stringBuilder.toString();
if(parseState == SECOND_SLASH) {
exchange.setRequestPath("/");
exchange.setRelativePath("/");
exchange.setRequestURI(path);
} else if (parseState < HOST_DONE) {
String decodedPath = decode(path, urlDecodeRequired, state, allowEncodedSlash);
exchange.setRequestPath(decodedPath);
exchange.setRelativePath(decodedPath);
exchange.setRequestURI(path);
} else {
String thePath = path.substring(canonicalPathStart);
exchange.setRequestPath(thePath);
exchange.setRelativePath(thePath);
exchange.setRequestURI(path, true);
}
state.state = ParseState.PATH_PARAMETERS;
state.stringBuilder.setLength(0);
state.parseState = 0;
state.pos = 0;
state.urlDecodeRequired = false;
}
private void beginQueryParameters(ByteBuffer buffer, ParseState state, HttpServerExchange exchange, StringBuilder stringBuilder, int parseState, int canonicalPathStart, boolean urlDecodeRequired) {
final String path = stringBuilder.toString();
if (parseState == SECOND_SLASH) {
exchange.setRequestPath("/");
exchange.setRelativePath("/");
exchange.setRequestURI(path);
} else if (parseState < HOST_DONE) {
String decodedPath = decode(path, urlDecodeRequired, state, allowEncodedSlash);
exchange.setRequestPath(decodedPath);
exchange.setRelativePath(decodedPath);
exchange.setRequestURI(path, false);
} else {
handleFullUrl(state, exchange, canonicalPathStart, urlDecodeRequired, path);
}
state.state = ParseState.QUERY_PARAMETERS;
state.stringBuilder.setLength(0);
state.parseState = 0;
state.pos = 0;
state.urlDecodeRequired = false;
handleQueryParameters(buffer, state, exchange);
}
private void handleFullUrl(ParseState state, HttpServerExchange exchange, int canonicalPathStart, boolean urlDecodeRequired, String path) {
String thePath = decode(path.substring(canonicalPathStart), urlDecodeRequired, state, allowEncodedSlash);
exchange.setRequestPath(thePath);
exchange.setRelativePath(thePath);
exchange.setRequestURI(path, true);
}
/**
* Parses a path value
*
* @param buffer The buffer
* @param state The current state
* @param exchange The exchange builder
* @return The number of bytes remaining
*/
@SuppressWarnings("unused")
final void handleQueryParameters(ByteBuffer buffer, ParseState state, HttpServerExchange exchange) {
StringBuilder stringBuilder = state.stringBuilder;
int queryParamPos = state.pos;
int mapCount = state.mapCount;
boolean urlDecodeRequired = state.urlDecodeRequired;
String nextQueryParam = state.nextQueryParam;
//so this is a bit funky, because it not only deals with parsing, but
//also deals with URL decoding the query parameters as well, while also
//maintaining a non-decoded version to use as the query string
//In most cases these string will be the same, and as we do not want to
//build up two separate strings we don't use encodedStringBuilder unless
//we encounter an encoded character
while (buffer.hasRemaining()) {
char next = (char) (buffer.get() & 0xFF);
if (next == ' ' || next == '\t') {
final String queryString = stringBuilder.toString();
exchange.setQueryString(queryString);
if (nextQueryParam == null) {
if (queryParamPos != stringBuilder.length()) {
exchange.addQueryParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true), "");
}
} else {
exchange.addQueryParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true));
}
state.state = ParseState.VERSION;
state.stringBuilder.setLength(0);
state.pos = 0;
state.nextQueryParam = null;
state.urlDecodeRequired = false;
state.mapCount = 0;
return;
} else if (next == '\r' || next == '\n') {
throw UndertowMessages.MESSAGES.failedToParsePath();
} else {
if (decode && (next == '+' || next == '%' || next > 127)) { //+ is only a whitespace substitute in the query part of the URL
urlDecodeRequired = true;
} else if (next == '=' && nextQueryParam == null) {
nextQueryParam = decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true);
urlDecodeRequired = false;
queryParamPos = stringBuilder.length() + 1;
} else if (next == '&' && nextQueryParam == null) {
if (++mapCount > maxParameters) {
throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
}
if (queryParamPos != stringBuilder.length()) {
exchange.addQueryParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true), "");
}
urlDecodeRequired = false;
queryParamPos = stringBuilder.length() + 1;
} else if (next == '&') {
if (++mapCount > maxParameters) {
throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
}
exchange.addQueryParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true));
urlDecodeRequired = false;
queryParamPos = stringBuilder.length() + 1;
nextQueryParam = null;
}
stringBuilder.append(next);
}
}
state.pos = queryParamPos;
state.nextQueryParam = nextQueryParam;
state.urlDecodeRequired = urlDecodeRequired;
state.mapCount = mapCount;
}
private String decode(final String value, boolean urlDecodeRequired, ParseState state, final boolean allowEncodedSlash) {
if (urlDecodeRequired) {
return URLUtils.decode(value, charset, allowEncodedSlash, state.decodeBuffer);
} else {
return value;
}
}
final void handlePathParameters(ByteBuffer buffer, ParseState state, HttpServerExchange exchange) {
StringBuilder stringBuilder = state.stringBuilder;
int queryParamPos = state.pos;
int mapCount = state.mapCount;
boolean urlDecodeRequired = state.urlDecodeRequired;
String nextQueryParam = state.nextQueryParam;
//so this is a bit funky, because it not only deals with parsing, but
//also deals with URL decoding the query parameters as well, while also
//maintaining a non-decoded version to use as the query string
//In most cases these string will be the same, and as we do not want to
//build up two separate strings we don't use encodedStringBuilder unless
//we encounter an encoded character
while (buffer.hasRemaining()) {
char next = (char) (buffer.get() & 0xFF);
if (next == ' ' || next == '\t' || next == '?') {
if (nextQueryParam == null) {
if (queryParamPos != stringBuilder.length()) {
exchange.addPathParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true), "");
}
} else {
exchange.addPathParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true));
}
exchange.setRequestURI(exchange.getRequestURI() + ';' + stringBuilder.toString(), state.parseState > HOST_DONE);
state.stringBuilder.setLength(0);
state.pos = 0;
state.nextQueryParam = null;
state.mapCount = 0;
state.urlDecodeRequired = false;
if (next == '?') {
state.state = ParseState.QUERY_PARAMETERS;
handleQueryParameters(buffer, state, exchange);
} else {
state.state = ParseState.VERSION;
}
return;
} else if (next == '\r' || next == '\n') {
throw UndertowMessages.MESSAGES.failedToParsePath();
} else {
if (decode && (next == '+' || next == '%' || next > 127)) {
urlDecodeRequired = true;
}
if (next == '=' && nextQueryParam == null) {
nextQueryParam = decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true);
urlDecodeRequired = false;
queryParamPos = stringBuilder.length() + 1;
} else if (next == '&' && nextQueryParam == null) {
if (++mapCount > maxParameters) {
throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
}
exchange.addPathParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true), "");
urlDecodeRequired = false;
queryParamPos = stringBuilder.length() + 1;
} else if (next == '&') {
if (++mapCount > maxParameters) {
throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
}
exchange.addPathParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true));
urlDecodeRequired = false;
queryParamPos = stringBuilder.length() + 1;
nextQueryParam = null;
}
stringBuilder.append(next);
}
}
state.pos = queryParamPos;
state.nextQueryParam = nextQueryParam;
state.mapCount = mapCount;
state.urlDecodeRequired = urlDecodeRequired;
}
/**
* The parse states for parsing heading values
*/
private static final int NORMAL = 0;
private static final int WHITESPACE = 1;
private static final int BEGIN_LINE_END = 2;
private static final int LINE_END = 3;
private static final int AWAIT_DATA_END = 4;
/**
* Parses a header value. This is called from the generated bytecode.
*
* @param buffer The buffer
* @param state The current state
* @param builder The exchange builder
* @return The number of bytes remaining
*/
@SuppressWarnings("unused")
final void handleHeaderValue(ByteBuffer buffer, ParseState state, HttpServerExchange builder) throws BadRequestException {
HttpString headerName = state.nextHeader;
StringBuilder stringBuilder = state.stringBuilder;
HashMap<HttpString, String> headerValuesCache = state.headerValuesCache;
if (stringBuilder.length() == 0) {
String existing = headerValuesCache.get(headerName);
if (existing != null) {
if (handleCachedHeader(existing, buffer, state, builder)) {
return;
}
}
}
handleHeaderValueCacheMiss(buffer, state, builder, headerName, headerValuesCache, stringBuilder);
}
private void handleHeaderValueCacheMiss(ByteBuffer buffer, ParseState state, HttpServerExchange builder, HttpString headerName, HashMap<HttpString, String> headerValuesCache, StringBuilder stringBuilder) throws BadRequestException {
int parseState = state.parseState;
while (buffer.hasRemaining() && parseState == NORMAL) {
final byte next = buffer.get();
if (next == '\r') {
parseState = BEGIN_LINE_END;
} else if (next == '\n') {
parseState = LINE_END;
} else if (next == ' ' || next == '\t') {
parseState = WHITESPACE;
} else {
stringBuilder.append((char) (next & 0xFF));
}
}
while (buffer.hasRemaining()) {
final byte next = buffer.get();
switch (parseState) {
case NORMAL: {
if (next == '\r') {
parseState = BEGIN_LINE_END;
} else if (next == '\n') {
parseState = LINE_END;
} else if (next == ' ' || next == '\t') {
parseState = WHITESPACE;
} else {
stringBuilder.append((char) (next & 0xFF));
}
break;
}
case WHITESPACE: {
if (next == '\r') {
parseState = BEGIN_LINE_END;
} else if (next == '\n') {
parseState = LINE_END;
} else if (next == ' ' || next == '\t') {
} else {
if (stringBuilder.length() > 0) {
stringBuilder.append(' ');
}
stringBuilder.append((char) (next & 0xFF));
parseState = NORMAL;
}
break;
}
case LINE_END:
case BEGIN_LINE_END: {
if (next == '\n' && parseState == BEGIN_LINE_END) {
parseState = LINE_END;
} else if (next == '\t' ||
next == ' ') {
//this is a continuation
parseState = WHITESPACE;
} else {
//we have a header
String headerValue = stringBuilder.toString();
if (++state.mapCount > maxHeaders) {
throw new BadRequestException(UndertowMessages.MESSAGES.tooManyHeaders(maxHeaders));
}
//TODO: we need to decode this according to RFC-2047 if we have seen a =? symbol
builder.getRequestHeaders().add(headerName, headerValue);
if(headerValuesCache.size() < maxHeaders) {
//we have a limit on how many we can cache
//to prevent memory filling and hash collision attacks
headerValuesCache.put(headerName, headerValue);
}
state.nextHeader = null;
state.leftOver = next;
state.stringBuilder.setLength(0);
if (next == '\r') {
parseState = AWAIT_DATA_END;
} else if (next == '\n') {
state.state = ParseState.PARSE_COMPLETE;
return;
} else {
state.state = ParseState.HEADER;
state.parseState = 0;
return;
}
}
break;
}
case AWAIT_DATA_END: {
state.state = ParseState.PARSE_COMPLETE;
return;
}
}
}
//we only write to the state if we did not finish parsing
state.parseState = parseState;
}
protected boolean handleCachedHeader(String existing, ByteBuffer buffer, ParseState state, HttpServerExchange builder) throws BadRequestException {
int pos = buffer.position();
while (pos < buffer.limit() && buffer.get(pos) == ' ') {
pos++;
}
if (existing.length() + 3 + pos > buffer.limit()) {
return false;
}
int i = 0;
while (i < existing.length()) {
byte b = buffer.get(pos + i);
if (b != existing.charAt(i)) {
return false;
}
++i;
}
if (buffer.get(pos + i++) != '\r') {
return false;
}
if (buffer.get(pos + i++) != '\n') {
return false;
}
int next = buffer.get(pos + i);
if (next == '\t' || next == ' ') {
//continuation
return false;
}
buffer.position(pos + i);
if (++state.mapCount > maxHeaders) {
throw new BadRequestException(UndertowMessages.MESSAGES.tooManyHeaders(maxHeaders));
}
//TODO: we need to decode this according to RFC-2047 if we have seen a =? symbol
builder.getRequestHeaders().add(state.nextHeader, existing);
state.nextHeader = null;
state.state = ParseState.HEADER;
state.parseState = 0;
return true;
}
protected void handleAfterVersion(ByteBuffer buffer, ParseState state) {
boolean newLine = state.leftOver == '\n';
while (buffer.hasRemaining()) {
final byte next = buffer.get();
if (newLine) {
if (next == '\n') {
state.state = ParseState.PARSE_COMPLETE;
return;
} else {
state.state = ParseState.HEADER;
state.leftOver = next;
return;
}
} else {
if (next == '\n') {
newLine = true;
} else if (next != '\r' && next != ' ' && next != '\t') {
state.state = ParseState.HEADER;
state.leftOver = next;
return;
} else {
throw UndertowMessages.MESSAGES.badRequest();
}
}
}
if (newLine) {
state.leftOver = '\n';
}
}
/**
* This is a bit of hack to enable the parser to get access to the HttpString's that are sorted
* in the static fields of the relevant classes. This means that in most cases a HttpString comparison
* will take the fast path == route, as they will be the same object
*
* @return
*/
@SuppressWarnings("unused")
protected static Map<String, HttpString> httpStrings() {
final Map<String, HttpString> results = new HashMap<>();
final Class[] classs = {Headers.class, Methods.class, Protocols.class};
for (Class<?> c : classs) {
for (Field field : c.getDeclaredFields()) {
if (field.getType().equals(HttpString.class)) {
HttpString result = null;
try {
result = (HttpString) field.get(null);
results.put(result.toString(), result);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
return results;
}
public static class BadRequestException extends Exception {
public BadRequestException(String msg) {
super(msg);
}
}
}
| {
"content_hash": "28d5b52d3406f99d785426745d6da367",
"timestamp": "",
"source": "github",
"line_count": 847,
"max_line_length": 236,
"avg_line_length": 43.14876033057851,
"alnum_prop": 0.5616056037431253,
"repo_name": "aradchykov/undertow",
"id": "5f9f73682c193db9ae7f160dccfc241889bf1878",
"size": "37258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/io/undertow/server/protocol/http/HttpRequestParser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1782"
},
{
"name": "Java",
"bytes": "6964777"
},
{
"name": "Shell",
"bytes": "86"
}
],
"symlink_target": ""
} |
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using GoogleCloudExtension.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
namespace GoogleCloudExtensionUnitTests.Utils
{
public static class ProtectedCommandTests
{
[TestClass]
public class ProtectedCommand0Tests : ExtensionTestBase
{
[TestMethod]
public void TestConstrutor_DefaultsCanExecuteCommandToTrue()
{
var objectUnderTest = new ProtectedCommand(() => { });
Assert.IsTrue(objectUnderTest.CanExecuteCommand);
}
[TestMethod]
public void TestConstrutor_OverridesDefaultCanExecuteCommandWithParameter()
{
var objectUnderTest = new ProtectedCommand(() => { }, false);
Assert.IsFalse(objectUnderTest.CanExecuteCommand);
}
[TestMethod]
public void TestExecute_InvokesProvidedAction()
{
var actionMock = new Mock<Action>();
var objectUnderTest = new ProtectedCommand(actionMock.Object);
objectUnderTest.Execute(null);
actionMock.Verify(f => f(), Times.Once);
}
[TestMethod]
public void TestExecute_DoesNotThrowWhenActionErrors()
{
var objectUnderTest = new ProtectedCommand(() => throw new Exception());
objectUnderTest.Execute(null);
}
}
[TestClass]
public class ProtectedCommand1Tests : ExtensionTestBase
{
[TestMethod]
public void TestConstrutor_DefaultsCanExecuteCommandToTrue()
{
var objectUnderTest = new ProtectedCommand<object>(_ => { });
Assert.IsTrue(objectUnderTest.CanExecuteCommand);
}
[TestMethod]
public void TestConstrutor_OverridesDefaultCanExecuteCommandWithParameter()
{
var objectUnderTest = new ProtectedCommand<object>(_ => { }, false);
Assert.IsFalse(objectUnderTest.CanExecuteCommand);
}
[TestMethod]
public void TestExecute_InvokesProvidedActionWithArgument()
{
var actionMock = new Mock<Action<object>>();
var objectUnderTest = new ProtectedCommand<object>(actionMock.Object);
var argument = new object();
objectUnderTest.Execute(argument);
actionMock.Verify(f => f(argument), Times.Once);
}
[TestMethod]
public void TestExecute_DoesNotThrowWhenActionErrors()
{
var objectUnderTest = new ProtectedCommand<object>(_ => throw new Exception());
objectUnderTest.Execute(null);
}
}
}
}
| {
"content_hash": "48fe2611656c9c18d9d08a32fcfb120d",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 95,
"avg_line_length": 33.095238095238095,
"alnum_prop": 0.6028776978417266,
"repo_name": "ILMTitan/google-cloud-visualstudio",
"id": "84ee89e20e82604e28d8adc524b009ac52905135",
"size": "3477",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "GoogleCloudExtension/GoogleCloudExtensionUnitTests/Utils/ProtectedCommandTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "223"
},
{
"name": "Batchfile",
"bytes": "1364"
},
{
"name": "C#",
"bytes": "3193071"
},
{
"name": "CSS",
"bytes": "3846"
},
{
"name": "HTML",
"bytes": "72878"
},
{
"name": "JavaScript",
"bytes": "21870"
},
{
"name": "PowerShell",
"bytes": "6740"
},
{
"name": "Python",
"bytes": "13763"
},
{
"name": "Shell",
"bytes": "4174"
}
],
"symlink_target": ""
} |
package com.streamsets.pipeline.lib.io.fileref;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.streamsets.pipeline.api.Stage;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Map;
/**
* The Implementation of {@link AbstractPrePostReadOperationPerformingStream} which maintains and updates the metrics
* for the stream read.
* @param <T> Stream implementation of {@link AutoCloseable}
*/
final class MetricEnabledWrapperStream<T extends AutoCloseable> extends AbstractPrePostReadOperationPerformingStream<T> {
private final Meter dataThroughputMeterForCurrentStream;
private final Meter dataTransferMeter;
private final Counter remainingBytesCounter;
private final Counter sentBytesCounter;
private final Map<String, Object> gaugeStatisticsMap;
private final long fileSize;
private final long completedFileCount;
private static final String[] UNITS = new String[]{"B", "KB", "MB", "GB", "TB"};
private static final DecimalFormat df = new DecimalFormat("#.##");
private static final String PER_SEC = "/s";
private static final String PERCENT = "%";
@SuppressWarnings("unchecked")
MetricEnabledWrapperStream(String id, long fileSize, Stage.Context context, T stream) {
super(stream);
this.fileSize = fileSize;
dataThroughputMeterForCurrentStream = new Meter();
remainingBytesCounter = new Counter();
sentBytesCounter = new Counter();
remainingBytesCounter.inc(fileSize);
FileRefUtil.initMetricsIfNeeded(context);
dataTransferMeter = context.getMeter(FileRefUtil.TRANSFER_THROUGHPUT_METER);
gaugeStatisticsMap = context.getGauge(FileRefUtil.GAUGE_NAME).getValue();
completedFileCount = (long)gaugeStatisticsMap.get(FileRefUtil.COMPLETED_FILE_COUNT);
//Shows the size of the file in the brack after the file name.
gaugeStatisticsMap.put(FileRefUtil.FILE, String.format(FileRefUtil.BRACKETED_TEMPLATE, id, convertBytesToDisplayFormat(fileSize)));
}
@Override
protected void performPreReadOperation(int bytesToBeRead) {
//NOOP
}
@Override
protected void performPostReadOperation(int bytesRead) {
if (bytesRead > 0) {
dataThroughputMeterForCurrentStream.mark(bytesRead);
//In KB
dataTransferMeter.mark(bytesRead);
sentBytesCounter.inc(bytesRead);
double sentBytes = (double) sentBytesCounter.getCount();
remainingBytesCounter.dec(bytesRead);
//Putting one minute rate because that is the latest speed of transfer
gaugeStatisticsMap.put(
FileRefUtil.TRANSFER_THROUGHPUT,
convertBytesToDisplayFormat(dataThroughputMeterForCurrentStream.getOneMinuteRate()) + PER_SEC
);
//Shows a percent of file copied in bracket after the sent bytes.
gaugeStatisticsMap.put(
FileRefUtil.SENT_BYTES,
String.format(
FileRefUtil.BRACKETED_TEMPLATE,
convertBytesToDisplayFormat(sentBytes),
(long)Math.floor( (sentBytes / fileSize) * 100) + PERCENT
)
);
gaugeStatisticsMap.put(
FileRefUtil.REMAINING_BYTES,
convertBytesToDisplayFormat((double)remainingBytesCounter.getCount())
);
}
}
/**
* Convert the bytes to a human readable format upto 2 decimal places
* The maximum unit is TB, so anything exceeding 1024 TB will be shown
* with TB unit.
* @param bytes the number of bytes.
* @return human readable format of bytes in units.
*/
static String convertBytesToDisplayFormat(double bytes) {
int unitIdx = 0;
double unitChangedBytes = bytes;
while (unitIdx < UNITS.length - 1 && Math.floor(unitChangedBytes / 1024) > 0) {
unitChangedBytes = unitChangedBytes / 1024;
unitIdx++;
}
return df.format(unitChangedBytes) + " " + UNITS[unitIdx];
}
@Override
public void close() throws IOException {
super.close();
//If close fails, completed file won't be updated.
gaugeStatisticsMap.put(FileRefUtil.COMPLETED_FILE_COUNT, completedFileCount + 1);
}
}
| {
"content_hash": "0d5a020eec820ed9504edd57fc343088",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 135,
"avg_line_length": 38.666666666666664,
"alnum_prop": 0.7258620689655172,
"repo_name": "z123/datacollector",
"id": "4825b8f88252f15346248af9e145415909934533",
"size": "4658",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "commonlib/src/main/java/com/streamsets/pipeline/lib/io/fileref/MetricEnabledWrapperStream.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "89702"
},
{
"name": "CSS",
"bytes": "124298"
},
{
"name": "Groovy",
"bytes": "11876"
},
{
"name": "HTML",
"bytes": "494482"
},
{
"name": "Java",
"bytes": "17299310"
},
{
"name": "JavaScript",
"bytes": "1013775"
},
{
"name": "Protocol Buffer",
"bytes": "3463"
},
{
"name": "Python",
"bytes": "16912"
},
{
"name": "Scala",
"bytes": "6805"
},
{
"name": "Shell",
"bytes": "28783"
}
],
"symlink_target": ""
} |
/**
* The core EndlessRunner blueprint game file.
*
* This file is only used to initalise (start-up) the main Kiwi Game
* and add all of the relevant states to that Game.
*
*/
//Initialise the Kiwi Game.
var game = new Kiwi.Game('content', 'NyanGame', null, {renderer: Kiwi.RENDERER_CANVAS, plugins:['LeapMotion']});
//Add all the States we are going to use.
game.states.addState(LoadingState);
game.states.addState(IntroState);
game.states.addState(PlayState);
game.states.addState(GameOverState);
game.states.switchState("LoadingState"); | {
"content_hash": "1d67777d712354aee2e12e2ec415fdcc",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 112,
"avg_line_length": 27.35,
"alnum_prop": 0.7422303473491774,
"repo_name": "tutsplus/kiwi-js-motion-control-with-leap",
"id": "2bfd6856c3e0ef473cabe7851b1b7b3402ffe53c",
"size": "547",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "FlappyNyanGame/FlappyNyanGame/src/game.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "150"
},
{
"name": "JavaScript",
"bytes": "3682039"
}
],
"symlink_target": ""
} |
@interface testNativeToJSCore : JSCoreTestCase
@end
@implementation testNativeToJSCore
-(void)testReturnJSSignal
{
__block NSMutableArray* output = [@[] mutableCopy];
int rangeLength = 5;
Kaare* kaare = [[Kaare alloc] initWithTransport:[[KaareJSCoreTransport alloc] initWithContextFinder:^JSContext *{
return [self getContextForTestAndEvaluate:@[@"var kaare = new Kaare()",
@"kaare.registerCommand('range', function(params) { return Rx.Observable.range(1,params[0]) })" ]];
}]];
[[kaare executeCommand:@"range" params:@[@(rangeLength)]]
subscribeNext:^(id v) { [output addObject:v]; }
error:^(NSError *error) { XCTFail(@"There should be no error: %@",error); }
completed:^{ isDone = YES; }
];
if (!isDone) WAIT_WHILE(!isDone, 2);
XCTAssertEqual(output.count, (NSUInteger)rangeLength,@"There should be right number of numbers");
[@[@1,@2,@3,@4,@5] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
XCTAssertEqualObjects(obj, output[idx],@"Returned value should be right");
}];
}
-(void)testReturnJSArray
{
__block NSMutableArray* output = [@[] mutableCopy];
Kaare* kaare = [[Kaare alloc] initWithTransport:[[KaareJSCoreTransport alloc] initWithContextFinder:^JSContext *{
return [self getContextForTestAndEvaluate:@[@"var kaare = new Kaare()",
@"kaare.registerCommand('split', function(params) { return Rx.Observable.fromArray(params[0].split('')) })" ]];
}]];
[[kaare executeCommand:@"split" params:@[@"hello"]]
subscribeNext:^(id v) { [output addObject:v]; }
error:^(NSError *error) { XCTFail(@"There should be no error: %@",error); }
completed:^{ isDone = YES; }
];
if (!isDone) WAIT_WHILE(!isDone, 2);
XCTAssertEqual(output.count, (NSUInteger)5,@"There should be right number of items");
[@[@"h",@"e",@"l",@"l",@"o"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
XCTAssertEqualObjects(obj, output[idx],@"Returned value should be right");
}];
}
-(void)testReturnJSInt
{
__block int output;
Kaare* kaare = [[Kaare alloc] initWithTransport:[[KaareJSCoreTransport alloc] initWithContextFinder:^JSContext *{
return [self getContextForTestAndEvaluate:@[@"var kaare = new Kaare()",
@"kaare.registerCommand('val', function(params) { return Rx.Observable.return(params[0]) })" ]];
}]];
[[kaare executeCommand:@"val" params:@[@(42)]]
subscribeNext:^(id v) {!output ? output = [v intValue] : XCTFail(@"Method should return value only once"); }
error:^(NSError *error) { XCTFail(@"There should be no error: %@",error); }
completed:^{ isDone = YES; }
];
if (!isDone) WAIT_WHILE(!isDone, 2);
XCTAssertEqual(output, 42,@"There should be right output");
}
-(void)testReturnJSObject
{
__block NSDictionary* output;
Kaare* kaare = [[Kaare alloc] initWithTransport:[[KaareJSCoreTransport alloc] initWithContextFinder:^JSContext *{
return [self getContextForTestAndEvaluate:@[@"var kaare = new Kaare()",
@"kaare.registerCommand('cust', function(params) { return Rx.Observable.return({a:1,b:2}) })" ]];
}]];
[[kaare executeCommand:@"cust" params:nil]
subscribeNext:^(id v) { !output ? output = v : XCTFail(@"Method should return value only once"); }
error:^(NSError *error) { XCTFail(@"There should be no error: %@",error); }
completed:^{ isDone = YES; }
];
if (!isDone) WAIT_WHILE(!isDone, 2);
NSDictionary* expectedOutput = @{@"a":@1,@"b":@2};
XCTAssertEqualObjects(output, expectedOutput, @"There should be right output");
}
-(void)testShouldReturnErrorIfCommandNotFound
{
Kaare* kaare = [[Kaare alloc] initWithTransport:[[KaareJSCoreTransport alloc] initWithContextFinder:^JSContext *{
return [self getContextForTestAndEvaluate:@[@"var kaare = new Kaare()"]];
}]];
[[kaare executeCommand:@"range" params:nil]
subscribeNext:^(id v) { XCTFail(@"There should be no value %@", v); }
error:^(NSError *error) {
XCTAssert([error isKindOfClass:NSError.class],@"There should be right type of an error");
XCTAssert([error.localizedDescription containsString:@"cannot be found"],@"There should be right message");
isDone = YES;
}
completed:^{ XCTFail(@"Complete should never be called");}
];
if (!isDone) WAIT_WHILE(!isDone, 2);
}
-(void)testShouldBeAbleToReceiveErrorsFromCommand
{
Kaare* kaare = [[Kaare alloc] initWithTransport:[[KaareJSCoreTransport alloc] initWithContextFinder:^JSContext *{
return [self getContextForTestAndEvaluate:@[@"var kaare = new Kaare()",
@"kaare.registerCommand('range', function(params) { return Rx.Observable.throw(new Error('Hello')) })" ]];
}]];
[[kaare executeCommand:@"range" params:nil]
subscribeNext:^(id v) { XCTFail(@"There should be no value %@", v); }
error:^(NSError *error) {
XCTAssert([error isKindOfClass:NSError.class],@"There should be right type of an error");
XCTAssert([error.localizedDescription containsString:@"Hello"],@"There should be right message");
XCTAssertNotNil(error.localizedFailureReason,@"There should be additional info about place of an error");
isDone = YES;
}
completed:^{ XCTFail(@"Complete should never be called");}
];
if (!isDone) WAIT_WHILE(!isDone, 2);
}
@end
| {
"content_hash": "e4f89b88d02be5acde1dcecd327f8754",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 163,
"avg_line_length": 41.32857142857143,
"alnum_prop": 0.6164880746629796,
"repo_name": "artemyarulin/Kaare",
"id": "b2c99e5c66bff7315a861860f2b632be6223a22c",
"size": "5814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iOS/KaareTests/testNativeToJSCore.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "392737"
},
{
"name": "Objective-C",
"bytes": "26720"
},
{
"name": "Ruby",
"bytes": "1363"
}
],
"symlink_target": ""
} |
package ru.job4j.generic;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author Dmitry Belokursky
* @since 21.10.17.
*/
public class RoleStoreTest {
@Test
public void add() throws Exception {
RoleStore roleStore = new RoleStore();
Role result = roleStore.add(new Role("test1"));
Role expected = new Role("test1");
assertThat(result, is(expected));
}
@Test
public void update() throws Exception {
RoleStore roleStore = new RoleStore();
roleStore.add(new Role("test2"));
Role result = roleStore.update(new Role("test2"), new Role("test2Updated"));
Role expected = new Role("test2");
assertThat(result, is(expected));
}
@Test
public void delete() throws Exception {
RoleStore roleStore = new RoleStore();
roleStore.add(new Role("test3"));
boolean result = roleStore.delete("test3");
boolean expected = true;
assertThat(result, is(expected));
}
} | {
"content_hash": "f6812544d9e96539b6a10b2e70e59694",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 84,
"avg_line_length": 26.625,
"alnum_prop": 0.6300469483568075,
"repo_name": "dbelokursky/dbelokursky",
"id": "f97838bdb998149d2439955e9c8154fa4524e721",
"size": "1065",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_005/src/test/java/ru/job4j/generic/RoleStoreTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18542"
},
{
"name": "HTML",
"bytes": "25852"
},
{
"name": "Java",
"bytes": "519057"
},
{
"name": "JavaScript",
"bytes": "2314"
},
{
"name": "TSQL",
"bytes": "487479"
},
{
"name": "XSLT",
"bytes": "494"
}
],
"symlink_target": ""
} |
set -e
# Store args to pass on to real terraform command
args="$@"
# Prompt for the 'region' variable if it's not set
if [ -z "$TF_VAR_region" ]; then
echo -n "Enter value for 'region': " && read TF_VAR_region
fi
export TF_VAR_region="$TF_VAR_region"
# Prompt for the 'environment' terraform variable if it's not set
if [ -z "$TF_VAR_environment" ]; then
echo -n "Enter value for 'environment': " && read TF_VAR_environment
fi
export TF_VAR_environment="$TF_VAR_environment"
# Prompt for the 's3_region' variable if it's not set
if [ -z "$TF_VAR_s3_region" ]; then
echo -n "Enter value for 's3_region': " && read TF_VAR_s3_region
fi
export TF_VAR_s3_region="$TF_VAR_s3_region"
# Prompt for the 's3_bucket' variable if it's not set
if [ -z "$TF_VAR_s3_bucket" ]; then
echo -n "Enter value for 's3_bucket': " && read TF_VAR_s3_bucket
fi
export TF_VAR_s3_bucket="$TF_VAR_s3_bucket"
# Print out config values so they can be copied & easily used on subsequent runs
echo
echo "CONFIG VARIABLES"
echo "export TF_VAR_region=\"$TF_VAR_region\""
echo "export TF_VAR_environment=\"$TF_VAR_environment\""
echo "export TF_VAR_s3_region=\"$TF_VAR_s3_region\""
echo "export TF_VAR_s3_bucket=\"$TF_VAR_s3_bucket\""
echo
# Configure S3 remote state storage
terraform remote config \
-backend=s3 \
-backend-config="region=$TF_VAR_s3_region" \
-backend-config="bucket=$TF_VAR_s3_bucket" \
-backend-config="key=$TF_VAR_environment/hello.tfstate"
# Get any modules
terraform get
# Execute terraform with the args passed to this script
terraform "$@"
| {
"content_hash": "3800710dc0263199095320ff74806732",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 80,
"avg_line_length": 31.08,
"alnum_prop": 0.7001287001287001,
"repo_name": "antonosmond/hello-world",
"id": "08bbfaa490bcd65688bfb40d42ed33466e061603",
"size": "1566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deploy/terraform.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "396"
}
],
"symlink_target": ""
} |
class NetworkDevice(object):
def __init__(self, ip, username, password):
self.ip = ip
self.username = username
self.password = password
def connect(self):
pass
def enable(self):
pass
def sh_ver(self):
pass
class NetworkDevice2(object):
def __init__(self, ip, username, password):
self.x = ip
self.y = username
self.z = password
class SomeClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
def a_sum(self):
return self.x + self.y
def a_product(self):
return self.x * self.y
class NewClass(SomeClass):
def __init__(self, x, y, z):
SomeClass.__init__(self, x, y)
self.z = z
def a_sum(self):
return self.x + self.y + self.z | {
"content_hash": "db39ef048c8fe3d6939928de8d85e52e",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 47,
"avg_line_length": 22.363636363636363,
"alnum_prop": 0.5894308943089431,
"repo_name": "bdlamprecht/python_class",
"id": "5286ba15a622b2d39cad96c1722463d0daf61f89",
"size": "738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "neteng/class_ex.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "32103"
}
],
"symlink_target": ""
} |
namespace aura {
namespace test {
namespace {
using ui_controls::DOWN;
using ui_controls::LEFT;
using ui_controls::MIDDLE;
using ui_controls::MouseButton;
using ui_controls::RIGHT;
using ui_controls::UIControlsAura;
using ui_controls::UP;
using namespace ui_controls::internal;
class UIControlsWin : public UIControlsAura {
public:
UIControlsWin() {}
// UIControlsAura overrides:
bool SendKeyPress(gfx::NativeWindow native_window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command) override {
DCHECK(!command); // No command key on Aura
HWND window =
native_window->GetHost()->GetAcceleratedWidget();
return SendKeyPressImpl(
window, key, control, shift, alt, base::Closure());
}
bool SendKeyPressNotifyWhenDone(gfx::NativeWindow native_window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command,
const base::Closure& task) override {
DCHECK(!command); // No command key on Aura
HWND window =
native_window->GetHost()->GetAcceleratedWidget();
return SendKeyPressImpl(window, key, control, shift, alt, task);
}
bool SendMouseMove(long screen_x, long screen_y) override {
return SendMouseMoveImpl(screen_x, screen_y, base::Closure());
}
bool SendMouseMoveNotifyWhenDone(long screen_x,
long screen_y,
const base::Closure& task) override {
return SendMouseMoveImpl(screen_x, screen_y, task);
}
bool SendMouseEvents(MouseButton type, int state) override {
return SendMouseEventsImpl(type, state, base::Closure());
}
bool SendMouseEventsNotifyWhenDone(MouseButton type,
int state,
const base::Closure& task) override {
return SendMouseEventsImpl(type, state, task);
}
bool SendMouseClick(MouseButton type) override {
return SendMouseEvents(type, UP | DOWN);
}
void RunClosureAfterAllPendingUIEvents(
const base::Closure& closure) override {
// On windows, posting UI events is synchronous so just post the closure.
DCHECK(base::MessageLoopForUI::IsCurrent());
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, closure);
}
private:
DISALLOW_COPY_AND_ASSIGN(UIControlsWin);
};
} // namespace
UIControlsAura* CreateUIControlsAura(WindowTreeHost* host) {
return new UIControlsWin();
}
} // namespace test
} // namespace aura
| {
"content_hash": "8cdff65f9bee8ec826ad49529d249eec",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 77,
"avg_line_length": 33.97530864197531,
"alnum_prop": 0.6101017441860465,
"repo_name": "Samsung/ChromiumGStreamerBackend",
"id": "7d1d2bbe4ef0775eb35aebeb574398c83168822e",
"size": "3323",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ui/aura/test/ui_controls_factory_aurawin.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
module Thrift.Transport.Empty
( EmptyTransport(..)
) where
import Thrift.Transport
-- | The Empty Transport has no reading or writing abilities and is permanently
-- closed. It allows you to use 'Protocols' when you are only serializing and
-- deserializing 'ByteString's, not actually reading and writing
data EmptyTransport = EmptyTransport
instance Transport EmptyTransport where
tIsOpen = const $ return False
tClose = const $ return ()
tRead _ _ = return ""
tPeek = const $ return Nothing
tWrite _ _ = return ()
tFlush = const$ return ()
| {
"content_hash": "5554ac66514400cd9ad4e3aacd7ba486",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 79,
"avg_line_length": 37.53846153846154,
"alnum_prop": 0.73224043715847,
"repo_name": "uber/fbthrift",
"id": "fb2daa3f664cdb2816a1709e4ee0899d0bf66855",
"size": "1464",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "thrift/lib/hs/Thrift/Transport/Empty.hs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "188545"
},
{
"name": "C#",
"bytes": "107003"
},
{
"name": "C++",
"bytes": "5373501"
},
{
"name": "D",
"bytes": "667874"
},
{
"name": "Emacs Lisp",
"bytes": "5154"
},
{
"name": "Erlang",
"bytes": "134547"
},
{
"name": "Go",
"bytes": "209167"
},
{
"name": "Haskell",
"bytes": "103787"
},
{
"name": "Java",
"bytes": "624082"
},
{
"name": "JavaScript",
"bytes": "4220"
},
{
"name": "Lua",
"bytes": "56935"
},
{
"name": "Makefile",
"bytes": "31183"
},
{
"name": "OCaml",
"bytes": "32172"
},
{
"name": "Objective-C",
"bytes": "94908"
},
{
"name": "PHP",
"bytes": "212169"
},
{
"name": "Perl",
"bytes": "69158"
},
{
"name": "Perl6",
"bytes": "1524"
},
{
"name": "Protocol Buffer",
"bytes": "585"
},
{
"name": "Python",
"bytes": "670664"
},
{
"name": "Ruby",
"bytes": "323073"
},
{
"name": "Scala",
"bytes": "1266"
},
{
"name": "Shell",
"bytes": "21155"
},
{
"name": "Smalltalk",
"bytes": "22812"
},
{
"name": "TeX",
"bytes": "48707"
},
{
"name": "Thrift",
"bytes": "101886"
},
{
"name": "VimL",
"bytes": "2837"
}
],
"symlink_target": ""
} |





 | {
"content_hash": "1e3534baeb23086e45504caf493891f1",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 61,
"avg_line_length": 58.5,
"alnum_prop": 0.7806267806267806,
"repo_name": "ktbyers/netmiko",
"id": "c5599fc8281271d161520e6fdcd7689835d567f3",
"size": "453",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/performance/performance_netmiko_scrapli.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jinja",
"bytes": "384"
},
{
"name": "Python",
"bytes": "726727"
},
{
"name": "Shell",
"bytes": "21540"
}
],
"symlink_target": ""
} |
Subsets and Splits