repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
jewsroch/art-matters-consulting | wp-content/plugins/security-ninja-core-scanner-addon/js/wf-sn-core.js | 5060 | jQuery(document).ready(function($){
$('a.sn-show-source').click(function() {
$($(this).attr('href')).dialog('option', { title: 'File source: ' + $(this).attr('data-file'), file_path: $(this).attr('data-file'), file_hash: $(this).attr('data-hash') } ).dialog('open');
return false;
});
$('a.sn-restore-source').click(function() {
$($(this).attr('href')).dialog('option', { title: 'Restore file source: ' + $(this).attr('data-file'), file_path: $(this).attr('data-file'), file_hash: $(this).attr('data-hash') } ).dialog('open');
return false;
});
$('#source-dialog').dialog({'dialogClass': 'wp-dialog',
'modal': true,
'resizable': false,
'zIndex': 9999,
'width': 800,
'height': 550,
'hide': 'fade',
'open': function(event, ui) { renderSource(event, ui); fixDialogClose(event, ui); },
'close': function(event, ui) { jQuery('#source-dialog').html('<p>Please wait.</p>') },
'show': 'fade',
'autoOpen': false,
'closeOnEscape': true
});
$('#restore-dialog').dialog({'dialogClass': 'wp-dialog',
'modal': true,
'resizable': false,
'zIndex': 9999,
'width': 450,
'height': 350,
'hide': 'fade',
'open': function(event, ui) { renderRestore(event, ui); fixDialogClose(event, ui); },
'close': function(event, ui) { jQuery('#restore-dialog').html('<p>Please wait.</p>') },
'show': 'fade',
'autoOpen': false,
'closeOnEscape': true
});
// scan files
$('#sn-run-scan').removeAttr('disabled').click(function(){
var data = {action: 'sn_core_run_scan'};
$(this).attr('disabled', 'disabled')
.val('Scanning files, please wait!');
$.blockUI({ message: 'Security Ninja is scanning your core files.<br />Please wait, it can take a minute.' });
$.post(ajaxurl, data, function(response) {
if (response != '1') {
alert('Undocumented error. Page will automatically reload.');
window.location.reload();
} else {
window.location.reload();
}
});
}); // run tests
}); // onload
function renderSource(event, ui) {
dialog_id = '#' + event.target.id;
jQuery.post(ajaxurl, {action: 'sn_core_get_file_source', filename: jQuery('#source-dialog').dialog('option', 'file_path'), hash: jQuery('#source-dialog').dialog('option', 'file_hash')}, function(response) {
if (response) {
if (response.err) {
jQuery(dialog_id).html('<p><b>An error occured.</b> ' + response.err + '</p>');
} else {
jQuery(dialog_id).html('<pre class="sn-core-source"></pre>');
jQuery('pre', dialog_id).text(response.source);
jQuery('pre', dialog_id).snippet(response.ext, {style: 'whitengrey'});
}
} else {
alert('An undocumented error occured. The page will reload.');
window.location.reload();
}
}, 'json');
} // renderSource
function renderRestore(event, ui) {
dialog_id = '#' + event.target.id;
jQuery.post(ajaxurl, {action: 'sn_core_restore_file', filename: jQuery(dialog_id).dialog('option', 'file_path'), hash: jQuery(dialog_id).dialog('option', 'file_hash')}, function(response) {
if (response) {
if (response.err) {
jQuery(dialog_id).html('<p><b>An error occured.</b> ' + response.err + '</p>');
} else {
jQuery(dialog_id).html(response.out);
jQuery('#sn-restore-file').on('click', function(event){
jQuery(this).attr('disabled', 'disabled').attr('value', 'Please wait ...');
jQuery.post(ajaxurl, {action: 'sn_core_restore_file_do', filename: jQuery(this).attr('data-filename')}, function(response) {
if (response == '1') {
alert('File successfully restored!\nThe page will reload and files will be rescanned.');
window.location.reload();
} else {
alert('An error occured - ' + response);
jQuery(this).attr('disabled', '').attr('value', 'Restore file');
}
});
});
}
} else {
alert('An undocumented error occured. The page will reload.');
window.location.reload();
}
}, 'json');
} // renderSource
function fixDialogClose(event, ui) {
jQuery('.ui-widget-overlay').bind('click', function(){ jQuery('#' + event.target.id).dialog('close'); });
} // fixDialogClose | mit |
garvanb/EasyDb | Source/EasyDb.Logic/BulkCodeGenerator.cs | 1021 | using EasyDb.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyDb.Logic
{
public class BulkCodeGenerator
{
public ObservableCollection<GeneratedCode> GenerateCode(string dbName, List<SqlTable> tables, List<Template> templates)
{
ObservableCollection<GeneratedCode> results = new ObservableCollection<GeneratedCode>();
foreach (Template template in templates)
{
foreach (SqlTable table in tables)
{
ICodeGenerator codeGenerator = new CodeGeneratorStrategy().GetStrategy(template.Type, template);
string code = codeGenerator.GenerateCode(dbName, template, table, table);
results.Add(new GeneratedCode(dbName, table, template, code));
}
}
return results;
}
}
}
| mit |
frmendes/rails-template-cache | lib/rails-template-cache.rb | 586 | require "rails-template-cache/template"
require "rails-template-cache/engine"
require "rails-template-cache/version"
module RailsTemplateCache
mattr_accessor :templates
self.templates ||= {}
def self.setup(&block)
set_config
yield @@config.rails_template_cache if block
@@config.rails_template_cache
end
def self.config
Rails.application.config
end
private
def self.set_config
unless @config
@@config = RailsTemplateCache::Engine::Configuration.new
@@config.rails_template_cache = ActiveSupport::OrderedOptions.new
end
end
end
| mit |
magnolo/23 | database/migrations/2015_12_16_151324_create_foreign_keys.php | 1991 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateForeignKeys extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
/*Schema::table('23_categories', function ($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('parent_id')->references('id')->on('23_categories');
$table->foreign('style_id')->references('id')->on('23_styles');
});
Schema::table('23_indicators', function ($table) {
$table->foreign('userdata_id')->references('id')->on('23_userdata');
$table->foreign('measure_type_id')->references('id')->on('23_measure_types');
$table->foreign('style_id')->references('id')->on('23_styles');
$table->foreign('dataprovider_id')->references('id')->on('23_dataproviders');
});
Schema::table('23_userdata', function ($table) {
$table->foreign('user_id')->references('id')->on('users');
});*/
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
/* Schema::table('23_categories', function ($table) {
$table->dropForeign('23_categories_user_id_foreign');
$table->dropForeign('23_categories_parent_id_foreign');
$table->dropForeign('23_categories_style_id_foreign');
});
Schema::table('23_indicators', function ($table) {
$table->dropForeign('23_indicators_userdata_id_foreign');
$table->dropForeign('23_indicators_measure_type_id_foreign');
$table->dropForeign('23_indicators_style_id_foreign');
$table->dropForeign('23_indicators_dataprovider_id_foreign');
});
Schema::table('23_userdata', function ($table) {
$table->dropForeign('23_userdata_user_id_foreign');
});*/
}
}
| mit |
nippur72/react-templates | Gruntfile.js | 3842 | 'use strict';
module.exports = function (grunt) {
grunt.initConfig({
clean: {
main: {
src: ['coverage', 'playground/**/*.rt.js']
}
},
eslint: {
all: {
src: [
'src/**/*.js', 'playground/**/*.js',
'test/src/**/*.js',
'!playground/libs/**/*.js',
'!playground/dist/**/*.js',
'!playground/**/*.rt.js'
]
}
},
jasmine_node: {
options: {
forceExit: true,
match: '.',
matchall: false,
specNameMatcher: 'spec',
extensions: 'js'
},
all: ['server/test'],
grunt: ['conf/tasks/test']
},
browserify: {
rt: {
files: {
'playground/dist/rt-main.browser.js': ['playground/rt-main.js']
},
options: {
transform: ['brfs'],
alias: ['react:react/addons']
}
}
},
tape: {
options: {
pretty: true,
output: 'console'
},
files: ['test/src/*.js']
},
watch: {
rt: {
files: [
'playground/*.rt'
],
tasks: ['rt'],
options: {
spawn: false
}
},
test: {
files: [
'src/**/*.*', 'test/**/*.*'
],
tasks: ['test'],
options: {
spawn: false
}
}
},
uglify: {
my_target: {
//options: {
// sourceMap: true,
// sourceMapIncludeSources: true,
// sourceMapIn: 'example/coffeescript-sourcemap.js', // input sourcemap from a previous compilation
//},
files: {
'playground/dist/rt-main.browser.min.js': ['playground/dist/rt-main.browser.js'],
'playground/libs/requirejs-plugins/text.min.js': ['playground/libs/requirejs-plugins/text.js'],
'playground/libs/requirejs-plugins/json.min.js': ['playground/libs/requirejs-plugins/json.js']
}
}
},
requirejs: {
compile: {
options: readConfig('./home.config.js')
},
playground: {
options: readConfig('./playground.config.js')
}
}
});
function readConfig(file) {
return eval(require('fs').readFileSync(file).toString()); // eslint-disable-line no-eval
}
grunt.loadNpmTasks('grunt-tape');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['eslint:all']);
grunt.registerTask('lint', ['eslint:all']);
grunt.registerTask('test', ['tape']);
grunt.registerTask('rt', () => {
const reactTemplates = require('./src/cli');
const files = grunt.file.expand('playground/*.rt');
const ret = reactTemplates.execute({modules: 'amd', force: true, _: files});
return ret === 0;
});
grunt.registerTask('build', ['rt', 'browserify:pg']);
grunt.registerTask('home', ['rt', 'browserify:home']);
grunt.registerTask('pgall', ['rt', 'browserify', 'uglify', 'requirejs']);
grunt.registerTask('all', ['default', 'test']);
};
| mit |
designforsf/brigade-matchmaker | components/admin/admin/urls.py | 906 | """admin URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from django.conf.urls import url
urlpatterns = [
path('', include('api.urls')),
path('admin/', admin.site.urls),
url(r'^', include('api.urls')),
url(r'^accounts/', include('allauth.urls')),
]
| mit |
woojung3/RewardScheme | RewardScheme/lib/jpbc-2.0.0/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/Point.java | 3031 | package it.unisa.dia.gas.jpbc;
/**
* This interface represents an element with two coordinates.
* (A point over an elliptic curve).
*
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 1.0.0
*/
public interface Point<E extends Element> extends Element, Vector<E> {
/**
* Returns the x-coordinate.
*
* @return the x-coordinate.
* @since 1.0.0
*/
E getX();
/**
* Returns the y-coordinate.
*
* @return the y-coordinate.
* @since 1.0.0
*/
E getY();
/**
* Returns the length in bytes needed to represent this element in a compressed way.
*
* @return the length in bytes needed to represent this element in a compressed way.
*/
int getLengthInBytesCompressed();
/**
* Converts this element to bytes. The number of bytes it will write can be determined calling getLengthInBytesCompressed().
*
* @return the bytes written.
* @since 1.0.0
*/
byte[] toBytesCompressed();
/**
* Reads this element from the buffer source. staring from the passed offset.
*
* @param source the source of bytes.
* @return the number of bytes read.
* @since 1.0.0
*/
int setFromBytesCompressed(byte[] source);
/**
* Reads the x-coordinate from the buffer source staring from the passed offset. The y-coordinate is then recomputed.
* Pay attention. the y-coordinate could be different from the element which originates the buffer source.
*
* @param source the source of bytes.
* @param offset the starting offset.
* @return the number of bytes read.
* @since 1.0.0
*/
int setFromBytesCompressed(byte[] source, int offset);
/**
* Returns the length in bytes needed to represent the x coordinate of this element.
*
* @return the length in bytes needed to represent the x coordinate of this element.
* @since 1.0.0
*/
int getLengthInBytesX();
/**
* Converts the x-coordinate to bytes. The number of bytes it will write can be determined calling getLengthInBytesX().
*
* @return the bytes written.
* @since 1.0.0
*/
byte[] toBytesX();
/**
* Reads the x-coordinate from the buffer source. The y-coordinate is then recomputed.
* Pay attention. the y-coordinate could be different from the element which originates the buffer source.
*
* @param source the source of bytes.
* @return the number of bytes read.
* @since 1.0.0
*/
int setFromBytesX(byte[] source);
/**
* Reads the x-coordinate from the buffer source staring from the passed offset. The y-coordinate is then recomputed.
* Pay attention. the y-coordinate could be different from the element which originates the buffer source.
*
* @param source the source of bytes.
* @param offset the starting offset.
* @return the number of bytes read.
* @since 1.0.0
*/
int setFromBytesX(byte[] source, int offset);
}
| mit |
brettclanton001/Dashous | config/initializers/rack_timeout.rb | 62 | Rack::Timeout.service_timeout = Settings.rack_timeout.seconds
| mit |
vaseug/PowerLib | PowerLib.System.Data.SqlTypes/Collections/SqlNameValueCollection.cs | 2864 | using System;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
namespace PowerLib.System.Data.SqlTypes.Collections
{
[SqlUserDefinedType(Format.UserDefined, Name = "NameValueCollection", IsByteOrdered = true, IsFixedLength = false, MaxByteSize = -1)]
public sealed class SqlNameValueCollection : INullable, IBinarySerialize
{
private static readonly SqlNameValueCollection @null = new SqlNameValueCollection();
private NameValueCollection _coll;
#region Contructors
public SqlNameValueCollection()
{
_coll = null;
}
public SqlNameValueCollection(NameValueCollection coll)
{
_coll = coll;
}
#endregion
#region Properties
public NameValueCollection Value
{
get { return _coll; }
set { _coll = value; }
}
public static SqlNameValueCollection Null
{
get { return @null; }
}
public bool IsNull
{
get { return _coll == null; }
}
public SqlInt32 Count
{
get { return _coll != null ? _coll.Count : SqlInt32.Null; }
}
#endregion
#region Methods
public static SqlNameValueCollection Parse(SqlString s)
{
if (s.IsNull)
return Null;
throw new NotSupportedException();
}
public override String ToString()
{
return _coll.ToString();
}
[SqlMethod]
public SqlNameValueCollection Clear()
{
_coll.Clear();
return this;
}
[SqlMethod]
public SqlNameValueCollection AddItem(SqlString name, SqlString value)
{
_coll.Add(name.IsNull ? default(String) : name.Value, value.IsNull ? default(String) : value.Value);
return this;
}
[SqlMethod]
public SqlNameValueCollection RemoveItem(SqlString name)
{
_coll.Remove(name.IsNull ? default(String) : name.Value);
return this;
}
[SqlMethod]
public SqlNameValueCollection SetItem(SqlString name, SqlString value)
{
_coll.Set(name.IsNull ? default(String) : name.Value, value.IsNull ? default(String) : value.Value);
return this;
}
[SqlMethod]
public SqlNameValueCollection AddRange(SqlNameValueCollection coll)
{
if (!coll.IsNull)
_coll.Add(coll._coll);
return this;
}
[SqlMethod]
public SqlString GetItem(SqlString name)
{
return _coll[name.IsNull ? default(String) : name.Value] ?? SqlString.Null;
}
#endregion
#region IBinarySerialize implementation
public void Read(BinaryReader rd)
{
_coll = (NameValueCollection)new BinaryFormatter().Deserialize(rd.BaseStream);
}
public void Write(BinaryWriter wr)
{
new BinaryFormatter().Serialize(wr.BaseStream, _coll);
}
#endregion
}
}
| mit |
GeoMash/nutsNBolts | widget/map/assets/Main.js | 4349 | $JSKK.Class.create
(
{
$namespace: 'nutsnbolts.widget.map',
$name: 'Main'
}
)
(
{},
{
id: null,
mapOptions: {},
map: null,
marker: null,
location: null,
zoomSlider: null,
field:
{
lng: null,
lat: null,
zoom: null
},
init: function(id)
{
this.id=id;
this.field.lat=$('#map-'+id+' .map-lat');
this.field.lng=$('#map-'+id+' .map-lng');
this.field.zoom=$('#map-'+id+' .map-zoom');
this.zoomSlider=$('#map-'+id+' .zoomSlider');
this.bindEvents.bind(this);
this.loadMap();
this.bindEvents();
//Slider initialize
this.zoomSlider.slider
(
{
min: 1,
max: 20,
animate: true,
step:1,
value:8,
slide: function(event, ui)
{
var handle=this.zoomSlider.find('.ui-slider-handle');
this.field.zoom.val(ui.value);
this.onFieldChange();
// Add zoom value on top of the handler
(function()
{
this.zoomSlider.find('p').css('left', handle.css('left'))
.text(ui.value);
}.bind(this)).defer(1);
}.bind(this)
}
);
this.zoomSlider.append('<p></p>');
},
loadMap: function()
{
if (Object.isUndefined(window.$mapCallbacks))
{
window.$mapCallbacks=[];
}
var index=window.$mapCallbacks.length;
window.$mapCallbacks[index]=this.onMapLoaded.bind(this);
window['$mapCallback_'+index]=window.$mapCallbacks[index];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=window.$mapCallback_'+index;
document.body.appendChild(script);
},
bindEvents: function()
{
//Bind field change events.
this.field.lat.bind("change",this.onFieldChange.bind(this));
this.field.lng.bind("change",this.onFieldChange.bind(this));
this.field.zoom.bind("change",this.onFieldChange.bind(this));
},
onMapLoaded: function()
{
if(!Object.isEmpty(this.field.lat.val()) && Object.isNumeric(this.field.lat.val()))
{
var defaultLatLng= new google.maps.LatLng(this.field.lat.val(), this.field.lng.val());
}
else
{
var defaultLatLng= new google.maps.LatLng(-34.397, 150.644);
}
var mapOptions =
{
center: defaultLatLng,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI:true
},
mapEl=$('#'+this.id);
this.map = new google.maps.Map(mapEl[0],mapOptions);
mapEl.width('100%').height(400);
this.onFieldChange();
},
onFieldChange: function(event)
{
//Update Google Map, reflecting field change.
var lng = this.field.lng.val();
var lat = this.field.lat.val();
var zoom = this.field.zoom.val();
if(!zoom)
{
zoom=8;
}
else
{
zoom=parseInt(zoom);
}
if(lng.length && lat.length)
{
var location = new google.maps.LatLng(lat,lng);
this.map.setCenter(location);
this.map.setZoom(zoom);
if (!Object.isNull(this.marker))
{
this.marker.setMap(null);
delete this.marker;
}
this.marker = new google.maps.Marker
(
{
position: location,
map:this.map,
draggable: true,
}
)
};
//change Lat and Lng by drag down the marker & update the center
google.maps.event.addListener
(
this.marker,
'dragend',
function(event)
{
var position=this.marker.getPosition();
this.field.lng.val(position.lng());
this.field.lat.val(position.lat());
var newLatLng= new google.maps.LatLng(this.field.lat.val(), this.field.lng.val());
this.map.panTo(newLatLng);
}.bind(this)
)
}
}
); | mit |
AlloyTeam/Nuclear | components/icon/esm/flag.js | 173 | import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"
}), 'Flag'); | mit |
cnamal/INF8405 | Project/app/src/main/java/com/ensipoly/project/strategy/ShowItinerary.java | 4259 | package com.ensipoly.project.strategy;
import android.graphics.Color;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.ensipoly.project.R;
import com.ensipoly.project.models.Itinerary;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.JointType;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.List;
import static com.ensipoly.project.R.id.itinerary;
abstract class ShowItinerary extends Strategy {
protected View mSelectedView;
protected List<LatLng> waypoints;
protected List<Marker> pictures;
protected List<Circle> circles;
protected Marker first;
protected Marker last;
protected Polyline line;
protected static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
TextView descView;
View v;
public ViewHolder(View v) {
super(v);
textView = (TextView) itemView.findViewById(itinerary);
descView = (TextView) itemView.findViewById(R.id.desc);
this.v = v;
}
void setOnClickListener(View.OnClickListener listener) {
v.setOnClickListener(listener);
}
}
protected ShowItinerary(Strategy.StrategyParameters params) {
super(params);
mBottomSheetBehavior1.setHideable(false);
mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
protected void select(View v, Object i) {
if (mSelectedView != null)
mSelectedView.setBackgroundColor(Color.WHITE);
mSelectedView = v;
mSelectedView.setTag(i);
mSelectedView.setBackgroundResource(R.color.colorAccent);
fab.setVisibility(View.VISIBLE);
cleanupMap();
}
protected void showItinerary() {
Itinerary itinerary = (Itinerary) mSelectedView.getTag();
showItinerary(itinerary);
}
protected void showItinerary(Itinerary itinerary) {
waypoints = itinerary.getGMapsWaypoints();
List<LatLng> picturesLatLng = itinerary.getGMapsPictures();
first = mMap.addMarker(new MarkerOptions().position(waypoints.get(0)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
last = mMap.addMarker(new MarkerOptions().position(waypoints.get(waypoints.size() - 1)));
line = mMap.addPolyline(new PolylineOptions().color(Color.RED).jointType(JointType.ROUND));
line.setPoints(waypoints);
circles = new ArrayList<>();
for (int i = 1; i < waypoints.size() - 1; i++)
circles.add(mMap.addCircle(new CircleOptions().center(waypoints.get(i)).radius(0.5).zIndex(1)));
if (picturesLatLng != null) {
pictures = new ArrayList<>();
for (LatLng picture : picturesLatLng)
pictures.add(mMap.addMarker(new MarkerOptions().position(picture).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))));
}
}
@Override
public void cleanup() {
mBottomSheetBehavior1.setHideable(true);
mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_HIDDEN);
fab.setVisibility(View.GONE);
cleanupMap();
}
@Override
protected int initiallyShownButtons() {
return 0;
}
@Override
public void onMapClick(LatLng latLng) {
}
protected void cleanupMap() {
if (first != null)
first.remove();
if (last != null)
last.remove();
if (line != null)
line.remove();
if (pictures != null)
for (Marker marker : pictures)
marker.remove();
if (circles != null)
for (Circle circle : circles)
circle.remove();
}
}
| mit |
mpapis/gh_contributors | lib/gh_contributors.rb | 697 | #/usr/bin/env ruby
##
# static content update for speed and avoiding GH limits
# read GitHub contributions, transform to urls and update files
# all public methods return self for easy chaining
#
# Example:
#
# GhContributors.load(org: 'railsisntaller').format.update('public/contributors.html')
# contributors = GhContributors.load(repo: 'railsisntaller/website')
# contributors.format(:html).update('public/index.html', 'public/contributors.html')
# contributors.format(:markdown).save('public/contriutors.md')
#
require 'pluginator'
require 'gh_contributors/calculator'
module GhContributors
def self.load(options: {})
GhContributors::Calculator.new(options)
end
end
| mit |
BK-TN/Sanicball | Subprojects/Core/Properties/AssemblyInfo.cs | 1402 | 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("SanicballCore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SanicballCore")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("ed8d5d1e-e70f-4005-a3ba-f03794ff7a40")]
// 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")]
| mit |
italinux/Authentication | lib/vendor/symfony/lib/form/sfFormField.class.php | 8466 | <?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfFormField represents a widget bind to a name and a value.
*
* @package symfony
* @subpackage form
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfFormField.class.php 22401 2010-09-25 03:49:27Z Kris.Wallsmith $
*/
class sfFormField
{
protected static
$toStringException = null;
protected
$widget = null,
$parent = null,
$name = '',
$value = null,
$error = null;
/**
* Constructor.
*
* @param sfWidgetForm $widget A sfWidget instance
* @param sfFormField $parent The sfFormField parent instance (null for the root widget)
* @param string $name The field name
* @param string $value The field value
* @param sfValidatorError $error A sfValidatorError instance
*/
public function __construct(sfWidgetForm $widget, sfFormField $parent = null, $name, $value, sfValidatorError $error = null)
{
$this->widget = $widget;
$this->parent = $parent;
$this->name = $name;
$this->value = $value;
$this->error = $error;
}
/**
* Returns the string representation of this form field.
*
* @return string The rendered field
*/
public function __toString()
{
try
{
return $this->render();
}
catch (Exception $e)
{
self::setToStringException($e);
// we return a simple Exception message in case the form framework is used out of symfony.
return 'Exception: '.$e->getMessage();
}
}
/**
* Returns true if a form thrown an exception in the __toString() method
*
* This is a hack needed because PHP does not allow to throw exceptions in __toString() magic method.
*
* @return boolean
*/
static public function hasToStringException()
{
return null !== self::$toStringException;
}
/**
* Gets the exception if one was thrown in the __toString() method.
*
* This is a hack needed because PHP does not allow to throw exceptions in __toString() magic method.
*
* @return Exception
*/
static public function getToStringException()
{
return self::$toStringException;
}
/**
* Sets an exception thrown by the __toString() method.
*
* This is a hack needed because PHP does not allow to throw exceptions in __toString() magic method.
*
* @param Exception $e The exception thrown by __toString()
*/
static public function setToStringException(Exception $e)
{
if (null === self::$toStringException)
{
self::$toStringException = $e;
}
}
/**
* Renders the form field.
*
* @param array $attributes An array of HTML attributes
*
* @return string The rendered widget
*/
function render($attributes = array())
{
if ($this->parent)
{
return $this->parent->getWidget()->renderField($this->name, $this->value, $attributes, $this->error);
}
else
{
return $this->widget->render($this->name, $this->value, $attributes, $this->error);
}
}
/**
* Returns a formatted row.
*
* The formatted row will use the parent widget schema formatter.
* The formatted row contains the label, the field, the error and
* the help message.
*
* @param array $attributes An array of HTML attributes to merge with the current attributes
* @param string $label The label name (not null to override the current value)
* @param string $help The help text (not null to override the current value)
*
* @return string The formatted row
*/
public function renderRow($attributes = array(), $label = null, $help = null)
{
if (null === $this->parent)
{
throw new LogicException(sprintf('Unable to render the row for "%s".', $this->name));
}
$field = $this->parent->getWidget()->renderField($this->name, $this->value, !is_array($attributes) ? array() : $attributes, $this->error);
$error = $this->error instanceof sfValidatorErrorSchema ? $this->error->getGlobalErrors() : $this->error;
$help = null === $help ? $this->parent->getWidget()->getHelp($this->name) : $help;
return strtr($this->parent->getWidget()->getFormFormatter()->formatRow($this->renderLabel($label), $field, $error, $help), array('%hidden_fields%' => ''));
}
/**
* Returns a formatted error list.
*
* The formatted list will use the parent widget schema formatter.
*
* @return string The formatted error list
*/
public function renderError()
{
if (null === $this->parent)
{
throw new LogicException(sprintf('Unable to render the error for "%s".', $this->name));
}
$error = $this->getWidget() instanceof sfWidgetFormSchema ? $this->getWidget()->getGlobalErrors($this->error) : $this->error;
return $this->parent->getWidget()->getFormFormatter()->formatErrorsForRow($error);
}
/**
* Returns the help text.
*
* @return string The help text
*/
public function renderHelp()
{
if (null === $this->parent)
{
throw new LogicException(sprintf('Unable to render the help for "%s".', $this->name));
}
return $this->parent->getWidget()->getFormFormatter()->formatHelp($this->parent->getWidget()->getHelp($this->name));
}
/**
* Returns the label tag.
*
* @param string $label The label name (not null to override the current value)
* @param array $attributes Optional html attributes
*
* @return string The label tag
*/
public function renderLabel($label = null, $attributes = array())
{
if (null === $this->parent)
{
throw new LogicException(sprintf('Unable to render the label for "%s".', $this->name));
}
if (null !== $label)
{
$currentLabel = $this->parent->getWidget()->getLabel($this->name);
$this->parent->getWidget()->setLabel($this->name, $label);
}
$html = $this->parent->getWidget()->getFormFormatter()->generateLabel($this->name, $attributes);
if (null !== $label)
{
$this->parent->getWidget()->setLabel($this->name, $currentLabel);
}
return $html;
}
/**
* Returns the label name given a widget name.
*
* @return string The label name
*/
public function renderLabelName()
{
if (null === $this->parent)
{
throw new LogicException(sprintf('Unable to render the label name for "%s".', $this->name));
}
return $this->parent->getWidget()->getFormFormatter()->generateLabelName($this->name);
}
/**
* Returns the name attribute of the widget.
*
* @return string The name attribute of the widget
*/
public function renderName()
{
return $this->parent ? $this->parent->getWidget()->generateName($this->name) : $this->name;
}
/**
* Returns the id attribute of the widget.
*
* @return string The id attribute of the widget
*/
public function renderId()
{
return $this->widget->generateId($this->parent ? $this->parent->getWidget()->generateName($this->name) : $this->name, $this->value);
}
/**
* Returns true if the widget is hidden.
*
* @return Boolean true if the widget is hidden, false otherwise
*/
public function isHidden()
{
return $this->widget->isHidden();
}
/**
* Returns the widget name.
*
* @return mixed The widget name
*/
public function getName()
{
return $this->name;
}
/**
* Returns the widget value.
*
* @return mixed The widget value
*/
public function getValue()
{
return $this->value;
}
/**
* Returns the wrapped widget.
*
* @return sfWidget A sfWidget instance
*/
public function getWidget()
{
return $this->widget;
}
/**
* Returns the parent form field.
*
* @return sfFormField A sfFormField instance
*/
public function getParent()
{
return $this->parent;
}
/**
* Returns the error for this field.
*
* @return sfValidatorError A sfValidatorError instance
*/
public function getError()
{
return $this->error;
}
/**
* Returns true is the field has an error.
*
* @return Boolean true if the field has some errors, false otherwise
*/
public function hasError()
{
return null !== $this->error && count($this->error);
}
}
| mit |
lucahaenni/PictureGallery | code/model/TagModel.php | 1607 | <?php
require_once 'lib/Model.php';
class TagModel extends Model
{
protected $tableName = 'tag';
public function create($name)
{
$query = "INSERT INTO $this->tableName (name) VALUES (?)";
$statement = ConnectionHandler::getConnection()->prepare($query);
$statement->bind_param('s', $name);
if(!$statement->execute()){
throw new Exception($statement->error);
}
}
public function update($id, $name){
$query = "UPDATE $this->tableName SET name=? WHERE id=?";
$statement = ConnectionHandler::getConnection()->prepare($query);
$statement->bind_param('si', $name, $id);
if(!$statement->execute()){
throw new Exception($statement->error);
}
}
public function readByName($name){
$query = "SELECT * FROM $this->tableName WHERE name=?";
$query = ConnectionHandler::getConnection()->prepare($query);
$query->bind_param('s',$name);
$query->execute();
$result = $query->get_result();
if(!$result){
throw new Exception($query->error);
}
$row = $result->fetch_object();
$result->close();
return $row;
}
public function deleteById($id)
{
parent::deleteById($id); // TODO: Change the autogenerated stub
}
public function readAll($max = 100)
{
return parent::readAll($max); // TODO: Change the autogenerated stub
}
public function readById($id)
{
return parent::readById($id); // TODO: Change the autogenerated stub
}
}
| mit |
bbondy/brianbondy.gae | gae_mini_profiler/profiler.py | 23829 | from __future__ import with_statement
import datetime
import time
import logging
import os
import re
import urlparse
import base64
try:
import threading
except ImportError:
import dummy_threading as threading
# use json in Python 2.7, fallback to simplejson for Python 2.5
try:
import json
except ImportError:
import simplejson as json
import StringIO
from types import GeneratorType
import zlib
from google.appengine.api import logservice
from google.appengine.api import memcache
from google.appengine.ext.appstats import recording
from google.appengine.ext.webapp import RequestHandler
import cookies
import pickle
import config
import util
dev_server = os.environ["SERVER_SOFTWARE"].startswith("Devel")
class CurrentRequestId(object):
"""A per-request identifier accessed by other pieces of mini profiler.
It is managed as part of the middleware lifecycle."""
# In production use threading.local() to make request ids threadsafe
_local = threading.local()
_local.request_id = None
# On the devserver don't use threading.local b/c it's reset on Thread.start
dev_server_request_id = None
@staticmethod
def get():
if dev_server:
return CurrentRequestId.dev_server_request_id
else:
return CurrentRequestId._local.request_id
@staticmethod
def set(request_id):
if dev_server:
CurrentRequestId.dev_server_request_id = request_id
else:
CurrentRequestId._local.request_id = request_id
class Mode(object):
"""Possible profiler modes.
TODO(kamens): switch this from an enum to a more sensible bitmask or other
alternative that supports multiple settings without an exploding number of
enums.
TODO(kamens): when this is changed from an enum to a bitmask or other more
sensible object with multiple properties, we should pass a Mode object
around the rest of this code instead of using a simple string that this
static class is forced to examine (e.g. if self.mode.is_rpc_enabled()).
"""
SIMPLE = "simple" # Simple start/end timing for the request as a whole
CPU_INSTRUMENTED = "instrumented" # Profile all function calls
CPU_SAMPLING = "sampling" # Sample call stacks
CPU_LINEBYLINE = "linebyline" # Line-by-line profiling on a subset of functions
RPC_ONLY = "rpc" # Profile all RPC calls
RPC_AND_CPU_INSTRUMENTED = "rpc_instrumented" # RPCs and all fxn calls
RPC_AND_CPU_SAMPLING = "rpc_sampling" # RPCs and sample call stacks
RPC_AND_CPU_LINEBYLINE = "rpc_linebyline" # RPCs and line-by-line profiling
@staticmethod
def get_mode(environ):
"""Get the profiler mode requested by current request's headers &
cookies."""
if "HTTP_G_M_P_MODE" in environ:
mode = environ["HTTP_G_M_P_MODE"]
else:
mode = cookies.get_cookie_value("g-m-p-mode")
if (mode not in [
Mode.SIMPLE,
Mode.CPU_INSTRUMENTED,
Mode.CPU_SAMPLING,
Mode.CPU_LINEBYLINE,
Mode.RPC_ONLY,
Mode.RPC_AND_CPU_INSTRUMENTED,
Mode.RPC_AND_CPU_SAMPLING,
Mode.RPC_AND_CPU_LINEBYLINE]):
mode = Mode.RPC_AND_CPU_INSTRUMENTED
return mode
@staticmethod
def is_rpc_enabled(mode):
return mode in [
Mode.RPC_ONLY,
Mode.RPC_AND_CPU_INSTRUMENTED,
Mode.RPC_AND_CPU_SAMPLING]
@staticmethod
def is_sampling_enabled(mode):
return mode in [
Mode.CPU_SAMPLING,
Mode.RPC_AND_CPU_SAMPLING]
@staticmethod
def is_instrumented_enabled(mode):
return mode in [
Mode.CPU_INSTRUMENTED,
Mode.RPC_AND_CPU_INSTRUMENTED]
@staticmethod
def is_linebyline_enabled(mode):
return mode in [
Mode.CPU_LINEBYLINE,
Mode.RPC_AND_CPU_LINEBYLINE]
class RawSharedStatsHandler(RequestHandler):
def get(self):
request_id = self.request.get("request_id")
request_stats = RequestStats.get(request_id)
if not request_stats:
self.response.out.write("Profiler stats no longer exist for this request.")
return
if not 'raw_stats' in request_stats.profiler_results:
self.response.out.write("No raw states available for this profile")
return
self.response.headers['Content-Disposition'] = (
'attachment; filename="g-m-p-%s.profile"' % str(request_id))
self.response.headers['Content-type'] = "application/octet-stream"
self.response.out.write(
base64.b64decode(request_stats.profiler_results['raw_stats']))
class SharedStatsHandler(RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "templates/shared.html")
request_id = self.request.get("request_id")
if not RequestStats.get(request_id):
self.response.out.write("Profiler stats no longer exist for this request.")
return
# Late-bind templatetags to avoid a circular import.
# TODO(chris): remove late-binding once templatetags has been teased
# apart and no longer contains so many broad dependencies.
import templatetags
profiler_includes = templatetags.profiler_includes_request_id(request_id, True)
# We are not using a templating engine here to avoid pulling in Jinja2
# or Django. It's an admin page anyway, and all other templating lives
# in javascript right now.
with open(path, 'rU') as f:
template = f.read()
template = template.replace('{{profiler_includes}}', profiler_includes)
self.response.out.write(template)
class RequestLogHandler(RequestHandler):
"""Handler for retrieving and returning a RequestLog from GAE's logs API.
See https://developers.google.com/appengine/docs/python/logs.
This GET request accepts a logging_request_id via query param that matches
the request_id from an App Engine RequestLog.
It returns a JSON object that contains the pieces of RequestLog info we
find most interesting, such as pending_ms and loading_request.
"""
def get(self):
self.response.headers["Content-Type"] = "application/json"
dict_request_log = None
# This logging_request_id should match a request_id from an App Engine
# request log.
# https://developers.google.com/appengine/docs/python/logs/functions
logging_request_id = self.request.get("logging_request_id")
# Grab the single request log from logservice
logs = logservice.fetch(request_ids=[logging_request_id])
# This slightly strange query result implements __iter__ but not next,
# so we have to iterate to get our expected single result.
for log in logs:
dict_request_log = {
"pending_ms": log.pending_time, # time spent in pending queue
"loading_request": log.was_loading_request, # loading request?
"logging_request_id": logging_request_id
}
# We only expect a single result.
break
# Log fetching doesn't work on the dev server and this data isn't
# relevant in dev server's case, so we return a simple fake response.
if dev_server:
dict_request_log = {
"pending_ms": 0,
"loading_request": False,
"logging_request_id": logging_request_id
}
self.response.out.write(json.dumps(dict_request_log))
class RequestStatsHandler(RequestHandler):
def get(self):
self.response.headers["Content-Type"] = "application/json"
list_request_ids = []
request_ids = self.request.get("request_ids")
if request_ids:
list_request_ids = request_ids.split(",")
list_request_stats = []
for request_id in list_request_ids:
request_stats = RequestStats.get(request_id)
if request_stats and not request_stats.disabled:
dict_request_stats = {}
for property in RequestStats.serialized_properties:
dict_request_stats[property] = request_stats.__getattribute__(property)
list_request_stats.append(dict_request_stats)
# Don't show temporary redirect profiles more than once automatically, as they are
# tied to URL params and may be copied around easily.
if request_stats.temporary_redirect:
request_stats.disabled = True
request_stats.store()
self.response.out.write(json.dumps(list_request_stats))
class RequestStats(object):
serialized_properties = ["request_id", "url", "s_dt",
"profiler_results", "appstats_results", "mode",
"temporary_redirect", "logs",
"logging_request_id"]
def __init__(self, profiler, environ):
# unique mini profiler request id
self.request_id = profiler.request_id
# App Engine's logservice request_id
# https://developers.google.com/appengine/docs/python/logs/
self.logging_request_id = profiler.logging_request_id
self.url = environ.get("PATH_INFO")
if environ.get("QUERY_STRING"):
self.url += "?%s" % environ.get("QUERY_STRING")
self.mode = profiler.mode
self.s_dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.profiler_results = profiler.profiler_results()
self.appstats_results = profiler.appstats_results()
self.logs = profiler.logs
self.temporary_redirect = profiler.temporary_redirect
self.disabled = False
def store(self):
# Store compressed results so we stay under the memcache 1MB limit
pickled = pickle.dumps(self)
compressed_pickled = zlib.compress(pickled)
if len(compressed_pickled) > memcache.MAX_VALUE_SIZE:
logging.warning('RequestStats bigger (%d) '
+ 'than max memcache size (%d), even after compression',
len(compressed_pickled), memcache.MAX_VALUE_SIZE)
return False
return memcache.set(RequestStats.memcache_key(self.request_id), compressed_pickled)
@staticmethod
def get(request_id):
if request_id:
compressed_pickled = memcache.get(RequestStats.memcache_key(request_id))
if compressed_pickled:
pickled = zlib.decompress(compressed_pickled)
return pickle.loads(pickled)
return None
@staticmethod
def memcache_key(request_id):
if not request_id:
return None
return "__gae_mini_profiler_request_%s" % request_id
class RequestProfiler(object):
"""Profile a single request."""
def __init__(self, request_id, mode):
self.request_id = request_id
self.mode = mode
self.instrumented_prof = None
self.sampling_prof = None
self.linebyline_prof = None
self.appstats_prof = None
self.temporary_redirect = False
self.handler = None
self.logs = None
self.logging_request_id = self.get_logging_request_id()
self.start = None
self.end = None
def profiler_results(self):
"""Return the CPU profiler results for this request, if any.
This will return a dictionary containing results for either the
sampling profiler, instrumented profiler results, or a simple
start/stop timer if both profilers are disabled."""
total_time = util.seconds_fmt(self.end - self.start, 0)
results = {"total_time": total_time}
if self.instrumented_prof:
results.update(self.instrumented_prof.results())
elif self.sampling_prof:
results.update(self.sampling_prof.results())
elif self.linebyline_prof:
results.update(self.linebyline_prof.results())
return results
def appstats_results(self):
"""Return the RPC profiler (appstats) results for this request, if any.
This will return a dictionary containing results from appstats or an
empty result set if appstats profiling is disabled."""
results = {
"calls": [],
"total_time": 0,
}
if self.appstats_prof:
results.update(self.appstats_prof.results())
return results
def profile_start_response(self, app, environ, start_response):
"""Collect and store statistics for a single request.
Use this method from middleware in place of the standard
request-serving pattern. Do:
profiler = RequestProfiler(...)
return profiler(app, environ, start_response)
Instead of:
return app(environ, start_response)
Depending on the mode, this method gathers timing information
and an execution profile and stores them in the datastore for
later access.
"""
# Always track simple start/stop time.
self.start = time.time()
if self.mode == Mode.SIMPLE:
# Detailed recording is disabled.
result = app(environ, start_response)
for value in result:
yield value
else:
# Add logging handler
self.add_handler()
if Mode.is_rpc_enabled(self.mode):
# Turn on AppStats monitoring for this request
# Note that we don't import appstats_profiler at the top of
# this file so we don't bring in a lot of imports for users who
# don't have the profiler enabled.
from . import appstats_profiler
self.appstats_prof = appstats_profiler.Profile()
app = self.appstats_prof.wrap(app)
# By default, we create a placeholder wrapper function that
# simply calls whatever function it is passed as its first
# argument.
result_fxn_wrapper = lambda fxn: fxn()
# TODO(kamens): both sampling_profiler and instrumented_profiler
# could subclass the same class. Then they'd both be guaranteed to
# implement run(), and the following if/else could be simplified.
if Mode.is_sampling_enabled(self.mode):
# Turn on sampling profiling for this request.
# Note that we don't import sampling_profiler at the top of
# this file so we don't bring in a lot of imports for users who
# don't have the profiler enabled.
from . import sampling_profiler
self.sampling_prof = sampling_profiler.Profile()
result_fxn_wrapper = self.sampling_prof.run
elif Mode.is_linebyline_enabled(self.mode):
from . import linebyline_profiler
self.linebyline_prof = linebyline_profiler.Profile()
result_fxn_wrapper = self.linebyline_prof.run
elif Mode.is_instrumented_enabled(self.mode):
# Turn on cProfile instrumented profiling for this request
# Note that we don't import instrumented_profiler at the top of
# this file so we don't bring in a lot of imports for users who
# don't have the profiler enabled.
from . import instrumented_profiler
self.instrumented_prof = instrumented_profiler.Profile()
result_fxn_wrapper = self.instrumented_prof.run
# Get wsgi result
result = result_fxn_wrapper(lambda: app(environ, start_response))
# If we're dealing w/ a generator, profile all of the .next calls as well
if type(result) == GeneratorType:
while True:
try:
yield result_fxn_wrapper(result.next)
except StopIteration:
break
else:
for value in result:
yield value
self.logs = self.get_logs(self.handler)
logging.getLogger().removeHandler(self.handler)
self.handler.stream.close()
self.handler = None
self.end = time.time()
# Store stats for later access
RequestStats(self, environ).store()
def get_logging_request_id(self):
"""Return the identifier for this request used by GAE's logservice.
This logging_request_id will match the request_id parameter of a
RequestLog object stored in App Engine's logging API:
https://developers.google.com/appengine/docs/python/logs/
"""
return os.environ.get("REQUEST_LOG_ID", None)
def add_handler(self):
if self.handler is None:
self.handler = RequestProfiler.create_handler()
logging.getLogger().addHandler(self.handler)
@staticmethod
def create_handler():
handler = logging.StreamHandler(StringIO.StringIO())
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("\t".join([
'%(levelno)s',
'%(asctime)s%(msecs)d',
'%(funcName)s',
'%(filename)s',
'%(lineno)d',
'%(message)s',
]), '%M:%S.')
handler.setFormatter(formatter)
return handler
@staticmethod
def get_logs(handler):
raw_lines = [l for l in handler.stream.getvalue().split("\n") if l]
lines = []
for line in raw_lines:
if "\t" in line:
fields = line.split("\t")
lines.append(fields)
else: # line is part of a multiline log message (prob a traceback)
prevline = lines[-1][-1]
if prevline: # ignore leading blank lines in the message
prevline += "\n"
prevline += line
lines[-1][-1] = prevline
return lines
class ProfilerWSGIMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
CurrentRequestId.set(None)
# Never profile calls to the profiler itself to avoid endless recursion.
if (not config.should_profile() or
environ.get("PATH_INFO", "").startswith("/gae_mini_profiler/")):
result = self.app(environ, start_response)
for value in result:
yield value
else:
# Set a random ID for this request so we can look up stats later
import base64
CurrentRequestId.set(base64.urlsafe_b64encode(os.urandom(5)))
# Send request id in headers so jQuery ajax calls can pick
# up profiles.
def profiled_start_response(status, headers, exc_info = None):
if status.startswith("302 "):
# Temporary redirect. Add request identifier to redirect location
# so next rendered page can show this request's profile.
headers = ProfilerWSGIMiddleware.headers_with_modified_redirect(environ, headers)
# Access the profiler in closure scope
profiler.temporary_redirect = True
# Append headers used when displaying profiler results from ajax requests
headers.append(("X-MiniProfiler-Id", CurrentRequestId.get()))
headers.append(("X-MiniProfiler-QS", environ.get("QUERY_STRING")))
return start_response(status, headers, exc_info)
# As a simple form of rate-limiting, appstats protects all
# its work with a memcache lock to ensure that only one
# appstats request ever runs at a time, across all
# appengine instances. (GvR confirmed this is the purpose
# of the lock). So our attempt to profile will fail if
# appstats is running on another instance. Boo-urns! We
# just turn off the lock-checking for us, which means we
# don't rate-limit quite as much with the mini-profiler as
# we would do without.
old_memcache_add = memcache.add
old_memcache_delete = memcache.delete
memcache.add = (lambda key, *args, **kwargs:
(True if key == recording.lock_key()
else old_memcache_add(key, *args, **kwargs)))
memcache.delete = (lambda key, *args, **kwargs:
(True if key == recording.lock_key()
else old_memcache_delete(key, *args, **kwargs)))
try:
profiler = RequestProfiler(CurrentRequestId.get(),
Mode.get_mode(environ))
result = profiler.profile_start_response(self.app, environ, profiled_start_response)
for value in result:
yield value
finally:
CurrentRequestId.set(None)
memcache.add = old_memcache_add
memcache.delete = old_memcache_delete
@staticmethod
def headers_with_modified_redirect(environ, headers):
"""Return headers with redirects modified to include miniprofiler id.
If this response is a redirect, we want the URL that's redirected *to*
to be able to display the profiler results from *this* request that's
being redirected *from*. We do this by adding a query string param,
'mp-r-id', to the location that is being redirected to. (mp-r-id stands
for mini profiler redirect id.) The value of this parameter is a unique
identifier for the profiler results for the current request that is
being redirected from.
The mini profiler then knows how to use this id to display profiler
results for two requests: the original request that redirected and the
request that was served as a result of the redirect.
e.g. if this set of headers is attempting to redirect to
Location:http://khanacademy.org?login, the modified header will be:
Location:http://khanacademy.org?login&mp-r-id={current request id}
"""
headers_modified = []
for header in headers:
if header[0] == "Location":
reg = re.compile("mp-r-id=([^&]+)")
# Keep any chain of redirects around
request_id_chain = CurrentRequestId.get()
match = reg.search(environ.get("QUERY_STRING"))
if match:
request_id_chain = ",".join([match.groups()[0], request_id_chain])
# Remove any pre-existing miniprofiler redirect id
url_parts = list(urlparse.urlparse(header[1]))
query_string = reg.sub("", url_parts[4])
# Add current request id as miniprofiler redirect id
if query_string and not query_string.endswith("&"):
query_string += "&"
query_string += "mp-r-id=%s" % request_id_chain
url_parts[4] = query_string
# Swap in the modified Location: header.
location = urlparse.urlunparse(url_parts)
headers_modified.append((header[0], location))
else:
headers_modified.append(header)
return headers_modified
| mit |
camwest/angular-ace | lib/angular-ace.js | 1433 | angular.module('ace', []).directive('ace', function() {
var ACE_EDITOR_CLASS = 'ace-editor';
function loadAceEditor(element, mode) {
var editor = ace.edit($(element).find('.' + ACE_EDITOR_CLASS)[0]);
editor.session.setMode("ace/mode/" + mode);
editor.renderer.setShowPrintMargin(false);
return editor;
}
function valid(editor) {
return (Object.keys(editor.getSession().getAnnotations()).length == 0);
}
return {
restrict: 'A',
require: '?ngModel',
transclude: true,
template: '<div class="transcluded" ng-transclude></div><div class="' + ACE_EDITOR_CLASS + '"></div>',
link: function(scope, element, attrs, ngModel) {
var textarea = $(element).find('textarea');
textarea.hide();
var mode = attrs.ace;
var editor = loadAceEditor(element, mode);
scope.ace = editor;
if (!ngModel) return; // do nothing if no ngModel
ngModel.$render = function() {
var value = ngModel.$viewValue || '';
editor.getSession().setValue(value);
textarea.val(value);
};
editor.getSession().on('change', function() {
if (valid(editor) && !scope.$$phase) {
scope.$apply(read);
}
});
editor.getSession().setValue(textarea.val());
read();
function read() {
ngModel.$setViewValue(editor.getValue());
textarea.val(editor.getValue());
}
}
}
});
| mit |
wqcsimple/dzjs | vendor/fayfox/widgets/images/controllers/IndexController.php | 768 | <?php
namespace fayfox\widgets\images\controllers;
use fayfox\core\Widget;
class IndexController extends Widget{
public function index($data){
//template
if(empty($data['template'])){
$this->view->render('template', array(
'files'=>isset($data['files']) ? $data['files'] : array(),
'data'=>$data,
'alias'=>$this->alias,
));
}else{
if(preg_match('/^[\w_-]+\/[\w_-]+\/[\w_-]+$/', $data['template'])){
\F::app()->view->renderPartial($data['template'], array(
'files'=>isset($data['files']) ? $data['files'] : array(),
'data'=>$data,
'alias'=>$this->alias,
));
}else{
$alias = $this->alias;
$files = isset($data['files']) ? $data['files'] : array();
eval('?>'.$data['template'].'<?php ');
}
}
}
} | mit |
OlafLee/keras | keras/layers/containers.py | 7878 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import theano.tensor as T
from ..layers.core import Layer, Merge
from six.moves import range
def ndim_tensor(ndim):
if ndim == 2:
return T.matrix()
elif ndim == 3:
return T.tensor3()
elif ndim == 4:
return T.tensor4()
return T.matrix()
class Sequential(Layer):
'''
contain layers and their params regularizers and constraints
Simple linear stack of layers.
inherited from Layer:
- get_params
- get_output_mask
- supports_masked_input
'''
def __init__(self, layers=[]):
self.layers = []
self.params = []
self.regularizers = []
self.constraints = []
for layer in layers:
self.add(layer)
def set_previous(self, layer):
self.layers[0].previous = layer
def add(self, layer):
self.layers.append(layer)
if len(self.layers) > 1:
self.layers[-1].set_previous(self.layers[-2])
params, regularizers, constraints = layer.get_params()
self.params += params
self.regularizers += regularizers
self.constraints += constraints
def get_output(self, train=False):
return self.layers[-1].get_output(train)
def set_input(self):
for l in self.layers:
if hasattr(l, 'input'):
ndim = l.input.ndim
self.layers[0].input = ndim_tensor(ndim)
break
def get_input(self, train=False):
if not hasattr(self.layers[0], 'input'):
self.set_input()
return self.layers[0].get_input(train)
@property
def input(self):
return self.get_input()
def get_weights(self):
weights = []
for layer in self.layers:
weights += layer.get_weights()
return weights
def set_weights(self, weights):
for i in range(len(self.layers)):
nb_param = len(self.layers[i].params)
self.layers[i].set_weights(weights[:nb_param])
weights = weights[nb_param:]
def get_config(self):
return {"name": self.__class__.__name__,
"layers": [layer.get_config() for layer in self.layers]}
class Graph(Layer):
'''
Implement a NN graph with arbitrary layer connections,
arbitrary number of inputs and arbitrary number of outputs.
Note: Graph can only be used as a layer
(connect, input, get_input, get_output)
when it has exactly one input and one output.
inherited from Layer:
- get_params
- get_output_mask
- supports_masked_input
- get_weights
- set_weights
'''
def __init__(self):
self.namespace = set() # strings
self.nodes = {} # layer-like
self.inputs = {} # layer-like
self.input_order = [] # strings
self.outputs = {} # layer-like
self.output_order = [] # strings
self.input_config = [] # dicts
self.output_config = [] # dicts
self.node_config = [] # dicts
self.params = []
self.regularizers = []
self.constraints = []
def set_previous(self, layer):
if len(self.inputs) != 1 or len(self.outputs) != 1:
raise Exception('The Graph container can only be used as a layer \
when it has exactly one input and one output.')
self.inputs[self.input_order[0]].set_previous(layer)
def get_input(self, train=False):
if len(self.inputs) != 1 or len(self.outputs) != 1:
raise Exception('The Graph container can only be used as a layer \
when it has exactly one input and one output.')
return self.inputs[self.input_order[0]].get_input(train)
@property
def input(self):
return self.get_input()
def get_output(self, train=False):
if len(self.inputs) != 1 or len(self.outputs) != 1:
raise Exception('The Graph container can only be used as a layer \
when it has exactly one input and one output.')
return self.outputs[self.output_order[0]].get_output(train)
def add_input(self, name, ndim=2, dtype='float'):
if name in self.namespace:
raise Exception('Duplicate node identifier: ' + name)
self.namespace.add(name)
self.input_order.append(name)
layer = Layer() # empty layer
if dtype == 'float':
layer.input = ndim_tensor(ndim)
else:
if ndim == 2:
layer.input = T.imatrix()
else:
raise Exception('Type "int" can only be used with ndim==2.')
layer.input.name = name
self.inputs[name] = layer
self.input_config.append({'name': name, 'ndim': ndim, 'dtype': dtype})
def add_node(self, layer, name, input=None, inputs=[], merge_mode='concat'):
if hasattr(layer, 'set_name'):
layer.set_name(name)
if name in self.namespace:
raise Exception('Duplicate node identifier: ' + name)
if input:
if input not in self.namespace:
raise Exception('Unknown identifier: ' + input)
if input in self.nodes:
layer.set_previous(self.nodes[input])
elif input in self.inputs:
layer.set_previous(self.inputs[input])
if inputs:
to_merge = []
for n in inputs:
if n in self.nodes:
to_merge.append(self.nodes[n])
elif n in self.inputs:
to_merge.append(self.inputs[n])
else:
raise Exception('Unknown identifier: ' + n)
merge = Merge(to_merge, mode=merge_mode)
layer.set_previous(merge)
self.namespace.add(name)
self.nodes[name] = layer
self.node_config.append({'name': name,
'input': input,
'inputs': inputs,
'merge_mode': merge_mode})
params, regularizers, constraints = layer.get_params()
self.params += params
self.regularizers += regularizers
self.constraints += constraints
def add_output(self, name, input=None, inputs=[], merge_mode='concat'):
if name in self.namespace:
raise Exception('Duplicate node identifier: ' + name)
if input:
if input not in self.namespace:
raise Exception('Unknown identifier: ' + input)
if input in self.nodes:
self.outputs[name] = self.nodes[input]
elif input in self.inputs:
self.ouputs[name] = self.inputs[input]
if inputs:
to_merge = []
for n in inputs:
if n not in self.nodes:
raise Exception('Unknown identifier: ' + n)
to_merge.append(self.nodes[n])
merge = Merge(to_merge, mode=merge_mode)
self.outputs[name] = merge
self.namespace.add(name)
self.output_order.append(name)
self.output_config.append({'name': name,
'input': input,
'inputs': inputs,
'merge_mode': merge_mode})
def get_config(self):
return {"name": self.__class__.__name__,
"input_config": self.input_config,
"node_config": self.node_config,
"output_config": self.output_config,
"input_order": self.input_order,
"output_order": self.output_order,
"nodes": dict([(c["name"], self.nodes[c["name"]].get_config()) for c in self.node_config])}
| mit |
vkurko/LadelaFormBundle | Twig/FormExtension.php | 4841 | <?php
namespace Ladela\FormBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\FormView;
/**
* Class FormExtension
* @package Ladela\FormBundle\Twig
*/
class FormExtension extends \Twig_Extension
{
/**
* Get function methods
*
* @return array
*/
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('form_js', array($this, 'renderFormJavascript'), array('is_safe' => array('html'))),
new \Twig_SimpleFunction('form_css', array($this, 'renderFormStylesheet'), array('is_safe' => array('html'))),
);
}
/**
* @param FormView $form
* @return string
*/
public function renderFormJavascript(FormView $form)
{
$javascript = '';
foreach ($form as $field) {
if (isset ($field->vars['javascript']) && is_array($field->vars['javascript'])) {
foreach ($field->vars['javascript'] as $plugin => $options) {
switch ($plugin) {
case 'datepicker':
$javascript .= $this->buildDatepickerJs($field, $options);
break;
case 'single_image':
$javascript .= $this->buildSingleImageJs($field, $options);
break;
}
}
}
}
return empty ($javascript) ? : sprintf(
'<script type="text/javascript">jQuery(function($){%s});</script>',
$javascript
);
}
/**
* @param FormView $form
* @return string
*/
public function renderFormStylesheet(FormView $form)
{
$stylesheet = '';
foreach ($form as $field) {
if (isset ($field->vars['stylesheet']) && is_array($field->vars['stylesheet'])) {
foreach ($field->vars['stylesheet'] as $plugin => $options) {
switch ($plugin) {
case 'datepicker':
$stylesheet .= $this->buildDatepickerCss($field, $options);
break;
case 'single_image':
$stylesheet .= $this->buildSingleImageCss($field, $options);
break;
}
}
}
}
return empty ($stylesheet) ? : sprintf('<style type="text/css">%s</style>', $stylesheet);
}
/**
* Build javascript for jQuery Datepicker
*
* @param FormView $field
* @param array $options
* @return string
*/
protected function buildDatepickerJs(FormView $field, array $options) {
return sprintf('$("#%s").datepicker(%s);', $field->vars['id'], json_encode($options));
}
/**
* Build stylesheet for jQuery Datepicker
*
* @param FormView $field
* @param array $options
* @return string
*/
protected function buildDatepickerCss(FormView $field, array $options) {
return '';
}
/**
* Build javascript for Single Image.
*
* @param FormView $field
* @param array $options
* @return string
*/
protected function buildSingleImageJs(FormView $field, array $options) {
return sprintf('
$("#single-image-preview-%1$s img").on("click", function() {
$("#%1$s").trigger("click");
});
if (typeof window["FileReader"] !== "undefined") {
$("#%1$s").change(function() {
var input = this;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#single-image-preview-%1$s img").attr("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
});
} else {
$("#%1$s").show();
}', $field->vars['id']);
}
/**
* Build stylesheet for Single Image.
*
* @param FormView $field
* @param array $options
* @return string
*/
protected function buildSingleImageCss(FormView $field, array $options) {
return '.single-image-preview img:hover {
-webkit-box-shadow: 0 0 5px 0 rgba(40, 111, 252, 0.75);
-moz-box-shadow: 0 0 5px 0 rgba(40, 111, 252, 0.75);
box-shadow: 0 0 5px 0 rgba(40, 111, 252, 0.75);
cursor: pointer;
}';
}
/**
* Get the name of the extension
*
* @return string
*/
public function getName()
{
return 'ladela_form_extension';
}
} | mit |
crashr42/docker_hosting | lib/docker_hosting/database_server_dockerfile.rb | 1098 | require 'docker_hosting/helpers/docker_helpers'
module DockerHosting
class DatabaseServerDockerfile
include DockerHosting::Helpers::DockerHelpers
attr_accessor :config
def initialize(config = {})
@config = config
end
def build!
[
'FROM centos',
build_database,
build_cmd,
''
].join("\n")
end
def image_tag
[config.app_name, config.app_env, 'db'].map(&:underscore).join('_')
end
private
def build_database
case config.app_database['adapter']
when 'postgresql'
package_file = File.basename(config.postgresql_package)
[
cmd_run(['cd /opt',
"wget #{config.postgresql_package}",
"rpm -Uvh #{package_file}",
"rm -rf #{package_file}"]),
cmd_env_path(config.postgresql_bin),
cmd_run("#{config.postgresql_ctrl} start")
]
else
raise "Unknown database adapter #{config.app_database['adapter']}"
end
end
end
end
| mit |
openlab-vn-ua/NanoWin32 | src/NanoWinFileSys.cpp | 13426 | // NanoWin32
// -----------------------------------------------------------------------
// Simple library to subset Win32(64) API functions implemenation on POSIX
// This software distributed by MIT license
// FileSys functions
#include "NanoWinFileSys.h"
#include "NanoWinStrConvert.h"
#include "NanoWinError.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <string>
#include <wchar.h>
#include <stdlib.h>
NW_EXTERN_C_BEGIN
extern BOOL WINAPI PathFileExistsA (_In_ LPCSTR lpPath)
{
if (lpPath == NULL)
{
SetLastError(ERROR_INVALID_DATA);
return(FALSE);
}
if (access(lpPath, F_OK) == 0)
{
return(TRUE);
}
SetLastError(ERROR_FILE_NOT_FOUND);
return(FALSE);
}
extern BOOL WINAPI PathFileExistsW (_In_ LPCWSTR lpPath)
{
NanoWin::WStrToStrClone sPath(lpPath);
return(PathFileExistsA(sPath.c_str()));
}
static bool CurrDirCalculateRequiredBufferSize (_Out_ DWORD *requiredBufferSize, _In_ DWORD startBufferSize)
{
constexpr size_t MAX_BUFFER_SIZE = 32 * 1024;
size_t currBufferSize = startBufferSize;
bool requiredSizeFound = false;
bool errorFlag = false;
char *buffer = NULL;
while (!errorFlag && !requiredSizeFound && currBufferSize <= MAX_BUFFER_SIZE)
{
char *temp = (char*)realloc(buffer, currBufferSize);
if (temp != NULL)
{
buffer = temp;
if (getcwd(buffer, currBufferSize) != NULL)
{
*requiredBufferSize = static_cast<DWORD>(strlen(buffer) + 1);
requiredSizeFound = true;
}
else
{
if (errno == ERANGE)
{
currBufferSize *= 2;
}
else
{
errorFlag = true;
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
}
}
else
{
errorFlag = true;
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
}
}
free(buffer);
return requiredSizeFound;
}
extern DWORD WINAPI GetCurrentDirectoryA (_In_ DWORD nBufferLength, _Out_ LPSTR lpBuffer)
{
DWORD result = 0;
if (lpBuffer == NULL)
{
constexpr DWORD START_BUFFER_SIZE = 512;
CurrDirCalculateRequiredBufferSize(&result, START_BUFFER_SIZE);
}
else
{
if (getcwd(lpBuffer, nBufferLength) != NULL)
{
// ok, return number of characters written not including null character
result = static_cast<DWORD>(strlen(lpBuffer));
}
else
{
if (errno == ERANGE)
{
// buffer is too small, need to return required size of buffer
CurrDirCalculateRequiredBufferSize(&result, nBufferLength);
}
else
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
}
}
return result;
}
extern DWORD WINAPI GetCurrentDirectoryW (_In_ DWORD nBufferLength, _Out_ LPWSTR lpBuffer)
{
char buffer[PATH_MAX];
DWORD multiByteLen;
char *currBuffer = buffer;
DWORD currBufferSize = sizeof(buffer);
// try to get current directory with local (non-heap) buffer
multiByteLen = GetCurrentDirectoryA(sizeof(buffer), buffer);
// dynamically allocate buffer if local buffer was too small.
// need to do it in a loop since current dir can be changed between the
// calls and returned length value may be outdated on subsequent call
while (multiByteLen > 0 && multiByteLen >= currBufferSize && currBuffer != NULL)
{
if (currBuffer == buffer)
{
currBuffer = (char*)malloc(multiByteLen);
}
else
{
char *tempBuffer = (char*)realloc(currBuffer, multiByteLen);
if (tempBuffer != NULL)
{
currBuffer = tempBuffer;
}
else
{
free(currBuffer);
currBuffer = NULL;
}
}
if (currBuffer != NULL)
{
currBufferSize = multiByteLen;
multiByteLen = GetCurrentDirectoryA(currBufferSize, currBuffer);
}
}
DWORD result = 0;
if (multiByteLen == 0)
{
}
else if (currBuffer == NULL)
{
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
}
else
{
std::wstring wideCurrDir;
try
{
wideCurrDir = NanoWin::StrConverter::Convert(currBuffer);
size_t wideCurrDirLen = wideCurrDir.length();
if (lpBuffer != NULL)
{
if (nBufferLength > wideCurrDirLen)
{
wcscpy(lpBuffer, wideCurrDir.c_str());
result = static_cast<DWORD>(wideCurrDirLen);
}
else
{
result = static_cast<DWORD>(wideCurrDirLen + 1);
}
}
else
{
result = static_cast<DWORD>(wideCurrDirLen + 1);
}
}
catch (NanoWin::StrConverter::Error)
{
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
}
}
if (currBuffer != buffer)
{
free(currBuffer);
}
return result;
}
extern BOOL WINAPI SetCurrentDirectoryA(_In_ LPCSTR lpPathName)
{
if (chdir(lpPathName) != 0)
{
NanoWinSetLastError(NanoWinErrorByErrnoAtFail(errno));
return FALSE;
}
else
{
return TRUE;
}
}
extern BOOL WINAPI SetCurrentDirectoryW(_In_ LPCWSTR lpPathName)
{
try
{
NanoWin::WStrToStrClone lpPathNameMb(lpPathName);
if (lpPathNameMb.is_valid())
{
return SetCurrentDirectoryA(lpPathNameMb.c_str());
}
else
{
NanoWinSetLastError(ERROR_NO_UNICODE_TRANSLATION);
return FALSE;
}
}
catch (std::bad_alloc&)
{
NanoWinSetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
}
extern BOOL WINAPI CreateDirectoryA (_In_ LPCSTR lpPathName, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
mode_t mode = lpSecurityAttributes == NULL ? (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) : (S_IRWXU);
if (mkdir(lpPathName, mode) != 0)
{
switch (errno)
{
case (EEXIST) :
{
SetLastError(ERROR_ALREADY_EXISTS);
} break;
case (ENOENT) :
{
SetLastError(ERROR_PATH_NOT_FOUND);
} break;
default :
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
}
return FALSE;
}
else
{
return TRUE;
}
}
extern BOOL WINAPI CreateDirectoryW (_In_ LPCWSTR lpPathName, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
try
{
std::string mbPathName = NanoWin::StrConverter::Convert(lpPathName);
return CreateDirectoryA(mbPathName.c_str(), lpSecurityAttributes);
}
catch (NanoWin::StrConverter::Error)
{
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
return FALSE;
}
}
static FILE *OpenFileForCopySrc(const char *fileName)
{
FILE *result = fopen(fileName,"rb");
if (result == NULL)
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
return result;
}
static FILE *OpenFileForCopyDst(const char *fileName, bool failIfExists)
{
FILE *result = NULL;
if (failIfExists)
{
// use the restrictive mode (owner read-write only) here assuming that after
// copying file content its mode will be copied from source file
int handle = open(fileName,O_EXCL | O_CREAT, S_IRUSR | S_IWUSR);
if (handle >= 0)
{
result = fdopen(handle,"wb");
if (result == NULL)
{
close(handle);
}
}
}
else
{
result = fopen(fileName,"wb");
}
if (result == NULL)
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
return result;
}
static bool CopyFileContent(FILE *dstFile, FILE *srcFile)
{
constexpr size_t COPY_BLOCK_SIZE = 32 * 1024;
unsigned char buffer[COPY_BLOCK_SIZE];
bool done = false;
bool ok = true;
while (ok && !done)
{
size_t read_size = fread(buffer,1,sizeof(buffer),srcFile);
if (read_size < sizeof(buffer))
{
ok = ferror(srcFile) == 0;
}
if (ok && read_size > 0)
{
if (fwrite(buffer, 1, read_size, dstFile) < read_size)
{
ok = false;
}
}
else
{
done = read_size == 0;
}
}
if (!ok)
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
return ok;
}
static bool CopyFileAttributes(const char *dstFileName, const char *srcFileName)
{
struct stat fileStat;
bool ok = false;
if (stat(srcFileName,&fileStat) == 0)
{
ok = chown(dstFileName, fileStat.st_uid, fileStat.st_gid) == 0;
ok = chmod(dstFileName, fileStat.st_mode & (~S_IFMT)) && ok;
}
return ok;
}
extern BOOL WINAPI CopyFileA (_In_ LPCSTR lpExistingFileName, _In_ LPCSTR lpNewFileName, _In_ BOOL bFailIfExists)
{
BOOL ok = FALSE;
FILE *srcFileStream = OpenFileForCopySrc(lpExistingFileName);
if (srcFileStream != NULL)
{
FILE *dstFileStream = OpenFileForCopyDst(lpNewFileName,bFailIfExists);
if (dstFileStream != NULL)
{
ok = CopyFileContent(dstFileStream,srcFileStream);
if (fclose(dstFileStream) != 0)
{
if (ok)
{
ok = FALSE; // FIXME: set last error
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
}
}
fclose(srcFileStream);
}
if (ok)
{
CopyFileAttributes(lpNewFileName,lpExistingFileName);
}
return(ok);
}
extern BOOL WINAPI CopyFileW (_In_ LPCWSTR lpExistingFileName, _In_ LPCWSTR lpNewFileName, _In_ BOOL bFailIfExists)
{
try
{
std::string mbExistingFileName = NanoWin::StrConverter::Convert(lpExistingFileName);
std::string mbNewFileName = NanoWin::StrConverter::Convert(lpNewFileName);
return CopyFileA(mbExistingFileName.c_str(), mbNewFileName.c_str(), bFailIfExists);
}
catch (NanoWin::StrConverter::Error)
{
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
return FALSE;
}
}
extern BOOL WINAPI DeleteFileA (_In_ LPCSTR lpFileName)
{
if (unlink(lpFileName) == 0)
{
return(TRUE);
}
else
{
if (errno == ENOENT)
{
SetLastError(ERROR_FILE_NOT_FOUND);
}
else if (errno == EACCES)
{
SetLastError(ERROR_ACCESS_DENIED);
}
else
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
}
return(FALSE);
}
}
extern BOOL WINAPI DeleteFileW (_In_ LPCWSTR lpFileName)
{
NanoWin::WStrToStrClone sFileName(lpFileName);
return(DeleteFileA(sFileName.c_str()));
}
extern DWORD GetFileAttributesA (_In_ LPCSTR lpFileName)
{
struct stat st;
if (stat(lpFileName, &st) != 0)
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
return(INVALID_FILE_ATTRIBUTES);
}
DWORD result = 0;
if (S_ISDIR(st.st_mode))
{
result |= FILE_ATTRIBUTE_DIRECTORY;
}
else if (S_ISREG(st.st_mode))
{
if ((st.st_mode & S_IWUSR) == 0) // Valid on files only, because absense of "write" permission on directory means different thing
{
result |= FILE_ATTRIBUTE_READONLY;
}
else
{
result = FILE_ATTRIBUTE_NORMAL;
}
}
else
{
result = 0; // Keep it zero for system files, devices, etc
}
return(result);
}
extern DWORD GetFileAttributesW (_In_ LPCWSTR lpFileName)
{
try
{
std::string mbPathName = NanoWin::StrConverter::Convert(lpFileName);
return GetFileAttributesA(mbPathName.c_str());
}
catch (NanoWin::StrConverter::Error)
{
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
return INVALID_FILE_ATTRIBUTES;
}
}
extern BOOL SetFileAttributesA(_In_ LPCSTR lpFileName, _In_ DWORD dwFileAttributes)
{
struct stat st;
if (stat(lpFileName, &st) != 0)
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
return(FALSE);
}
if (!S_ISREG(st.st_mode))
{
SetLastError(ERROR_INVALID_PARAMETER);
return(FALSE);
}
else
{
if (dwFileAttributes == FILE_ATTRIBUTE_NORMAL ||
dwFileAttributes == 0 ||
dwFileAttributes == FILE_ATTRIBUTE_READONLY)
{
mode_t oldMode = st.st_mode;
mode_t newMode;
if (dwFileAttributes & FILE_ATTRIBUTE_READONLY)
{
newMode = oldMode & (~S_IWUSR);
newMode &= ~S_IWGRP;
newMode &= ~S_IWOTH;
}
else
{
newMode = oldMode | S_IWUSR; // enable "write" permissions for file owner only
}
if (newMode != oldMode)
{
if (chmod(lpFileName, newMode) == 0)
{
return TRUE;
}
else
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
return(FALSE);
}
}
else
{
return TRUE;
}
}
else
{
SetLastError(ERROR_INVALID_PARAMETER);
return(FALSE);
}
}
}
extern BOOL SetFileAttributesW (_In_ LPCWSTR lpFileName, _In_ DWORD dwFileAttributes)
{
try
{
std::string mbPathName = NanoWin::StrConverter::Convert(lpFileName);
return SetFileAttributesA(mbPathName.c_str(),dwFileAttributes);
}
catch (NanoWin::StrConverter::Error)
{
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
return FALSE;
}
}
extern BOOL WINAPI MoveFileA(_In_ LPCSTR lpExistingFileName, _In_ LPCSTR lpNewFileName)
{
if (rename(lpExistingFileName, lpNewFileName) == 0)
{
return TRUE;
}
else
{
SetLastError(NanoWinErrorByErrnoAtFail(errno));
return FALSE;
}
}
extern BOOL WINAPI MoveFileW(_In_ LPCWSTR lpExistingFileName, _In_ LPCWSTR lpNewFileName)
{
try
{
std::string lpExistingFileNameMb = NanoWin::StrConverter::Convert(lpExistingFileName);
std::string lpNewFileNameMb = NanoWin::StrConverter::Convert(lpNewFileName);
return MoveFileA(lpExistingFileNameMb.c_str(),lpNewFileNameMb.c_str());
}
catch (NanoWin::StrConverter::Error)
{
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
return FALSE;
}
}
NW_EXTERN_C_END
| mit |
NoUseFreak/Blockr | src/Blockr/Block/BaseBlock.php | 2007 | <?php
/**
* This file is part of the Blockr package.
*
* (c) Dries De Peuter <dries@nousefreak.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Blockr\Block;
use Blockr\Context\Context;
use Blockr\Media\Media;
use Symfony\Component\HttpFoundation\Response;
abstract class BaseBlock implements BlockInterface
{
/**
* @var string|int The blocks identifier.
*/
protected $id;
/**
* @var string The type of the block.
*/
protected $type = 'block';
/**
* @var Context The context of the block.
*/
protected $context;
/**
* @var \Symfony\Component\HttpFoundation\Response
*/
protected $response;
/**
* @var Media
*/
protected $media;
/**
* Set the block's identifier.
*
* @param string|int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Get the block's identifier
*
* @return int|string
*/
public function getId()
{
return $this->id;
}
/**
* Get the block's type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @param Context $context
*/
public function setContext(Context $context)
{
$this->context = $context;
}
/**
* @return Context
*/
public function getContext()
{
return $this->context;
}
/**
* @param Response $response
*/
public function setResponse(Response $response)
{
$this->response = $response;
}
/**
* @return Response
*/
public function getResponse()
{
return $this->response;
}
/**
* @return Media
*/
public function getMedia()
{
if (is_null($this->media)) {
$this->media = new Media();
}
return $this->media;
}
}
| mit |
rickhan2014/moco | moco-core/src/test/java/com/github/dreamhead/moco/MocoTest.java | 23095 | package com.github.dreamhead.moco;
import com.google.common.io.ByteStreams;
import org.apache.http.Header;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.Request;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import static com.github.dreamhead.moco.HttpProtocolVersion.VERSION_1_0;
import static com.github.dreamhead.moco.Moco.*;
import static com.github.dreamhead.moco.Runner.running;
import static com.github.dreamhead.moco.helper.RemoteTestUtils.remoteUrl;
import static com.github.dreamhead.moco.helper.RemoteTestUtils.root;
import static com.google.common.collect.ImmutableMap.of;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;
public class MocoTest extends AbstractMocoHttpTest {
@Test
public void should_return_expected_response() throws Exception {
server.response("foo");
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.get(root()), is("foo"));
}
});
}
@Test
public void should_return_expected_response_with_text_api() throws Exception {
server.response(text("foo"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(root()), is("foo"));
}
});
}
@Test
public void should_return_expected_response_with_content_api() throws Exception {
server.response(with("foo"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(root()), is("foo"));
}
});
}
@Test
public void should_return_expected_response_from_file() throws Exception {
server.response(file("src/test/resources/foo.response"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(root()), is("foo.response"));
}
});
}
@Test
public void should_return_expected_response_from_path_resource() throws Exception {
server.response(pathResource("foo.response"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.get(root()), is("foo.response"));
}
});
}
@Test
public void should_return_expected_response_based_on_path_resource() throws Exception {
server.request(by(pathResource("foo.request"))).response("foo");
running(server, new Runnable() {
@Override
public void run() throws Exception {
InputStream asStream = this.getClass().getClassLoader().getResourceAsStream("foo.request");
assertThat(helper.postBytes(root(), ByteStreams.toByteArray(asStream)), is("foo"));
}
});
}
@Test(expected = HttpResponseException.class)
public void should_throw_exception_for_unknown_request() throws Exception {
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(root()), is("bar"));
}
});
}
@Test
public void should_return_expected_response_based_on_specified_request() throws Exception {
server.request(by("foo")).response("bar");
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.postContent(root(), "foo"), is("bar"));
}
});
}
@Test
public void should_return_expected_response_based_on_specified_request_with_text_api() throws Exception {
server.request(by(text("foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.postContent(root(), "foo"), is("bar"));
}
});
}
@Test
public void should_return_expected_response_based_on_specified_uri() throws Exception {
server.request(by(uri("/foo"))).response("bar");
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
}
});
}
@Test
public void should_match_request_based_on_multiple_matchers() throws Exception {
server.request(and(by("foo"), by(uri("/foo")))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.postContent(remoteUrl("/foo"), "foo"), is("bar"));
}
});
}
@Test(expected = HttpResponseException.class)
public void should_throw_exception_even_if_match_one_of_conditions() throws Exception {
server.request(and(by("foo"), by(uri("/foo")))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
helper.get(remoteUrl("/foo"));
}
});
}
@Test
public void should_match_request_based_on_either_matcher() throws Exception {
server.request(or(by("foo"), by(uri("/foo")))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
assertThat(helper.postContent(remoteUrl("/foo"), "foo"), is("bar"));
}
});
}
@Test
public void should_match_request_based_on_not_matcher() throws Exception {
server.request(not(by(uri("/foo")))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/bar")), is("bar"));
}
});
}
@Test
public void should_match_request_based_on_simplified_either_matcher() throws Exception {
server.request(by("foo"), by(uri("/foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
assertThat(helper.postContent(root(), "foo"), is("bar"));
}
});
}
@Test
public void should_match_get_method_by_method_api() throws Exception {
server.request(and(by(uri("/foo")), by(method("get")))).response("bar");
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
}
});
}
@Test(expected = HttpResponseException.class)
public void should_not_response_for_get_while_http_method_is_not_get() throws Exception {
server.get(by(uri("/foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
helper.postContent(remoteUrl("/foo"), "");
}
});
}
@Test
public void should_match_put_method_via_api() throws Exception {
server.request(and(by(uri("/foo")), by(method("put")))).response("bar");
running(server, new Runnable() {
@Override
public void run() throws IOException {
String response = Request.Put(remoteUrl("/foo")).execute().returnContent().toString();
assertThat(response, is("bar"));
}
});
}
@Test
public void should_match_delete_method_via_api() throws Exception {
server.request(and(by(uri("/foo")), by(method("delete")))).response("bar");
running(server, new Runnable() {
@Override
public void run() throws IOException {
String response = Request.Delete(remoteUrl("/foo")).execute().returnContent().toString();
assertThat(response, is("bar"));
}
});
}
@Test(expected = HttpResponseException.class)
public void should_not_response_for_post_while_http_method_is_not_post() throws Exception {
server.post(by(uri("/foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
helper.get(remoteUrl("/foo"));
}
});
}
@Test
public void should_return_content_one_by_one() throws Exception {
server.request(by(uri("/foo"))).response(seq("bar", "blah"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
assertThat(helper.get(remoteUrl("/foo")), is("blah"));
assertThat(helper.get(remoteUrl("/foo")), is("blah"));
}
});
}
@Test
public void should_return_content_one_by_one_with_text_api() throws Exception {
server.request(by(uri("/foo"))).response(seq(text("bar"), text("blah")));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
assertThat(helper.get(remoteUrl("/foo")), is("blah"));
assertThat(helper.get(remoteUrl("/foo")), is("blah"));
}
});
}
@Test
public void should_return_response_one_by_one() throws Exception {
server.request(by(uri("/foo"))).response(seq(status(302), status(302), status(200)));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.getForStatus(remoteUrl("/foo")), is(302));
assertThat(helper.getForStatus(remoteUrl("/foo")), is(302));
assertThat(helper.getForStatus(remoteUrl("/foo")), is(200));
}
});
}
@Test
public void should_match() throws Exception {
server.request(match(uri("/\\w*/foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.get(remoteUrl("/bar/foo")), is("bar"));
assertThat(helper.get(remoteUrl("/blah/foo")), is("bar"));
}
});
}
@Test
public void should_match_header() throws Exception {
server.request(match(header("foo"), "bar|blah")).response("header");
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.getWithHeader(root(), of("foo", "bar")), is("header"));
assertThat(helper.getWithHeader(root(), of("foo", "blah")), is("header"));
}
});
}
@Test
public void should_exist_header() throws Exception {
server.request(exist(header("foo"))).response(text("header"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.getWithHeader(root(), of("foo", "bar")), is("header"));
assertThat(helper.getWithHeader(root(), of("foo", "blah")), is("header"));
}
});
}
@Test
public void should_starts_with() throws Exception {
server.request(startsWith(uri("/foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.get(remoteUrl("/foo/a")), is("bar"));
assertThat(helper.get(remoteUrl("/foo/b")), is("bar"));
}
});
}
@Test
public void should_starts_with_for_resource() throws Exception {
server.request(startsWith(header("foo"), "bar")).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.getWithHeader(root(), of("foo", "barA")), is("bar"));
assertThat(helper.getWithHeader(root(), of("foo", "barB")), is("bar"));
}
});
}
@Test
public void should_ends_with() throws Exception {
server.request(endsWith(uri("foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.get(remoteUrl("/a/foo")), is("bar"));
assertThat(helper.get(remoteUrl("/b/foo")), is("bar"));
}
});
}
@Test
public void should_ends_with_for_resource() throws Exception {
server.request(endsWith(header("foo"), "bar")).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.getWithHeader(root(), of("foo", "Abar")), is("bar"));
assertThat(helper.getWithHeader(root(), of("foo", "Bbar")), is("bar"));
}
});
}
@Test
public void should_contain() throws Exception {
server.request(contain(uri("foo"))).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.get(remoteUrl("/a/foo")), is("bar"));
assertThat(helper.get(remoteUrl("/foo/a")), is("bar"));
}
});
}
@Test
public void should_contain_for_resource() throws Exception {
server.request(contain(header("foo"), "bar")).response(text("bar"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(helper.getWithHeader(root(), of("foo", "Abar")), is("bar"));
assertThat(helper.getWithHeader(root(), of("foo", "barA")), is("bar"));
}
});
}
@Test
public void should_eq_header() throws Exception {
server.request(eq(header("foo"), "bar")).response("blah");
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.getWithHeader(root(), of("foo", "bar")), is("blah"));
}
});
}
@Test(expected = HttpResponseException.class)
public void should_throw_exception_without_specified_header() throws Exception {
server.request(eq(header("foo"), "bar")).response("blah");
running(server, new Runnable() {
@Override
public void run() throws IOException {
helper.get(remoteUrl("/foo"));
}
});
}
@Test
public void should_return_expected_response_for_specified_query() throws Exception {
server.request(and(by(uri("/foo")), eq(query("param"), "blah"))).response("bar");
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(remoteUrl("/foo?param=blah")), is("bar"));
}
});
}
@Test
public void should_match_version() throws Exception {
server.request(by(version(VERSION_1_0))).response("foo");
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.getWithVersion(root(), HttpVersion.HTTP_1_0), is("foo"));
}
});
}
@Test
public void should_return_expected_version() throws Exception {
server.response(version(VERSION_1_0));
running(server, new Runnable() {
@Override
public void run() throws IOException {
ProtocolVersion version = Request.Get(root()).execute().returnResponse().getProtocolVersion();
assertThat(version.getMajor(), is(1));
assertThat(version.getMinor(), is(0));
}
});
}
@Test
public void should_return_excepted_version_with_version_api() throws Exception {
server.response(version(VERSION_1_0));
running(server, new Runnable() {
@Override
public void run() throws IOException {
ProtocolVersion version = Request.Get(root()).execute().returnResponse().getProtocolVersion();
assertThat(version.getMajor(), is(1));
assertThat(version.getMinor(), is(0));
}
});
}
@Test
public void should_return_expected_status_code() throws Exception {
server.response(status(200));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.getForStatus(root()), is(200));
}
});
}
@Test
public void should_return_expected_header() throws Exception {
server.response(header("content-type", "application/json"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
String value = Request.Get(root()).execute().returnResponse().getFirstHeader("content-type").getValue();
assertThat(value, is("application/json"));
}
});
}
@Test
public void should_return_multiple_expected_header() throws Exception {
server.response(header("content-type", "application/json"), header("foo", "bar"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
String json = Request.Get(root()).execute().returnResponse().getFirstHeader("content-type").getValue();
assertThat(json, is("application/json"));
String bar = Request.Get(root()).execute().returnResponse().getFirstHeader("foo").getValue();
assertThat(bar, is("bar"));
}
});
}
@Test
public void should_wait_for_awhile() throws Exception {
final long latency = 1000;
final long delta = 200;
server.response(latency(latency));
running(server, new Runnable() {
@Override
public void run() throws IOException {
long start = System.currentTimeMillis();
helper.get(root());
int code = helper.getForStatus(root());
long stop = System.currentTimeMillis();
long gap = stop - start + delta;
assertThat(gap, greaterThan(latency));
assertThat(code, is(200));
}
});
}
@Test
public void should_wait_for_awhile_with_time_unit() throws Exception {
final long delta = 200;
server.response(latency(1, TimeUnit.SECONDS));
running(server, new Runnable() {
@Override
public void run() throws IOException {
long start = System.currentTimeMillis();
helper.get(root());
int code = helper.getForStatus(root());
long stop = System.currentTimeMillis();
long gap = stop - start + delta;
assertThat(gap, greaterThan(TimeUnit.SECONDS.toMillis(1)));
assertThat(code, is(200));
}
});
}
@Test
public void should_return_same_http_version_without_specified_version() throws Exception {
server.response("foobar");
running(server, new Runnable() {
@Override
public void run() throws IOException {
ProtocolVersion version10 = Request.Get(root()).version(HttpVersion.HTTP_1_0).execute().returnResponse().getProtocolVersion();
assertThat(version10.getMajor(), is(1));
assertThat(version10.getMinor(), is(0));
ProtocolVersion version11 = Request.Get(root()).version(HttpVersion.HTTP_1_1).execute().returnResponse().getProtocolVersion();
assertThat(version11.getMajor(), is(1));
assertThat(version11.getMinor(), is(1));
}
});
}
@Test
public void should_return_same_http_version_without_specified_version_for_error_response() throws Exception {
running(server, new Runnable() {
@Override
public void run() throws IOException {
ProtocolVersion version10 = Request.Get(root()).version(HttpVersion.HTTP_1_0).execute().returnResponse().getProtocolVersion();
assertThat(version10.getMajor(), is(1));
assertThat(version10.getMinor(), is(0));
ProtocolVersion version11 = Request.Get(root()).version(HttpVersion.HTTP_1_1).execute().returnResponse().getProtocolVersion();
assertThat(version11.getMajor(), is(1));
assertThat(version11.getMinor(), is(1));
}
});
}
@Test
public void should_return_default_content_type() throws Exception {
server.response(with(text("foo")));
running(server, new Runnable() {
@Override
public void run() throws Exception {
Header header = Request.Get(root()).execute().returnResponse().getFirstHeader("Content-Type");
assertThat(header.getValue(), is("text/plain; charset=UTF-8"));
}
});
}
@Test
public void should_return_specified_content_type() throws Exception {
server.response(with(text("foo")), header("Content-Type", "text/html"));
running(server, new Runnable() {
@Override
public void run() throws Exception {
Header header = Request.Get(root()).execute().returnResponse().getFirstHeader("Content-Type");
assertThat(header.getValue(), is("text/html"));
}
});
}
@Test
public void should_return_specified_content_type_no_matter_order() throws Exception {
server.response(header("Content-Type", "text/html"), with(text("foo")));
running(server, new Runnable() {
@Override
public void run() throws Exception {
Header header = Request.Get(root()).execute().returnResponse().getFirstHeader("Content-Type");
assertThat(header.getValue(), is("text/html"));
}
});
}
}
| mit |
ashfaqfarooqui/SP | gui/web/src/app/volvo-robot-scheduling/volvo-robot-scheduling.controller.js | 3933 | /**
* Created by Martin on 2016-05-24.
*/
(function () {
'use strict';
angular
.module('app.volvoRobotScheduling')
.controller('volvoRobotSchedulingController', volvoRobotSchedulingController);
volvoRobotSchedulingController.$inject = ['$scope', 'dashboardService','logger', 'modelService',
'itemService', 'spServicesService', 'restService',
'eventService'];
/* @ngInject */
function volvoRobotSchedulingController($scope, dashboardService, logger, modelService, itemService,
spServicesService, restService, eventService) {
var vm = this;
vm.widget = $scope.$parent.$parent.$parent.vm.widget;
vm.dashboard = $scope.$parent.$parent.$parent.vm.dashboard;
vm.selectedSchedules = [];
vm.removeSchedule = removeSchedule;
vm.state = 'selecting';
vm.calculate = calculate;
vm.numStates = 0;
vm.minTime = 0.0;
vm.cpCompleted = false;
vm.cpTime = 0.0;
vm.sops = [];
vm.openSOP = openSOP;
var waitID = '';
function updateSelected(nowSelected, previouslySelected) {
var n = _.difference(nowSelected, previouslySelected);
vm.selectedSchedules = vm.selectedSchedules.concat(n);
console.log(vm.selectedSchedules);
}
function actOnSelectionChanges() {
$scope.$watchCollection(
function() {
return itemService.selected;
},
updateSelected
);
}
function removeSchedule(s) {
vm.selectedSchedules = _.difference(vm.selectedSchedules,[s]);
}
activate();
function onEvent(ev){
if(ev.reqID == waitID) {
console.log(ev.attributes);
vm.numStates = ev.attributes['numStates'];
vm.sops = ev.attributes['cpSops'];
if(vm.sops.length == 0) {
vm.state = 'no sols';
} else {
vm.minTime = vm.sops[0]._1;
vm.cpCompleted = ev.attributes['cpCompleted'];
vm.cpTime = ev.attributes['cpTime'];
vm.state = 'done';
}
}
}
function activate() {
$scope.$on('closeRequest', function() {
dashboardService.closeWidget(vm.widget.id);
// maybe add some clean up here
});
eventService.addListener('Response', onEvent);
actOnSelectionChanges();
}
function calculate() {
if(vm.selectedSchedules.length == 0) {
console.log('Must select a least one schedule');
return;
}
vm.state = 'calculating';
var selected = _.map(vm.selectedSchedules, function(x) {return x.id;});
var mess = {
'core': {
'model': modelService.activeModel.id,
'responseToModel': true
},
'setup': {
'selectedSchedules':selected
}
};
spServicesService.callService('VolvoRobotSchedule',{'data':mess},function(x){},function(x){}).then(function(repl){
waitID = repl.reqID;
});
}
function openSOP(sopid) {
var widgetKind = _.find(dashboardService.widgetKinds, {title: 'SOP Maker'});
if (widgetKind === undefined) {
logger.error('Item Explorer: Open with SOP Maker failed. ' +
'Could not find widgetKind "SOPMaker".');
}
dashboardService.addWidget(vm.dashboard, widgetKind, {sopSpecID: sopid});
}
}
})();
| mit |
Nickito12/stepmania-server | smserver/pluginmanager.py | 4407 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
import inspect
import os
import pkgutil
try:
from importlib import reload
except ImportError:
pass
class StepmaniaPlugin(object):
def __init__(self, server):
self.server = server
def on_packet(self, session, serv, packet):
pass
def on_nscping(self, session, serv, packet):
pass
def on_nscpingr(self, session, serv, packet):
pass
def on_nschello(self, session, serv, packet):
pass
def on_nscgsr(self, session, serv, packet):
pass
def on_nscgon(self, session, serv, packet):
pass
def on_nscgsu(self, session, serv, packet):
pass
def on_nscsu(self, session, serv, packet):
pass
def on_nsccm(self, session, serv, packet):
pass
def on_nscrsg(self, session, serv, packet):
pass
def on_nsccuul(self, session, serv, packet):
pass
def on_nsscsms(self, session, serv, packet):
pass
def on_nscuopts(self, session, serv, packet):
pass
def on_nssmonl(self, session, serv, packet):
func = getattr(self, "on_%s" % packet["packet"].command.name.lower(), None)
if not func:
return None
return func(session, serv, packet["packet"])
def on_nscformatted(self, session, serv, packet):
pass
def on_nscattack(self, session, serv, packet):
pass
def on_xmlpacket(self, session, serv, packet):
pass
def on_login(self, session, serv, packet):
pass
def on_enterroom(self, session, serv, packet):
pass
def on_createroom(self, session, serv, packet):
pass
def on_roominfo(self, session, serv, packet):
pass
class PluginError(Exception):
pass
class PluginManager(list):
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
def __init__(self, plugin_class, paths=None, directory=None, plugin_file=None, force_reload=False):
if not isinstance(plugin_class, list):
plugin_class = [plugin_class]
self.plugin_class = plugin_class
self.plugin_file = plugin_file
self.directory = directory
if paths is None:
paths = self.all_paths(directory)
if not paths:
paths = []
self.paths = paths
self.load(force_reload)
def all_paths(self, directory):
directory_path = os.path.join(self.__location__, "/".join(directory.split(".")[1:]))
for _, name, _ in pkgutil.iter_modules([directory_path]):
yield name
def load(self, force_reload=False):
del self[:]
for path in self.paths:
fullpath = '.'.join([p for p in (self.directory, path, self.plugin_file) if p is not None])
self.extend(self.import_plugin(fullpath,
plugin_classes=self.plugin_class,
force_reload=force_reload))
def init(self, *opt):
for idx, app in enumerate(self):
self[idx] = app(*opt)
@staticmethod
def import_plugin(path, plugin_classes, force_reload=False):
if not isinstance(plugin_classes, list):
plugin_classes = [plugin_classes]
module = __import__(path, fromlist=plugin_classes)
if force_reload:
reload(module)
apps = []
for cls in inspect.getmembers(module, inspect.isclass):
app = getattr(module, cls[0])
if not app:
continue
for plugin_class in plugin_classes:
if plugin_class in [x.__name__ for x in app.__bases__]:
apps.append(app)
return apps
@classmethod
def get_plugin(cls, path, plugin_classes, default=None, force_reload=False):
apps = cls.import_plugin(path, plugin_classes, force_reload)
if not apps:
return default
return apps[0]
if __name__ == "__main__":
print(PluginManager.get_plugin("auth.database", ["AuthPlugin"]))
plugins = PluginManager("StepmaniaPlugin", ["example"], "plugins", "plugin")
plugins.load()
print(plugins)
plugins.init("a")
print(plugins)
print(PluginManager("StepmaniaController", None, "smserver.controllers"))
print(PluginManager("ChatPlugin", None, "smserver.chat_commands"))
| mit |
will-gilbert/OSWf-OSWorkflow-fork | oswf/core/src/main/java/org/informagen/oswf/security/DefaultSecurityProvider.java | 2146 | package org.informagen.oswf.security;
import org.informagen.oswf.security.Role;
import org.informagen.oswf.security.User;
// Java - Collections
import java.util.Collection;
import java.util.Set;
import java.util.HashSet;
public class DefaultSecurityProvider implements SecurityProvider {
Set<Role> roles = new HashSet<Role>();
Set<User> users = new HashSet<User>();
// G R O U P S ===========================================================================
public Role createRole(String roleName) {
Role role = getRole(roleName);
if(role != null)
return role;
role = new DefaultRole(roleName);
addRole(role);
return role;
}
public void addRole(Role role) {
roles.add(role);
users.addAll(role.getUsers());
}
public void addRoles(Collection<Role> roles) {
this.roles.addAll(roles);
}
public Set<Role> getRoles() {
return roles;
}
// Return Role with given name
public Role getRole(String roleName) {
for(Role role : roles)
if(role.getName().equals(roleName))
return role;
return null;
}
// U S E R S ==============================================================================
public User createUser(String userName) {
User user = getUser(userName);
if(user != null)
return user;
user = new DefaultUser(userName);
addUser(user);
return user;
}
// When adding a user also add their roles
public void addUser(User user) {
users.add(user);
roles.addAll(user.getRoles());
}
public void addUsers(Collection<User> users) {
for(User user : users)
addUser(user);
}
public Set<User> getUsers() {
return users;
}
// Return user with given name.
public User getUser(String userName) {
for(User user : users)
if(user.getName().equals(userName))
return user;
return null;
}
}
| mit |
AlexStefan/template-app | Internationalization/Internationalization.Touch/AppDelegate.cs | 525 | using Foundation;
using Internationalization.Core;
using MvvmCross.Platforms.Ios.Core;
using UIKit;
namespace Internationalization.Touch
{
[Register("AppDelegate")]
public class AppDelegate : MvxApplicationDelegate<Setup, App>
{
public override UIWindow Window
{
get;
set;
}
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
return base.FinishedLaunching(application, launchOptions);
}
}
} | mit |
cuboktahedron/tetsimu | js/test/model/description-test.js | 4552 | (function() {
var description;
module('DescriptionTest', {
setup: function() {
description = new C.Description();
}
});
test('技なし確認', function() {
deepEqual(description.data(), {
ren: 0,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.None
});
});
test('1ライン消し確認', function() {
description.ren(1);
description.clearLineNum(1);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.Single
});
});
test('TSSM確認', function() {
description.ren(1);
description.spinType(C.Constants.SpinType.TSpinMini);
description.clearLineNum(1);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.TSSM
});
});
test('TSS確認', function() {
description.ren(1);
description.spinType(C.Constants.SpinType.TSpin);
description.clearLineNum(1);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.TSS
});
});
test('2ライン消し確認', function() {
description.ren(2);
description.clearLineNum(2);
description.fixData();
deepEqual(description.data(), {
ren: 2,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.Double
});
});
test('TSD確認', function() {
description.ren(1);
description.spinType(C.Constants.SpinType.TSpinMini);
description.clearLineNum(2);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.TSD
});
description.spinType(C.Constants.SpinType.TSpin);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: true,
perfectCleared: false,
trick: C.Constants.Trick.TSD
});
});
test('3ライン消し確認', function() {
description.ren(2);
description.clearLineNum(3);
description.fixData();
deepEqual(description.data(), {
ren: 2,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.Triple
});
});
test('TST確認', function() {
description.ren(1);
description.spinType(C.Constants.SpinType.TSpinMini);
description.clearLineNum(3);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.TST
});
// このパターンは実際ありえない
description.spinType(C.Constants.SpinType.TSpin);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: true,
perfectCleared: false,
trick: C.Constants.Trick.TST
});
});
test('テトリス確認', function() {
description.ren(2);
description.clearLineNum(4);
description.fixData();
deepEqual(description.data(), {
ren: 2,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.Tetris
});
});
test('Overテトリス確認', function() {
description.ren(2);
description.clearLineNum(5);
description.fixData();
deepEqual(description.data(), {
ren: 2,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.OverTetris
});
});
test('TS確認', function() {
description.ren(0);
description.spinType(C.Constants.SpinType.TSpin);
description.clearLineNum(0);
description.fixData();
deepEqual(description.data(), {
ren: 0,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.TS
});
});
test('TSM確認', function() {
description.ren(0);
description.spinType(C.Constants.SpinType.TSpinMini);
description.clearLineNum(0);
description.fixData();
deepEqual(description.data(), {
ren: 0,
b2b: false,
perfectCleared: false,
trick: C.Constants.Trick.TSM
});
});
test('パーフェクトクリア確認', function() {
description.ren(1);
description.spinType(C.Constants.SpinType.None);
description.clearLineNum(4);
description.perfectCleared(true);
description.fixData();
deepEqual(description.data(), {
ren: 1,
b2b: false,
perfectCleared: true,
trick: C.Constants.Trick.Tetris,
});
});
})();
| mit |
InfinityRaider/SettlerCraft | src/main/java/com/infinityraider/settlercraft/settlement/settler/profession/builder/TaskRemoveBlockForBuilding.java | 1094 | package com.infinityraider.settlercraft.settlement.settler.profession.builder;
import com.infinityraider.settlercraft.settlement.settler.ai.task.TaskWithParentBase;
import net.minecraft.block.material.Material;
import net.minecraft.util.math.BlockPos;
public class TaskRemoveBlockForBuilding extends TaskWithParentBase<TaskBuildBuilding> {
private final BlockPos pos;
public TaskRemoveBlockForBuilding(TaskBuildBuilding parentTask, BlockPos pos) {
super(parentTask);
this.pos = pos;
}
@Override
public void onTaskStarted() {}
@Override
public void onTaskUpdated() {
//TODO
}
@Override
public void onTaskCancel() {
this.getParentTask().onSubTaskCancelled();
}
@Override
public boolean isCompleted() {
return getSettler().getWorld().getBlockState(this.pos).getMaterial() == Material.AIR;
}
@Override
public void onTaskCompleted() {
this.getParentTask().onSubTaskCompleted();
}
}
| mit |
uber-common/opentracing-python | tests/test_noop_context.py | 2565 | # Copyright (c) 2015 Uber Technologies, Inc.
#
# 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.
from __future__ import absolute_import
from opentracing import TraceContext, TraceContextSource
from opentracing import TraceContextEncoder, TraceContextDecoder
def test_context():
ctx = TraceContext()
assert ctx.get_trace_attribute('x') is None
ctx.set_trace_attribute('X_y', 'value').\
set_trace_attribute('ZZ', 'value2')
assert ctx.get_trace_attribute('X_y') is None
def test_context_source():
singleton = TraceContextSource.singleton_noop_trace_context
source = TraceContextSource()
assert source.new_root_trace_context() == singleton
child, attr = source.new_child_trace_context(
parent_trace_context=singleton)
assert child == singleton
assert attr is None
def test_encoder():
singleton = TraceContextSource.singleton_noop_trace_context
e = TraceContextEncoder()
x, y = e.trace_context_to_binary(trace_context=singleton)
assert x == bytearray()
assert y is None
x, y = e.trace_context_to_text(trace_context=singleton)
assert x == {}
assert y is None
def test_decoder():
singleton = TraceContextSource.singleton_noop_trace_context
d = TraceContextDecoder()
ctx = d.trace_context_from_binary(trace_context_id=None,
trace_attributes=None)
assert singleton == ctx
ctx = d.trace_context_from_text(trace_context_id=None,
trace_attributes=None)
assert singleton == ctx
| mit |
brdara/java-cloud-filesystem-provider | core/src/main/java/com/uk/xarixa/cloud/filesystem/core/file/attribute/CloudPermissionFileAttribute.java | 640 | package com.uk.xarixa.cloud.filesystem.core.file.attribute;
import java.nio.file.attribute.FileAttribute;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class CloudPermissionFileAttribute<P extends Object> implements FileAttribute<P> {
private final P permissions;
public CloudPermissionFileAttribute(P permissions) {
this.permissions = permissions;
}
@Override
public String name() {
return "cloud:permission";
}
@Override
public P value() {
return permissions;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
| mit |
fotinakis/travis-web | app/initializers/app.js | 251 | var Initializer, initialize;
initialize = function (app) {
if (typeof window !== 'undefined') {
return window.Travis = app;
}
};
Initializer = {
name: 'app',
initialize: initialize
};
export { initialize };
export default Initializer;
| mit |
srisa/teamroq | config/deploy/staging.rb | 1467 | # Simple Role Syntax
# ==================
# Supports bulk-adding hosts to roles, the primary server in each group
# is considered to be the first unless any hosts have the primary
# property set. Don't declare `role :all`, it's a meta role.
# role :app, %w{deploy@example.com}
# role :web, %w{deploy@example.com}
# role :db, %w{deploy@example.com}
# Extended Server Syntax
# ======================
# This can be used to drop a more detailed server definition into the
# server list. The second argument is a, or duck-types, Hash and is
# used to set extended properties on the server.
# server 'example.com', user: 'deploy', roles: %w{web app}, my_property: :my_value
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult[net/ssh documentation](http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start).
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# And/or per server (overrides global)
# ------------------------------------
# server 'example.com',
# user: 'user_name',
# roles: %w{web app},
# ssh_options: {
# user: 'user_name', # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: 'please use keys'
# }
| mit |
raym/prah-framework | lib/routes.sample.js | 242 | module.exports = {
homepage: 'http://example.com/',
redirects: {
'a-page-i-took-down': 'page-one',
'another-page-i-took-down': 'page-three'
},
valid_routes: [
'home',
'page-one',
'page-two',
'page-three'
]
}
| mit |
OpenTl/OpenTl.Schema | src/OpenTl.Schema/_generated/_Entities/UserStatus/TUserStatusOffline.cs | 346 | // ReSharper disable All
namespace OpenTl.Schema
{
using System;
using System.Collections;
using System.Text;
using OpenTl.Schema;
using OpenTl.Schema.Serialization.Attributes;
[Serialize(0x8c703f)]
public sealed class TUserStatusOffline : IUserStatus
{
[SerializationOrder(0)]
public int WasOnline {get; set;}
}
}
| mit |
tylerhunt/brewery_db | spec/brewery_db/mash_spec.rb | 482 | require 'spec_helper'
describe BreweryDB::Mash do
it { is_expected.to be_a(Hashie::Mash) }
context '#convert_key' do
it 'underscores camelcased keys' do
response = described_class.new(currentPage: 1)
expect(response.current_page).to eq(1)
end
end
context '#convert_value' do
it 'converts CR+LF to LF' do
response = described_class.new(description: "This.\r\nThat.")
expect(response.description).to eq("This.\nThat.")
end
end
end
| mit |
matiaskorhonen/s3itch_client | spec/spec_helper.rb | 137 | require "simplecov"
SimpleCov.start
require "bundler"
Bundler.setup
require "rspec"
require "webmock/rspec"
require "s3itch_client"
| mit |
mathiasbynens/unicode-data | 8.0.0/categories/Zl-symbols.js | 73 | // All symbols in the `Zl` category as per Unicode v8.0.0:
[
'\u2028'
]; | mit |
s-light/OLA_Cherrypy_example | server/static/js/slightDirectives/TabbedContent/slTabbedContent.js | 6444 | /******************************************************************************
slTabbedContent directive
written by stefan krueger (s-light),
mail@s-light.eu, http://s-light.eu, https://github.com/s-light/
havely based on
https://docs.angularjs.org/guide/directive#creating-directives-that-communicate
changelog / history
see git commits
TO DO:
~ enjoy your life :-)
******************************************************************************/
/******************************************************************************
Copyright 2015 Stefan Krueger
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.
The MIT License (MIT)
Copyright (c) 2015 Stefan Krüger
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.
******************************************************************************/
var slTabbedContent = angular.module('slTabbedContent', [
// 'xx',
]);
// get current script path
// http://stackoverflow.com/a/21103831/574981
// var scripts = document.getElementsByTagName("script");
// var myDTl_scriptPath = scripts[scripts.length-1].src;
var slTabbedContent_scriptElement = document.querySelector(
"[src*=slTabbedContent]"
);
var slTabbedContent_scriptPath = slTabbedContent_scriptElement.getAttribute('src');
var slTabbedContent_templateURL = slTabbedContent_scriptPath.replace('.js', '.html');
var slTabbedContent_templateURL_Pane = slTabbedContent_templateURL.replace('.html', '_Pane.html');
slTabbedContent.directive('slTabbedContent', [
// 'slTabbedContentController',
'$filter',
function(
// slTabbedContentController,
$filter
) { return {
restrict: 'E',
transclude: true,
scope: {
initialPane: '@',
},
// template: '<ul class=""></ul>',
// templateUrl: 'js/xxx.html',
// templateUrl: slTabbedContent_templateURL,
templateUrl: function() {
// only for development!!!!!
// this disables the caching of the template file..
return slTabbedContent_templateURL + '?' + new Date();
},
controller:[
'$scope',
// '$filter',
function($scope) {
// console.log("slTabbedContent");
// console.log("$scope", $scope);
var panes = $scope.panes = [];
/******************************************/
/** functions **/
$scope.test = function(event) {
// console.group("test");
// console.log("event", event);
// console.groupEnd();
};
$scope.switchToPane = function(pane) {
// console.group("switchToPane");
// console.log("pane", pane);
// deactivate all but given
angular.forEach(panes, function(paneCurrent, paneIndex){
if (paneCurrent == pane) {
paneCurrent.active = true;
} else {
paneCurrent.active = false;
}
});
// console.groupEnd();
};
this.addPane = function(pane) {
// console.group("addPane");
// console.log("pane", pane);
// add new pane to list
panes.push(pane);
// show first added pane
if (pane.title == $scope.initialPane) {
$scope.switchToPane(pane);
}
// console.log("panes", panes);
// console.groupEnd();
};
}
]
};}
]);
slTabbedContent.directive('slPane', [
'$filter',
// 'slTabbedContent',
function(
$filter
// slTabbedContent
) { return {
restrict: 'E',
require: '^slTabbedContent',
transclude: true,
scope: {
title: '@',
},
// template: '<ul class=""></ul>',
// templateUrl: 'something/xxxx.html',
// templateUrl: slTabbedContent_templateURL_Pane,
templateUrl: function() {
// only for development!!!!!
// this disables the caching of the template file..
// console.log("slTabbedContent_templateURL_Pane:", slTabbedContent_templateURL_Pane);
return slTabbedContent_templateURL_Pane + '?' + new Date();
},
link: function(scope, element, attr, tabedCtrl) {
// console.log("slPane");
// console.log("scope", scope);
// console.log("element", element);
// console.log("attrs", attrs);
// console.log("tabedCtrl", tabedCtrl);
/******************************************/
/** functions **/
// add me to my parent :-)
tabedCtrl.addPane(scope);
scope.test = function(event) {
// console.group("test", event);
// console.log("testinfo");
// console.groupEnd();
};
}
};}
]);
| mit |
mgoeminne/github_etl | src/main/scala/gh2011c/models/CreateEventPayload.scala | 735 | package gh2011c.models
import net.liftweb.json.JsonAST.JValue
case class CreateEventPayload(ref: Option[String], ref_type: String, description: Option[String], master_branch: String)
object CreateEventPayload
{
def apply(json: JValue): Option[CreateEventPayload] =
{
val n2s = gh3.node2String(json)(_)
val n2os = gh3.node2OptionString(json)(_)
val ref = n2os("ref")
val ref_type = n2s("ref_type")
val description = n2os("description")
val master_branch = n2s("master_branch")
val params = Seq(ref, ref_type, description, master_branch)
if(params.forall(_.isDefined)) Some(CreateEventPayload(ref.get, ref_type.get, description.get, master_branch.get))
else None
}
}
| mit |
tonywok/realms | spec/cards/patrol_mech_spec.rb | 810 | require "spec_helper"
RSpec.describe Realms::Cards::PatrolMech do
include_examples "factions", :machine_cult
include_examples "cost", 4
describe "#primary_ability" do
include_context "primary_ability" do
before { game.play(card) }
end
context "trade" do
it { expect { game.decide(:patrol_mech, :trade) }.to change { game.active_turn.trade }.by(3) }
end
context "combat" do
it { expect { game.decide(:patrol_mech, :combat) }.to change { game.active_turn.combat }.by(5) }
end
end
describe "#ally_ability" do
include_context "ally_ability", Realms::Cards::BattleStation
include_examples "scrap_card_from_hand_or_discard_pile" do
before do
game.decide(:patrol_mech, :trade)
game.ally_ability(card)
end
end
end
end
| mit |
highj/highj | src/main/java/org/highj/typeclass1/monad/Applicative.java | 207 | package org.highj.typeclass1.monad;
import org.derive4j.hkt.__;
public interface Applicative<M> extends Apply<M> {
// pure (Data.Pointed, Control.Applicative)
<A> __<M, A> pure(A a);
}
| mit |
Adezandee/shopify-bundle | DependencyInjection/ShopifyExtension.php | 945 | <?php
namespace Adezandee\ShopifyBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class ShopifyExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$container->setParameter('shopify.options', $config);
}
}
| mit |
cnamal/INF8405 | Events/app/src/main/java/com/ensipoly/events/fragments/CreateEventFragment.java | 9699 | package com.ensipoly.events.fragments;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.ensipoly.events.FirebaseUtils;
import com.ensipoly.events.R;
import com.ensipoly.events.Utils;
import com.ensipoly.events.activities.MapsActivity;
import com.ensipoly.events.models.Event;
import com.ensipoly.events.models.Location;
import com.github.clans.fab.FloatingActionButton;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class CreateEventFragment extends Fragment {
private static final String GROUP_ID = "groupID";
private EditText startingDateText;
private Calendar startingDateCalendar = Calendar.getInstance();
private EditText endingDateText;
private Calendar endingDateCalendar = Calendar.getInstance();
private Calendar currentCalendar = Calendar.getInstance();
private EditText nameText;
private TextView placeText;
private EditText infoText;
private String mGroupID;
private Location mLocation;
public static CreateEventFragment getInstance(Location location, String groupID) {
CreateEventFragment fragment = new CreateEventFragment();
Bundle bundle = new Bundle();
location.addArguments(bundle);
bundle.putString(GROUP_ID, groupID);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_create_event, container, false);
final FloatingActionButton mFAB = (FloatingActionButton) getActivity().findViewById(R.id.fab_done);
mFAB.hide(true);
mLocation = Location.getLocationFromBundle(getArguments());
mGroupID = getArguments().getString(GROUP_ID);
startingDateText = (EditText) v.findViewById(R.id.input_starting_date);
endingDateText = (EditText) v.findViewById(R.id.input_ending_date);
nameText = (EditText) v.findViewById(R.id.input_name);
nameText.setText(mLocation.getName());
placeText = (TextView) v.findViewById(R.id.location);
placeText.setText(Utils.formatLocation(mLocation));
infoText = (EditText) v.findViewById(R.id.input_info);
setupDates();
final DatabaseReference eventDBReference = FirebaseUtils.getEventDBReference();
// Setup the submit button
Button submitButton = (Button) v.findViewById(R.id.create_event_create_button);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Check if the form is OK. If not print error and return
String error = verifyForm();
if (error != null) {
Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
return;
}
Event event = new Event(nameText.getText().toString(),
infoText.getText().toString().trim(),
mLocation.getLatitude(),
mLocation.getLongitude(),
startingDateCalendar.getTime(), endingDateCalendar.getTime());
String eventId = eventDBReference.push().getKey();
DatabaseReference ref = FirebaseUtils.getDatabase().getReference();
Map<String, Object> children = new HashMap<>();
children.put("/groups/" + mGroupID + "/event", eventId);
children.put("/events/" + eventId, event);
ref.updateChildren(children).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(getContext(), "Event created", Toast.LENGTH_SHORT).show();
((MapsActivity) getActivity()).hideBottomSheet();
}
});
}
});
return v;
}
private void setupDates() {
// Setup the listener to call when the date is set. Therefore we need to set the time.
// At the end, the label is updated.
final TimePickerDialog.OnTimeSetListener startingTime = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
startingDateCalendar.set(Calendar.HOUR_OF_DAY, hour);
startingDateCalendar.set(Calendar.MINUTE, minute);
updateStartingLabel();
}
};
final TimePickerDialog.OnTimeSetListener endingTime = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
endingDateCalendar.set(Calendar.HOUR_OF_DAY, hour);
endingDateCalendar.set(Calendar.MINUTE, minute);
updateEndingLabel();
}
};
// Setup the listener to call when we want to set the date.
// At the end, set the time.
final DatePickerDialog.OnDateSetListener startingDate = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
startingDateCalendar.set(Calendar.YEAR, year);
startingDateCalendar.set(Calendar.MONTH, monthOfYear);
startingDateCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// Now set the time
new TimePickerDialog(getContext(), startingTime,
currentCalendar.get(Calendar.HOUR_OF_DAY),
currentCalendar.get(Calendar.MINUTE),
false).show();
}
};
final DatePickerDialog.OnDateSetListener endingDate = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
endingDateCalendar.set(Calendar.YEAR, year);
endingDateCalendar.set(Calendar.MONTH, monthOfYear);
endingDateCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// Now set the time
new TimePickerDialog(getContext(), endingTime,
currentCalendar.get(Calendar.HOUR_OF_DAY),
currentCalendar.get(Calendar.MINUTE),
false).show();
}
};
// Set the listener to open the DatePicker on click
// Open it at the current date.
startingDateText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(getContext(), startingDate,
currentCalendar.get(Calendar.YEAR),
currentCalendar.get(Calendar.MONTH),
currentCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
endingDateText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(getContext(), endingDate,
currentCalendar.get(Calendar.YEAR),
currentCalendar.get(Calendar.MONTH),
currentCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
// Format the calendar to update the starting date label
private void updateStartingLabel() {
String myFormat = "MM/dd/yy hh:mm aaa"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
startingDateText.setText(sdf.format(startingDateCalendar.getTime()));
}
// Format the calendar to update the ending date label
private void updateEndingLabel() {
String myFormat = "MM/dd/yy hh:mm aaa"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
endingDateText.setText(sdf.format(endingDateCalendar.getTime()));
}
private String verifyForm() {
if (nameText.getText().toString().equals(""))
return getString(R.string.create_event_name_missing);
if (placeText.getText().toString().equals(""))
return getString(R.string.create_event_place_missing);
if (startingDateText.getText().toString().equals(""))
return getString(R.string.create_event_starting_date_missing);
if (endingDateText.getText().toString().equals(""))
return getString(R.string.create_event_ending_date_missing);
if (startingDateCalendar.after(endingDateCalendar))
return getString(R.string.create_event_ending_date_before_starting_date_error);
return null;
}
}
| mit |
sachinnitw1317/artphillic | application/modules/compete/views/competition.php | 9269 | <div class="row" style="font-family:lato;">
<div class="col-xs-20 col-sm-20 col-md-offset-2 col-md-20 col-lg-offset-2 col-lg-20">
<div class="col-md-24">
<center id><h1>COMPETITIONS</h1>
<h3>Enroll in a competition, Show off your talent and win amazing prizes</h3>
<form method="POST" id="search" action=" ">
<select name="cate" onchange="submit()">
<option value="0" name="cat">Choose a category</option>
<option value="1" name="cat">Painter</option>
<option value="2" name="cat">Dancer</option>
<option value="3" name="cat">Musician</option>
<option value="4" name="cat">Writer</option>
<option value="5" name="cat">Director</option>
<option value="6" name="cat">Actor</option>
</select></form>
</center>
<br>
<ul class="nav nav-justified nav-pills">
<li class="active"><a href="#past" data-toggle="tab">Past</a></li>
<li ><a href="#running" data-toggle="tab">Running</a></li>
<li ><a href="#upcomings" data-toggle="tab">Upcomings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="past" class="col-md-8">
<br>
<div class="row">
<div class="col-sm-8 col-md-7 col-md-offset-1" style="background-color:#f1f1f1;">
<div class="post">
<div class="post-img-content">
<img src="<?php echo base_url(); ?>/images/competition_default.jpg" class="img-responsive" />
<span class="post-title"><b>Make a Image Blur Effects With</b><br />
<b>CSS3 Blur</b></span>
</div>
<div class="content">
<div class="author">
By <b>Bhaumik</b> |
<time datetime="2014-01-20">January 20th, 2014</time>
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
<a href="http://www.jquery2dotnet.com/2014/01/jquery-highlight-table-row-and-column.html" class="btn btn-warning btn-sm">Read more</a>
</div>
</div>
</div>
</div>
<div class="col-sm-8 col-md-7 col-md-offset-1" style="background-color:#f1f1f1;">
<div class="post">
<div class="post-img-content">
<img src="<?php echo base_url(); ?>/images/competition_default.jpg" class="img-responsive" />
<span class="post-title"><b>Make a Image Blur Effects With</b><br />
<b>CSS3 Blur</b></span>
</div>
<div class="content">
<div class="author">
By <b>Bhaumik</b> |
<time datetime="2014-01-20">January 20th, 2014</time>
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
<a href="http://www.jquery2dotnet.com/2013/11/share-social-media-round-buttons.html" class="btn btn-primary btn-sm">Read more</a>
</div>
</div>
</div>
</div>
<div class="col-sm-8 col-md-7 col-md-offset-1" style="background-color:#f1f1f1;">
<div class="post">
<div class="post-img-content">
<img src="<?php echo base_url(); ?>/images/competition_default.jpg" class="img-responsive" />
<span class="post-title"><b>Make a Image Blur Effects With</b><br />
<b>CSS3 Blur</b></span>
</div>
<div class="content">
<div class="author">
By <b>Bhaumik</b> |
<time datetime="2014-01-20">January 20th, 2014</time>
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
<a href="http://www.jquery2dotnet.com/2013/07/cool-social-sharing-button-using-css3.html" class="btn btn-success btn-sm">Read more</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade in" id="running" class="col-md-8">
<br>
</div>
<div class="tab-pane fade in" id="upcomings" class="col-md-8">
<br>
<div class="row">
<div class="col-sm-8 col-md-7 col-md-offset-1" style="background-color:#f1f1f1;">
<div class="post">
<div class="post-img-content">
<img src="<?php echo base_url(); ?>/images/competition_default.jpg" class="img-responsive" />
<span class="post-title"><b>Make a Image Blur Effects With</b><br />
<b>CSS3 Blur</b></span>
</div>
<div class="content">
<div class="author">
By <b>Bhaumik</b> |
<time datetime="2014-01-20">January 20th, 2014</time>
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
<a href="http://www.jquery2dotnet.com/2014/01/jquery-highlight-table-row-and-column.html" class="btn btn-warning btn-sm">Read more</a>
</div>
</div>
</div>
</div>
<div class="col-sm-8 col-md-7 col-md-offset-1" style="background-color:#f1f1f1;">
<div class="post">
<div class="post-img-content">
<img src="http://placehold.it/460x250/2980b9/ffffff&text=CSS3" class="img-responsive" />
<span class="post-title"><b>Make a Image Blur Effects With</b><br />
<b>CSS3 Blur</b></span>
</div>
<div class="content">
<div class="author">
By <b>Bhaumik</b> |
<time datetime="2014-01-20">January 20th, 2014</time>
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
<a href="http://www.jquery2dotnet.com/2013/11/share-social-media-round-buttons.html" class="btn btn-primary btn-sm">Read more</a>
</div>
</div>
</div>
</div>
<div class="col-sm-8 col-md-8">
<div class="post">
<div class="post-img-content">
<img src="http://placehold.it/460x250/47A447/ffffff&text=jQuery" class="img-responsive" />
<span class="post-title"><b>Make a Image Blur Effects With</b><br />
<b>CSS3 Blur</b></span>
</div>
<div class="content">
<div class="author">
By <b>Bhaumik</b> |
<time datetime="2014-01-20">January 20th, 2014</time>
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
<a href="http://www.jquery2dotnet.com/2013/07/cool-social-sharing-button-using-css3.html" class="btn btn-success btn-sm">Read more</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| mit |
octobusjs/octobus | src/EventStore.js | 306 | /**
* @TODO
* should extend EventEmitter
* store.on('event', saveToStorageEngine);
* could also use batched saving
*/
class EventStore {
constructor() {
this.history = [];
}
add({ topic, id, timestamp }) {
this.history.push({ topic, id, timestamp });
}
}
export default EventStore;
| mit |
ayeletshpigelman/azure-sdk-for-net | sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/ComputeManagementClient.cs | 24391 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Compute Client
/// </summary>
public partial class ComputeManagementClient : ServiceClient<ComputeManagementClient>, IComputeManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default value is
/// 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When set to
/// true a unique x-ms-client-request-id value is generated and included in
/// each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IAvailabilitySetsOperations.
/// </summary>
public virtual IAvailabilitySetsOperations AvailabilitySets { get; private set; }
/// <summary>
/// Gets the IProximityPlacementGroupsOperations.
/// </summary>
public virtual IProximityPlacementGroupsOperations ProximityPlacementGroups { get; private set; }
/// <summary>
/// Gets the IDedicatedHostGroupsOperations.
/// </summary>
public virtual IDedicatedHostGroupsOperations DedicatedHostGroups { get; private set; }
/// <summary>
/// Gets the IDedicatedHostsOperations.
/// </summary>
public virtual IDedicatedHostsOperations DedicatedHosts { get; private set; }
/// <summary>
/// Gets the ISshPublicKeysOperations.
/// </summary>
public virtual ISshPublicKeysOperations SshPublicKeys { get; private set; }
/// <summary>
/// Gets the IVirtualMachineExtensionImagesOperations.
/// </summary>
public virtual IVirtualMachineExtensionImagesOperations VirtualMachineExtensionImages { get; private set; }
/// <summary>
/// Gets the IVirtualMachineExtensionsOperations.
/// </summary>
public virtual IVirtualMachineExtensionsOperations VirtualMachineExtensions { get; private set; }
/// <summary>
/// Gets the IVirtualMachineImagesOperations.
/// </summary>
public virtual IVirtualMachineImagesOperations VirtualMachineImages { get; private set; }
/// <summary>
/// Gets the IVirtualMachineImagesEdgeZoneOperations.
/// </summary>
public virtual IVirtualMachineImagesEdgeZoneOperations VirtualMachineImagesEdgeZone { get; private set; }
/// <summary>
/// Gets the IUsageOperations.
/// </summary>
public virtual IUsageOperations Usage { get; private set; }
/// <summary>
/// Gets the IVirtualMachinesOperations.
/// </summary>
public virtual IVirtualMachinesOperations VirtualMachines { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetsOperations VirtualMachineScaleSets { get; private set; }
/// <summary>
/// Gets the IVirtualMachineSizesOperations.
/// </summary>
public virtual IVirtualMachineSizesOperations VirtualMachineSizes { get; private set; }
/// <summary>
/// Gets the IImagesOperations.
/// </summary>
public virtual IImagesOperations Images { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetExtensionsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetExtensionsOperations VirtualMachineScaleSetExtensions { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetRollingUpgradesOperations.
/// </summary>
public virtual IVirtualMachineScaleSetRollingUpgradesOperations VirtualMachineScaleSetRollingUpgrades { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetVMExtensionsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetVMExtensionsOperations VirtualMachineScaleSetVMExtensions { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetVMsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMs { get; private set; }
/// <summary>
/// Gets the ILogAnalyticsOperations.
/// </summary>
public virtual ILogAnalyticsOperations LogAnalytics { get; private set; }
/// <summary>
/// Gets the IVirtualMachineRunCommandsOperations.
/// </summary>
public virtual IVirtualMachineRunCommandsOperations VirtualMachineRunCommands { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetVMRunCommandsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetVMRunCommandsOperations VirtualMachineScaleSetVMRunCommands { get; private set; }
/// <summary>
/// Gets the IResourceSkusOperations.
/// </summary>
public virtual IResourceSkusOperations ResourceSkus { get; private set; }
/// <summary>
/// Gets the IDisksOperations.
/// </summary>
public virtual IDisksOperations Disks { get; private set; }
/// <summary>
/// Gets the ISnapshotsOperations.
/// </summary>
public virtual ISnapshotsOperations Snapshots { get; private set; }
/// <summary>
/// Gets the IDiskEncryptionSetsOperations.
/// </summary>
public virtual IDiskEncryptionSetsOperations DiskEncryptionSets { get; private set; }
/// <summary>
/// Gets the IDiskAccessesOperations.
/// </summary>
public virtual IDiskAccessesOperations DiskAccesses { get; private set; }
/// <summary>
/// Gets the IDiskRestorePointOperations.
/// </summary>
public virtual IDiskRestorePointOperations DiskRestorePoint { get; private set; }
/// <summary>
/// Gets the IGalleriesOperations.
/// </summary>
public virtual IGalleriesOperations Galleries { get; private set; }
/// <summary>
/// Gets the IGalleryImagesOperations.
/// </summary>
public virtual IGalleryImagesOperations GalleryImages { get; private set; }
/// <summary>
/// Gets the IGalleryImageVersionsOperations.
/// </summary>
public virtual IGalleryImageVersionsOperations GalleryImageVersions { get; private set; }
/// <summary>
/// Gets the IGalleryApplicationsOperations.
/// </summary>
public virtual IGalleryApplicationsOperations GalleryApplications { get; private set; }
/// <summary>
/// Gets the IGalleryApplicationVersionsOperations.
/// </summary>
public virtual IGalleryApplicationVersionsOperations GalleryApplicationVersions { get; private set; }
/// <summary>
/// Gets the ICloudServiceRoleInstancesOperations.
/// </summary>
public virtual ICloudServiceRoleInstancesOperations CloudServiceRoleInstances { get; private set; }
/// <summary>
/// Gets the ICloudServiceRolesOperations.
/// </summary>
public virtual ICloudServiceRolesOperations CloudServiceRoles { get; private set; }
/// <summary>
/// Gets the ICloudServicesOperations.
/// </summary>
public virtual ICloudServicesOperations CloudServices { get; private set; }
/// <summary>
/// Gets the ICloudServicesUpdateDomainOperations.
/// </summary>
public virtual ICloudServicesUpdateDomainOperations CloudServicesUpdateDomain { get; private set; }
/// <summary>
/// Gets the ICloudServiceOperatingSystemsOperations.
/// </summary>
public virtual ICloudServiceOperatingSystemsOperations CloudServiceOperatingSystems { get; private set; }
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling ComputeManagementClient.Dispose(). False: will not dispose provided httpClient</param>
protected ComputeManagementClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ComputeManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ComputeManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ComputeManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ComputeManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling ComputeManagementClient.Dispose(). False: will not dispose provided httpClient</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Operations = new Operations(this);
AvailabilitySets = new AvailabilitySetsOperations(this);
ProximityPlacementGroups = new ProximityPlacementGroupsOperations(this);
DedicatedHostGroups = new DedicatedHostGroupsOperations(this);
DedicatedHosts = new DedicatedHostsOperations(this);
SshPublicKeys = new SshPublicKeysOperations(this);
VirtualMachineExtensionImages = new VirtualMachineExtensionImagesOperations(this);
VirtualMachineExtensions = new VirtualMachineExtensionsOperations(this);
VirtualMachineImages = new VirtualMachineImagesOperations(this);
VirtualMachineImagesEdgeZone = new VirtualMachineImagesEdgeZoneOperations(this);
Usage = new UsageOperations(this);
VirtualMachines = new VirtualMachinesOperations(this);
VirtualMachineScaleSets = new VirtualMachineScaleSetsOperations(this);
VirtualMachineSizes = new VirtualMachineSizesOperations(this);
Images = new ImagesOperations(this);
VirtualMachineScaleSetExtensions = new VirtualMachineScaleSetExtensionsOperations(this);
VirtualMachineScaleSetRollingUpgrades = new VirtualMachineScaleSetRollingUpgradesOperations(this);
VirtualMachineScaleSetVMExtensions = new VirtualMachineScaleSetVMExtensionsOperations(this);
VirtualMachineScaleSetVMs = new VirtualMachineScaleSetVMsOperations(this);
LogAnalytics = new LogAnalyticsOperations(this);
VirtualMachineRunCommands = new VirtualMachineRunCommandsOperations(this);
VirtualMachineScaleSetVMRunCommands = new VirtualMachineScaleSetVMRunCommandsOperations(this);
ResourceSkus = new ResourceSkusOperations(this);
Disks = new DisksOperations(this);
Snapshots = new SnapshotsOperations(this);
DiskEncryptionSets = new DiskEncryptionSetsOperations(this);
DiskAccesses = new DiskAccessesOperations(this);
DiskRestorePoint = new DiskRestorePointOperations(this);
Galleries = new GalleriesOperations(this);
GalleryImages = new GalleryImagesOperations(this);
GalleryImageVersions = new GalleryImageVersionsOperations(this);
GalleryApplications = new GalleryApplicationsOperations(this);
GalleryApplicationVersions = new GalleryApplicationVersionsOperations(this);
CloudServiceRoleInstances = new CloudServiceRoleInstancesOperations(this);
CloudServiceRoles = new CloudServiceRolesOperations(this);
CloudServices = new CloudServicesOperations(this);
CloudServicesUpdateDomain = new CloudServicesUpdateDomainOperations(this);
CloudServiceOperatingSystems = new CloudServiceOperatingSystemsOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| mit |
adiachenko/catchy_api | app/Http/Requests/Auth/FacebookAuthentication.php | 502 | <?php
namespace App\Http\Requests\Auth;
use App\Http\Requests\Request;
class FacebookAuthentication extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'token' => 'required'
];
}
}
| mit |
ActiveState/code | recipes/Python/576602_safe_print/recipe-576602.py | 276 | def _safe_print(u, errors="replace"):
"""Safely print the given string.
If you want to see the code points for unprintable characters then you
can use `errors="xmlcharrefreplace"`.
"""
s = u.encode(sys.stdout.encoding or "utf-8", errors)
print(s)
| mit |
restorando/rbrules | lib/rbrules.rb | 971 | class RbRules
attr_reader :rules
@rule_sets = Hash.new { |hash, key| hash[key] = new }
def +(other)
self.class.new do |builder|
rules.each { |rule| builder.rule(rule) }
if other.is_a?(self.class)
other.rules.each { |rule| builder.rule(rule) }
else
builder.rule(other)
end
end
end
def self.[](key)
@rule_sets[key]
end
def initialize(&block)
@rules = []
yield(self) if block_given?
end
def rule(name_or_rule, &block)
if name_or_rule.respond_to? :call
rules << name_or_rule
else
rules << Rule.new(name_or_rule, block)
end
end
%w[all? none?].each do |method_name|
define_method method_name do |*args|
rules.public_send(method_name) { |rule| rule.call(*args) }
end
end
def any?(*args)
rules.find do |rule|
rule.call(*args)
end
end
class Rule < Struct.new(:name, :block)
def call(*args); block.call(*args) end
end
end
| mit |
packetloop/jira | lib/jira.js | 635 | var querystring = require('querystring');
exports.curl = function(url) {
if (!process.env.JIRA_TOKEN) {
throw new Error('JIRA_TOKEN env required');
}
var cmd = ['curl --silent',
' -u ', process.env.JIRA_TOKEN,
' -H "Content-Type: application/json"',
' "', url, '"'
].join('');
// console.log('Executing: \n', cmd);
return cmd;
};
exports.url = function(path, params) {
params = params || {};
if (!process.env.JIRA_URL) {
throw new Error('JIRA_URL env required');
}
return [process.env.JIRA_URL.replace(/\/$/, ''), '/rest/api/2', path,
'?', querystring.stringify(params)].join('');
};
| mit |
Teamsquare/s2_netbox | lib/s2_netbox/commands/authentication.rb | 409 | class S2Netbox::Commands::Authentication < S2Netbox::ApiRequest
include S2Netbox::Helpers
def self.login
S2Netbox.request(S2Netbox::BASIC_ENDPOINT, build_command('Login', {:'USERNAME' => S2Netbox.configuration.username, :'PASSWORD' => S2Netbox.configuration.password}))
end
def self.logout(session_id)
S2Netbox.request(S2Netbox::BASIC_ENDPOINT, build_command('Logout'), session_id)
end
end | mit |
jiunjiun/barcodecat | db/migrate/20170126095020_create_events.rb | 320 | class CreateEvents < ActiveRecord::Migration[5.0]
def change
create_table :events do |t|
t.integer :category
t.string :title
t.text :desc
t.string :link_name
t.text :keywords
t.string :image
t.boolean :enable, default: false
t.timestamps
end
end
end
| mit |
weiht/nrt.boot | nrt-boot-strap/src/main/java/nrt/boot/velocity/AuthDirective.java | 1815 | package nrt.boot.velocity;
import java.io.IOException;
import java.io.Writer;
import org.apache.shiro.SecurityUtils;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;
public class AuthDirective
extends Directive {
@Override
public String getName() {
return "auth";
}
@Override
public int getType() {
return BLOCK;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer,
Node node) throws IOException, ResourceNotFoundException,
ParseErrorException, MethodInvocationException {
boolean authRequired = authenticatedRequired(context, node);
boolean auth = authState();
if (authRequired == auth) {
return doRender(context, writer, node);
}
return false;
}
protected boolean authState() {
return SecurityUtils.getSubject().isAuthenticated();
}
private boolean authenticatedRequired(InternalContextAdapter context,
Node node) {
if (node.jjtGetNumChildren() < 2) return true;
SimpleNode n = (SimpleNode) node.jjtGetChild(0);
Object v = n.value(context);
if (v == null) return true;
if (v instanceof Boolean) {
return (Boolean)v;
}
return true;
}
private boolean doRender(InternalContextAdapter context, Writer writer,
Node node)
throws MethodInvocationException, ParseErrorException,
ResourceNotFoundException, IOException {
SimpleNode block = (SimpleNode) node.jjtGetChild(node.jjtGetNumChildren() - 1);
return block.render(context, writer);
}
}
| mit |
ermaker/no_proxy_fix | spec/lib/cext/generic_find_proxy_spec.rb | 368 | require 'no_proxy_fix'
RSpec.describe URI do
around do |example|
http_proxy = ENV['http_proxy']
no_proxy = ENV['no_proxy']
example.run
ENV['http_proxy'] = http_proxy
ENV['no_proxy'] = no_proxy
end
it 'works' do
ENV['http_proxy'] = 'http://127.0.0.1'
ENV['no_proxy'] = '192.0.2.2'
URI('http://example.org/').find_proxy
end
end
| mit |
odaper/angular2-sample-taskmanager | src/app/business/pages/pages.module.ts | 1698 | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { PagesRoutingModule } from './pages-routing.module';
import { CustomerComponent } from './customer/customer.component';
import { ProductComponent } from './product/product.component';
import { MainComponent } from './main/main.component';
import { MyThemeModule } from '../../themes/my-theme/my-theme.module';
import {CdkColumnDef, CdkTable, CdkTableModule} from '@angular/cdk';
import {
MdButtonModule, MdCardModule, MdMenuModule, MdToolbarModule, MdIconModule, MdSidenavModule, MdInputModule,
MdDatepickerModule, MdRadioModule, MdNativeDateModule, MdSlideToggleModule, MdCheckboxModule, MdAutocompleteModule,
MdTableModule, MdSelectModule, MaterialModule, MdPaginatorModule
} from '@angular/material';
@NgModule({
imports: [
CommonModule,
PagesRoutingModule,
MyThemeModule,
MdButtonModule,
MdMenuModule,
MdCardModule,
MdToolbarModule,
MdIconModule,
MdSidenavModule,
MdInputModule,
MdDatepickerModule,
MdRadioModule,
MdNativeDateModule,
FormsModule,
MdCheckboxModule,
MdAutocompleteModule,
ReactiveFormsModule,
MdTableModule,
CdkTableModule,
MdPaginatorModule,
MdMenuModule,
],
providers: [CdkColumnDef, CdkTable],
declarations: [
CustomerComponent, ProductComponent, MainComponent ],
exports: [MainComponent]
})
export class PagesModule { }
| mit |
maybeShuo/netease-music-juke-box | src/nm/app/ApplicationController.js | 3679 | import NJUApplicationController from "../../nju/app/ApplicationController";
import Application from "./Application";
import ServiceClient from "../service/ServiceClient";
export default class ApplicationController extends NJUApplicationController
{
init()
{
super.init();
this._playLists = [];
this._activePlayList = null;
this._activeTrack = null;
}
get playLists()
{
return this._playLists;
}
set playLists(value)
{
this._playLists = value;
this._onPlayListsChanged();
}
get activePlayList()
{
return this._activePlayList;
}
set activePlayList(value)
{
if (this.activePlayList !== value)
{
this._activePlayList = value;
this._onActivePlayListChanged();
}
}
get activeTrack()
{
return this._activeTrack;
}
set activeTrack(value)
{
if (this._activeTrack !== value)
{
this._activeTrack = value;
this._onActiveTrackChanged();
}
}
createApplication()
{
const application = new Application();
return application;
}
initView(options)
{
super.initView(options)
this.playerView = this.application.playerView;
this.playListView = this.application.playListView;
this.playListView.on("selectionchanged", this._playListView_selectionchanged.bind(this));
this.searchView = this.application.searchView;
this.searchView.on("search", this._searchView_search.bind(this));
this.trackTableView = this.application.trackTableView;
this.trackTableView.on("itemdblclick", this._trackTableView_itemdblclick.bind(this));
}
async run()
{
console.log("Netease Music Webapp is now running...");
try {
await ServiceClient.getInstance().login();
await this._loadUserPlayList();
}
catch (e)
{
console.log(e);
}
}
async _loadUserPlayList()
{
this.playLists = await ServiceClient.getInstance().getUserPlayLists();
if (this.playLists.length > 0)
{
this.playListView.selection = this.playLists[0];
}
}
_onPlayListsChanged()
{
this.playListView.items = this.playLists;
}
_onActivePlayListChanged()
{
if (this.activePlayList)
{
this.trackTableView.items = this.activePlayList.tracks;
if (this.activePlayList.id === "search")
{
this.playListView.selection = null;
}
}
else
{
this.trackTableView.items = [];
}
}
_onActiveTrackChanged()
{
if (this.activeTrack !== null)
{
this.playerView.track = this.activeTrack;
}
else
{
this.playerView.track = null;
}
}
async _playListView_selectionchanged(e)
{
if (this.playListView.selectedId)
{
const playList = await ServiceClient.getInstance().getPlayListDetail(this.playListView.selectedId);
this.activePlayList = playList;
}
}
_trackTableView_itemdblclick(e)
{
const track = this.trackTableView.selection;
this.activeTrack = track;
}
async _searchView_search(e)
{
if (this.searchView.text.trim() !== "")
{
this.activePlayList = {
id: "search",
tracks: await ServiceClient.getInstance().search(this.searchView.text)
}
}
}
}
| mit |
GridProtectionAlliance/openHistorian | Source/Applications/openHistorian/openHistorian/Grafana/public/app/plugins/datasource/loki/configuration/DebugSection.test.tsx | 2459 | import React from 'react';
import { DebugSection } from './DebugSection';
import { mount } from 'enzyme';
import { getLinkSrv, LinkService, LinkSrv, setLinkSrv } from '../../../../features/panel/panellinks/link_srv';
import { TimeSrv } from '../../../../features/dashboard/services/TimeSrv';
import { dateTime } from '@grafana/data';
import { TemplateSrv } from '../../../../features/templating/template_srv';
describe('DebugSection', () => {
let originalLinkSrv: LinkService;
// This needs to be setup so we can test interpolation in the debugger
beforeAll(() => {
// We do not need more here and TimeSrv is hard to setup fully.
const timeSrvMock: TimeSrv = {
timeRangeForUrl() {
const from = dateTime().subtract(1, 'h');
const to = dateTime();
return { from, to, raw: { from, to } };
},
} as any;
const linkService = new LinkSrv(new TemplateSrv(), timeSrvMock);
originalLinkSrv = getLinkSrv();
setLinkSrv(linkService);
});
afterAll(() => {
setLinkSrv(originalLinkSrv);
});
it('does not render any field if no debug text', () => {
const wrapper = mount(<DebugSection derivedFields={[]} />);
expect(wrapper.find('DebugFieldItem').length).toBe(0);
});
it('does not render any field if no derived fields', () => {
const wrapper = mount(<DebugSection derivedFields={[]} />);
const textarea = wrapper.find('textarea');
(textarea.getDOMNode() as HTMLTextAreaElement).value = 'traceId=1234';
textarea.simulate('change');
expect(wrapper.find('DebugFieldItem').length).toBe(0);
});
it('renders derived fields', () => {
const derivedFields = [
{
matcherRegex: 'traceId=(\\w+)',
name: 'traceIdLink',
url: 'http://localhost/trace/${__value.raw}',
},
{
matcherRegex: 'traceId=(\\w+)',
name: 'traceId',
},
{
matcherRegex: 'traceId=(',
name: 'error',
},
];
const wrapper = mount(<DebugSection derivedFields={derivedFields} />);
const textarea = wrapper.find('textarea');
(textarea.getDOMNode() as HTMLTextAreaElement).value = 'traceId=1234';
textarea.simulate('change');
expect(wrapper.find('table').length).toBe(1);
// 3 rows + one header
expect(wrapper.find('tr').length).toBe(4);
expect(
wrapper
.find('tr')
.at(1)
.contains('http://localhost/trace/1234')
).toBeTruthy();
});
});
| mit |
biow0lf/evemonk | app/queries/eve/search_corporations_query.rb | 375 | # frozen_string_literal: true
module Eve
class SearchCorporationsQuery < BaseQuery
attr_reader :search, :scope
def initialize(search = nil, scope = Eve::Corporation.all)
@search = search
@scope = scope
end
def query
if search.present?
scope.search_by_name_and_ticker(search)
else
scope
end
end
end
end
| mit |
wojciech-panek/study-group-6-redux | app/modules/weather/weather.sagas.js | 929 | import { call, put, takeLatest, select } from 'redux-saga/effects';
import envConfig from 'env-config';
import { WeatherActions } from './weather.redux';
import { MapTypes } from '../map/map.redux';
import { selectPosition } from '../map/map.selectors';
import { GoogleActions } from '../google/google.redux';
import { get } from '../api/api.sagas';
export function* getWeatherSaga() {
try {
const position = yield select(selectPosition);
const data = yield call(get, 'api/openweathermap/', {
'lat': position.get('lat'),
'lon': position.get('long'),
'appid': envConfig.openweathermap.apiKey,
});
yield put(WeatherActions.getWeatherSuccess(data));
yield put(GoogleActions.choosePlaces());
} catch (e) {
yield put(WeatherActions.getWeatherFailure(e));
}
}
export default function* weatherSaga() {
yield [
yield takeLatest(MapTypes.CHANGE_POSITION, getWeatherSaga),
];
}
| mit |
macoss/livequestions | client/startup.js | 121 | Accounts.config({
forbidClientAccountCreation : true
});
_.extend(Notifications.defaultOptions, {
timeout: 5000
});
| mit |
AndrioCelos/CBot | CBot/Properties/AssemblyInfo.cs | 1285 | 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("CBot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Andrio Celos")]
[assembly: AssemblyProduct("CBot")]
[assembly: AssemblyCopyright("© 2012-2018 Andrea Giannone")]
[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(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("596948e1-e97d-4095-9569-f35dd3369e48")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("3.7.0.0")]
[assembly: AssemblyFileVersion("3.7.0.0")]
[assembly: InternalsVisibleTo("CBotTests")]
| mit |
AxioDL/PathShagged | Runtime/Graphics/CPVSVisSet.hpp | 658 | #pragma once
#include "Runtime/RetroTypes.hpp"
#include <zeus/CVector3f.hpp>
namespace metaforce {
class CPVSVisOctree;
enum class EPVSVisSetState { EndOfTree, NodeFound, OutOfBounds };
class CPVSVisSet {
EPVSVisSetState x0_state;
u32 x4_numBits;
u32 x8_numLights;
// bool xc_; Used to be part of auto_ptr
const u8* x10_ptr;
public:
void Reset(EPVSVisSetState state);
EPVSVisSetState GetState() const { return x0_state; }
EPVSVisSetState GetVisible(u32 idx) const;
void SetFromMemory(u32 numBits, u32 numLights, const u8* leafPtr);
void SetTestPoint(const CPVSVisOctree& octree, const zeus::CVector3f&);
};
} // namespace metaforce
| mit |
mlilley/testing_nodejs_with_mocha | basic_project/test/async_adder.js | 375 | var should = require('should');
var Adder = require('../async_adder').Adder;
describe('Asynchronous Adder', function() {
describe('add()', function() {
it('should callback with 3 when adding 1 and 2', function(done) {
var adder = new Adder();
adder.add(1, 2, function(result) {
result.should.equal(3);
done();
});
});
});
}); | mit |
peregrinogris/lsystems-js | src/lsystems/parser.js | 2883 | // http://eli.thegreenplace.net/2013/07/16/hand-written-lexer-in-javascript-compared-to-the-regex-based-ones
// https://github.com/thejameskyle/the-super-tiny-compiler/blob/master/super-tiny-compiler.js
import Lexer from './lexer';
class Parser {
constructor(_input) {
this.pos = 0;
this.tokens = [];
this.input(_input);
}
input(_input) {
let token = null;
const lexer = new Lexer();
lexer.input(_input);
for (;;) {
token = lexer.token();
if (!token) {
break;
}
this.tokens.push(token);
}
}
scanParameters() {
let token = null;
const params = [];
const nextToken = this.tokens[this.pos + 1];
// Module or Rotation with parameters
if (
this.pos < this.tokens.length - 1 &&
nextToken.type === 'KEYWORD' &&
nextToken.value === '('
) {
this.pos += 2;
token = this.tokens[this.pos];
while (
(token.type !== 'KEYWORD') ||
(token.type === 'KEYWORD' && token.value !== ')')
) {
if (token.type === 'KEYWORD' && token.value === ',') {
this.pos += 1;
} else {
params.push(this.walk());
}
token = this.tokens[this.pos];
}
}
return params;
}
walk() {
const token = this.tokens[this.pos];
let node = {};
// Number
if (token.type === 'NUMBER') {
this.pos += 1;
return {
type: 'NumberLiteral',
value: token.value,
};
}
// State
if (token.type === 'STATE') {
this.pos += 1;
return {
type: token.value === '[' ? 'PushState' : 'PopState',
value: token.value,
};
}
// Module or Rotation
if (token.type === 'MODULE' || token.type === 'ROTATION') {
// eslint-disable-next-line vars-on-top
node = {
type: token.type === 'MODULE' ? 'Module' : 'Rotation',
name: token.value,
params: this.scanParameters(),
};
this.pos += 1;
return node;
}
// Modifier
if (token.type === 'MODIFIER') {
// eslint-disable-next-line vars-on-top
node = {
type: 'Modifier',
name: token.value,
params: this.scanParameters(),
};
this.pos += 1;
return node;
}
// Keyword
if (token.type === 'KEYWORD' && !token.value.match(/[()]/)) {
// Keywords are not parametric, otherwise they should be modifiers.
this.pos += 1;
return {
type: 'Keyword',
value: token.value,
};
}
throw Error(`Unexpected token ${token.value} at position ${this.pos}`);
}
parse() {
const ast = {
type: 'Program',
body: [],
};
while (this.pos < this.tokens.length) {
ast.body.push(this.walk());
}
return ast;
}
}
const parse = input => ((new Parser(input)).parse());
export default parse;
| mit |
RogueException/Discord.Net | src/Discord.Net.Core/RequestOptions.cs | 3332 | using System.Threading;
namespace Discord
{
/// <summary>
/// Represents options that should be used when sending a request.
/// </summary>
public class RequestOptions
{
/// <summary>
/// Creates a new <see cref="RequestOptions" /> class with its default settings.
/// </summary>
public static RequestOptions Default => new RequestOptions();
/// <summary>
/// Gets or sets the maximum time to wait for for this request to complete.
/// </summary>
/// <remarks>
/// Gets or set the max time, in milliseconds, to wait for for this request to complete. If
/// <c>null</c>, a request will not time out. If a rate limit has been triggered for this request's bucket
/// and will not be unpaused in time, this request will fail immediately.
/// </remarks>
/// <returns>
/// A <see cref="int"/> in milliseconds for when the request times out.
/// </returns>
public int? Timeout { get; set; }
/// <summary>
/// Gets or sets the cancellation token for this request.
/// </summary>
/// <returns>
/// A <see cref="CancellationToken"/> for this request.
/// </returns>
public CancellationToken CancelToken { get; set; } = CancellationToken.None;
/// <summary>
/// Gets or sets the retry behavior when the request fails.
/// </summary>
public RetryMode? RetryMode { get; set; }
public bool HeaderOnly { get; internal set; }
/// <summary>
/// Gets or sets the reason for this action in the guild's audit log.
/// </summary>
/// <remarks>
/// Gets or sets the reason that will be written to the guild's audit log if applicable. This may not apply
/// to all actions.
/// </remarks>
public string AuditLogReason { get; set; }
/// <summary>
/// Gets or sets whether or not this request should use the system
/// clock for rate-limiting. Defaults to <c>true</c>.
/// </summary>
/// <remarks>
/// This property can also be set in <see cref="DiscordConfig">.
///
/// On a per-request basis, the system clock should only be disabled
/// when millisecond precision is especially important, and the
/// hosting system is known to have a desynced clock.
/// </remarks>
public bool? UseSystemClock { get; set; }
internal bool IgnoreState { get; set; }
internal string BucketId { get; set; }
internal bool IsClientBucket { get; set; }
internal bool IsReactionBucket { get; set; }
internal static RequestOptions CreateOrClone(RequestOptions options)
{
if (options == null)
return new RequestOptions();
else
return options.Clone();
}
/// <summary>
/// Initializes a new <see cref="RequestOptions" /> class with the default request timeout set in
/// <see cref="DiscordConfig"/>.
/// </summary>
public RequestOptions()
{
Timeout = DiscordConfig.DefaultRequestTimeout;
}
public RequestOptions Clone() => MemberwiseClone() as RequestOptions;
}
}
| mit |
sensu/sensu-plugin-python | sensu_plugin/handler.py | 9342 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This provides a base SensuHandler class that can be used for writing
python-based Sensu handlers.
'''
from __future__ import print_function
import argparse
import os
import sys
import json
import requests
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from sensu_plugin.utils import get_settings, map_v2_event_into_v1
class SensuHandler(object):
'''
Base class for Sensu Handlers.
'''
def __init__(self, autorun=True):
if autorun:
self.run()
def run(self):
'''
Set up the event object, global settings and command line
arguments.
'''
# Parse the stdin into a global event object
stdin = self.read_stdin()
self.event = self.read_event(stdin)
# Prepare global settings
self.settings = get_settings()
self.api_settings = self.get_api_settings()
# Prepare command line arguments and
self.parser = argparse.ArgumentParser()
# set up the 2.x to 1.x event mapping argument
self.parser.add_argument("--map-v2-event-into-v1",
action="store_true",
default=False,
dest="v2event")
if hasattr(self, 'setup'):
self.setup()
(self.options, self.remain) = self.parser.parse_known_args()
# map the event if required
if (self.options.v2event or
os.environ.get("SENSU_MAP_V2_EVENT_INTO_V1")):
self.event = map_v2_event_into_v1(self.event)
# Filter (deprecated) and handle
self.filter()
self.handle()
def read_stdin(self):
'''
Read data piped from stdin.
'''
try:
return sys.stdin.read()
except Exception:
raise ValueError('Nothing read from stdin')
def read_event(self, check_result):
'''
Convert the piped check result (json) into a global 'event' dict
'''
try:
event = json.loads(check_result)
event['occurrences'] = event.get('occurrences', 1)
event['check'] = event.get('check', {})
event['client'] = event.get('client', {})
return event
except Exception:
raise ValueError('error reading event: ' + check_result)
def handle(self):
'''
Method that should be overwritten to provide handler logic.
'''
print("ignoring event -- no handler defined.")
def filter(self):
'''
Filters exit the proccess if the event should not be handled.
Filtering events is deprecated and will be removed in a future release.
'''
if self.deprecated_filtering_enabled():
print('warning: event filtering in sensu-plugin is deprecated,' +
'see http://bit.ly/sensu-plugin')
self.filter_disabled()
self.filter_silenced()
self.filter_dependencies()
if self.deprecated_occurrence_filtering():
print('warning: occurrence filtering in sensu-plugin is' +
'deprecated, see http://bit.ly/sensu-plugin')
self.filter_repeated()
def deprecated_filtering_enabled(self):
'''
Evaluates whether the event should be processed by any of the
filter methods in this library. Defaults to true,
i.e. deprecated filters are run by default.
returns bool
'''
return self.event['check'].get('enable_deprecated_filtering', False)
def deprecated_occurrence_filtering(self):
'''
Evaluates whether the event should be processed by the
filter_repeated method. Defaults to true, i.e. filter_repeated
will filter events by default.
returns bool
'''
return self.event['check'].get(
'enable_deprecated_occurrence_filtering', False)
def bail(self, msg):
'''
Gracefully terminate with message
'''
client_name = self.event['client'].get('name', 'error:no-client-name')
check_name = self.event['check'].get('name', 'error:no-check-name')
print('{}: {}/{}'.format(msg, client_name, check_name))
sys.exit(0)
def get_api_settings(self):
'''
Return a dict of API settings derived first from ENV['SENSU_API_URL']
if set, then Sensu config `api` scope if configured, and finally
falling back to to ipv4 localhost address on default API port.
return dict
'''
sensu_api_url = os.environ.get('SENSU_API_URL')
if sensu_api_url:
uri = urlparse(sensu_api_url)
api_settings = {
'host': '{0}://{1}'.format(uri.scheme, uri.hostname),
'port': uri.port,
'user': uri.username,
'password': uri.password
}
else:
api_settings = self.settings.get('api', {})
api_settings['host'] = api_settings.get(
'host', '127.0.0.1')
api_settings['port'] = api_settings.get(
'port', 4567)
return api_settings
# API requests
def api_request(self, method, path):
'''
Query Sensu api for information.
'''
if not hasattr(self, 'api_settings'):
ValueError('api.json settings not found')
if method.lower() == 'get':
_request = requests.get
elif method.lower() == 'post':
_request = requests.post
domain = self.api_settings['host']
uri = '{}:{}/{}'.format(domain, self.api_settings['port'], path)
if self.api_settings.get('user') and self.api_settings.get('password'):
auth = (self.api_settings['user'], self.api_settings['password'])
else:
auth = ()
req = _request(uri, auth=auth)
return req
def stash_exists(self, path):
'''
Query Sensu API for stash data.
'''
return self.api_request('get', '/stash' + path).status_code == 200
def event_exists(self, client, check):
'''
Query Sensu API for event.
'''
return self.api_request(
'get',
'events/{}/{}'.format(client, check)
).status_code == 200
# Filters
def filter_disabled(self):
'''
Determine whether a check is disabled and shouldn't handle.
'''
if self.event['check']['alert'] is False:
self.bail('alert disabled')
def filter_silenced(self):
'''
Determine whether a check is silenced and shouldn't handle.
'''
stashes = [
('client', '/silence/{}'.format(self.event['client']['name'])),
('check', '/silence/{}/{}'.format(
self.event['client']['name'],
self.event['check']['name'])),
('check', '/silence/all/{}'.format(self.event['check']['name']))
]
for scope, path in stashes:
if self.stash_exists(path):
self.bail(scope + ' alerts silenced')
def filter_dependencies(self):
'''
Determine whether a check has dependencies.
'''
dependencies = self.event['check'].get('dependencies', None)
if dependencies is None or not isinstance(dependencies, list):
return
for dependency in self.event['check']['dependencies']:
if not str(dependency):
continue
dependency_split = tuple(dependency.split('/'))
# If there's a dependency on a check from another client, then use
# that client name, otherwise assume same client.
if len(dependency_split) == 2:
client, check = dependency_split
else:
client = self.event['client']['name']
check = dependency_split[0]
if self.event_exists(client, check):
self.bail('check dependency event exists')
def filter_repeated(self):
'''
Determine whether a check is repeating.
'''
defaults = {
'occurrences': 1,
'interval': 30,
'refresh': 1800
}
# Override defaults with anything defined in the settings
if isinstance(self.settings['sensu_plugin'], dict):
defaults.update(self.settings['sensu_plugin'])
occurrences = int(self.event['check'].get(
'occurrences', defaults['occurrences']))
interval = int(self.event['check'].get(
'interval', defaults['interval']))
refresh = int(self.event['check'].get(
'refresh', defaults['refresh']))
if self.event['occurrences'] < occurrences:
self.bail('not enough occurrences')
if (self.event['occurrences'] > occurrences and
self.event['action'] == 'create'):
return
number = int(refresh / interval)
if (number == 0 or
(self.event['occurrences'] - occurrences) % number == 0):
return
self.bail('only handling every ' + str(number) + ' occurrences')
| mit |
rnorth/test-containers | modules/selenium/src/test/java/org/testcontainers/junit/LocalServerWebDriverContainerTest.java | 2402 | package org.testcontainers.junit;
import org.junit.*;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.ResourceHandler;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testcontainers.containers.BrowserWebDriverContainer;
import org.testcontainers.utility.TestEnvironment;
import static org.apache.commons.lang.SystemUtils.IS_OS_MAC_OSX;
import static org.rnorth.visibleassertions.VisibleAssertions.assertEquals;
/**
* Test that a browser running in a container can access a web server hosted on the host machine (i.e. the one running
* the tests)
*/
public class LocalServerWebDriverContainerTest {
@Rule
public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer().withCapabilities(new ChromeOptions());
private int localPort;
/**
* The getTestHostIpAddress() method is only implemented for OS X running docker-machine. Skip JUnit execution elsewhere.
*/
@BeforeClass
public static void checkOS() {
Assume.assumeTrue("These tests are currently only applicable to OS X", IS_OS_MAC_OSX);
Assume.assumeTrue("These tests are only applicable to docker machine", TestEnvironment.dockerIsDockerMachine());
}
@Before
public void setupLocalServer() throws Exception {
// Set up a local Jetty HTTP server
Server server = new Server();
server.addConnector(new SocketConnector());
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase("src/test/resources/server");
server.addHandler(resourceHandler);
server.start();
// The server will have a random port assigned, so capture that
localPort = server.getConnectors()[0].getLocalPort();
}
@Test
public void testConnection() {
RemoteWebDriver driver = chrome.getWebDriver();
// Construct a URL that the browser container can access
String hostIpAddress = chrome.getTestHostIpAddress();
driver.get("http://" + hostIpAddress + ":" + localPort);
String headingText = driver.findElement(By.cssSelector("h1")).getText().trim();
assertEquals("The hardcoded success message was found on a page fetched from a local server", "It worked", headingText);
}
}
| mit |
uoinfusion/Infusion | Infusion.Proxy/Properties/AssemblyInfo.cs | 388 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Infusion.Proxy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: Guid("5e814151-7f4c-4d71-bcb2-97fd303f04a8")]
[assembly: InternalsVisibleTo("Infusion.Proxy.Tests")]
[assembly: InternalsVisibleTo("Infusion.Desktop")] | mit |
BacktrackAcademy/workshop-iv-dev | app/models/product.rb | 58 | class Product < ActiveRecord::Base
belongs_to :user
end
| mit |
tburrows13/Game-of-Life | tools.py | 771 | import time
def import_grid(file_to_open):
grid = []
print(file_to_open)
with open(file_to_open) as file:
for i, line in enumerate(file):
if i == 0:
iterations = int(line.split(" ")[0])
delay = float(line.split(" ")[1])
else:
grid.append([])
line = line.strip()
for item in line:
grid[i-1].append(int(item))
return grid, iterations, delay
def save_grid(file, grid):
with open(file, 'w') as file:
for line in grid:
file.write(line + "\n")
def check_time(prev_time, freq):
if time.time() - prev_time > freq:
return True
else:
return False
| mit |
dannycho7/express-form-post | lib/fileHandler.js | 2589 | const Busboy = require("busboy");
module.exports = function(req, res, cb) {
if(req.method == "POST") {
if(req._body) return cb();
/*
* _finished is false by default and set to true if efp has "finished". Usually this just means that
* the next middleware has been called already and further calls to finished and handleError does nothing
* efp.busboy._finished is false by default and true if busboy is done parsing
* _data tracks each inidividual's file size and stream
*/
req.efp = { _finished: false, _data: {}, busboy: { _finished: false }};
req.body = {};
req._body = true; // prevent multiple multipart middleware and body-parser from colliding
req.files = {};
/*
* In middleware, req.efp.finished passes on to next middleware
* Validation checking in req.efp.finished because of upload function cb not next param in middleware
* In upload function, req.efp.finished will be the callback with an err parameter. (err be undefined)
* req.efp.finished will be called when finished with parsing the request to pass on to the cb action
* buffers array holds file contents that should be sent to the store if the body is valid
*/
req.efp.finished = function() {
if(req.efp._finished) return;
if(Object.keys(req.files).length == Object.keys(req.efp._data).length && req.efp.busboy._finished) {
// all files that were sent to the store have been uploaded and busboy is done parsing
req.efp._finished = true;
return cb();
}
};
// make sure this is called before handleError call
req.efp._removeAllUploads = function() {
req.body = {};
for(let key in req.efp._data) {
req.efp._data[key].stream ? req.efp._data[key].stream.emit("destroy") : delete req.efp._data[key];
}
};
/*
* A call to req.efp.handleError will nullify any subsequent calls to req.efp.finished and req.efp.handleError
*/
req.efp.handleError = (err) => {
if(req.efp._finished) return;
req.efp._finished = true;
req.unpipe(busboy);
busboy.removeAllListeners();
req.on("readable", () => req.read());
req.efp._removeAllUploads();
cb(err);
};
req.efp.skip = (fieldname, file) => {
delete req.efp._data[fieldname];
return file.resume();
}
try {
var busboy = new Busboy({
headers: req.headers,
limits: {
fileSize: this.opts.maxfileSize.size
}
});
this._attachListeners(busboy, req);
req.pipe(busboy);
} catch(err) {
req.efp.handleError(err);
}
} else {
return cb();
}
}; | mit |
wadey/node-syncrepl | syncrepl.js | 29252 | // Copyright Joyent, Inc. and other Node contributors.
//
// 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.
/* A repl library that you can include in your own code to get a runtime
* interface to your program.
*
* var repl = require("/repl.js");
* // start repl on stdin
* repl.start("prompt> ");
*
* // listen for unix socket connections and start repl on them
* net.createServer(function(socket) {
* repl.start("node via Unix socket> ", socket);
* }).listen("/tmp/node-repl-sock");
*
* // listen for TCP socket connections and start repl on them
* net.createServer(function(socket) {
* repl.start("node via TCP socket> ", socket);
* }).listen(5001);
*
* // expose foo to repl context
* repl.start("node > ").context.foo = "stdin is fun";
*/
var util = require('util');
var inherits = require('util').inherits;
var Stream = require('stream');
var vm = require('vm');
var path = require('path');
var fs = require('fs');
var rl = require('readline');
var EventEmitter = require('events').EventEmitter;
var syncfunc = require('./syncfunc')
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
// hack for require.resolve("./relative") to work properly.
module.filename = path.resolve('repl');
// hack for repl require to work properly with node_modules folders
module.paths = require('module')._nodeModulePaths(module.filename);
// Can overridden with custom print functions, such as `probe` or `eyes.js`.
// This is the default "writer" value if none is passed in the REPL options.
exports.writer = util.inspect;
exports._builtinLibs = ['assert', 'buffer', 'child_process', 'cluster',
'crypto', 'dgram', 'dns', 'events', 'fs', 'http', 'https', 'net',
'os', 'path', 'punycode', 'querystring', 'readline', 'repl',
'string_decoder', 'tls', 'tty', 'url', 'util', 'vm', 'zlib'];
function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
if (!(this instanceof REPLServer)) {
return new REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined);
}
EventEmitter.call(this);
var options, input, output;
if (typeof prompt == 'object') {
// an options object was given
options = prompt;
stream = options.stream || options.socket;
input = options.input;
output = options.output;
eval_ = options.eval;
useGlobal = options.useGlobal;
ignoreUndefined = options.ignoreUndefined;
prompt = options.prompt;
} else if (typeof prompt != 'string') {
throw new Error('An options Object, or a prompt String are required');
} else {
options = {};
}
var self = this;
self.useGlobal = !!useGlobal;
self.ignoreUndefined = !!ignoreUndefined;
self.eval = eval_ || function(code, context, file, cb) {
var err, result;
try {
if (self.useGlobal) {
result = vm.runInThisContext(code, file);
} else {
result = vm.runInContext(code, context, file);
}
} catch (e) {
err = e;
}
cb(err, result);
};
self.resetContext();
self.bufferedCommand = '';
if (!input && !output) {
// legacy API, passing a 'stream'/'socket' option
if (!stream) {
// use stdin and stdout as the default streams if none were given
stream = process;
}
if (stream.stdin && stream.stdout) {
// We're given custom object with 2 streams, or the `process` object
input = stream.stdin;
output = stream.stdout;
} else {
// We're given a duplex readable/writable Stream, like a `net.Socket`
input = stream;
output = stream;
}
}
self.inputStream = input;
self.outputStream = output;
self.prompt = (prompt != undefined ? prompt : '> ');
function complete(text, callback) {
self.complete(text, callback);
}
var rli = rl.createInterface({
input: self.inputStream,
output: self.outputStream,
completer: complete,
terminal: options.terminal
});
self.rli = rli;
this.commands = {};
defineDefaultCommands(this);
// figure out which "writer" function to use
self.writer = options.writer || exports.writer;
if (typeof options.useColors === 'undefined') {
options.useColors = rli.terminal;
}
self.useColors = !!options.useColors;
if (self.useColors && self.writer === util.inspect) {
// Turn on ANSI coloring.
self.writer = function(obj, showHidden, depth) {
return util.inspect(obj, showHidden, depth, true);
};
}
rli.setPrompt(self.prompt);
rli.on('close', function() {
self.emit('exit');
});
var sawSIGINT = false;
rli.on('SIGINT', function() {
var empty = rli.line.length === 0;
rli.clearLine();
if (!(self.bufferedCommand && self.bufferedCommand.length > 0) && empty) {
if (sawSIGINT) {
rli.close();
sawSIGINT = false;
return;
}
rli.output.write('(^C again to quit)\n');
sawSIGINT = true;
} else {
sawSIGINT = false;
}
self.bufferedCommand = '';
self.displayPrompt();
});
rli.on('line', function(cmd) {
sawSIGINT = false;
var skipCatchall = false;
var async = false;
cmd = trimWhitespace(cmd);
// Check to see if a REPL keyword was used. If it returns true,
// display next prompt and return.
if (cmd && cmd.charAt(0) === '.') {
var matches = cmd.match(/^(\.[^\s]+)\s*(.*)$/);
var keyword = matches && matches[1];
var rest = matches && matches[2];
if (self.parseREPLKeyword(keyword, rest) === true) {
return;
} else {
self.outputStream.write('Invalid REPL keyword\n');
skipCatchall = true;
}
}
// Check if a builtin module name was used and then include it
// if there's no conflict.
if (exports._builtinLibs.indexOf(cmd) !== -1) {
var lib = require(cmd);
if (cmd in self.context && lib !== self.context[cmd]) {
self.outputStream.write('A different "' + cmd +
'" already exists globally\n');
} else {
self.context._ = self.context[cmd] = lib;
self.outputStream.write(self.writer(lib) + '\n');
}
self.displayPrompt();
return;
}
if (!skipCatchall) {
var evalCmd = self.bufferedCommand + cmd + '\n';
var sync = self.context.sync = syncfunc(cmd, self.context, function(err, ret) {
if (err) {
// on error: Print the error and clear the buffer
self.outputStream.write((err.stack || err) + '\n')
} else {
if (ret !== undefined) {
self.context._ = ret;
self.outputStream.write(exports.writer(ret) + '\n')
}
}
self.bufferedCommand = '';
self.displayPrompt();
})
// This try is for determining if the command is complete, or should
// continue onto the next line.
// We try to evaluate both expressions e.g.
// '{ a : 1 }'
// and statements e.g.
// 'for (var i = 0; i < 10; i++) console.log(i);'
// First we attempt to eval as expression with parens.
// This catches '{a : 1}' properly.
self.eval('(' + evalCmd + ')',
self.context,
'repl',
function(e, ret) {
if (e && !isSyntaxError(e)) return finish(e);
if (typeof ret === 'function' &&
/^[\r\n\s]*function/.test(evalCmd) ||
e) {
// Now as statement without parens.
self.eval(evalCmd, self.context, 'repl', finish);
} else {
finish(null, ret);
}
});
} else {
finish(null);
}
function finish(e, ret) {
self.memory(cmd);
// If error was SyntaxError and not JSON.parse error
if (isSyntaxError(e)) {
if (!self.bufferedCommand && cmd.trim().match(/^npm /)) {
self.outputStream.write('npm should be run outside of the ' +
'node repl, in your normal shell.\n' +
'(Press Control-D to exit.)\n');
self.bufferedCmd = '';
self.displayPrompt();
return;
}
// Start buffering data like that:
// {
// ... x: 1
// ... }
self.bufferedCommand += cmd + '\n';
self.displayPrompt();
return;
} else if (e) {
self.outputStream.write((e.stack || e) + '\n');
}
async = syncfunc.called(sync)
// Clear buffer if no SyntaxErrors
self.bufferedCommand = '';
// If we got any output - print it (if no error)
if (!e && !async && (!self.ignoreUndefined || ret !== undefined)) {
self.context._ = ret;
self.outputStream.write(self.writer(ret) + '\n');
}
if (!async) {
// Display prompt again
self.displayPrompt();
}
};
});
rli.on('SIGCONT', function() {
self.displayPrompt(true);
});
self.displayPrompt();
}
inherits(REPLServer, EventEmitter);
exports.REPLServer = REPLServer;
// prompt is a string to print on each line for the prompt,
// source is a stream to use for I/O, defaulting to stdin/stdout.
exports.start = function(prompt, source, eval_, useGlobal, ignoreUndefined) {
var repl = new REPLServer(prompt, source, eval_, useGlobal, ignoreUndefined);
if (!exports.repl) exports.repl = repl;
return repl;
};
REPLServer.prototype.createContext = function() {
var context;
if (this.useGlobal) {
context = global;
} else {
context = vm.createContext();
for (var i in global) context[i] = global[i];
}
context.module = module;
context.require = require;
context.global = context;
context.global.global = context;
this.lines = [];
this.lines.level = [];
return context;
};
REPLServer.prototype.resetContext = function() {
for (var i in require.cache) delete require.cache[i];
this.context = this.createContext();
};
REPLServer.prototype.displayPrompt = function(preserveCursor) {
var prompt = this.prompt;
if (this.bufferedCommand.length) {
prompt = '...';
var levelInd = new Array(this.lines.level.length).join('..');
prompt += levelInd + ' ';
}
this.rli.setPrompt(prompt);
this.rli.prompt(preserveCursor);
};
// A stream to push an array into a REPL
// used in REPLServer.complete
function ArrayStream() {
Stream.call(this);
this.run = function(data) {
var self = this;
data.forEach(function(line) {
self.emit('data', line + '\n');
});
}
}
util.inherits(ArrayStream, Stream);
ArrayStream.prototype.readable = true;
ArrayStream.prototype.writable = true;
ArrayStream.prototype.resume = function() {};
ArrayStream.prototype.write = function() {};
var requireRE = /\brequire\s*\(['"](([\w\.\/-]+\/)?([\w\.\/-]*))/;
var simpleExpressionRE =
/(([a-zA-Z_$](?:\w|\$)*)\.)*([a-zA-Z_$](?:\w|\$)*)\.?$/;
// Provide a list of completions for the given leading text. This is
// given to the readline interface for handling tab completion.
//
// Example:
// complete('var foo = util.')
// -> [['util.print', 'util.debug', 'util.log', 'util.inspect', 'util.pump'],
// 'util.' ]
//
// Warning: This eval's code like "foo.bar.baz", so it will run property
// getter code.
REPLServer.prototype.complete = function(line, callback) {
// There may be local variables to evaluate, try a nested REPL
if (this.bufferedCommand != undefined && this.bufferedCommand.length) {
// Get a new array of inputed lines
var tmp = this.lines.slice();
// Kill off all function declarations to push all local variables into
// global scope
this.lines.level.forEach(function(kill) {
if (kill.isFunction) {
tmp[kill.line] = '';
}
});
var flat = new ArrayStream(); // make a new "input" stream
var magic = new REPLServer('', flat); // make a nested REPL
magic.context = magic.createContext();
flat.run(tmp); // eval the flattened code
// all this is only profitable if the nested REPL
// does not have a bufferedCommand
if (!magic.bufferedCommand) {
return magic.complete(line, callback);
}
}
var completions;
// list of completion lists, one for each inheritance "level"
var completionGroups = [];
var completeOn, match, filter, i, j, group, c;
// REPL commands (e.g. ".break").
var match = null;
match = line.match(/^\s*(\.\w*)$/);
if (match) {
completionGroups.push(Object.keys(this.commands));
completeOn = match[1];
if (match[1].length > 1) {
filter = match[1];
}
completionGroupsLoaded();
} else if (match = line.match(requireRE)) {
// require('...<Tab>')
//TODO: suggest require.exts be exposed to be introspec registered
//extensions?
//TODO: suggest include the '.' in exts in internal repr: parity with
//`path.extname`.
var exts = ['.js', '.node'];
var indexRe = new RegExp('^index(' + exts.map(regexpEscape).join('|') +
')$');
completeOn = match[1];
var subdir = match[2] || '';
var filter = match[1];
var dir, files, f, name, base, ext, abs, subfiles, s;
group = [];
var paths = module.paths.concat(require('module').globalPaths);
for (i = 0; i < paths.length; i++) {
dir = path.resolve(paths[i], subdir);
try {
files = fs.readdirSync(dir);
} catch (e) {
continue;
}
for (f = 0; f < files.length; f++) {
name = files[f];
ext = path.extname(name);
base = name.slice(0, -ext.length);
if (base.match(/-\d+\.\d+(\.\d+)?/) || name === '.npm') {
// Exclude versioned names that 'npm' installs.
continue;
}
if (exts.indexOf(ext) !== -1) {
if (!subdir || base !== 'index') {
group.push(subdir + base);
}
} else {
abs = path.resolve(dir, name);
try {
if (fs.statSync(abs).isDirectory()) {
group.push(subdir + name + '/');
subfiles = fs.readdirSync(abs);
for (s = 0; s < subfiles.length; s++) {
if (indexRe.test(subfiles[s])) {
group.push(subdir + name);
}
}
}
} catch (e) {}
}
}
}
if (group.length) {
completionGroups.push(group);
}
if (!subdir) {
completionGroups.push(exports._builtinLibs);
}
completionGroupsLoaded();
// Handle variable member lookup.
// We support simple chained expressions like the following (no function
// calls, etc.). That is for simplicity and also because we *eval* that
// leading expression so for safety (see WARNING above) don't want to
// eval function calls.
//
// foo.bar<|> # completions for 'foo' with filter 'bar'
// spam.eggs.<|> # completions for 'spam.eggs' with filter ''
// foo<|> # all scope vars with filter 'foo'
// foo.<|> # completions for 'foo' with filter ''
} else if (line.length === 0 || line[line.length - 1].match(/\w|\.|\$/)) {
match = simpleExpressionRE.exec(line);
if (line.length === 0 || match) {
var expr;
completeOn = (match ? match[0] : '');
if (line.length === 0) {
filter = '';
expr = '';
} else if (line[line.length - 1] === '.') {
filter = '';
expr = match[0].slice(0, match[0].length - 1);
} else {
var bits = match[0].split('.');
filter = bits.pop();
expr = bits.join('.');
}
// Resolve expr and get its completions.
var obj, memberGroups = [];
if (!expr) {
// If context is instance of vm.ScriptContext
// Get global vars synchronously
if (this.useGlobal ||
this.context.constructor &&
this.context.constructor.name === 'Context') {
var contextProto = this.context;
while (contextProto = Object.getPrototypeOf(contextProto)) {
completionGroups.push(Object.getOwnPropertyNames(contextProto));
}
completionGroups.push(Object.getOwnPropertyNames(this.context));
addStandardGlobals(completionGroups, filter);
completionGroupsLoaded();
} else {
this.eval('.scope', this.context, 'repl', function(err, globals) {
if (err || !globals) {
addStandardGlobals(completionGroups, filter);
} else if (Array.isArray(globals[0])) {
// Add grouped globals
globals.forEach(function(group) {
completionGroups.push(group);
});
} else {
completionGroups.push(globals);
addStandardGlobals(completionGroups, filter);
}
completionGroupsLoaded();
});
}
} else {
this.eval(expr, this.context, 'repl', function(e, obj) {
// if (e) console.log(e);
if (obj != null) {
if (typeof obj === 'object' || typeof obj === 'function') {
memberGroups.push(Object.getOwnPropertyNames(obj));
}
// works for non-objects
try {
var sentinel = 5;
var p;
if (typeof obj === 'object' || typeof obj === 'function') {
p = Object.getPrototypeOf(obj);
} else {
p = obj.constructor ? obj.constructor.prototype : null;
}
while (p !== null) {
memberGroups.push(Object.getOwnPropertyNames(p));
p = Object.getPrototypeOf(p);
// Circular refs possible? Let's guard against that.
sentinel--;
if (sentinel <= 0) {
break;
}
}
} catch (e) {
//console.log("completion error walking prototype chain:" + e);
}
}
if (memberGroups.length) {
for (i = 0; i < memberGroups.length; i++) {
completionGroups.push(memberGroups[i].map(function(member) {
return expr + '.' + member;
}));
}
if (filter) {
filter = expr + '.' + filter;
}
}
completionGroupsLoaded();
});
}
} else {
completionGroupsLoaded();
}
} else {
completionGroupsLoaded();
}
// Will be called when all completionGroups are in place
// Useful for async autocompletion
function completionGroupsLoaded(err) {
if (err) throw err;
// Filter, sort (within each group), uniq and merge the completion groups.
if (completionGroups.length && filter) {
var newCompletionGroups = [];
for (i = 0; i < completionGroups.length; i++) {
group = completionGroups[i].filter(function(elem) {
return elem.indexOf(filter) == 0;
});
if (group.length) {
newCompletionGroups.push(group);
}
}
completionGroups = newCompletionGroups;
}
if (completionGroups.length) {
var uniq = {}; // unique completions across all groups
completions = [];
// Completion group 0 is the "closest"
// (least far up the inheritance chain)
// so we put its completions last: to be closest in the REPL.
for (i = completionGroups.length - 1; i >= 0; i--) {
group = completionGroups[i];
group.sort();
for (var j = 0; j < group.length; j++) {
c = group[j];
if (!hasOwnProperty(c)) {
completions.push(c);
uniq[c] = true;
}
}
completions.push(''); // separator btwn groups
}
while (completions.length && completions[completions.length - 1] === '') {
completions.pop();
}
}
callback(null, [completions || [], completeOn]);
}
};
/**
* Used to parse and execute the Node REPL commands.
*
* @param {keyword} keyword The command entered to check.
* @return {Boolean} If true it means don't continue parsing the command.
*/
REPLServer.prototype.parseREPLKeyword = function(keyword, rest) {
var cmd = this.commands[keyword];
if (cmd) {
cmd.action.call(this, rest);
return true;
}
return false;
};
REPLServer.prototype.defineCommand = function(keyword, cmd) {
if (typeof cmd === 'function') {
cmd = {action: cmd};
} else if (typeof cmd.action !== 'function') {
throw new Error('bad argument, action must be a function');
}
this.commands['.' + keyword] = cmd;
};
REPLServer.prototype.memory = function memory(cmd) {
var self = this;
self.lines = self.lines || [];
self.lines.level = self.lines.level || [];
// save the line so I can do magic later
if (cmd) {
// TODO should I tab the level?
self.lines.push(new Array(self.lines.level.length).join(' ') + cmd);
} else {
// I don't want to not change the format too much...
self.lines.push('');
}
// I need to know "depth."
// Because I can not tell the difference between a } that
// closes an object literal and a } that closes a function
if (cmd) {
// going down is { and ( e.g. function() {
// going up is } and )
var dw = cmd.match(/{|\(/g);
var up = cmd.match(/}|\)/g);
up = up ? up.length : 0;
dw = dw ? dw.length : 0;
var depth = dw - up;
if (depth) {
(function workIt() {
if (depth > 0) {
// going... down.
// push the line#, depth count, and if the line is a function.
// Since JS only has functional scope I only need to remove
// "function() {" lines, clearly this will not work for
// "function()
// {" but nothing should break, only tab completion for local
// scope will not work for this function.
self.lines.level.push({
line: self.lines.length - 1,
depth: depth,
isFunction: /\s*function\s*/.test(cmd)
});
} else if (depth < 0) {
// going... up.
var curr = self.lines.level.pop();
if (curr) {
var tmp = curr.depth + depth;
if (tmp < 0) {
//more to go, recurse
depth += curr.depth;
workIt();
} else if (tmp > 0) {
//remove and push back
curr.depth += depth;
self.lines.level.push(curr);
}
}
}
}());
}
// it is possible to determine a syntax error at this point.
// if the REPL still has a bufferedCommand and
// self.lines.level.length === 0
// TODO? keep a log of level so that any syntax breaking lines can
// be cleared on .break and in the case of a syntax error?
// TODO? if a log was kept, then I could clear the bufferedComand and
// eval these lines and throw the syntax error
} else {
self.lines.level = [];
}
};
function addStandardGlobals(completionGroups, filter) {
// Global object properties
// (http://www.ecma-international.org/publications/standards/Ecma-262.htm)
completionGroups.push(['NaN', 'Infinity', 'undefined',
'eval', 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'decodeURI',
'decodeURIComponent', 'encodeURI', 'encodeURIComponent',
'Object', 'Function', 'Array', 'String', 'Boolean', 'Number',
'Date', 'RegExp', 'Error', 'EvalError', 'RangeError',
'ReferenceError', 'SyntaxError', 'TypeError', 'URIError',
'Math', 'JSON']);
// Common keywords. Exclude for completion on the empty string, b/c
// they just get in the way.
if (filter) {
completionGroups.push(['break', 'case', 'catch', 'const',
'continue', 'debugger', 'default', 'delete', 'do', 'else',
'export', 'false', 'finally', 'for', 'function', 'if',
'import', 'in', 'instanceof', 'let', 'new', 'null', 'return',
'switch', 'this', 'throw', 'true', 'try', 'typeof', 'undefined',
'var', 'void', 'while', 'with', 'yield']);
}
}
function defineDefaultCommands(repl) {
// TODO remove me after 0.3.x
repl.defineCommand('break', {
help: 'Sometimes you get stuck, this gets you out',
action: function() {
this.bufferedCommand = '';
this.displayPrompt();
}
});
var clearMessage;
if (repl.useGlobal) {
clearMessage = 'Alias for .break';
} else {
clearMessage = 'Break, and also clear the local context';
}
repl.defineCommand('clear', {
help: clearMessage,
action: function() {
this.bufferedCommand = '';
if (!this.useGlobal) {
this.outputStream.write('Clearing context...\n');
this.resetContext();
}
this.displayPrompt();
}
});
repl.defineCommand('exit', {
help: 'Exit the repl',
action: function() {
this.rli.close();
}
});
repl.defineCommand('help', {
help: 'Show repl options',
action: function() {
var self = this;
Object.keys(this.commands).sort().forEach(function(name) {
var cmd = self.commands[name];
self.outputStream.write(name + '\t' + (cmd.help || '') + '\n');
});
this.displayPrompt();
}
});
repl.defineCommand('save', {
help: 'Save all evaluated commands in this REPL session to a file',
action: function(file) {
try {
fs.writeFileSync(file, this.lines.join('\n') + '\n');
this.outputStream.write('Session saved to:' + file + '\n');
} catch (e) {
this.outputStream.write('Failed to save:' + file + '\n');
}
this.displayPrompt();
}
});
repl.defineCommand('load', {
help: 'Load JS from a file into the REPL session',
action: function(file) {
try {
var stats = fs.statSync(file);
if (stats && stats.isFile()) {
var self = this;
var data = fs.readFileSync(file, 'utf8');
var lines = data.split('\n');
this.displayPrompt();
lines.forEach(function(line) {
if (line) {
self.rli.write(line + '\n');
}
});
}
} catch (e) {
this.outputStream.write('Failed to load:' + file + '\n');
}
this.displayPrompt();
}
});
}
function trimWhitespace(cmd) {
var trimmer = /^\s*(.+)\s*$/m,
matches = trimmer.exec(cmd);
if (matches && matches.length === 2) {
return matches[1];
}
return '';
}
function regexpEscape(s) {
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
/**
* Converts commands that use var and function <name>() to use the
* local exports.context when evaled. This provides a local context
* on the REPL.
*
* @param {String} cmd The cmd to convert.
* @return {String} The converted command.
*/
REPLServer.prototype.convertToContext = function(cmd) {
var self = this, matches,
scopeVar = /^\s*var\s*([_\w\$]+)(.*)$/m,
scopeFunc = /^\s*function\s*([_\w\$]+)/;
// Replaces: var foo = "bar"; with: self.context.foo = bar;
matches = scopeVar.exec(cmd);
if (matches && matches.length === 3) {
return 'self.context.' + matches[1] + matches[2];
}
// Replaces: function foo() {}; with: foo = function foo() {};
matches = scopeFunc.exec(self.bufferedCommand);
if (matches && matches.length === 2) {
return matches[1] + ' = ' + self.bufferedCommand;
}
return cmd;
};
/**
* Returns `true` if "e" is a SyntaxError, `false` otherwise.
* This function filters out false positives likes JSON.parse() errors and
* RegExp syntax errors.
*/
function isSyntaxError(e) {
// Convert error to string
e = e && (e.stack || e.toString());
return e && e.match(/^SyntaxError/) &&
// RegExp syntax error
!e.match(/^SyntaxError: Invalid regular expression/) &&
!e.match(/^SyntaxError: Invalid flags supplied to RegExp constructor/) &&
// JSON.parse() error
!(e.match(/^SyntaxError: Unexpected (token .*|end of input)/) &&
e.match(/\n at Object.parse \(native\)\n/));
}
if (process.mainModule == module) {
exports.start("> ")
}
| mit |
Spartan322/Hacknet-Pathfinder | docs/html/class_hacknet_1_1_program_runner.js | 258 | var class_hacknet_1_1_program_runner =
[
[ "ExecuteProgram", "class_hacknet_1_1_program_runner.html#ac0bd0a5315b65daae57adfc88768b807", null ],
[ "ExeProgramExists", "class_hacknet_1_1_program_runner.html#a2bf577e0bd9b2951c34964d6d3f3b7c2", null ]
]; | mit |
wavesplatform/Waves | lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/UnaryOperation.scala | 1280 | package com.wavesplatform.lang.v1.parser
import com.wavesplatform.lang.v1.parser.Expressions._
import fastparse._
sealed abstract class UnaryOperation {
val func: String
def parser[_:P]: P[Any]
def expr(start: Int, end: Int, op: EXPR): EXPR
}
object UnaryOperation {
implicit def hack(p: fastparse.P[Any]): fastparse.P[Unit] = p.map(_ => ())
val unaryOps: List[UnaryOperation] = List(
NEGATIVE_OP,
NOT_OP
)
case object POSITIVE_OP extends UnaryOperation {
val func = "+"
override def parser[_:P]: P[Any] = P("+" ~ !CharIn("0-9"))
override def expr(start: Int, end: Int, op: EXPR): EXPR = {
FUNCTION_CALL(Pos(start, end), PART.VALID(Pos(start, end), "+"), List(op))
}
}
case object NEGATIVE_OP extends UnaryOperation {
val func = "-"
override def parser[_:P]: P[Any] = P("-" ~ !CharIn("0-9"))
override def expr(start: Int, end: Int, op: EXPR): EXPR = {
FUNCTION_CALL(Pos(start, end), PART.VALID(Pos(start, end), "-"), List(op))
}
}
case object NOT_OP extends UnaryOperation {
val func = "!"
override def parser[_:P]: P[Any] = P("!")
override def expr(start: Int, end: Int, op: EXPR): EXPR = {
FUNCTION_CALL(Pos(start, end), PART.VALID(Pos(start, end), "!"), List(op))
}
}
}
| mit |
agladysh/js-lua | java/ru/aagg/jslua/Main.java | 591 | /**
* Main.java: JS-Lua implementation
*/
package ru.aagg.jslua;
import com.google.gwt.core.client.EntryPoint;
import mnj.lua.*;
/**
* JSLua Main.
*/
public class Main implements EntryPoint
{
public void onModuleLoad()
{
Lua L = new Lua();
BaseLib.open(L);
PackageLib.open(L);
StringLib.open(L);
TableLib.open(L);
MathLib.open(L);
OSLib.open(L);
L.loadString(
" test='poop on you'"+
" for i=1,10 do"+
" test=test..' and you'"+
" end"+
" ",
"test"
);
L.call(0, 0);
}
}
| mit |
InnovateUKGitHub/innovation-funding-service | ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/finance/transactional/ProjectFinanceRowService.java | 2002 | package org.innovateuk.ifs.finance.transactional;
import org.innovateuk.ifs.commons.security.NotSecured;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.finance.handler.item.FinanceRowHandler;
import org.innovateuk.ifs.finance.resource.ProjectFinanceResource;
import org.innovateuk.ifs.finance.resource.cost.FinanceRowItem;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.List;
/**
* Transactional service to support operations on ProjectFinanceRow. This is only permitted for use by internal finance users.
*/
public interface ProjectFinanceRowService {
@PreAuthorize("hasPermission(#rowId, 'org.innovateuk.ifs.finance.domain.ProjectFinanceRow', 'CRUD')")
ServiceResult<FinanceRowItem> get(long rowId);
@PreAuthorize("hasPermission(#newCostItem.targetId, 'org.innovateuk.ifs.finance.resource.ProjectFinanceResource', 'ADD_ROW')")
ServiceResult<FinanceRowItem> create(FinanceRowItem newCostItem);
@PreAuthorize("hasPermission(#rowId, 'org.innovateuk.ifs.finance.domain.ProjectFinanceRow', 'CRUD')")
ServiceResult<FinanceRowItem> update(long rowId, FinanceRowItem newCostItem);
@PreAuthorize("hasPermission(#rowId, 'org.innovateuk.ifs.finance.domain.ProjectFinanceRow', 'CRUD')")
ServiceResult<Void> delete(long rowId);
@PostAuthorize("hasPermission(returnObject, 'READ_PROJECT_FINANCE')")
ServiceResult<ProjectFinanceResource> financeChecksDetails(long projectId, long organisationId);
@PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'READ_OVERVIEW')")
ServiceResult<List<ProjectFinanceResource>> financeChecksTotals(long projectId);
@NotSecured(value = "This is not getting data from the database, just getting a FinanceRowHandler for project", mustBeSecuredByOtherServices = false)
FinanceRowHandler getCostHandler(FinanceRowItem costItemId);
}
| mit |
John-Hayes-Reed/bottled_decorators | lib/generators/bottled_decorator/bottled_decorator_generator.rb | 842 | require 'rails/generators'
class BottledDecoratorGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :attributes, type: :array, default: []
def generate_bottled_service
puts "Generating Bottled Decorator: #{name}"
create_file "app/decorators/#{file_name}.rb", <<-File
class #{class_name}
include BottledDecorator
#{ "".tap do |str|
attributes.each do |attribute|
puts "injecting method: #{attribute.name}"
str << "
def #{attribute.name}
# access the decorated object through the @component instance variable
# note, you dont need to call methods of the component in the instance variable.
# if your decorated model or class has a user_name method, you can just call user_name.
end
"
end
end
}
end
File
end
end
| mit |
ntbrock/seatop-watch-pebble | Android/app/src/main/java/com/ntbrock/seatop/pebble/aggregate/SeatopFrequencyAggregator.java | 11356 | package com.ntbrock.seatop.pebble.aggregate;
import java.util.Vector;
/**
* A basic stats package for freuency counting, bucketing.
*
* SeatopStatFrequency implements SeatopDataReceiver with a filter
* so that it can receive points from any emitter.
*
*
* Created by brockman on 2/3/16.
* Ported by brockman on 2/7/16.
*/
public class SeatopFrequencyAggregator implements SeatopDataReceiver {
public static int RECOMMENDED_BUCKET_COUNT = 19;
// Keep some limited data storage, determined by lifetime.
Vector<SeatopDataPoint> livingPoints = new Vector();
SeatopDataLifetime lifetime;
SeatopDataFilter filter;
int numBuckets;
SeatopStatBucket[] buckets = new SeatopStatBucket[0];
// Stored calculations from teh last run of calcultate();
public int pointCount;
public SeatopDataPoint mostRecentPoint;
public SeatopDataPoint pointMax;
public SeatopDataPoint pointMin;
public double fullSum;
public double fullMean;
public int fullMoving;
public double halfSum;
public double halfMean;
public int halfMoving;
public int frequencyMaxTotal;
public int frequencyMaxBucket;
public int frequencyMinTotal;
public int frequencyMinBucket;
public SeatopFrequencyAggregator( int numBuckets,
SeatopDataFilter filter,
SeatopDataLifetime lifetime ) {
this.numBuckets = numBuckets;
this.lifetime = lifetime;
this.filter = filter;
}
/**
* Callers can ask if the aggregation is ready. Hide away the internals.
* @return
*/
public boolean isReady() {
return this.mostRecentPoint != null;
}
@Override
public void handleSinglePoint(SeatopDataPoint dataPoint) {
// Skip this point if it doesn't match the filter, keep our stored data much smaller.
if ( ! filter.isPointInteresting(dataPoint) ) { return; }
System.out.println("[SeatopStatFrequency:65] Filter: " + filter.measurement + " Incoming DataPoint: "+ dataPoint);
ingressPoint(dataPoint);
calculate();
reconstructBuckets();
bucketize();
}
private int getBucketNumberForValue(double pointValue) {
// Gracefully (?) handle two extreme cases, out of bounds.
if ( pointValue <= pointMin.timevalue ) { return 0; }
if ( pointValue >= pointMax.timevalue ) { return buckets.length-1; }
// use divided linear search.
/*
if ( pointValue > pointMean ) {
// Start at end
} else {
// Start at begin
}*/
// Simple , inefficient, minimum linear search for now. Optimize later.
for ( int b = 0; b < buckets.length ; b++ ) { // Changed to reverse mode for fun
// System.out.println("SCANNING Bucket[" + b + "] MinValue: " +buckets[b].minValue + " MaxValue: "+ buckets[b].maxValue );
if ( buckets[b].minValue <= pointValue && pointValue < buckets[b].maxValue ) {
return b;
}
}
// ---------------------------------------------------------------
// No bucket found!! Ruh Oh
// WE are about to explode, print some debugging.
for ( int b = 0; b < buckets.length; b++ ) {
System.err.println("DEBUG Bucket[" + b + "] MinValue: " + buckets[b].minValue + " MaxValue: " + buckets[b].maxValue);
}
throw new RuntimeException("[SeatopStatFrequency:90] No suitable bucket found for value: " + pointValue + ". Should have been caught in max/min defense: Min: "+ pointMin.timevalue + " Max: " + pointMax.timevalue);
}
/**
* Scan the living dataset and re-calculcate bucket frequency.
*/
public void bucketize() {
// Efficiency question - better to loop by buckets or by datapoints? points!
if ( buckets != null && buckets.length > 0 ) {
// zero out bucket values -- Could optimize this later with deltas.
for (int j = 0; j < buckets.length; j++) { buckets[j].zero(); }
for (int i = 0; i < livingPoints.size(); i++) {
SeatopDataPoint point = livingPoints.elementAt(i);
int bucketNumber = getBucketNumberForValue(point.timevalue);
SeatopStatBucket bucket = buckets[bucketNumber];
// what cycle of life are we in?
if ( lifetime.isPointNew(point) ) {
bucket.numNew += 1;
bucket.numTotal += 1;
} else if ( lifetime.isPointMidlife(point) ) {
bucket.numMidlife += 1;
bucket.numTotal += 1;
} else if ( lifetime.isPointAged(point) ) {
bucket.numAged += 1;
bucket.numTotal += 1;
} else if ( lifetime.isPointExpired(point)) {
// NO-Operation
} else {
throw new RuntimeException("[SeatopStatFrequency:129] Caught a point that was in an uncretain state of life: "+ point);
}
}
// Another loop to detect new min + max values.
int newFreqMaxTotal = 0;
int newFreqMaxBucket = 0;
int newFreqMinTotal = 0;
int newFreqMinBucket = 0;
// Find the biggest bucket and the most frequency
// Accelerates the Height of the visual
for (int j = buckets.length-1; j >= 0; j--) {
if (buckets[j].numTotal > newFreqMaxTotal) {
newFreqMaxTotal = buckets[j].numTotal;
newFreqMaxBucket = j;
}
if (buckets[j].numTotal > newFreqMinTotal) {
newFreqMinTotal = buckets[j].numTotal;
newFreqMinBucket = j;
}
}
this.frequencyMaxTotal = newFreqMaxTotal;
this.frequencyMaxBucket = newFreqMaxBucket;
this.frequencyMinTotal = newFreqMinTotal;
this.frequencyMinBucket = newFreqMinBucket;
}
}
/**
* Destroy and re-initialize the bucket array.
* This is helpful to happen when min or max changes.
*/
public void reconstructBuckets() {
// the domain is the max-min
double domain = pointMax.timevalue - pointMin.timevalue;
if ( domain <= 0 ) {
System.err.println("[SeatopStatFrequency:64] Refusing to create a zero width domain");
return;
}
double perBucketDomain = domain / numBuckets;
// Completely Build the buckets! trying array storage here.
buckets = new SeatopStatBucket[numBuckets];
for ( int b = 0; b < numBuckets; b++ ) {
buckets[b] = new SeatopStatBucket();
buckets[b].minValue = pointMin.timevalue + b * perBucketDomain;
buckets[b].maxValue = pointMin.timevalue + (b+1) * perBucketDomain;
//System.out.println("Rebuilding Bucket[" + b + "] MinValue: " +buckets[b].minValue + " MaxValue: "+ buckets[b].maxValue );
}
// Sanity check that the max on the final bucket == domainMax
if ( buckets[numBuckets-1].maxValue != pointMax.timevalue ) {
String message = "Error Bucketizing, Sanity check: Final Bucket Max ("+buckets[numBuckets-1].maxValue+") was != Domain Max ("+pointMax.timevalue+")";
System.err.println(message);
// This happened only one time during testing with one of those double preceision point errors, of by 0.000000000001
// throw new RuntimeException(message);
}
}
public void calculate() {
if ( livingPoints.size() <= 0 ) { return; } // no work to do.
int newCount = 0;
double newSum = 0.0;
SeatopDataPoint newMax = livingPoints.firstElement();
SeatopDataPoint newMin = livingPoints.firstElement();
for ( int i = 0; i < livingPoints.size(); i++ ) {
SeatopDataPoint point = livingPoints.elementAt(i);
if ( ! lifetime.isPointExpired(point) ) { // Expired points will be collected on the next sweep.
// Max
if (point.timevalue > newMax.timevalue) {
newMax = point;
}
// Min
if (point.timevalue < newMin.timevalue) {
newMin = point;
}
// Count
newCount += 1;
newSum += point.timevalue;
}
}
double newMean = newSum / (double)newCount;
// Stored calculations from teh last run of calcultate();
this.pointCount = newCount;
this.fullSum = newSum;
this.fullMean = newMean;
this.pointMax = newMax;
this.pointMin = newMin;
// This becomes a percentage.
// Important Calculation for usability
// Going with the difference between the NOW value -vs- the total average as a percentage of the recently seen range.
this.fullMoving = (int) ( ( this.mostRecentPoint.timevalue - newMean ) / ( this.pointMax.timevalue - this.pointMin.timevalue ) * 100.0 ); // Pct relative.
this.halfMoving = (int) ( this.mostRecentPoint.timevalue - 0 );
}
/**
* Store the point into internal memory, dropping any dead points.
*/
public void ingressPoint(SeatopDataPoint dataPoint) {
int deadCount = 0;
int iDead = -1;
for ( int i = 0; i < livingPoints.size(); i++ ) {
SeatopDataPoint point = livingPoints.elementAt(i);
if ( lifetime.isPointExpired(point) ) {
iDead = i;
deadCount++;
}
}
if ( iDead >= 0 ) {
livingPoints.setElementAt(dataPoint, iDead);
} else {
// Grow the array
livingPoints.add(dataPoint);
}
// MAke a 2nd graveyard pass only if needed.
if ( deadCount > 1 ) {
// Multiple points expired
// System.err.println("[SeatopStatFrequency] Multiple points expired: " + deadCount );
for ( int i = 0; i < livingPoints.size(); i++ ) {
SeatopDataPoint point = livingPoints.elementAt(i);
if ( lifetime.isPointExpired(point) ) { livingPoints.remove(i); }
}
}
mostRecentPoint = dataPoint;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(" Min=" + pointMin.timevalue + "Max=" + pointMax.timevalue + " Mean=" + (int)fullMean + " Buckets=" + numBuckets + " FreqMax=" + frequencyMaxTotal + " in Bucket=" + frequencyMaxBucket + " ");
// Iterate Buckets
if ( buckets != null && buckets.length > 0 ) {
for (int i = 0; i < buckets.length; i++) {
sb.append(buckets[i].numTotal + " " );
}
}
sb.append (" ");
// Iterate Buckets Again for ageyness
if ( buckets != null && buckets.length > 0 ) {
for (int i = 0; i < buckets.length; i++) {
sb.append(buckets[i].numNew + "/" + buckets[i].numMidlife + "/" + buckets[i].numAged + " " );
}
}
return sb.toString();
}
}
| mit |
Hearthstonepp/Hearthstonepp | Sources/Rosetta/Models/Hero.cpp | 1583 | // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Hero.hpp>
#include <Rosetta/Models/Player.hpp>
#include <utility>
namespace RosettaStone
{
Hero::Hero(Player& _owner, Card& _card, std::map<GameTag, int> tags)
: Character(_owner, _card, std::move(tags))
{
// Do nothing
}
Hero::~Hero()
{
delete weapon;
delete heroPower;
}
int Hero::GetAttack() const
{
return HasWeapon() ? Character::GetAttack() + weapon->GetAttack()
: Character::GetAttack();
}
int Hero::GetArmor() const
{
return GetGameTag(GameTag::ARMOR);
}
void Hero::SetArmor(int armor)
{
SetGameTag(GameTag::ARMOR, armor);
}
void Hero::AddWeapon(Weapon& _weapon)
{
RemoveWeapon();
weapon = &_weapon;
weapon->orderOfPlay = owner->GetGame()->GetNextOOP();
weapon->SetZoneType(ZoneType::PLAY);
weapon->SetZonePosition(0);
if (weapon->GetGameTag(GameTag::WINDFURY) == 1 && IsExhausted() &&
GetNumAttacksThisTurn() == 1)
{
SetExhausted(false);
}
}
void Hero::RemoveWeapon()
{
if (!HasWeapon())
{
return;
}
owner->GetGraveyardZone().Add(*weapon);
weapon = nullptr;
}
bool Hero::HasWeapon() const
{
return weapon != nullptr;
}
void Hero::GainArmor(int amount)
{
SetArmor(GetArmor() + amount);
}
} // namespace RosettaStone
| mit |
yuikns/argcv | docs/html/search/files_2.js | 316 | var searchData=
[
['changelog_2emd_355',['CHANGELOG.md',['../_c_h_a_n_g_e_l_o_g_8md.html',1,'']]],
['code_2eh_356',['code.h',['../code_8h.html',1,'']]],
['concurrency_2ecc_357',['concurrency.cc',['../concurrency_8cc.html',1,'']]],
['concurrency_2eh_358',['concurrency.h',['../concurrency_8h.html',1,'']]]
];
| mit |
KissKissBankBank/kitten | assets/javascripts/kitten/components/structure/cards/vertical-card/test.js | 966 | import React from 'react'
import renderer from 'react-test-renderer'
import { VerticalCard } from './index'
describe('<VerticalCard />', () => {
let component
describe('by default', () => {
beforeEach(() => {
component = renderer
.create(
<VerticalCard
title="Custom title"
imageProps={{ src: '#image', alt: '' }}
/>,
)
.toJSON()
})
it('matches with snapshot', () => {
expect(component).toMatchSnapshot()
})
})
describe('with some props', () => {
beforeEach(() => {
component = renderer
.create(
<VerticalCard
imageProps={{
src: '#image',
alt: 'Image alt',
}}
title="Custom title"
description="Custom text"
/>,
)
.toJSON()
})
it('matches with snapshot', () => {
expect(component).toMatchSnapshot()
})
})
})
| mit |
pact-foundation/pact_broker | lib/pact_broker/api/decorators/embedded_version_decorator.rb | 554 | require_relative "base_decorator"
module PactBroker
module Api
module Decorators
class EmbeddedVersionDecorator < BaseDecorator
camelize_property_names
property :number
if PactBroker.feature_enabled?(:branches)
property :branch
property :build_url
end
link :self do | options |
{
title: "Version",
name: represented.number,
href: version_url(options.fetch(:base_url), represented)
}
end
end
end
end
end
| mit |
cfsghost/jsdx-toolkit | src/widgets/box_layout.hpp | 1622 | #ifndef JSDX_TOOLKIT_WIDGET_BOX_LAYOUT_H_
#define JSDX_TOOLKIT_WIDGET_BOX_LAYOUT_H_
#include <clutter/clutter.h>
#include <mx/mx.h>
#include <v8.h>
#include "widget.hpp"
namespace JSDXToolkit {
class BoxLayout : public Widget {
public:
static v8::Persistent<v8::FunctionTemplate> constructor;
static void Initialize(v8::Handle<v8::Object> target);
static void PrototypeMethodsInit(v8::Handle<v8::FunctionTemplate> constructor_template);
protected:
BoxLayout();
static v8::Handle<v8::Value> New(const v8::Arguments& args);
/* Accessor */
static v8::Handle<v8::Value> OrientationGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info);
static void OrientationSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
static v8::Handle<v8::Value> SpacingGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info);
static void SpacingSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
static v8::Handle<v8::Value> EnableAnimationsGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info);
static void EnableAnimationsSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
static v8::Handle<v8::Value> ScrollToFocusedGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info);
static void ScrollToFocusedSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
/* Methods */
static v8::Handle<v8::Value> Add(const v8::Arguments& args);
static v8::Handle<v8::Value> SetExpand(const v8::Arguments& args);
};
}
#endif
| mit |
zblogcn/zblogphp | zb_users/theme/tpure/main.php | 28081 | <?php
require '../../../zb_system/function/c_system_base.php';
require '../../../zb_system/function/c_system_admin.php';
$zbp->Load();
$action = 'root';
if (!$zbp->CheckRights($action)) {
$zbp->ShowError(6);
die();
}
if (!$zbp->CheckPlugin('tpure')) {
$zbp->ShowError(48);
die();
}
$blogtitle = '拓源纯净主题设置';
$dependplugin = array('UEditor'=>'UEditor编辑器');
foreach ($dependplugin as $key=>$pluginname) {
if (!$zbp->CheckPlugin($key)) {
$zbp->ShowHint('bad', '请您安装或启用 ' . $pluginname . ' (' . $key . ') 插件!');
}
}
$act = $_GET['act'] == "base" ? 'base' : $_GET['act'];
require $blogpath . 'zb_system/admin/admin_header.php';
require $blogpath . 'zb_system/admin/admin_top.php';
if ($zbp->CheckPlugin('UEditor')) {
echo '<script type="text/javascript" src="' . $zbp->host . 'zb_users/plugin/UEditor/ueditor.config.php"></script>';
echo '<script type="text/javascript" src="' . $zbp->host . 'zb_users/plugin/UEditor/ueditor.all.min.js"></script>';
}
?>
<link rel="stylesheet" href="./script/admin.css">
<script type="text/javascript" src="./script/custom.js"></script>
<div class="twrapper">
<div class="theader">
<div class="theadbg"></div>
<div class="tuser">
<div class="tuserimg"><img src="style/images/sethead.png" /></div>
<div class="tusername"><?php echo $blogtitle; ?></div>
</div>
<div class="tmenu">
<ul>
<?php tpure_SubMenu($act); ?>
</ul>
</div>
</div>
<div class="tmain">
<?php
if ($act == 'base') {
if (isset($_POST['PostLOGO'])) {
CheckIsRefererValid();
$zbp->Config('tpure')->PostLOGO = $_POST['PostLOGO']; //网站LOGO
$zbp->Config('tpure')->PostLOGOON = $_POST['PostLOGOON']; //图片LOGO开关
$zbp->Config('tpure')->PostFAVICON = $_POST['PostFAVICON']; //浏览器标签栏图标
$zbp->Config('tpure')->PostFAVICONON = $_POST['PostFAVICONON']; //浏览器标签栏图标开关
$zbp->Config('tpure')->PostTHUMB = $_POST['PostTHUMB']; //固定缩略图
$zbp->Config('tpure')->PostTHUMBON = $_POST['PostTHUMBON']; //随机缩略图开关
$zbp->Config('tpure')->PostBANNER = $_POST['PostBANNER']; //首页banner图片
$zbp->Config('tpure')->PostIMGON = $_POST['PostIMGON']; //列表缩略图总开关
$zbp->Config('tpure')->PostSEARCHON = $_POST['PostSEARCHON']; //导航搜索功能开关
$zbp->Config('tpure')->PostSCHTXT = $_POST['PostSCHTXT']; //导航搜索默认文字
$zbp->Config('tpure')->PostVIEWALLON = $_POST['PostVIEWALLON']; //内容页查看全部开关
$zbp->Config('tpure')->PostVIEWALLHEIGHT = $_POST['PostVIEWALLHEIGHT'];
$zbp->Config('tpure')->PostVIEWALLSTYLE = $_POST['PostVIEWALLSTYLE'];
$zbp->Config('tpure')->PostLISTINFO = json_encode($_POST['post_list_info']); //列表辅助信息
$zbp->Config('tpure')->PostARTICLEINFO = json_encode($_POST['post_article_info']); //文章辅助信息
$zbp->Config('tpure')->PostPAGEINFO = json_encode($_POST['post_page_info']); //页面辅助信息
$zbp->Config('tpure')->PostSINGLEKEY = $_POST['PostSINGLEKEY']; //上下篇左右键翻页
$zbp->Config('tpure')->PostPAGEKEY = $_POST['PostPAGEKEY']; //列表底部分页条左右键翻页
$zbp->Config('tpure')->PostRELATEON = $_POST['PostRELATEON']; //文章页相关文章开关
$zbp->Config('tpure')->PostRELATENUM = $_POST['PostRELATENUM']; //文章页相关文章展示个数
$zbp->Config('tpure')->PostINTRONUM = $_POST['PostINTRONUM']; //摘要字数限制
$zbp->Config('tpure')->PostFILTERCATEGORY = $_POST['PostFILTERCATEGORY']; //首页过滤分类
$zbp->Config('tpure')->PostSHARE = $_POST['PostSHARE']; //文章底部HTML
$zbp->Config('tpure')->PostMOREBTNON = $_POST['PostMOREBTNON']; //列表查看全文按钮开关
$zbp->Config('tpure')->PostARTICLECMTON = $_POST['PostARTICLECMTON']; //文章评论开关
$zbp->Config('tpure')->PostPAGECMTON = $_POST['PostPAGECMTON']; //页面评论开关
$zbp->Config('tpure')->PostFIXMENUON = $_POST['PostFIXMENUON']; //导航悬浮开关
$zbp->Config('tpure')->PostLOGOHOVERON = $_POST['PostLOGOHOVERON']; //LOGO划过动效开关
$zbp->Config('tpure')->PostBANNERDISPLAYON = $_POST['PostBANNERDISPLAYON']; //首页banner滚动效果开关
$zbp->Config('tpure')->PostBLANKON = $_POST['PostBLANKON']; //全局链接新窗口开关
$zbp->Config('tpure')->PostGREYON = $_POST['PostGREYON']; //整站变灰开关
$zbp->Config('tpure')->PostREMOVEPON = $_POST['PostREMOVEPON']; //隐藏文章空段落开关
$zbp->Config('tpure')->PostTIMEAGOON = $_POST['PostTIMEAGOON']; //个性化时间
$zbp->Config('tpure')->PostBACKTOTOPON = $_POST['PostBACKTOTOPON']; //返回顶部开关
$zbp->Config('tpure')->PostSAVECONFIG = $_POST['PostSAVECONFIG']; //保存配置开关
$zbp->SaveConfig('tpure');
$zbp->BuildTemplate();
$zbp->ShowHint('good');
} ?>
<dl>
<form method="post" class="setting">
<input type="hidden" name="csrfToken" value="<?php echo $zbp->GetCSRFToken() ?>">
<dt>基本设置</dt>
<dd>
<label for="PostLOGO">图片LOGO</label>
<table>
<tbody>
<tr>
<th width="25%">缩略图</th>
<th width="35%">图片地址</th>
<th width="15%">上传</th>
<th width=20%>图片LOGO与动效</th>
</tr>
<tr>
<td><?php if ($zbp->Config('tpure')->PostLOGO) { ?><img src="<?php echo $zbp->Config('tpure')->PostLOGO; ?>" width="120" class="thumbimg" /><?php } else { ?><img src="style/images/logo.png" width="120" class="thumbimg" /><?php } ?></td>
<td><input type="text" id="PostLOGO" name="PostLOGO" value="<?php if ($zbp->Config('tpure')->PostLOGO) {
echo $zbp->Config('tpure')->PostLOGO;
} else {
echo $zbp->host . 'zb_users/theme/tpure/style/images/logo.png';
} ?>" class="urltext thumbsrc"></td>
<td><input type="button" class="uploadimg" value="上传"></td>
<td><br>是否启用 <input type="text" id="PostLOGOON" name="PostLOGOON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostLOGOON; ?>" /><br><br>启用动效 <input type="text" id="PostLOGOHOVERON" name="PostLOGOHOVERON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostLOGOHOVERON; ?>" /><br><br></td>
</tr>
</tbody>
</table>
<i class="help"></i><span class="helpcon">上传图片LOGO,关闭图片LOGO则使用文字LOGO(调用网站名称);<br>
图片LOGO与后台登录页LOGO同步开启展示;<br>图片LOGO支持鼠标滑过显示高光特效,支持开启与关闭。</span>
</dd>
<dd>
<label for="PostFAVICON">标签栏图标</label>
<table>
<tbody>
<tr>
<th width="25%">缩略图</th>
<th width="35%">图片地址</th>
<th width="15%">上传</th>
<th width="20%">是否启用图标</th>
</tr>
<tr>
<td><?php if ($zbp->Config('tpure')->PostFAVICON) { ?><img src="<?php echo $zbp->Config('tpure')->PostFAVICON; ?>" width="16" class="thumbimg" /><?php } else { ?><img src="style/images/favicon.ico" width="16" class="thumbimg" /><?php } ?></td>
<td><input type="text" id="PostFAVICON" name="PostFAVICON" value="<?php if ($zbp->Config('tpure')->PostFAVICON) {
echo $zbp->Config('tpure')->PostFAVICON;
} else {
echo $zbp->host . 'zb_users/theme/tpure/style/images/favicon.ico';
} ?>" class="urltext thumbsrc"></td>
<td><input type="button" class="uploadimg" value="上传"></td>
<td><input type="text" id="PostFAVICONON" name="PostFAVICONON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostFAVICONON; ?>" /></td>
</tr>
</tbody>
</table>
<i class="help"></i><span class="helpcon">浏览器标签栏图标最佳尺寸:16x16px的ICO格式图标。</span>
</dd>
<dd>
<label for="PostTHUMB">缩略图设置</label>
<table>
<tbody>
<tr>
<th width="25%">缩略图</th>
<th width="35%">图片地址</th>
<th width="15%">上传</th>
<th width="20%">是否启用默认图</th>
</tr>
<tr>
<td><?php if ($zbp->Config('tpure')->PostTHUMB) { ?><img src="<?php echo $zbp->Config('tpure')->PostTHUMB; ?>" width="120" class="thumbimg" /><?php } else { ?><img src="style/images/thumb.png" width="120" class="thumbimg" /><?php } ?></td>
<td><input type="text" id="PostTHUMB" name="PostTHUMB" value="<?php if ($zbp->Config('tpure')->PostTHUMB) {
echo $zbp->Config('tpure')->PostTHUMB;
} else {
echo $zbp->host . 'zb_users/theme/tpure/style/images/thumb.png';
} ?>" class="urltext thumbsrc"></td>
<td><input type="button" class="uploadimg" value="上传"></td>
<td><br>无图默认 <input type="text" id="PostTHUMBON" name="PostTHUMBON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostTHUMBON; ?>" /><br><br>有则展示 <input type="text" id="PostIMGON" name="PostIMGON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostIMGON; ?>" /><br><br></td>
</tr>
</tbody>
</table>
<i class="help"></i><span class="helpcon">上传默认缩略图,需开启“无图默认”开关。<br>仅显示文章缩略图,请开启“有则展示”开关。<br>如不需要任何缩略图,请关闭“有则展示”开关。</span>
</dd>
<dd>
<label for="PostBANNER">首页Banner</label>
<table>
<tbody>
<tr>
<th width="25%">缩略图</th>
<th width="35%">图片地址</th>
<th width="15%">上传</th>
<th width=20%>视差滚动效果</th>
</tr>
<tr>
<td><?php if ($zbp->Config('tpure')->PostBANNER) { ?><img src="<?php echo $zbp->Config('tpure')->PostBANNER; ?>" width="120" class="thumbimg" /><?php } else { ?><img src="style/images/banner.jpg" width="120" class="thumbimg" /><?php } ?></td>
<td><input type="text" id="PostBANNER" name="PostBANNER" value="<?php if ($zbp->Config('tpure')->PostBANNER) {
echo $zbp->Config('tpure')->PostBANNER;
} else {
echo $zbp->host . 'zb_users/theme/tpure/style/images/banner.jpg';
} ?>" class="urltext thumbsrc"></td>
<td><input type="button" class="uploadimg" value="上传"></td>
<td>视差滚动 <input type="text" id="PostBANNERDISPLAYON" name="PostBANNERDISPLAYON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostBANNERDISPLAYON; ?>" /></td>
</tr>
</tbody>
</table>
<i class="help"></i><span class="helpcon">“ON”为开启首页Banner背景视差滚动效果;<br>“OFF”为关闭Banner背景视差滚动效果。<br>移动端不支持视差滚动。<br>Banner文字调用后台右上角“网站设置-网站副标题”。</span>
</dd>
<dt>搜索设置</dt>
<dd class="half">
<label>导航搜索开关</label>
<input type="text" id="PostSEARCHON" name="PostSEARCHON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostSEARCHON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为显示导航搜索;<br>“OFF”为隐藏导航搜索。</span>
</dd>
<dd class="half">
<label for="PostSCHTXT">搜索默认文字</label>
<input type="text" id="PostSCHTXT" name="PostSCHTXT" value="<?php echo $zbp->Config('tpure')->PostSCHTXT; ?>" class="settext" />
<i class="help"></i><span class="helpcon">导航搜索条中默认显示的文字</span>
</dd>
<dt>文章页阅读更多设置</dt>
<dd>
<label>阅读更多开关</label>
<input type="text" id="PostVIEWALLON" name="PostVIEWALLON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostVIEWALLON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为启用长文章正文自动折叠;<br>“OFF”为加载全部正文。</span>
</dd>
<dd class="half">
<label for="PostVIEWALLHEIGHT">自动阅读高度</label>
<input type="number" id="PostVIEWALLHEIGHT" name="PostVIEWALLHEIGHT" value="<?php echo $zbp->Config('tpure')->PostVIEWALLHEIGHT; ?>" min="1" step="1" class="settext" />
<i class="help"></i><span class="helpcon">设置页面已读区域高度(单位px)。</span>
</dd>
<dd class="half">
<label>阅读更多样式</label>
<div class="layoutset">
<input type="radio" id="layoutl" name="PostVIEWALLSTYLE" value="1" <?php echo $zbp->Config('tpure')->PostVIEWALLSTYLE == '1' ? 'checked="checked"' : ''; ?> class="hideradio" />
<label for="layoutl"<?php echo $zbp->Config('tpure')->PostVIEWALLSTYLE == '1' ? ' class="on"' : ''; ?>><img src="style/images/viewallstyle1.png" alt=""></label>
<input type="radio" id="layoutr" name="PostVIEWALLSTYLE" value="0" <?php echo $zbp->Config('tpure')->PostVIEWALLSTYLE == '0' ? 'checked="checked"' : ''; ?> class="hideradio" />
<label for="layoutr"<?php echo $zbp->Config('tpure')->PostVIEWALLSTYLE == '0' ? ' class="on"' : ''; ?>><img src="style/images/viewallstyle0.png" alt=""></label>
</div>
<i class="help"></i><span class="helpcon">“ON”为显示未读百分比;<br>“OFF”为显示查看更多按钮样式。</span>
</dd>
<dt>列表页辅助信息设置 (可拖拽排序)</dt>
<dd class="ckbox">
<?php
$post_info = array(
'user'=> '用户名',
'date'=> '日期',
'cate'=> '分类名',
'view'=> '浏览数',
'cmt' => '评论数',
);
$list_info = json_decode($zbp->Config('tpure')->PostLISTINFO, true);
if (count($list_info)) {
foreach ($list_info as $key => $info) {
echo '<div class="checkui' . ($info == 1 ? ' on' : '') . '">' . $post_info[$key] . '<input name="post_list_info[' . $key . ']" value="' . $info . '"></div>';
}
} ?>
<i class="help"></i><span class="helpcon">列表页辅助信息,自定义选择启用,支持拖拽排序。</span>
</dd>
<dt>文章页辅助信息设置 (可拖拽排序)</dt>
<dd class="ckbox">
<?php
$article_info = json_decode($zbp->Config('tpure')->PostARTICLEINFO, true);
if (count($article_info)) {
foreach ($article_info as $key => $info) {
echo '<div class="checkui' . ($info == 1 ? ' on' : '') . '">' . $post_info[$key] . '<input name="post_article_info[' . $key . ']" value="' . $info . '"></div>';
}
} ?>
<i class="help"></i><span class="helpcon">文章页辅助信息,自定义选择启用,支持拖拽排序。</span>
</dd>
<dt>页面辅助信息设置 (可拖拽排序)</dt>
<dd class="ckbox">
<?php
$page_info = json_decode($zbp->Config('tpure')->PostPAGEINFO, true);
if (count($page_info)) {
foreach ($page_info as $key => $info) {
echo '<div class="checkui' . ($info == 1 ? ' on' : '') . '">' . $post_info[$key] . '<input name="post_page_info[' . $key . ']" value="' . $info . '"></div>';
}
} ?>
<i class="help"></i><span class="helpcon">独立页面辅助信息,自定义选择启用,支持拖拽排序。</span>
</dd>
<dt>键盘左右键翻页设置</dt>
<dd class="half">
<label>上下篇翻页</label>
<input type="text" id="PostSINGLEKEY" name="PostSINGLEKEY" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostSINGLEKEY; ?>" />
<i class="help"></i><span class="helpcon">“ON”为开启文章上一篇与下一篇左右键翻页;<br>“OFF”为关闭文章上一篇与下一篇左右键翻页。</span>
</dd>
<dd class="half">
<label>列表分页条</label>
<input type="text" id="PostPAGEKEY" name="PostPAGEKEY" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostPAGEKEY; ?>" />
<i class="help"></i><span class="helpcon">“ON”为开启列表底部分页条左右键翻页;<br>“OFF”为关闭列表底部分页条左右键翻页。</span>
</dd>
<dt>相关文章设置</dt>
<dd class="half">
<label>相关文章开关</label>
<input type="text" id="PostRELATEON" name="PostRELATEON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostRELATEON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为显示文章页相关文章;<br>“OFF”为文章页不加载相关文章。</span>
</dd>
<dd class="half">
<label for="PostRELATENUM">相关文章条数</label>
<input type="number" id="PostRELATENUM" name="PostRELATENUM" value="<?php echo $zbp->Config('tpure')->PostRELATENUM; ?>" min="1" step="1" class="settext" />
<i class="help"></i><span class="helpcon">设置文章页相关文章条数,默认6条。</span>
</dd>
<dt>其他设置</dt>
<dd>
<label for="PostINTRONUM">摘要字数</label>
<input type="number" id="PostINTRONUM" name="PostINTRONUM" value="<?php echo $zbp->Config('tpure')->PostINTRONUM; ?>" step="10" class="settext" />
<i class="help"></i><span class="helpcon">列表摘要字数限制,留空则显示系统摘要。</span>
</dd>
<dd class="half">
<label for="PostFILTERCATEGORY">首页过滤分类</label>
<select size="1" name="PostFILTERCATEGORY" id="PostFILTERCATEGORY"><?php echo tpure_Exclude_CategorySelect($zbp->Config('tpure')->PostFILTERCATEGORY); ?></select>
<i class="help"></i><span class="helpcon">设置首页不显示此分类下的文章。</span>
</dd>
<dd class="half<?php if ($zbp->Config('tpure')->PostFILTERCATEGORY != '0') {
echo " hide";
} ?>">
<label for="PostFILTERCATEGORYID">过滤的分类ID</label>
<input type="text" id="PostFILTERCATEGORYID"<?php if ($zbp->Config('tpure')->PostFILTERCATEGORY == '0') {
echo ' name="PostFILTERCATEGORY"';
} ?> value="<?php echo $zbp->Config('tpure')->PostFILTERCATEGORY; ?>" placeholder="不过滤请留空" class="PostFILTERCATEGORY settext" />
<i class="help"></i><span class="helpcon">请填写首页需要屏蔽的分类ID,<br>多个分类ID之间用英文逗号分隔,首尾不加逗号,<br>不限个数及顺序,留空提交则不过滤。<br></span>
</dd>
<dd>
<label for="PostSHARE">文章底部HTML</label>
<textarea name="PostSHARE" id="PostSHARE" cols="30" rows="5" class="setinput"><?php echo $zbp->Config('tpure')->PostSHARE; ?></textarea>
<i class="help"></i><span class="helpcon">请填写文章页底部HTML代码,留空则不显示。</span>
</dd>
<dd class="half">
<label>查看全文按钮</label>
<input type="text" id="PostMOREBTNON" name="PostMOREBTNON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostMOREBTNON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为显示列表查看全文按钮;<br>“OFF”为隐藏列表查看全文按钮。</span>
</dd>
<dd class="half">
<label>文章评论开关</label>
<input type="text" id="PostARTICLECMTON" name="PostARTICLECMTON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostARTICLECMTON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为显示文章(article)评论功能;<br>“OFF”为隐藏文章(article)评论功能。</span>
</dd>
<dd class="half">
<label>页面评论开关</label>
<input type="text" id="PostPAGECMTON" name="PostPAGECMTON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostPAGECMTON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为显示页面(page)评论功能;<br>“OFF”为隐藏页面(page)评论功能。</span>
</dd>
<dd class="half">
<label>导航悬浮开关</label>
<input type="text" id="PostFIXMENUON" name="PostFIXMENUON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostFIXMENUON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为开启导航菜单浮动屏幕顶部;<br>“OFF”为导航固定页面顶部。</span>
</dd>
<dd class="half">
<label>链接新窗口</label>
<input type="text" id="PostBLANKON" name="PostBLANKON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostBLANKON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为链接最佳SEO状态;<br>“OFF”为全站链接新窗口打开。</span>
</dd>
<dd class="half">
<label>整站变灰</label>
<input type="text" id="PostGREYON" name="PostGREYON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostGREYON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为开启整站变灰效果;<br>“OFF”为关闭整站变灰效果。</span>
</dd>
<dd class="half">
<label>清理空段落</label>
<input type="text" id="PostREMOVEPON" name="PostREMOVEPON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostREMOVEPON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为清理文章页空白段落;<br>“OFF”为显示文章页空白段落。</span>
</dd>
<dd class="half">
<label>友好化时间</label>
<input type="text" id="PostTIMEAGOON" name="PostTIMEAGOON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostTIMEAGOON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为友好化时间[格式如:5分钟前];<br>“OFF”为传统时间[格式如:1970-01-01];</span>
</dd>
<dd class="half">
<label>返回顶部开关</label>
<input type="text" id="PostBACKTOTOPON" name="PostBACKTOTOPON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostBACKTOTOPON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为启用"返回顶部"功能;<br>“OFF”为取消"返回顶部"功能。</span>
</dd>
<dd class="half">
<label>保存配置信息</label>
<input type="text" id="PostSAVECONFIG" name="PostSAVECONFIG" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostSAVECONFIG; ?>" />
<i class="help"></i><span class="helpcon">“ON”为保存配置信息,启用或卸载主题后不清空配置信息;<br>“OFF”为删除配置信息,启用或卸载主题后将清空配置信息。<br>若不再使用本主题,请选择"OFF"提交,则清空配置信息。</span>
</dd>
<dd class="setok"><input type="submit" value="保存设置" class="setbtn" /><img id="statloading" src="style/images/loading.gif" /></dd>
</form>
</dl>
<?php
}
if ($act == 'seo') {
if (isset($_POST['SEOON'])) {
$zbp->Config('tpure')->SEOON = $_POST['SEOON']; //关键词设置
$zbp->Config('tpure')->SEOTITLE = $_POST['SEOTITLE']; //关键词设置
$zbp->Config('tpure')->SEOKEYWORDS = $_POST['SEOKEYWORDS']; //关键词设置
$zbp->Config('tpure')->SEODESCRIPTION = $_POST['SEODESCRIPTION']; //描述设置
$zbp->SaveConfig('tpure');
$zbp->BuildTemplate();
$zbp->ShowHint('good');
} ?>
<form name="seo" method="post" class="setting">
<input type="hidden" name="csrfToken" value="<?php echo $zbp->GetCSRFToken() ?>">
<dl>
<dt>SEO设置</dt>
<dd class="seoon">
<label>SEO开关</label>
<input type="text" id="SEOON" name="SEOON" class="checkbox" value="<?php echo $zbp->Config('tpure')->SEOON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为启用首页/分类/标签/文章自定义SEO信息;<br>“OFF”为关闭自定义SEO信息。<br>开启后,编辑文章/分类/标签时可设置自定义SEO信息。</span>
</dd>
<div class="seoinfo"<?php echo $zbp->Config('tpure')->SEOON == 1 ? '' : ' style="display:none"'; ?>>
<dd><label for="SEOTITLE">首页标题</label><input type="text" name="SEOTITLE" id="SEOTITLE" class="settext" value="<?php echo $zbp->Config('tpure')->SEOTITLE; ?>" /><i class="help"></i><span class="helpcon">请设置网站首页标题。</span></dd>
<dd><label for="SEOKEYWORDS">首页关键词</label><input type="text" name="SEOKEYWORDS" id="SEOKEYWORDS" class="settext" value="<?php echo $zbp->Config('tpure')->SEOKEYWORDS; ?>" /><i class="help"></i><span class="helpcon">请设置网站首页关键词。</span></dd>
<dd><label for="SEODESCRIPTION">首页描述</label><textarea name="SEODESCRIPTION" id="SEODESCRIPTION" cols="30" rows="3" class="setinput"><?php echo $zbp->Config('tpure')->SEODESCRIPTION; ?></textarea><i class="help"></i><span class="helpcon">请设置网站首页描述。</span></dd>
</div>
<dd class="setok"><input type="submit" value="保存设置" class="setbtn" /><img id="statloading" src="style/images/loading.gif" /></dd>
</dl>
</form>
<?php
}
if ($act == 'color') {
if (isset($_POST['PostCOLORON'])) {
$zbp->Config('tpure')->PostCOLORON = $_POST['PostCOLORON']; //自定义配色开关
$zbp->Config('tpure')->PostCOLOR = $_POST['PostCOLOR']; //主色调
$zbp->Config('tpure')->PostBGCOLOR = $_POST['PostBGCOLOR']; //页面背景色
$zbp->Config('tpure')->PostSIDELAYOUT = $_POST['PostSIDELAYOUT']; //侧栏位置
$zbp->Config('tpure')->PostCUSTOMCSS = $_POST['PostCUSTOMCSS']; //自定义CSS
$tpure_color = tpure_color();
@file_put_contents($zbp->path . 'zb_users/theme/tpure/include/skin.css', $tpure_color);
$zbp->SaveConfig('tpure');
$zbp->BuildTemplate();
$zbp->ShowHint('good');
} ?>
<script type="text/javascript" src="./script/jscolor.js"></script>
<form name="color" method="post" class="setting">
<input type="hidden" name="csrfToken" value="<?php echo $zbp->GetCSRFToken() ?>">
<dl>
<dt>色彩设置</dt>
<dd class="coloron">
<label>自定义配色</label>
<input type="text" id="PostCOLORON" name="PostCOLORON" class="checkbox" value="<?php echo $zbp->Config('tpure')->PostCOLORON; ?>" />
<i class="help"></i><span class="helpcon">“ON”为启用自定义配色;<br>“OFF”为使用主题默认颜色。</span>
</dd>
<div class="colorinfo"<?php echo $zbp->Config('tpure')->PostCOLORON == 1 ? '' : ' style="display:none"'; ?>>
<dd class="half">
<label for="PostCOLOR">主色调</label>
<input type="text" name="PostCOLOR" id="PostCOLOR" class="color settext" value="<?php echo $zbp->Config('tpure')->PostCOLOR; ?>" />
<i class="help"></i><span class="helpcon">请设置网站主色调,默认为 004c98。</span>
</dd>
<dd class="half">
<label for="PostBGCOLOR">页面背景色</label>
<input type="text" name="PostBGCOLOR" id="PostBGCOLOR" class="color settext" value="<?php echo $zbp->Config('tpure')->PostBGCOLOR; ?>" />
<i class="help"></i><span class="helpcon">请设置页面body背景色,默认为 ffffff。</span>
</dd>
<dd>
<label for="">侧栏位置</label>
<div class="layoutset">
<input type="radio" id="layoutl" name="PostSIDELAYOUT" value="l" <?php echo $zbp->Config('tpure')->PostSIDELAYOUT == 'l' ? 'checked="checked"' : ''; ?> class="hideradio" />
<label for="layoutl"<?php echo $zbp->Config('tpure')->PostSIDELAYOUT == 'l' ? ' class="on"' : ''; ?>><img src="style/images/sideleft.png" alt=""></label>
<input type="radio" id="layoutr" name="PostSIDELAYOUT" value="r" <?php echo $zbp->Config('tpure')->PostSIDELAYOUT == 'r' ? 'checked="checked"' : ''; ?> class="hideradio" />
<label for="layoutr"<?php echo $zbp->Config('tpure')->PostSIDELAYOUT == 'r' ? ' class="on"' : ''; ?>><img src="style/images/sideright.png" alt=""></label>
</div>
<i class="help"></i><span class="helpcon">请设置侧栏位置,默认为侧栏居右。</span>
</dd>
<dd>
<label for="">自定义CSS</label>
<div class="layoutset">
<textarea name="PostCUSTOMCSS" id="PostCUSTOMCSS" cols="30" rows="5" class="setinput"><?php echo $zbp->Config('tpure')->PostCUSTOMCSS; ?></textarea>
</div>
<i class="help"></i><span class="helpcon">自定义CSS,辅助配色。</span>
</dd>
</div>
<dd class="setok"><input type="submit" value="保存设置" class="setbtn" /><img id="statloading" src="style/images/loading.gif" /></dd>
</dl>
</form>
<?php
} ?>
</div>
</div>
<div class="tfooter">
<p>Copyright © 2010-<script>document.write(new Date().getFullYear());</script> <a href="https://www.toyean.com/" target="_blank">拓源网</a> all rights reserved.</p>
</div>
<script type="text/javascript">ActiveTopMenu("topmenu_tpure");</script>
<?php
require $blogpath . 'zb_system/admin/admin_footer.php';
RunTime();
?> | mit |
ddrscott/wheeler | spec/spec_helper.rb | 77 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'wheeler'
| mit |
KiKiFoo78/LinstantSoin | src/InstantSoin/UserBundle/Controller/SecurityController.php | 20077 | <?php
namespace InstantSoin\UserBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;
use InstantSoin\UserBundle\Entity\Enquiry;
use InstantSoin\UserBundle\Form\EnquiryType;
use InstantSoin\UserBundle\Entity\User;
use InstantSoin\UserBundle\Form\UserType;
use InstantSoin\ProductBundle\Entity\CategorieProd;
use InstantSoin\ProductBundle\Repository\CategorieProdRepository;
use InstantSoin\ProductBundle\Entity\CategorieServ;
use InstantSoin\ProductBundle\Repository\CategorieServRepository;
class SecurityController extends Controller
{
/******************************************************************************************************************************
* CONNEXION USER
******************************************************************************************************************************/
public function loginAction(Request $request)
{
$search = $this->createFormBuilder()
->add('recherche', 'search', array('label' => '', 'attr' => array('class' => 'livreSearch')))
->add('save', 'submit', array('label' => 'Rechercher','attr' => array('class' => 'livreSearch')))
->getForm();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirect($this->generateUrl('product_homepage'));
}
$session = $request->getSession();
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render('UserBundle:Security:login.html.twig', array(
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
'search' => $search->createView(),
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd
));
}
public function lastLogDate($token)
{
$user = $token->getUser('lastLogin');
$date = getdate();
$user->setLastLogin($date);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return true;
//var_dump($user->getLastLogin());
//die();
}
/******************************************************************************************************************************
* CREATION USER BY HIMSELF
******************************************************************************************************************************/
public function new_accountAction(Request $request){
$search = $this->createFormBuilder()
->add('recherche', 'search', array('label' => '', 'attr' => array('class' => 'productSearch')))
->add('save', 'submit', array('label' => 'Rechercher','attr' => array('class' => 'productSearch')))
->getForm();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
$session = $this->getRequest()->getSession();
$user = new User();
$form = $this->createFormBuilder($user)
->add('nom', 'text', array('required' => true))
->add('prenom', 'text', array('required' => true))
->add('adresse1', 'text', array('required' => true))
->add('adresse2', 'text', array('required' => false))
->add('codepostal', 'number', array('required' => true))
->add('ville', 'text', array('required' => true))
->add('telephone', 'text', array('required' => true))
->add('email', 'text', array('required' => true))
->add('username', 'text', array(
'required' => true,
'read_only' => true,
))
->add('password', 'text', array(
'required' => true,
'read_only' => true,
))
->add('save', 'submit', array('label' => 'Enregistrer'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($form->get('password')->getData(), $user->getSalt());
$user->setPassword($password);
$role = 'ROLE_USER';
$user->setRoles($role);
$username = $form->get('username')->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->get('session')->getFlashBag()->clear();
$session->getFlashBag()->add('user_add_success', 'Votre compte a été correctement créé ! Vous pouvez dores et déjà vous connecter à votre espace.');
$session->getFlashBag()->add('user_add_warning', 'Votre mot de passe est identique à votre nom d\'utilisateur : ' .$username. ' Veuillez le changer dans votre profil lors de votre première connexion');
return $this->redirect($this->generateUrl('new_account'));
}
return $this->render('UserBundle:Security:new_account.html.twig',
array(
'search' => $search->createView(),
'form' => $form->createView(),
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd
));
}
/******************************************************************************************************************************
* CREATION USER BY ADMIN
******************************************************************************************************************************/
public function new_account_adminAction(Request $request){
$session = $this->getRequest()->getSession();
$user = new User();
$form = $this->createFormBuilder($user)
->add('nom', 'text', array('required' => true))
->add('prenom', 'text', array('required' => true))
->add('adresse1', 'text', array('required' => true))
->add('adresse2', 'text', array('required' => false))
->add('codepostal', 'number', array('required' => true))
->add('ville', 'text', array('required' => true))
->add('telephone', 'text', array('required' => true))
->add('email', 'text', array('required' => true))
->add('username', 'text', array(
'required' => true,
'read_only' => true,
))
->add('password', 'text', array(
'required' => true,
'read_only' => true,
))
->add('save', 'submit', array('label' => 'Enregistrer'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($form->get('password')->getData(), $user->getSalt());
$user->setPassword($password);
$role = 'ROLE_USER';
$user->setRoles($role);
$username = $form->get('username')->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add('user_add_success', 'Le compte a été correctement créé ! Le client peut dores et déjà se connecter à son espace.');
$this->get('session')->getFlashBag()->add('user_add_warning', 'Le mot de passe est identique au nom d\'utilisateur : ' .$username. ' Veuillez le changer dans le profil lors de la première connexion');
return $this->redirect($this->generateUrl('new_account_admin'));
}
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
return $this->render('UserBundle:Security:new_account_admin.html.twig',
array(
'form' => $form->createView(),
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd
));
}
/******************************************************************************************************************************
* MODIFICATION USER BY HIMSELF
******************************************************************************************************************************/
public function profilAction()
{
$search = $this->createFormBuilder()
->add('recherche', 'search', array('label' => '', 'attr' => array('class' => 'livreSearch')))
->add('save', 'submit', array('label' => 'Rechercher','attr' => array('class' => 'livreSearch')))
->getForm();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
$username = $this->get('security.context')->getToken()->getUsername();
return $this->render('UserBundle:Security:profil.html.twig',
array(
'search' => $search->createView(),
'username' => $username,
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd
));
}
public function profil_infoAction($username, request $request)
{
$search = $this->createFormBuilder()
->add('recherche', 'search', array('label' => '', 'attr' => array('class' => 'livreSearch')))
->add('save', 'submit', array('label' => 'Rechercher','attr' => array('class' => 'livreSearch')))
->getForm();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
$session = $this->getRequest()->getSession();
$this->get('session')->getFlashBag()->clear();
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->findByUsername($username)[0];
$form = $this->createFormBuilder($user)
->add('nom', 'text', array('required' => true))
->add('prenom', 'text', array('required' => true))
->add('adresse1', 'text', array('required' => true))
->add('adresse2', 'text', array('required' => false))
->add('codepostal', 'number', array('required' => true))
->add('ville', 'text', array('required' => true))
->add('telephone', 'text', array('required' => true))
->add('email', 'text', array('required' => true))
->add('password', 'repeated', array(
'type' => 'password',
'options' => array(
'required' => true,
'read_only' => false,
),
'first_options' => array('label' => 'Mot de passe'),
'invalid_message' => 'Les mots de passe doivent correspondre',
'second_options' => array('label' => 'Mot de passe (vérification)'),
))
->add('save', 'submit', array(
'label' => 'Enregistrer',
'attr' => array(
'class' => 'submit spacer'
)
))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($form->get('password')->getData(), $user->getSalt());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->flush();
$session->getFlashBag()->add('user_modif_success', 'Les données ont été mises à jour correctement.');
return $this->redirect($this->generateUrl('profil_info', array('username' => $username)));
}
return $this->render('UserBundle:Security:profil_info.html.twig',
array('search' => $search->createView(),
'form'=> $form->createView(),
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd
));
}
/******************************************************************************************************************************
* MODIFICATION USER BY ADMIN
******************************************************************************************************************************/
public function updateCustomerAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->findById($id)[0];
$form = $this->createFormBuilder($user)
->add('nom', 'text', array('required' => true,'label' => 'Entrez le nom du client :'))
->add('prenom', 'text', array('required' => true,'label' => 'Entrez le prénom :'))
->add('adresse1', 'text', array('required' => true,'label' => 'Entrez le champs adresse :'))
->add('adresse2', 'text', array('required' => false,'label' => 'Entrez la suite de l\'adresse :'))
->add('codepostal', 'number', array('required' => true,'label' => 'Entrez le code postal :'))
->add('ville', 'text', array('required' => true,'label' => 'Entrez la ville :'))
->add('telephone', 'text', array('required' => true,'label' => 'Entrez le numéro de téléphone :'))
->add('email', 'text', array('required' => true,'label' => 'Entrez l\'adresse email :'))
->add('password', 'repeated', array(
'type' => 'password',
'options' => array(
'required' => true,
'read_only' => false,
),
'first_options' => array('label' => 'Mot de passe'),
'invalid_message' => 'Les mots de passe doivent correspondre',
'second_options' => array('label' => 'Mot de passe (vérification)'),
))
->add('save', 'submit', array(
'label' => 'Enregistrer',
'attr' => array(
'class' => 'submit spacer'
)
))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($form->get('password')->getData(), $user->getSalt());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->flush();
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add('user_modif_success', 'Les données ont été mises à jour correctement.');
return $this->redirect($this->generateUrl('updateCustomer', array('id' => $id)));
}
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
return $this->render('UserBundle:Security:updateCustomer.html.twig',
array(
'form' => $form->createView(),
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd,
));
}
/******************************************************************************************************************************
* LISTING USER BY ADMIN
******************************************************************************************************************************/
public function listingCustomerAction()
{
$repository = $this->getDoctrine()->getManager()->getRepository('UserBundle:User');
$Users = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
return $this->render('UserBundle:Security:listingCustomer.html.twig',
array(
'users' => $Users,
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd,
));
}
/******************************************************************************************************************************
* ENVOI EMAIL CLIENT OU ANONYMOUS
******************************************************************************************************************************/
public function contactAction()
{
$search = $this->createFormBuilder()
->add('recherche', 'search', array('label' => '', 'attr' => array('class' => 'livreSearch')))
->add('save', 'submit', array('label' => 'Rechercher','attr' => array('class' => 'livreSearch')))
->getForm();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieProd');
$categoriesProd = $repository->findAllOrderedByName();
$repository = $this->getDoctrine()->getManager()->getRepository('ProductBundle:CategorieServ');
$categoriesServ = $repository->findAllOrderedByName();
$enquiry = new Enquiry();
$form = $this->createForm(new EnquiryType(), $enquiry);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setSubject('Demande de contact / de renseignements à partir du site L\'Instant Soin')
->setFrom('arnaud.hascoet@gmail.com')
->setTo($this->container->getParameter('InstantSoin.emails.contact_email'))
->setBody($this->renderView('UserBundle:Security:contactEmail.txt.twig', array('enquiry' => $enquiry)));
$this->get('mailer')->send($message);
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add('contact-notice', 'Votre message a bien été envoyé. Merci !');
return $this->redirect($this->generateUrl('Demande_contact'));
}
}
return $this->render('UserBundle:Security:contact.html.twig',
array(
'search' => $search->createView(),
'form' => $form->createView(),
'categoriesServ' => $categoriesServ,
'categoriesProd' => $categoriesProd
));
}
} | mit |
sidazad/django-backbone-stack-1 | django_backbone_basic/static/django_backbone_basic/js/controller.js | 1629 | /*
Copyright (c) 2010-2013 VisionHatch Technologies
@author Sid Azad Email: sidazad@gmail.com Twitter: @sid_azad
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.
*/
define([
'jquery',
'marionette',
'vent',
],
function($,Marionette,vent){
return {
showLanding : function(param) {
console.log("controller:showLanding");
vent.trigger("show:landing");
},
showDashboard: function(param) {
console.log("controller:showDashboard");
vent.trigger("show:dashboard");
},
};
});
| mit |
winnieau/ruby-kickstart | session2/3-challenge/4_array.rb | 509 | # Write a method named get_squares that takes an array of numbers
# and returns a sorted array containing only the numbers whose square is also in the array
#
# get_squares [9] # => []
# get_squares [9,3] # => [3]
# get_squares [9,3,81] # => [3, 9]
# get_squares [25, 4, 9, 6, 50, 16, 5] # => [4, 5]
# This time you will have to define the method, it's called: get_squares
def get_squares numbers
numbers.select {|n| numbers.include? n**2 }.sort
end
| mit |
HotblackDesiato/collabware | core.model/src/main/java/collabware/model/operations/SerializationConstants.java | 1068 | package collabware.model.operations;
public class SerializationConstants {
public static final String TYPE = "t";
public static final String NO_OPERATION = "no";
public static final String ADD_NODE_OPERATION = "an";
public static final String NODE_ID = "n";
public static final String REMOVE_NODE_OPERATION = "rn";
public static final String SET_ATTRIBUTE_OPERATION = "sa";
public static final String ATTRIBUTE_NAME = "a";
public static final String OLD_VALUE = "ov";
public static final String NEW_VALUE = "nv";
public static final String SET_REFERENCE_OPERATION = "sr";
public static final String REFERENCE_NAME = "r";
public static final String OLD_TARGET_ID = "ot";
public static final String NEW_TARGET_ID = "nt";
public static final String ADD_REFERENCE_OPERATION = "ar";
public static final String REMOVE_REFERENCE_OPERATION = "rr";
public static final String POSITION = "p";
public static final String COMPLEX_OPERATION = "c";
public static final String DESCRIPTION = "d";
public static final String OPERATIONS = "ops";
}
| mit |
opennode/waldur-homeport | src/customer/services/CustomerPermissionsService.ts | 315 | import Axios from 'axios';
import { post } from '@waldur/core/api';
export const CustomerPermissionsService = {
create(payload) {
return post('/customer-permissions/', payload);
},
delete(url) {
return Axios.delete(url);
},
update(url, payload) {
return Axios.patch(url, payload);
},
};
| mit |
runjak/css-flags | src/Flags/Germany.js | 324 | // @flow
import React from 'react';
import LinearFlag from './LinearFlag';
import gradient from '../utils/gradient';
const black = '#000000';
const red = '#DE0000';
const yellow = '#FFCF00';
export default function Germany() {
return (
<LinearFlag
gradient={`${gradient([black, red, yellow])}`}
/>
);
}
| mit |
ageapps/docker-chat | app/adapters/redis.js | 257 | const redis = require('socket.io-redis');
const redis_host = process.env.REDIS_HOST || 'redis';
const redis_port = process.env.REDIS_PORT || '6379';
exports.get = function () {
return redis({
host: redis_host,
port: redis_port
});
} | mit |
ehrid/countriesYouVisited | src/com/countriesyouvisited/wheel/OnWheelClickedListener.java | 304 | package com.countriesyouvisited.wheel;
public interface OnWheelClickedListener {
/**
* Callback method to be invoked when current item clicked
* @param wheel the wheel view
* @param itemIndex the index of clicked item
*/
void onItemClicked(WheelView wheel, int itemIndex);
}
| mit |
fredericksilva/JsBackpack | Node - Pro/capitulo-3/async-06-ModeloCascata.js | 643 | //Modelo Cascata
//npm install async
/*
obs: só funciona com matriz notação de objeto
não é suportada
obs2: somente o resultado da ultima tarefa é retornado
obs3: as funções podem receber argumentos adicionais
das tarefas anteriores
*Listagem 3-24
* Um cascata que calcula o comprimento da hipotenusa de um triangulo
retangulo
*/
var async = require("async");
async.waterfall([
function(callback) {
callback(null, Math.random(), Math.random());
},
function(a, b, callback){
callback(null, a * a + b * b);
},
function(cc, callback) {
callback(null, Math.sqrt(cc));
}
],function(error, c) {
console.log(c);
});
| mit |
g5search/yield_star_client | spec/lib/yield_star_client/models/floor_plan_spec.rb | 1001 | require "spec_helper"
module YieldStarClient
describe FloorPlan do
describe ".new_from_rent_summary_hash" do
let(:hash) do
{
unit_type: "1BRa",
min_market_rent: 10,
max_market_rent: 30,
min_final_rent: 15,
max_final_rent: 35,
avg_sq_ft: 800,
bed_rooms: 2,
bath_rooms: 1.5
}
end
it "maps hash attributes to the correct FloorPlan attribute" do
floor_plan = FloorPlan.new_from_rent_summary_hash(hash)
expect(floor_plan.id).to eq "1BRa"
expect(floor_plan.name).to eq "1BRa"
expect(floor_plan.min_market_rent).to eq 10.0
expect(floor_plan.max_market_rent).to eq 30.0
expect(floor_plan.min_final_rent).to eq 15.0
expect(floor_plan.max_final_rent).to eq 35.0
expect(floor_plan.square_feet).to eq 800
expect(floor_plan.bedrooms).to eq 2.0
expect(floor_plan.bathrooms).to eq 1.5
end
end
end
end
| mit |
energonQuest/dtOcean | ext/src/osgOcean-rev_256/src/osgOcean/OceanTechnique.cpp | 4281 | /*
* This source file is part of the osgOcean library
*
* Copyright (C) 2009 Kim Bale
* Copyright (C) 2009 The University of Hull, UK
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* http://www.gnu.org/copyleft/lesser.txt.
*/
#include <osgOcean/OceanTechnique>
#include <osgDB/Registry>
using namespace osgOcean;
OceanTechnique::OceanTechnique(void)
:_isDirty ( true )
,_isAnimating( true )
{}
OceanTechnique::OceanTechnique( const OceanTechnique& copy, const osg::CopyOp& copyop )
:osg::Geode ( copy, copyop )
,_isDirty ( true )
,_isAnimating( copy._isAnimating )
{}
void OceanTechnique::build(void)
{
osg::notify(osg::DEBUG_INFO) << "OceanTechnique::build() Not Implemented" << std::endl;
}
float OceanTechnique::getSurfaceHeight(void) const
{
osg::notify(osg::DEBUG_INFO) << "OceanTechnique::getSurfaceHeight() Not Implemented" << std::endl;
return 0.f;
}
float OceanTechnique::getMaximumHeight(void) const
{
osg::notify(osg::DEBUG_INFO) << "OceanTechnique::getMaximumHeight() Not Implemented" << std::endl;
return 0.f;
}
/** Check if the ocean surface is visible or not. Basic test is very
simple, subclasses can do a better test. */
bool OceanTechnique::isVisible( osgUtil::CullVisitor& cv, bool eyeAboveWater )
{
if (getNodeMask() == 0) return false;
// Use a cutoff to unconditionally cull ocean surface if we can't see it.
// This test is valid when the eye is close to the horizon, but further up
// it will be too conservative (i.e. it will return true even when the
// surface is not visible because it does the test relative to a horizontal
// plane at the eye position).
osg::Camera* currentCamera = cv.getCurrentRenderBin()->getStage()->getCamera();
if (currentCamera->getProjectionMatrix()(3,3) == 0.0) // Perspective
{
double fovy, ratio, zNear, zFar;
currentCamera->getProjectionMatrixAsPerspective(fovy, ratio, zNear, zFar);
static const float cutoff = fovy / 2.0;
osg::Vec3 lookVector = cv.getLookVectorLocal();
float dotProduct = lookVector * osg::Vec3(0,0,1);
return ( eyeAboveWater && dotProduct < cutoff) ||
(!eyeAboveWater && dotProduct > -cutoff);
}
else // Ortho
{
return true;
}
// A better way would be to check if any of the frustum corners intersect
// the plane at (0,0,ocean_height) with normal (0,0,1), and if not then
// return true.
}
void OceanTechnique::addResourcePaths(void)
{
const std::string shaderPath = "resources/shaders/";
const std::string texturePath = "resources/textures/";
osgDB::FilePathList& pathList = osgDB::Registry::instance()->getDataFilePathList();
bool shaderPathPresent = false;
bool texturePathPresent = false;
for(unsigned int i = 0; i < pathList.size(); ++i )
{
if( pathList.at(i).compare(shaderPath) == 0 )
shaderPathPresent = true;
if( pathList.at(i).compare(texturePath) == 0 )
texturePathPresent = true;
}
if(!texturePathPresent)
pathList.push_back(texturePath);
if(!shaderPathPresent)
pathList.push_back(shaderPath);
}
// --------------------------------------------------------
// EventHandler implementation
// --------------------------------------------------------
OceanTechnique::EventHandler::EventHandler(OceanTechnique* oceanSurface)
:_oceanSurface(oceanSurface)
{
}
bool OceanTechnique::EventHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*)
{
if (ea.getHandled()) return false;
// Nothing to do
return false;
}
void OceanTechnique::EventHandler::getUsage(osg::ApplicationUsage& usage) const
{}
| mit |
Speelpenning-nl/laravel-authentication | src/Console/Commands/Admin.php | 1830 | <?php
namespace Speelpenning\Authentication\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Validation\Factory;
use Illuminate\Contracts\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Str;
use Speelpenning\Authentication\Http\Requests\StoreUserRequest;
use Speelpenning\Authentication\Jobs\SendPasswordResetLink;
use Speelpenning\Contracts\Authentication\Repositories\UserRepository;
class Admin extends Command
{
use DispatchesJobs;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user:admin
{email : The users e-mail address}
{--revoke : Revokes the administrator privileges}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Grant or revokes administrator privileges.';
/**
* Execute the console command.
*
* @param UserRepository $users
* @return mixed
*/
public function handle(UserRepository $users)
{
try {
$user = $users->findByEmailAddress($this->argument('email'));
if ($this->option('revoke')) {
$user->{$user->managesUsersIndicator()} = false;
$this->info(trans('authentication::user.admin_revoked', ['email' => $user->email]));
} else {
$user->{$user->managesUsersIndicator()} = true;
$this->info(trans('authentication::user.admin_granted', ['email' => $user->email]));
}
$users->save($user);
} catch (ModelNotFoundException $e) {
$this->error('User not found.');
}
}
}
| mit |