code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
/*
* This file is part of the Black package.
*
* (c) Alexandre Balmes <albalmes@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Black\Bundle\MenuBundle\Model;
/**
* Class MenuInterface
*
* @package Black\Bundle\MenuBundle\Model
* @author Alexandre Balmes <albalmes@gmail.com>
* @license http://opensource.org/licenses/mit-license.php MIT
*/
interface MenuInterface
{
/**
* @return mixed
*/
public function getId();
/**
* @return mixed
*/
public function getName();
/**
* @return mixed
*/
public function getSlug();
/**
* @return mixed
*/
public function getDescription();
/**
* @return mixed
*/
public function getItems();
}
| Java |
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-9">
<div class="post-header">
<h2>{{page.page_title}}</h2>
</div>
{% if page.image %}
<div class="video-wrapper">
<img class="img-responsive" src="/static/media/{{page.image}}" alt="{{page.title}}">
</div>
{% endif %}
<div class="page-body">
{{page.body|safe}}
</div>
<div class="page-share">
<a href="https://www.facebook.com/profile.php?id=100012050839136" target="_blank"><span class="share-box"><i class="fa fa-facebook"></i></span></a>
<a href="https://www.instagram.com/theamateuravantgarde/" target="_blank"><span class="share-box"><i class="fa fa-instagram"></i></span></a>
<a href="https://twitter.com/Eleni_Zouliami" target="_blank"><span class="share-box"><i class="fa fa-twitter"></i></span></a>
</div>
</div>
<div class="col-lg-3 custom-sidebar">
{% if page.image %}
<div class="col-md-6">
<div class="video-wrapper">
<img src="/media/{{page.image}}" alt="{{page.title}}">
</div>
</div>
{% endif %}
{% include "sidebar.html" %}
</div>
</div>
</div>
{% endblock content %}
| Java |
#ifndef LIBFEEDKIT_CONSTANTS_H
#define LIBFEEDKIT_CONSTANTS_H
#include <String.h>
#include <vector>
namespace FeedKit {
class Channel;
class Content;
class Enclosure;
class Feed;
class Item;
extern const char *ServerSignature;
typedef std::vector<BString> uuid_list_t;
typedef std::vector<Content *> content_list_t;
typedef std::vector<Channel *> channel_list_t;
typedef std::vector<Enclosure *> enclosure_list_t;
typedef std::vector<Feed *> feed_list_t;
typedef std::vector<Item *> item_list_t;
namespace FromServer {
enum msg_what {
SettingsUpdated = 'rfsu', // Settings have been updated
};
};
namespace ErrorCode {
enum code {
UnableToParseFeed = 'ecpf', // Unable to parse the Feed
InvalidItem = 'ecii', // Invalid Item
InvalidEnclosure = 'ecie', // Invalid Enclosure
InvalidEnclosurePath = 'ecip', // Invalid Enclosure path
UnableToStartDownload = 'ecsd', // Unable to start downloading the Enclosure
};
};
// The Settings namespace details things relating to settings and settings templates
namespace Settings {
enum display_type {
Unset = ' ', // Unset - don't use, used internally
Hidden = 'hide', // A setting not controlled by the user
RadioButton = 'rabu', // Radio buttons
CheckBox = 'chkb', // Check boxes
MenuSingle = 'mens', // Single-select menu
MenuMulti = 'menm', // Multiple-select menu
TextSingle = 'txts', // Single line text control
TextMulti = 'txtm', // Multi line text control
TextPassword = 'txtp', // Single line, hidden input, text control
FilePickerSingle = 'fpks', // File Picker - single file
FilePickerMulti = 'fpkm', // File Picker - multiple file
DirectoryPickerSingle = 'dpks', // Directory Picker - single
DirectoryPickerMultiple = 'dpkm', // Directory picker - multiple
};
// These are some common types of applications. The Type param of FeedListener is free
// form but you should use one of these constants, if possible, to ensure consistency
namespace AppTypes {
extern const char *SettingClient; // Something which allows user interaction
extern const char *SettingServer; // The server
extern const char *SettingUtil; // Interacts with the FeedKit but not the
// user
extern const char *SettingParser; // An addon for parsing data into FeedKit
// objects
extern const char *SettingFeed; // Settings specific to a feed
};
namespace Icon {
enum Location {
Contents = 'cnts', // Icon comes from the contents of the file
TrackerIcon = 'trki', // Use the Tracker icon
};
};
};
};
#endif
| Java |
<?php
/**
* Response Already Send Exception
*
* @author Tom Valk <tomvalk@lt-box.info>
* @copyright 2017 Tom Valk
*/
namespace Arvici\Exception;
class ResponseAlreadySendException extends ArviciException
{
/**
* ResponseAlreadySendException constructor.
* @param string $message
* @param int $code
* @param \Exception $previous
*/
public function __construct($message, $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
| Java |
#include <stdio.h>
struct Employee {
unsigned int id;
char name[256];
char gender;
float salary;
};
void addEmployee(FILE *f) {
struct Employee emp;
printf("Adding a new employee, please type his id \n");
int id;
scanf("%d", &id);
if (id > 0) {
while (1) { //search if id already in use
struct Employee tmp;
fread(&tmp, sizeof(struct Employee), 1, f);
if (feof(f) != 0) { //end of file
emp.id = id;
break;
}
if (id == tmp.id) {
printf("Id already in use, id must be unique \n");
return;
} else {
emp.id = id;
}
}
} else {
printf("Id must be greater than 0 \n");
return;
}
printf("Please type his name \n");
scanf("%s", &emp.name);
printf("Please type his gender (m or f) \n");
scanf(" %c", &emp.gender);
if ((emp.gender != 'm') && (emp.gender != 'f')) {
printf("Gender should be 'm' or 'f'");
return;
}
printf("Please type his salary \n");
scanf("%f", &emp.salary);
fwrite(&emp, sizeof(struct Employee), 1, f);
}
void removeEmployee(FILE *f) {
printf("Removing employee, please type his id \n");
int id;
scanf("%d)", &id);
while (1) {
struct Employee tmp;
fread(&tmp, sizeof(struct Employee), 1, f);
if (feof(f) != 0) {
printf("Employee not found");
return;
}
if (id == tmp.id) {
fseek(f, -sizeof(struct Employee), SEEK_CUR);
tmp.id = 0;
fwrite(&tmp, sizeof(struct Employee), 1, f);
printf("Sucess \n");
return;
}
}
}
void calculateAvarageSalaryByGender(FILE *f) {
printf("Calculating the avarage salary by gender \n");
int maleNumber = 0;
int femaleNumber = 0;
float sumMale = 0;
float sumFemale = 0;
while (1) {
struct Employee tmp;
fread(&tmp, sizeof(struct Employee), 1, f);
if (feof(f) != 0)
break;
if (tmp.id == 0)
continue;
if (tmp.gender == 'm') {
maleNumber++;
sumMale += tmp.salary;
} else {
femaleNumber++;
sumFemale += tmp.salary;
}
}
printf("Avarage male salary: %f \n", sumMale/maleNumber);
printf("Avarage female salary: %f \n", sumFemale/femaleNumber);
}
void exportTextFile(FILE *f) {
char path[256];
printf("Please type the name of the file to store the data \n");
scanf("%s)", &path);
FILE *final;
if ((final = fopen(path, "w")) == NULL) {
printf("Error opening/creating the file");
} else {
while (1) {
struct Employee tmp;
fread(&tmp, sizeof(struct Employee), 1, f);
if (feof(f) != 0)
break;
if (tmp.id != 0) {
fprintf(final, "ID: %d \n", tmp.id);
fprintf(final, "Name: %s \n", tmp.name);
fprintf(final, "Gender: %c \n", tmp.gender);
fprintf(final, "Salary: %f \n", tmp.salary);
}
}
}
fclose(final);
}
void compactData(FILE *f, char fileName[]) {
FILE *copy;
if ((copy = fopen("copy", "wb")) == NULL) {
printf("Error creating the copy file");
} else {
while (1) {
struct Employee tmp;
fread(&tmp, sizeof(struct Employee), 1, f);
if (feof(f) != 0)
break;
if (tmp.id != 0) {
fwrite(&tmp, sizeof(struct Employee), 1, copy);
}
}
fclose(copy);
remove(fileName);
rename("copy", fileName);
}
printf("Database compacted");
}
int main(int argc, char *argv[]) {
if (argc == 3) {
int option = atoi(argv[2]);
FILE *f;
f = fopen(argv[1], "ab+");
fclose(f);
switch(option) {
case 1:
if ((f = fopen(argv[1], "ab+")) == NULL) {
printf("Error opening/creating the file");
} else {
addEmployee(f);
fclose(f);
}
break;
case 2:
if ((f = fopen(argv[1], "rb+")) == NULL) {
printf("Error opening/creating the file");
} else {
removeEmployee(f);
fclose(f);
}
break;
case 3:
if ((f = fopen(argv[1], "rb")) == NULL) {
printf("Error opening/creating the file");
} else {
calculateAvarageSalaryByGender(f);
fclose(f);
}
break;
case 4:
if ((f = fopen(argv[1], "rb")) == NULL) {
printf("Error opening/creating the file");
} else {
exportTextFile(f);
fclose(f);
}
break;
case 5:
if ((f = fopen(argv[1], "rb")) == NULL) {
printf("Error opening/creating the file");
} else {
compactData(f, argv[1]);
fclose(f);
}
break;
}
} else {
printf("Need to provide two arguments, the first one is the binary file and second is the option. \n");
printf("1 - Add employee \n");
printf("2 - Remove employee \n");
printf("3 - Calculate avarage salary by gender \n");
printf("4 - Export data to a text file \n");
printf("5 - Compact data \n");
}
return 0;
}
| Java |
---
layout: post
date: 2016-05-17
title: "WEDDING DRESSES Jersey Cap Sleeve Bridal Dress JB98629"
category: WEDDING DRESSES
tags: [WEDDING DRESSES]
---
### WEDDING DRESSES Jersey Cap Sleeve Bridal Dress JB98629
Just **$279.99**
###
<a href="https://www.readybrides.com/en/wedding-dresses/40561-jersey-cap-sleeve-bridal-dress-jb98629.html"><img src="//img.readybrides.com/88522/jersey-cap-sleeve-bridal-dress-jb98629.jpg" alt="Jersey Cap Sleeve Bridal Dress JB98629" style="width:100%;" /></a>
<!-- break --><a href="https://www.readybrides.com/en/wedding-dresses/40561-jersey-cap-sleeve-bridal-dress-jb98629.html"><img src="//img.readybrides.com/88523/jersey-cap-sleeve-bridal-dress-jb98629.jpg" alt="Jersey Cap Sleeve Bridal Dress JB98629" style="width:100%;" /></a>
<a href="https://www.readybrides.com/en/wedding-dresses/40561-jersey-cap-sleeve-bridal-dress-jb98629.html"><img src="//img.readybrides.com/88524/jersey-cap-sleeve-bridal-dress-jb98629.jpg" alt="Jersey Cap Sleeve Bridal Dress JB98629" style="width:100%;" /></a>
<a href="https://www.readybrides.com/en/wedding-dresses/40561-jersey-cap-sleeve-bridal-dress-jb98629.html"><img src="//img.readybrides.com/88525/jersey-cap-sleeve-bridal-dress-jb98629.jpg" alt="Jersey Cap Sleeve Bridal Dress JB98629" style="width:100%;" /></a>
<a href="https://www.readybrides.com/en/wedding-dresses/40561-jersey-cap-sleeve-bridal-dress-jb98629.html"><img src="//img.readybrides.com/88521/jersey-cap-sleeve-bridal-dress-jb98629.jpg" alt="Jersey Cap Sleeve Bridal Dress JB98629" style="width:100%;" /></a>
Buy it: [https://www.readybrides.com/en/wedding-dresses/40561-jersey-cap-sleeve-bridal-dress-jb98629.html](https://www.readybrides.com/en/wedding-dresses/40561-jersey-cap-sleeve-bridal-dress-jb98629.html)
| Java |
#!/usr/bin/env node
//
// cli.js
//
// Copyright (c) 2016-2017 Junpei Kawamoto
//
// This software is released under the MIT License.
//
// http://opensource.org/licenses/mit-license.php
//
const {
start,
crawl
} = require("../lib/crawler");
const argv = require("yargs")
.option("lang", {
describe: "Language to be used to scrape trand pages. Not used in crawl command."
})
.default("lang", "EN")
.option("dir", {
describe: "Path to the directory to store database files"
})
.demandOption(["dir"])
.command("*", "Start crawling", () => {}, (argv) => {
start(argv.lang, argv.dir);
})
.command("crawl", "Crawl comments form a video", () => {}, (argv) => {
crawl(argv.dir).catch((err) => {
console.error(err);
});
})
.help("h")
.alias("h", "help")
.argv;
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CollegeFbsRankings.Domain.Games;
using CollegeFbsRankings.Domain.Rankings;
using CollegeFbsRankings.Domain.Teams;
namespace CollegeFbsRankings.Domain.Validations
{
public class ValidationService
{
public Validation<GameId> GameValidationFromRanking<TRankingValue>(
IEnumerable<CompletedGame> games,
Ranking<TeamId, TRankingValue> performance)
where TRankingValue : IRankingValue
{
return new Validation<GameId>(games.Select(game =>
{
var winningTeamData = performance[game.WinningTeamId];
var losingTeamData = performance[game.LosingTeamId];
foreach (var values in winningTeamData.Values.Zip(losingTeamData.Values, Tuple.Create))
{
if (values.Item1 > values.Item2)
return new KeyValuePair<GameId, eValidationResult>(game.Id, eValidationResult.Correct);
if (values.Item1 < values.Item2)
return new KeyValuePair<GameId, eValidationResult>(game.Id, eValidationResult.Incorrect);
}
return new KeyValuePair<GameId, eValidationResult>(game.Id, eValidationResult.Skipped);
}));
}
}
}
| Java |
/* ----------------------------------------------------------------------------
* Copyright (C) 2013 Arne F. Claassen
* geekblog [at] claassen [dot] net
* http://github.com/sdether/Calculon
*
* 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.
* ----------------------------------------------------------------------------
*/
using Droog.Calculon.Backstage;
using NUnit.Framework;
namespace Droog.Calculon.Tests {
[TestFixture]
public class BuilderTests {
public interface IFoo {
}
public class Foo : AActor, IFoo {
}
[Test]
public void Can_create_class() {
var builder = new ActorBuilder();
var foo = builder.GetBuilder<Foo>()();
Assert.IsNotNull(foo);
Assert.IsInstanceOfType(typeof(Foo),foo);
}
[Test]
public void Can_create_interface_with_appropriately_named_class() {
var builder = new ActorBuilder();
var foo = builder.GetBuilder<IFoo>()();
Assert.IsNotNull(foo);
Assert.IsInstanceOfType(typeof(Foo), foo);
}
}
}
| Java |
<div class="container" >
<div class="row page-title">
<div class="col-xs-12 text-center">
<span>Consultation</span>
</div>
</div>
</div>
<script type="text/javascript">
/**
* Created by Kupletsky Sergey on 05.11.14.
*
* Material Design Responsive Table
* Tested on Win8.1 with browsers: Chrome 37, Firefox 32, Opera 25, IE 11, Safari 5.1.7
* You can use this table in Bootstrap (v3) projects. Material Design Responsive Table CSS-style will override basic bootstrap style.
* JS used only for table constructor: you don't need it in your project
*/
$(document).ready(function() {
var table = $('#table');
// Table bordered
$('#table-bordered').change(function() {
var value = $( this ).val();
table.removeClass('table-bordered').addClass(value);
});
// Table striped
$('#table-striped').change(function() {
var value = $( this ).val();
table.removeClass('table-striped').addClass(value);
});
// Table hover
$('#table-hover').change(function() {
var value = $( this ).val();
table.removeClass('table-hover').addClass(value);
});
// Table color
$('#table-color').change(function() {
var value = $(this).val();
table.removeClass(/^table-mc-/).addClass(value);
});
});
// jQuery’s hasClass and removeClass on steroids
// by Nikita Vasilyev
// https://github.com/NV/jquery-regexp-classes
(function(removeClass) {
jQuery.fn.removeClass = function( value ) {
if ( value && typeof value.test === "function" ) {
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
var classNames = elem.className.split( /\s+/ );
for ( var n = classNames.length; n--; ) {
if ( value.test(classNames[n]) ) {
classNames.splice(n, 1);
}
}
elem.className = jQuery.trim( classNames.join(" ") );
}
}
} else {
removeClass.call(this, value);
}
return this;
}
})(jQuery.fn.removeClass);
</script>
<style media="screen">
/* -- Material Design Table style -------------- */
.table {
width: 100%;
max-width: 100%;
margin-bottom: 2rem;
background-color: #fff;
}
.table > thead > tr,
.table > tbody > tr,
.table > tfoot > tr {
-webkit-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
text-align: left;
padding: 1.6rem;
vertical-align: top;
border-top: 0;
-webkit-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.table > thead > tr > th {
font-weight: 400;
color: #757575;
vertical-align: bottom;
border-bottom: 1px solid rgba(0, 0, 0, 0.12);
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 1px solid rgba(0, 0, 0, 0.12);
}
.table .table {
background-color: #fff;
}
.table .no-border {
border: 0;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 0.8rem;
}
.table-bordered {
border: 0;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 0;
border-bottom: 1px solid #e0e0e0;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr:hover > td,
.table-hover > tbody > tr:hover > th {
background-color: rgba(0, 0, 0, 0.12);
}
@media screen and (max-width: 768px) {
.table-responsive-vertical > .table {
margin-bottom: 0;
background-color: transparent;
}
.table-responsive-vertical > .table > thead,
.table-responsive-vertical > .table > tfoot {
display: none;
}
.table-responsive-vertical > .table > tbody {
display: block;
}
.table-responsive-vertical > .table > tbody > tr {
display: block;
border: 1px solid #e0e0e0;
border-radius: 2px;
margin-bottom: 1.6rem;
}
.table-responsive-vertical > .table > tbody > tr > td {
background-color: #fff;
display: block;
vertical-align: middle;
text-align: right;
}
.table-responsive-vertical > .table > tbody > tr > td[data-title]:before {
content: attr(data-title);
float: left;
font-size: inherit;
font-weight: 400;
color: #757575;
}
.table-responsive-vertical.shadow-z-1 {
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
.table-responsive-vertical.shadow-z-1 > .table > tbody > tr {
border: none;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24);
}
.table-responsive-vertical > .table-bordered {
border: 0;
}
.table-responsive-vertical > .table-bordered > tbody > tr > td {
border: 0;
border-bottom: 1px solid #e0e0e0;
}
.table-responsive-vertical > .table-bordered > tbody > tr > td:last-child {
border-bottom: 0;
}
.table-responsive-vertical > .table-striped > tbody > tr > td,
.table-responsive-vertical > .table-striped > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical > .table-striped > tbody > tr > td:nth-child(odd) {
background-color: #f5f5f5;
}
.table-responsive-vertical > .table-hover > tbody > tr:hover > td,
.table-responsive-vertical > .table-hover > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical > .table-hover > tbody > tr > td:hover {
background-color: rgba(0, 0, 0, 0.12);
}
}
.table-striped.table-mc-red > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-red > tbody > tr:nth-child(odd) > th {
background-color: #fde0dc;
}
.table-hover.table-mc-red > tbody > tr:hover > td,
.table-hover.table-mc-red > tbody > tr:hover > th {
background-color: #f9bdbb;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-red > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-red > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-red > tbody > tr > td:nth-child(odd) {
background-color: #fde0dc;
}
.table-responsive-vertical .table-hover.table-mc-red > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-red > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-red > tbody > tr > td:hover {
background-color: #f9bdbb;
}
}
.table-striped.table-mc-pink > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-pink > tbody > tr:nth-child(odd) > th {
background-color: #fce4ec;
}
.table-hover.table-mc-pink > tbody > tr:hover > td,
.table-hover.table-mc-pink > tbody > tr:hover > th {
background-color: #f8bbd0;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-pink > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-pink > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-pink > tbody > tr > td:nth-child(odd) {
background-color: #fce4ec;
}
.table-responsive-vertical .table-hover.table-mc-pink > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-pink > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-pink > tbody > tr > td:hover {
background-color: #f8bbd0;
}
}
.table-striped.table-mc-purple > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-purple > tbody > tr:nth-child(odd) > th {
background-color: #f3e5f5;
}
.table-hover.table-mc-purple > tbody > tr:hover > td,
.table-hover.table-mc-purple > tbody > tr:hover > th {
background-color: #e1bee7;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-purple > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-purple > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-purple > tbody > tr > td:nth-child(odd) {
background-color: #f3e5f5;
}
.table-responsive-vertical .table-hover.table-mc-purple > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-purple > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-purple > tbody > tr > td:hover {
background-color: #e1bee7;
}
}
.table-striped.table-mc-deep-purple > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-deep-purple > tbody > tr:nth-child(odd) > th {
background-color: #ede7f6;
}
.table-hover.table-mc-deep-purple > tbody > tr:hover > td,
.table-hover.table-mc-deep-purple > tbody > tr:hover > th {
background-color: #d1c4e9;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-deep-purple > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-deep-purple > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-deep-purple > tbody > tr > td:nth-child(odd) {
background-color: #ede7f6;
}
.table-responsive-vertical .table-hover.table-mc-deep-purple > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-deep-purple > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-deep-purple > tbody > tr > td:hover {
background-color: #d1c4e9;
}
}
.table-striped.table-mc-indigo > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-indigo > tbody > tr:nth-child(odd) > th {
background-color: #e8eaf6;
}
.table-hover.table-mc-indigo > tbody > tr:hover > td,
.table-hover.table-mc-indigo > tbody > tr:hover > th {
background-color: #c5cae9;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-indigo > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-indigo > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-indigo > tbody > tr > td:nth-child(odd) {
background-color: #e8eaf6;
}
.table-responsive-vertical .table-hover.table-mc-indigo > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-indigo > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-indigo > tbody > tr > td:hover {
background-color: #c5cae9;
}
}
.table-striped.table-mc-blue > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-blue > tbody > tr:nth-child(odd) > th {
background-color: #e7e9fd;
}
.table-hover.table-mc-blue > tbody > tr:hover > td,
.table-hover.table-mc-blue > tbody > tr:hover > th {
background-color: #d0d9ff;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-blue > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-blue > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-blue > tbody > tr > td:nth-child(odd) {
background-color: #e7e9fd;
}
.table-responsive-vertical .table-hover.table-mc-blue > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-blue > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-blue > tbody > tr > td:hover {
background-color: #d0d9ff;
}
}
.table-striped.table-mc-light-blue > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-light-blue > tbody > tr:nth-child(odd) > th {
background-color: #e1f5fe;
}
.table-hover.table-mc-light-blue > tbody > tr:hover > td,
.table-hover.table-mc-light-blue > tbody > tr:hover > th {
background-color: #b3e5fc;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-light-blue > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-light-blue > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-light-blue > tbody > tr > td:nth-child(odd) {
background-color: #e1f5fe;
}
.table-responsive-vertical .table-hover.table-mc-light-blue > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-light-blue > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-light-blue > tbody > tr > td:hover {
background-color: #b3e5fc;
}
}
.table-striped.table-mc-cyan > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-cyan > tbody > tr:nth-child(odd) > th {
background-color: #e0f7fa;
}
.table-hover.table-mc-cyan > tbody > tr:hover > td,
.table-hover.table-mc-cyan > tbody > tr:hover > th {
background-color: #b2ebf2;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-cyan > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-cyan > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-cyan > tbody > tr > td:nth-child(odd) {
background-color: #e0f7fa;
}
.table-responsive-vertical .table-hover.table-mc-cyan > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-cyan > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-cyan > tbody > tr > td:hover {
background-color: #b2ebf2;
}
}
.table-striped.table-mc-teal > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-teal > tbody > tr:nth-child(odd) > th {
background-color: #e0f2f1;
}
.table-hover.table-mc-teal > tbody > tr:hover > td,
.table-hover.table-mc-teal > tbody > tr:hover > th {
background-color: #b2dfdb;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-teal > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-teal > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-teal > tbody > tr > td:nth-child(odd) {
background-color: #e0f2f1;
}
.table-responsive-vertical .table-hover.table-mc-teal > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-teal > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-teal > tbody > tr > td:hover {
background-color: #b2dfdb;
}
}
.table-striped.table-mc-green > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-green > tbody > tr:nth-child(odd) > th {
background-color: #d0f8ce;
}
.table-hover.table-mc-green > tbody > tr:hover > td,
.table-hover.table-mc-green > tbody > tr:hover > th {
background-color: #a3e9a4;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-green > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-green > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-green > tbody > tr > td:nth-child(odd) {
background-color: #d0f8ce;
}
.table-responsive-vertical .table-hover.table-mc-green > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-green > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-green > tbody > tr > td:hover {
background-color: #a3e9a4;
}
}
.table-striped.table-mc-light-green > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-light-green > tbody > tr:nth-child(odd) > th {
background-color: #f1f8e9;
}
.table-hover.table-mc-light-green > tbody > tr:hover > td,
.table-hover.table-mc-light-green > tbody > tr:hover > th {
background-color: #dcedc8;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-light-green > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-light-green > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-light-green > tbody > tr > td:nth-child(odd) {
background-color: #f1f8e9;
}
.table-responsive-vertical .table-hover.table-mc-light-green > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-light-green > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-light-green > tbody > tr > td:hover {
background-color: #dcedc8;
}
}
.table-striped.table-mc-lime > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-lime > tbody > tr:nth-child(odd) > th {
background-color: #f9fbe7;
}
.table-hover.table-mc-lime > tbody > tr:hover > td,
.table-hover.table-mc-lime > tbody > tr:hover > th {
background-color: #f0f4c3;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-lime > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-lime > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-lime > tbody > tr > td:nth-child(odd) {
background-color: #f9fbe7;
}
.table-responsive-vertical .table-hover.table-mc-lime > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-lime > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-lime > tbody > tr > td:hover {
background-color: #f0f4c3;
}
}
.table-striped.table-mc-yellow > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-yellow > tbody > tr:nth-child(odd) > th {
background-color: #fffde7;
}
.table-hover.table-mc-yellow > tbody > tr:hover > td,
.table-hover.table-mc-yellow > tbody > tr:hover > th {
background-color: #fff9c4;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-yellow > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-yellow > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-yellow > tbody > tr > td:nth-child(odd) {
background-color: #fffde7;
}
.table-responsive-vertical .table-hover.table-mc-yellow > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-yellow > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-yellow > tbody > tr > td:hover {
background-color: #fff9c4;
}
}
.table-striped.table-mc-amber > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-amber > tbody > tr:nth-child(odd) > th {
background-color: #fff8e1;
}
.table-hover.table-mc-amber > tbody > tr:hover > td,
.table-hover.table-mc-amber > tbody > tr:hover > th {
background-color: #ffecb3;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-amber > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-amber > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-amber > tbody > tr > td:nth-child(odd) {
background-color: #fff8e1;
}
.table-responsive-vertical .table-hover.table-mc-amber > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-amber > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-amber > tbody > tr > td:hover {
background-color: #ffecb3;
}
}
.table-striped.table-mc-orange > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-orange > tbody > tr:nth-child(odd) > th {
background-color: #fff3e0;
}
.table-hover.table-mc-orange > tbody > tr:hover > td,
.table-hover.table-mc-orange > tbody > tr:hover > th {
background-color: #ffe0b2;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-orange > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-orange > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-orange > tbody > tr > td:nth-child(odd) {
background-color: #fff3e0;
}
.table-responsive-vertical .table-hover.table-mc-orange > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-orange > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-orange > tbody > tr > td:hover {
background-color: #ffe0b2;
}
}
.table-striped.table-mc-deep-orange > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-deep-orange > tbody > tr:nth-child(odd) > th {
background-color: #fbe9e7;
}
.table-hover.table-mc-deep-orange > tbody > tr:hover > td,
.table-hover.table-mc-deep-orange > tbody > tr:hover > th {
background-color: #ffccbc;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-deep-orange > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-deep-orange > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-deep-orange > tbody > tr > td:nth-child(odd) {
background-color: #fbe9e7;
}
.table-responsive-vertical .table-hover.table-mc-deep-orange > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-deep-orange > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-deep-orange > tbody > tr > td:hover {
background-color: #ffccbc;
}
}
.new{
color: #49c4d5;
background-color: white;
border: 1px solid #49c4d5;
font-weight: 400;
margin-left: 10px;
}
.page-link{
color: rgb(157, 157, 157) !important;
font-size: 10px;
}
</style>
<div class="container" ng-controller="consultation" ng-init="uid='<?=$uid?>';init()">
<div class="row" style="max-width:1000px; margin:auto; margin-bottom:70px;">
<div class="col-xs-12 ">
<table id="table" class="table table-hover table-mc-light-blue" >
<thead>
<tr>
<th class="hidden-xs">Num</th>
<th>Title</th>
<th class="hidden-xs">Author</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in consultList" ng-click="openConsult(i)" style="color:#9d9d9d">
<td data-title="Number" style="width:50px;" class="hidden-xs">{{$index+(start)+1}}</td>
<td data-title="Title" style="color:#525252">{{i.TITLE}} ({{i.count}}) <div class="label label-default new" ng-show="i.TIME|new">new</div></td>
<td data-title="Author" class="hidden-xs" style="width:150px;">
{{i.AUTHOR}}
</td>
<td data-title="Date" style="width:150px;">
{{i.TIME|Cdate}}
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-12" style="text-align:center">
<ul class="pagination">
<!-- <li class="page-item">
<a class="page-link" href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li> -->
<li class="page-item" ng-repeat="i in consultRange">
<a class="page-link" ng-click="goConsult(i)">{{i}}</a>
</li>
<!-- <li class="page-item">
<a class="page-link" href="#" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li> -->
</ul>
</div>
<div class="col-xs-12">
<div onclick="$('#write_new').modal('show')" class="pull-right banner-button" >WRITE
</div>
</div>
</div>
<div class="modal fade" id="write_new" tabindex="-1" role="dialog" aria-labelledby="" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:0">
<div class="row" >
<div class="col-xs-12">
<div class="well" ng-init="consult={}" style="margin-bottom:0;">
<!-- <div class="text-center page-title">
<span >Consultation</span>
</div> -->
<div class="form-group has-feedback-none has-feedback-left-none">
<input type="text" class="placeholder form-control no-border" placeholder="Name" ng-model="consult.author" />
</div>
<div class="form-group has-feedback-none has-feedback-left-none">
<input type="text" class="placeholder form-control no-border" placeholder="Title" ng-model="consult.title" />
</div>
<div class="form-group has-feedback-none has-feedback-left-none">
<input type="password" class=" placeholder form-control no-border" placeholder="Password" ng-model="consult.password"/>
</div>
<div class="form-group has-feedback-none has-feedback-left-none">
<textarea style="resize:none;border:none;"class="placeholder form-control" rows="5" style="border:none; box-shadow:none;" placeholder="Message" ng-model="consult.body" ></textarea>
</div>
<div class="btn btnForm btn-block" ng-click="consultForm(consult)">SEND</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| Java |
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("DecimalToHex")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DecimalToHex")]
[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("3e808379-6e11-4c24-853e-7d2b4720cbb1")]
// 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")]
| Java |
const AppError = require('../../../lib/errors/app')
const assert = require('assert')
function doSomethingBad () {
throw new AppError('app error message')
}
it('Error details', function () {
try {
doSomethingBad()
} catch (err) {
assert.strictEqual(
err.name,
'AppError',
"Name property set to error's name"
)
assert(
err instanceof AppError,
'Is an instance of its class'
)
assert(
err instanceof Error,
'Is instance of built-in Error'
)
assert(
require('util').isError(err),
'Should be recognized by Node.js util#isError'
)
assert(
err.stack,
'Should have recorded a stack'
)
assert.strictEqual(
err.toString(),
'AppError: app error message',
'toString should return the default error message formatting'
)
assert.strictEqual(
err.stack.split('\n')[0],
'AppError: app error message',
'Stack should start with the default error message formatting'
)
assert.strictEqual(
err.stack.split('\n')[1].indexOf('doSomethingBad'),
7,
'The first stack frame should be the function where the error was thrown'
)
}
})
| Java |
require 'spec_helper'
describe Blogitr::Document do
def parse text, filter=:html
@doc = Blogitr::Document.new :text => text, :filter => filter
end
def should_parse_as headers, body, extended=nil
@doc.headers.should == headers
@doc.body.should == body
@doc.extended.should == extended
end
it "should raise an error if an unknown fitler is specified" do
lambda do
parse "foo *bar* \"baz\"", :unknown
end.should raise_error(Blogitr::UnknownFilterError)
end
it "should parse documents with a YAML header" do
parse <<EOD
title: My Doc
subtitle: An Essay
foo
bar
EOD
should_parse_as({ 'title' => "My Doc", 'subtitle' => 'An Essay' },
"foo\n\nbar\n")
end
it "should parse documents without a YAML header" do
parse "foo\nbar\nbaz"
should_parse_as({}, "foo\nbar\nbaz")
end
it "should parse documents with a YAML header but no body" do
parse "title: My Doc"
should_parse_as({ 'title' => "My Doc" }, '')
end
it "should separate extended content from the main body" do
parse <<EOD
foo
<!--more-->
bar
EOD
should_parse_as({}, "foo", "bar\n")
end
it "should expand macros" do
input = "title: Foo\n\n<macro:example foo=\"bar\">baz</macro:example>"
parse input
should_parse_as({'title' => "Foo"},
"Options: {\"foo\"=>\"bar\"}\nBody: baz")
end
it "should provide access to raw body and extended content" do
parse "*foo*\n<!--more-->\n_bar_", :textile
@doc.raw_body.should == "*foo*"
@doc.raw_extended.should == "_bar_"
end
describe "with a :textile filter" do
it "should filter content" do
parse "foo *bar*\n<!--more-->\n\"baz\"", :textile
should_parse_as({}, "<p>foo <strong>bar</strong></p>",
"<p>“baz”</p>")
end
it "should protect expanded macros from filtering" do
text = "\n<macro:example>*foo*</macro:example>"
parse text, :textile
should_parse_as({}, "Options: {}\nBody: *foo*")
end
end
describe "with a :markdown filter" do
it "should filter content" do
parse "foo *bar* \"baz\"", :markdown
should_parse_as({}, "<p>foo <em>bar</em> “baz”</p>\n")
end
it "should protect expanded macros from filtering" do
text = "\n<macro:example>*foo*</macro:example>"
parse text, :markdown
should_parse_as({},
"<div class=\"raw\">Options: {}\nBody: *foo*</div>\n\n")
end
end
describe "#to_s" do
def should_serialize_as headers, body, extended, serialized
opts = { :headers => headers, :raw_body => body,
:raw_extended => extended, :filter => :html }
Blogitr::Document.new(opts).to_s.should == serialized
end
it "should serialize documents with headers" do
should_serialize_as({'title' => 'Foo'}, "_Bar_.", nil,
"title: Foo\n\n_Bar_.")
end
it "should serialize documents without headers" do
should_serialize_as({}, "_Bar_.", nil, "\n_Bar_.")
end
it "should serialize extended content using \\<!--more-->" do
should_serialize_as({}, "Bar.", "_Baz_.", "\nBar.\n<!--more-->\n_Baz_.")
end
end
end
| Java |
<?php
namespace Grupo3TallerUNLP\ConfiguracionBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ConfiguracionControllerTest extends WebTestCase
{
/*
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient();
// Create a new entry in the database
$crawler = $client->request('GET', '/configuracion/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /configuracion/");
$crawler = $client->click($crawler->selectLink('Create a new entry')->link());
// Fill in the form and submit it
$form = $crawler->selectButton('Create')->form(array(
'grupo3tallerunlp_configuracionbundle_configuracion[field_name]' => 'Test',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")');
// Edit the entity
$crawler = $client->click($crawler->selectLink('Edit')->link());
$form = $crawler->selectButton('Update')->form(array(
'grupo3tallerunlp_configuracionbundle_configuracion[field_name]' => 'Foo',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]');
// Delete the entity
$client->submit($crawler->selectButton('Delete')->form());
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
}
| Java |
## iScript
包含项目:
> *[L]* *[W]* *[LW]* 分别表示,在linux, windows, linux和windows 下通过测试。
> ***windows用户可在babun (https://github.com/babun/babun) 下运行。***
- *[L]* [xiami.py](#xiami.py) - 下载或播放高品质虾米音乐(xiami.com)
- *[L]* [pan.baidu.com.py](#pan.baidu.com.py) - 百度网盘的下载、离线下载、上传、播放、转存、文件操作
- *[L]* [bt.py](#bt.py) - magnet torrent 互转、及 过滤敏.感.词
- *[L]* [115.py](#115.py) - 115网盘的下载和播放
- *[L]* [yunpan.360.cn.py](#yunpan.360.cn.py) - 360网盘的下载
- *[L]* [music.baidu.com.py](#music.baidu.com.py) - 下载或播放高品质百度音乐(music.baidu.com)
- *[L]* [music.163.com.py](#music.163.com.py) - 下载或播放高品质网易音乐(music.163.com)
- *[L]* [flvxz_cl.py](#flvxz_cl.py) - flvxz.com 视频解析 client - 支持下载、播放
- *[L]* [tumblr.py](#tumblr.py) - 下载某个tumblr.com的所有图片
- *[L]* [unzip.py](#unzip.py) - 解决linux下unzip乱码的问题
- *[L]* [ed2k_search.py](#ed2k_search.py) - 基于 donkey4u.com 的emule搜索
- *[L]* [91porn.py](#91porn.py) - 下载或播放91porn
- *[L]* [ThunderLixianExporter.user.js](#ThunderLixianExporter.user.js) - A fork of https://github.com/binux/ThunderLixianExporter - 增加了mpv和mplayer的导出。
- 待续
---
---
<a name="xiami.py"></a>
### xiami.py - 下载或播放高品质虾米音乐(xiami.com)
1. 依赖
wget
python2-requests (https://github.com/kennethreitz/requests)
python2-mutagen (https://code.google.com/p/mutagen/)
mpv (http://mpv.io)
2. 使用说明
初次使用需要登录 xm login
**支持淘宝账户** xm logintaobao
**对于淘宝账户,登录后只保存有关虾米的cookies,删除了有关淘宝的cookies**
**vip账户**支持高品质音乐的下载和播放。
下载的MP3默认添加id3 tags,保存在当前目录下。
cookies保存在 ~/.Xiami.cookies。
关于播放操作:
> 在运行脚本的终端,输入1次Enter,关闭当前播放并播放下一个文件,连续输入2次Enter,关闭当前播放并退出。
命令:
# 虾米账号登录
g
login
login username
login username password
# 淘宝账号登录
gt
logintaobao
logintaobao username
logintaobao username password
signout # 退出登录
d 或 download url1 url2 .. # 下载
p 或 play url1 url2 .. # 播放
s 或 save url1 url2 .. # 收藏
参数:
-p, --play play with mpv
-d, --undescription 不加入disk的描述
-f num, --from_ num 从第num个开始
-t TAGS, --tags TAGS 收藏用的tags,用英文逗号分开, eg: -t piano,cello,guitar
-n, --undownload 不下载,用于修改已存在的MP3的id3 tags
3. 用法
\# xm 是xiami.py的马甲 (alias xm='python2 /path/to/xiami.py')
# 登录
xm g
xm login
xm login username
xm login username password
# 退出登录
xm signout
# 下载专辑
xm d http://www.xiami.com/album/168709?spm=a1z1s.6928801.1561534521.114.ShN6mD
# 下载单曲
xm d http://www.xiami.com/song/2082998?spm=a1z1s.6659513.0.0.DT2j7T
# 下载精选集
xm d http://www.xiami.com/song/showcollect/id/30374035?spm=a1z1s.3061701.6856305.16.fvh75t
# 下载该艺术家所有专辑, Top 20 歌曲, radio
xm d http://www.xiami.com/artist/23460?spm=a1z1s.6928801.1561534521.115.ShW08b
# 下载用户的收藏, 虾米推荐, radio
xm d http://www.xiami.com/u/141825?spm=a1z1s.3521917.0.0.zI0APP
# 下载排行榜
xm d http://www.xiami.com/chart/index/c/2?spm=a1z1s.2943549.6827465.6.VrEAoY
# 下载 风格 genre, radio
xm d http://www.xiami.com/genre/detail/gid/2?spm=a1z1s.3057857.6850221.1.g9ySan
xm d http://www.xiami.com/genre/detail/sid/2970?spm=a1z1s.3057857.6850221.4.pkepgt
播放:
# url 是上面的
xm p url
收藏:
xm s http://www.xiami.com/album/168709?spm=a1z1s.6928801.1561534521.114.ShN6mD
xm s -t 'tag1,tag 2,tag 3' http://www.xiami.com/song/2082998?spm=a1z1s.6659513.0.0.DT2j7T
xm s http://www.xiami.com/song/showcollect/id/30374035?spm=a1z1s.3061701.6856305.16.fvh75t
xm s http://www.xiami.com/artist/23460?spm=a1z1s.6928801.1561534521.115.ShW08b
4. 参考:
> http://kanoha.org/2011/08/30/xiami-absolute-address/
> http://www.blackglory.me/xiami-vip-audition-with-no-quality-difference-between-downloading/
> https://gist.github.com/lepture/1014329
> 淘宝登录代码: https://github.com/ly0/xiami-tools
---
<a name="pan.baidu.com.py"></a>
### pan.baidu.com.py - 百度网盘的下载、离线下载、上传、播放、转存、文件操作
1. 依赖
wget, aria2
python2-requests (https://github.com/kennethreitz/requests)
requests-toolbelt (https://github.com/sigmavirus24/requests-toolbelt)
mpv (http://mpv.io)
mplayer # 我的linux上mpv播放wmv出错,换用mplayer
2. 使用说明
初次使用需要登录 bp login
**支持多帐号登录**
他人分享的网盘连接,只支持单个的下载。
下载工具默认为wget, 可用参数-a num选用aria2
下载的文件,保存在当前目录下。
下载默认为非递归,递归下载加 -R
搜索时,默认在 /
搜索支持高亮
上传模式默认是 c (续传)。
理论上,上传的单个文件最大支持 2T
cookies保存在 ~/.bp.cookies
上传数据保存在 ~/.bp.pickle
关于播放操作:
> 在运行脚本的终端,输入1次Enter,关闭当前播放并播放下一个文件,连续输入2次Enter,关闭当前播放并退出。
<a name="cmd"></a>
命令:
**!!注意:命令参数中,所有网盘的路径必须是 绝对路径**
# 登录
g
login
login username
login username password
# 删除帐号
userdelete 或 ud
# 切换帐号
userchange 或 uc
# 帐号信息
user
p 或 play url1 url2 .. path1 path2 .. 播放
u 或 upload localpath remotepath 上传
s 或 save url remotepath [-s secret] 转存
# 下载
d 或 download url1 url2 .. path1 path2 .. 非递归下载 到当前目录(cwd)
d 或 download url1 url2 .. path1 path2 .. -R 递归下载 到当前目录(cwd)
# !! 注意:
# d /path/to/download -R 递归下载 *download文件夹* 到当前目录(cwd)
# d /path/to/download/ -R 递归下载 *download文件夹中的文件* 到当前目录(cwd)
# 文件操作
md 或 mkdir path1 path2 .. 创建文件夹
rn 或 rename path new_path 重命名
rm 或 remove path1 path2 .. 删除
mv 或 move path1 path2 .. /path/to/directory 移动
cp 或 copy path /path/to/directory_or_file 复制
cp 或 copy path1 path2 .. /path/to/directory 复制
# 使用正则表达式进行文件操作
rnr 或 rnre foo bar dir1 dir2 .. -I re1 re2 .. 重命名文件夹中的文件名
rmr 或 rmre dir1 dir2 .. -E re1 re2 .. 删除文件夹下匹配到的文件
mvr 或 mvre dir1 dir2 .. /path/to/dir -H head1 head2 .. 移动文件夹下匹配到的文件
cpr 或 cpre dir1 dir2 .. /path/to/dir -T tail1 tail2 .. 复制文件夹下匹配到的文件
# 递归加 -R
# rmr, mvr, cpr 中 -t, -I, -E, -H, -T 至少要有一个,放在命令行末尾
# -I, -E, -H, -T 后可跟多个匹配式
# 可以用 -t 指定操作的文件类型
-t f # 文件
-t d # 文件夹
# rnr 中 foo bar 都是 regex
# -y, --yes # 不显示警示,直接进行。 !!注意,除非你知道你做什么,否则请不要使用。
rmr / -I '.*' -y # !! 删除网盘中的所有文件
# 回复用bt.py做base64加密的文件
rnr /path/to/decode1 /path/to/decode2 .. -t f,bd64
# 搜索
f 或 find keyword1 keyword2 .. [directory] 非递归搜索
ff keyword1 keyword2 .. [directory] 非递归搜索 反序
ft keyword1 keyword2 .. [directory] 非递归搜索 by time
ftt keyword1 keyword2 .. [directory] 非递归搜索 by time 反序
fs keyword1 keyword2 .. [directory] 非递归搜索 by size
fss keyword1 keyword2 .. [directory] 非递归搜索 by size 反序
fn keyword1 keyword2 .. [directory] 非递归搜索 by name
fnn keyword1 keyword2 .. [directory] 非递归搜索 by name 反序
# 递归搜索加 -R
f 'ice and fire' /doc -R
# 搜索所有的账户加 -t all
f keyword1 keyword2 .. [directory] -t all -R
f keyword1 keyword2 .. [directory] -t f,all -R
# directory 默认为 /
# 关于-H, -T, -I, -E
# -I, -E, -H, -T 后可跟多个匹配式, 需要放在命令行末尾
f keyword1 keyword2 ... [directory] -H head -T tail -I "re(gul.*) ex(p|g)ress$"
f keyword1 keyword2 ... [directory] -H head -T tail -E "re(gul.*) ex(p|g)ress$"
# 搜索 加 通道(只支持 donwload, play, rnre, rm, mv)
f keyword1 keyword2 .. [directory] \| d -R 递归搜索后递归下载
ftt keyword1 keyword2 .. [directory] \| p -R 递归搜索(by time 反序)后递归播放
f keyword1 keyword2 .. [directory] \| rnr foo bar -R 递归搜索后rename by regex
f keyword1 keyword2 .. [directory] \| rm -R -T tail 递归搜索后删除
f keyword1 keyword2 .. [directory] \| mv /path/to -R 递归搜索后移动
# 列出文件
l path1 path2 .. ls by name
ll path1 path2 .. ls by name 反序
ln path1 path2 .. ls by name
lnn path1 path2 .. ls by name 反序
lt path1 path2 .. ls by time
ltt path1 path2 .. ls by time 反序
ls path1 path2 .. ls by size
lss path1 path2 .. ls by size 反序
l /doc/books /videos
# 以下是只列出文件或文件夹
l path1 path2 .. -t f ls files
l path1 path2 .. -t d ls directorys
# 关于-H, -T, -I, -E
# -I, -E, -H, -T 后可跟多个匹配式, 需要放在命令行末尾
l path1 path2 .. -H head -T tail -I "^re(gul.*) ex(p|g)ress$"
l path1 path2 .. -H head -T tail -E "^re(gul.*) ex(p|g)ress$"
# 显示文件size, md5
l path1 path2 .. -v
# 空文件夹
l path1 path2 -t e,d
# 非空文件夹
l path1 path2 -t ne,d
# 查看文件占用空间
du path1 path2 .. 文件夹下所有*文件(不包含下层文件夹)*总大小
du path1 path2 .. -R 文件夹下所有*文件(包含下层文件夹)*总大小
如果下层文件多,会花一些时间
# 相当于 l path1 path2 .. -t du [-R]
# eg:
du /doc /videos -R
# 离线下载
a 或 add http https ftp ed2k .. remotepath
a 或 add magnet .. remotepath [-t {m,i,d,p}]
a 或 add remote_torrent .. [-t {m,i,d,p}] # 使用网盘中torrent
# 离线任务操作
j 或 job # 列出离线下载任务
jd 或 jobdump # 清除全部 *非正在下载中的任务*
jc 或 jobclear taskid1 taskid2 .. # 清除 *正在下载中的任务*
jca 或 jobclearall # 清除 *全部任务*
参数:
-a num, --aria2c num aria2c分段下载数量: eg: -a 10
-p, --play play with mpv
-y, --yes yes # 用于 rmre, mvre, cpre, !!慎用
-q, --quiet 无输出模式
-v, --view view detail
eg: a magnet /path -v # 离线下载并显示下载的文件
d -p url1 url2 .. -v # 显示播放文件的完整路径
l path1 path2 .. -v # 显示文件的size, md5
-s SECRET, --secret SECRET 提取密码
-f number, --from_ number 从第几个开始(用于download, play),eg: p /video -f 42
-t ext, --type_ ext 类型参数, 用 “,” 分隔
eg:
l -t f # 文件
l -t d # 文件夹
l -t du # 查看文件占用空间
l -t e,d # 空文件夹
f -t all # 搜索所有账户
a -t m,d,p,a
u -t r # 只进行 rapidupload
u -t e # 如果云端已经存在则不上传(不比对md5)
u -t r,e
-l amount, --limit amount 下载速度限制,eg: -l 100k
-m {o,c}, --uploadmode {o,c} 上传模式: o # 重新上传. c # 连续上传.
-R, --recursive 递归, 用于download, play, ls, find, rmre, rnre, rmre, cpre
-H HEADS, --head HEADS 匹配开头的字符,eg: -H Headishere
-T TAILS, --tail TAILS 匹配结尾的字符,eg: -T Tailishere
-I INCLUDES, --include INCLUDES 不排除匹配到表达的文件名, 可以是正则表达式,eg: -I "*.mp3"
-E EXCLUDES, --exclude EXCLUDES 排除匹配到表达的文件名, 可以是正则表达式,eg: -E "*.html"
-c {on, off}, --ls_color {on, off} ls 颜色,默认是on
# -t, -H, -T, -I, -E 都能用于 download, play, ls, find, rnre, rmre, cpre, mvre
3. 用法
\# bp 是pan.baidu.com.py的马甲 (alias bp='python2 /path/to/pan.badiu.com.py')
登录:
bp g
bp login
bp login username
bp login username password
# 多帐号登录
# 一直用 bp login 即可
删除帐号:
bp ud
切换帐号:
bp uc
帐号信息:
bp user
下载:
# 下载自己网盘中的*单个或多个文件*
bp d http://pan.baidu.com/disk/home#dir/path=/path/to/filename1 http://pan.baidu.com/disk/home#dir/path=/path/to/filename2 ..
# or
bp d /path/to/filename1 /path/to/filename2 ..
# 递归下载自己网盘中的*单个或多个文件夹*
bp d -R http://pan.baidu.com/disk/home#dir/path=/path/to/directory1 http://pan.baidu.com/disk/home#dir/path=/path/to/directory2 ..
# or
bp d -R /path/to/directory1 /path/to/directory2 ..
# 递归下载后缀为 .mp3 的文件
bp d -R /path/to/directory1 /path/to/directory2 .. -T .mp3
# 非递归下载
bp d /path/to/directory1 /path/to/directory2 ..
# 下载别人分享的*单个文件*
bp d http://pan.baidu.com/s/1o6psfnxx ..
bp d http://pan.baidu.com/share/link?shareid=1622654699&uk=1026372002&fid=2112674284 ..
# 下载别人加密分享的*单个文件*,密码参数-s
bp d http://pan.baidu.com/s/1i3FVlw5 -s vuej
# 用aria2下载
bp d http://pan.baidu.com/s/1i3FVlw5 -s vuej -a 5
bp d /movie/her.mkv -a 4
bp d url -s [secret] -a 10
播放:
bp p /movie/her.mkv
bp p http://pan.baidu.com/s/xxxxxxxxx -s [secret]
bp p /movie -R # 递归播放 /movie 中所有媒体文件
离线下载:
bp a http://mirrors.kernel.org/archlinux/iso/latest/archlinux-2014.06.01-dual.iso /path/to/save
bp a https://github.com/PeterDing/iScript/archive/master.zip /path/to/save
bp a ftp://ftp.netscape.com/testfile /path/to/save
bp a 'magnet:?xt=urn:btih:64b7700828fd44b37c0c045091939a2c0258ddc2' /path/to/save -v -t a
bp a 'ed2k://|file|[美]徐中約《中国近代史》第六版原版PDF.rar|547821118|D09FC5F70DEA63E585A74FBDFBD7598F|/' /path/to/save
bp a /path/to/a.torrent .. -v -t m,i # 使用网盘中torrent,下载到/path/to
# 注意 ---------------------
↓
网盘中的torrent
magnet离线下载 -- 文件选择:
-t m # 视频文件 (默认), 如: mkv, avi ..etc
-t i # 图像文件, 如: jpg, png ..etc
-t d # 文档文件, 如: pdf, doc, docx, epub, mobi ..etc
-t p # 压缩文件, 如: rar, zip ..etc
-t a # 所有文件
m, i, d, p, a 可以任意组合(用,分隔), 如: -t m,i,d -t d,p -t i,p
remotepath 默认为 /
bp a 'magnet:?xt=urn:btih:64b7700828fd44b37c0c045091939a2c0258ddc2' /path/to/save -v -t p,d
bp a /download/a.torrent -v -t m,i,d # 使用网盘中torrent,下载到/download
离线任务操作:
bp j
bp j 3482938 8302833
bp jd
bp jc taskid1 taskid2 ..
bp jc 1208382 58239221 ..
bp jca
上传:
bp u ~/Documents/reading/三体\ by\ 刘慈欣.mobi /doc -m o
# 上传模式:
# -m o --> 重传
# -m c --> 续传 (默认)
bp u ~/Videos/*.mkv /videos -t r
# 只进行rapidupload
bp u ~/Documents ~/Videos ~/Documents /backup -t e
# 如果云端已经存在则不上传(不比对md5)
# 用 -t e 时, -m o 无效
bp u ~/Documents ~/Videos ~/Documents /backup -t r,e # 以上两种模式
转存:
bp s url remotepath [-s secret]
# url是他人分享的连接, 如: http://pan.baidu.com/share/link?shareid=xxxxxxx&uk=xxxxxxx, http://pan.baidu.com/s/xxxxxxxx
bp s http://pan.baidu.com/share/link?shareid=xxxxxxx&uk=xxxxxxx /path/to/save
bp s http://pan.baidu.com/s/xxxxxxxx /path/to/save
bp s http://pan.baidu.com/s/xxxxxxxx /path/to/save -s xxxx
bp s http://pan.baidu.com/s/xxxxxxxx#dir/path=/path/to/anything /path/to/save -s xxxx
bp s http://pan.baidu.com/inbox/i/xxxxxxxx /path/to/save
搜索:
bp f keyword1 keyword2
bp f "this is one keyword" "this is another keyword" /path/to/search
bp f ooxx -R
bp f 三体 /doc/fiction -R
bp f 晓波 /doc -R
bp ff keyword1 keyword2 .. /path/to/music 非递归搜索 反序
bp ft keyword1 keyword2 .. /path/to/doc 非递归搜索 by time
bp ftt keyword1 keyword2 .. /path/to/other 非递归搜索 by time 反序
bp fs keyword1 keyword2 .. 非递归搜索 by size
bp fss keyword1 keyword2 .. 非递归搜索 by size 反序
bp fn keyword1 keyword2 .. 非递归搜索 by name
bp fnn keyword1 keyword2 .. 非递归搜索 by name 反序
# 递归搜索加 -R
# 关于-H, -T, -I, -E
bp f mp3 /path/to/search -H "[" "01" -T ".tmp" -I ".*-.*" -R
# 搜索所有的账户
f iDoNotKnow .. [directory] -t all -R
f archlinux ubuntu .. [directory] -t f,all -T .iso -R
# 搜索 加 通道(只支持 donwload, play, rnre, rm, mv)
f bioloy \| d -R 递归搜索后递归下载
ftt ooxx \| p -R -t f 递归搜索(by time 反序)后递归播放
f sound \| rnr mp3 mp4 -R 递归搜索后rename by regex
f ccav \| rm -R -T avi 递归搜索后删除
f 新闻联播(大结局) \| mv /Favor -R 递归搜索后移动
回复用bt.py做base64加密的文件:
rnr /ooxx -t f,bd64
!! 注意: /ooxx 中的所有文件都必须是被base64加密的,且加密段要有.base64后缀
# 可以参考 by.py 的用法
ls、重命名、移动、删除、复制、使用正则表达式进行文件操作:
见[命令](#cmd)
4. 参考:
> https://gist.github.com/HououinRedflag/6191023
> https://github.com/banbanchs/pan-baidu-download/blob/master/bddown_core.py
> https://github.com/houtianze/bypy
---
<a name="bt.py"></a>
### bt.py - magnet torrent 互转、及 过滤敏.感.词
1. 依赖
python2-requests (https://github.com/kennethreitz/requests)
bencode (https://github.com/bittorrent/bencode)
2. 使用说明
magnet 和 torrent 的相互转换
~~过滤敏.感.词功能用于净网时期的 baidu, xunlei~~
**8.30日后,无法使用。 见 http://tieba.baidu.com/p/3265467666**
~~**!! 注意:过滤后生成的torrent在百度网盘只能用一次,如果需要再次使用,则需用 -n 改顶层目录名**~~
磁力连接转种子,用的是
http://bt.box.n0808.com
http://btcache.me
http://www.sobt.org # 302 --> http://www.win8down.com/url.php?hash=
http://www.31bt.com
http://178.73.198.210
http://www.btspread.com # link to http://btcache.me
http://torcache.net
http://zoink.it
http://torrage.com # 用torrage.com需要设置代理, eg: -p 127.0.0.1:8087
http://torrentproject.se
http://istoretor.com
http://torrentbox.sx
http://www.torrenthound.com
http://www.silvertorrent.org
http://magnet.vuze.com
如果有更好的种子库,请提交issue
> 对于baidu, 加入离线任务后,需等待一段时间才会下载完成。
命令:
# magnet 2 torrent
m 或 mt magnet_link1 magnet_link2 .. [-d /path/to/save]
m -i /there/are/files -d new
# torrent 2 magnet, 输出magnet
t 或 tm path1 path2 ..
# 过滤敏.感.词
# 有2种模式
# -t n (默认) 用数字替换文件名
# -t be64 用base64加密文件名,torrent用百度下载后,可用 pan.baidu.com.py rnr /path -t f,bd64 改回原名字
c 或 ct magnet_link1 magnet_link2 .. /path/to/torrent1 /path/to/torrent2 .. [-d /path/to/save]
c -i /there/are/files and_other_dir -d new # 从文件或文件夹中寻找 magnet,再过滤
# 过滤敏.感.词 - 将magnet或torrent转成不敏感的 torrent
# /path/to/save 默认为 .
# 用base64加密的文件名:
c magnet_link1 magnet_link2 .. /path/to/torrent1 /path/to/torrent2 .. [-d /path/to/save] -t be64
# 使用正则表达式过滤敏.感.词
cr 或 ctre foo bar magnet_link1 /path/to/torrent1 .. [-d /path/to/save]
# foo bar 都是 regex
参数:
-p PROXY, --proxy PROXY proxy for torrage.com, eg: -p 127.0.0.1:8087 (默认)
-t TYPE_, --type_ TYPE_ 类型参数:
-t n (默认) 用数字替换文件名
-t be64 用base64加密文件名,torrent用百度下载后,可用 pan.baidu.com.py rnr /path -t f,bd64 改回原名字
-d DIRECTORY, --directory DIRECTORY 指定torrents的保存路径, eg: -d /path/to/save
-n NAME, --name NAME 顶级文件夹名称, eg: -m thistopdirectory
-i localpath1 localpath2 .., --import_from localpath1 localpath2 .. 从本地文本文件导入magnet (用正则表达式匹配)
3. 用法
\# bt 是bt.py的马甲 (alias bt='python2 /path/to/bt.py')
bt mt magnet_link1 magnet_link2 .. [-d /path/to/save]
bt tm path1 path2 ..
bt ct magnet_link1 path1 .. [-d /path/to/save]
bt m magnet_link1 magnet_link2 .. [-d /path/to/save]
bt t path1 path2 ..
bt c magnet_link1 path1 .. [-d /path/to/save]
# 用torrage.com
bt m magnet_link1 path1 .. -p 127.0.0.1:8087
bt c magnet_link1 path1 .. -p 127.0.0.1:8087
# 从文件或文件夹中寻找 magnet,再过滤
bt c -i ~/Downloads -d new
# 使用正则表达式过滤敏.感.词
bt cr '.*(old).*' '\1' magnet_link
bt cr 'old.iso' 'new.iso' /path/to/torrent
# 用base64加密的文件名:
bt c magnet_link -t be64
4. 参考:
> http://blog.chinaunix.net/uid-28450123-id-4051635.html
> http://en.wikipedia.org/wiki/Torrent_file
---
<a name="115.py"></a>
### 115.py - 115网盘的下载和播放
1. 依赖
wget, aria2
python2-requests (https://github.com/kennethreitz/requests)
mpv (http://mpv.io)
mplayer # 我的linux上mpv播放wmv出错,换用mplayer
2. 使用说明
初次使用需要登录 pan115 login
**脚本是用于下载自己的115网盘文件,不支持他人分享文件。**
**非vip用户下载只能有4个通道,理论上,用aria2的下载速度最大为 4*300kb/s。**
下载工具默认为wget, 可用参数-a选用aria2。
对所有文件,默认执行下载(用wget),如要播放媒体文件,加参数-p。
下载的文件,保存在当前目录下。
cookies保存在 ~/.115.cookies
关于播放操作:
> 在运行脚本的终端,输入1次Enter,关闭当前播放并播放下一个文件,连续输入2次Enter,关闭当前播放并退出。
参数:
-a, --aria2c download with aria2c
-p, --play play with mpv
-f number, --from_ number 从第几个开始下载,eg: -f 42
-t ext, --type_ ext 要下载的文件的后缀,eg: -t mp3
-l amount, --limit amount 下载速度限制,eg: -l 100k
-d "url" 增加离线下载 "http/ftp/magnet/ed2k"
3. 用法
\# pan115 是115.py的马甲 (alias pan115='python2 /path/to/115.py')
# 登录
pan115 g
pan115 login
pan115 login username
pan115 login username password
# 退出登录
pan115 signout
# 递归下载自己网盘中的*文件夹*
pan115 http://115.com/?cid=xxxxxxxxxxxx&offset=0&mode=wangpan
# 下载自己网盘中的*单个文件* -- 只能是115上可单独打开的文件,如pdf,视频
pan115 http://wenku.115.com/preview/?pickcode=xxxxxxxxxxxx
# 下载用aria2, url 是上面的
pan115 -a url
# 增加离线下载
pan115 -d "magnet:?xt=urn:btih:757fc565c56462b28b4f9c86b21ac753500eb2a7&dn=archlinux-2014.04.01-dual.iso"
播放
# url 是上面的
pan115 -p url
4. 参考:
> http://passport.115.com/static/wap/js/common.js?v=1.6.39
---
<a name="yunpan.360.cn.py"></a>
### yunpan.360.cn.py - 360网盘的下载
1. 依赖
wget, aria2
python2-requests (https://github.com/kennethreitz/requests)
2. 使用说明
初次使用需要登录 yp login
**!!!!!! 万恶的360不支持断点续传 !!!!!!**
由于上面的原因,不能播放媒体文件。
只支持自己的\*文件夹\*的递归下载。
下载工具默认为wget, 可用参数-a选用aria2
下载的文件,保存在当前目录下。
cookies保存在 ~/.360.cookies
参数:
-a, --aria2c download with aria2c
-f number, --from_ number 从第几个开始下载,eg: -f 42
-t ext, --type_ ext 要下载的文件的后缀,eg: -t mp3
-l amount, --limit amount 下载速度限制,eg: -l 100k
3. 用法
\# yp 是yunpan.360.cn.py的马甲 (alias yp='python2 /path/to/yunpan.360.cn.py')
# 登录
yp g
yp login
yp login username
yp login username password
# 退出登录
yp signout
# 递归下载自己网盘中的*文件夹*
yp http://c17.yunpan.360.cn/my/?sid=#/path/to/directory
yp http://c17.yunpan.360.cn/my/?sid=#%2Fpath%3D%2Fpath%2Fto%2Fdirectory
# or
yp sid=/path/to/directory
yp sid%3D%2Fpath%2Fto%2Fdirectory
# 下载用aria2, url 是上面的
yp -a url
4. 参考:
> https://github.com/Shu-Ji/gorthon/blob/master/_3rdapp/CloudDisk360/main.py
---
<a name="music.baidu.com.py"></a>
### music.baidu.com.py - 下载或播放高品质百度音乐(music.baidu.com)
1. 依赖
wget
python2-mutagen (https://code.google.com/p/mutagen/)
mpv (http://mpv.io)
2. 使用说明
默认执行下载,如要播放,加参数-p。
参数:
-f, --flac download flac
-i, --high download 320, default
-l, --low download 128
-p, --play play with mpv
下载的MP3默认添加id3 tags,保存在当前目录下。
关于播放操作:
> 在运行脚本的终端,输入1次Enter,关闭当前播放并播放下一个文件,连续输入2次Enter,关闭当前播放并退出。
3. 用法
\# bm 是music.baidu.com.py的马甲 (alias bm='python2 /path/to/music.baidu.com.py')
# 下载专辑
bm http://music.baidu.com/album/115032005
# 下载单曲
bm http://music.baidu.com/song/117948039
播放:
# url 是上面的
bm -p url
4. 参考:
> http://v2ex.com/t/77685 # 第9楼
---
<a name="music.163.com.py"></a>
### music.163.com.py - 下载或播放高品质网易音乐(music.163.com)
1. 依赖
wget
python2-requests (https://github.com/kennethreitz/requests)
python2-mutagen (https://code.google.com/p/mutagen/)
mpv (http://mpv.io)
2. 使用说明
**默认下载和播放高品质音乐,如果服务器没有高品质音乐则转到低品质音乐。**
默认执行下载,如要播放,加参数-p。
下载的MP3默认添加id3 tags,保存在当前目录下。
关于播放操作:
> 在运行脚本的终端,输入1次Enter,关闭当前播放并播放下一个文件,连续输入2次Enter,关闭当前播放并退出。
3. 用法
\# nm 是music.163.com.py的马甲 (alias nm='python2 /path/to/music.163.com.py')
# 下载专辑
nm http://music.163.com/#/album?id=18915
# 下载单曲
nm http://music.163.com/#/song?id=186114
# 下载歌单
nm http://music.163.com/#/playlist?id=12214308
# 下载该艺术家所有专辑或 Top 50 歌曲
nm http://music.163.com/#/artist?id=6452
# 下载DJ节目
nm http://music.163.com/#/dj?id=675051
# 下载排行榜
nm http://music.163.com/#/discover/toplist?id=11641012
播放:
# url 是上面的
nm -p url
4. 参考:
> https://github.com/yanunon/NeteaseCloudMusic/wiki/%E7%BD%91%E6%98%93%E4%BA%91%E9%9F%B3%E4%B9%90API%E5%88%86%E6%9E%90
> http://s3.music.126.net/s/2/core.js
---
<a name="flvxz_cl.py"></a>
### flvxz_cl.py - flvxz.com 视频解析 client - 支持下载、播放
1. 依赖
wget
python2-requests (https://github.com/kennethreitz/requests)
mpv (http://mpv.io)
2. 使用说明
flvxz.com 视频解析
**不提供视频合并操作**
支持的网站:
"""
已知支持120个以上视频网站,覆盖大多数国内视频站点,少量国外视频站点
"""
-- flvxz.com
关于播放操作:
> 在运行脚本的终端,输入1次Enter,关闭当前播放并播放下一个文件,连续输入2次Enter,关闭当前播放并退出。
3. 用法
\# fl是flvxz_cl.py的马甲 (alias fl='python2 /path/to/flvxz_cl.py')
下载:
fl http://v.youku.com/v_show/id_XNTI2Mzg4NjAw.html
fl http://www.tudou.com/albumplay/Lqfme5hSolM/tJ_Gl3POz7Y.html
播放:
# url 是上面的
fl url -p
4. 相关脚本:
> https://github.com/iambus/youku-lixian
> https://github.com/rg3/youtube-dl
> https://github.com/soimort/you-get
---
<a name="tumblr.py"></a>
### tumblr.py - 下载某个tumblr.com的所有图片
1. 依赖
wget
python2-requests (https://github.com/kennethreitz/requests)
2. 使用说明
* 使用前需用在 http://www.tumblr.com/oauth/apps 加入一个app,证实后得到api_key,再在源码中填入,完成后则可使用。
* 或者用 http://www.tumblr.com/docs/en/api/v2 提供的api_key ( fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4 )
默认开5个进程,如需改变用参数-p [num]。
下载的文件,保存在当前目录下。
默认下载原图。
支持连续下载,下载进度储存在下载文件夹内的 json.json。
参数:
-p PROCESSES, --processes PROCESSES 指定多进程数,默认为5个,最多为20个 eg: -p 20
-c, --check 尝试修复未下载成功的图片
-t TAG, --tag TAG 下载特定tag的图片, eg: -t beautiful
3. 用法
\# tm是tumblr.py的马甲 (alias tm='python2 /path/to/tumblr.py')
# 下载某个tumblr
tm http://sosuperawesome.tumblr.com/
tm http://sosuperawesome.tumblr.com/ -t beautiful
# 指定tag下载
tm beautiful
tm cool
---
<a name="unzip.py"></a>
### unzip.py - 解决linux下unzip乱码的问题
用法
python2 unzip.py azipfile1.zip azipfile2.zip ..
python2 unzip.py azipfile.zip -s secret
# -s 密码
代码来自以下连接,我改了一点。
> http://wangqige.com/the-solution-of-unzip-files-which-zip-under-windows/解决在Linux环境下解压zip的乱码问题
---
<a name="ed2k_search.py"></a>
### ed2k_search.py - 基于 donkey4u.com 的emule搜索
1. 依赖
python2
2. 用法
\# ed 是ed2k_search.py的马甲 (alias ed='python2 /path/to/ed2k_search.py')
ed this is a keyword
or
ed "this is a keyword"
---
<a name="91porn.py"></a>
### 91porn.py - 下载或播放91porn
**警告: 18岁以下者,请自觉远离。**
1. 依赖
wget, aria2
python2-requests (https://github.com/kennethreitz/requests)
mpv (http://mpv.io)
2. 使用说明
> 没有解决 *7个/day* 限制
下载工具默认为wget, 可用参数-a选用aria2
默认执行下载,如要播放媒体文件,加参数-p。
下载的文件,保存在当前目录下。
关于播放操作:
> 在运行脚本的终端,输入1次Enter,关闭当前播放并播放下一个文件,连续输入2次Enter,关闭当前播放并退出。
3. 用法
\# pn 是91porn.py的马甲 (alias pn='python2 /path/to/91porn.py')
pn url # 91porn.com(或其镜像) 视频的url
播放:
pn -p url
4. 参考
> http://v2ex.com/t/110196 # 第16楼
---
<a name="ThunderLixianExporter.user.js"></a>
### ThunderLixianExporter.user.js - A fork of https://github.com/binux/ThunderLixianExporter
**一个github.com/binux的迅雷离线导出脚本的fork。**
增加了mpv和mplayer的导出。
用法见: https://github.com/binux/ThunderLixianExporter
| Java |
export default {
cache: function (state, payload) {
state.apiCache[payload.api_url] = payload.api_response;
},
addConfiguredType: function (state, type) {
state.configuredTypes.push(type);
},
removeConfiguredType: function (state, index) {
state.configuredTypes.splice(index, 1);
},
updateConfiguredType: function (state, type) {
for (var i = 0, len = state.configuredTypes.length; i < len; i++) {
if (state.configuredTypes[i].name === type.name) {
state.configuredTypes.splice(i, 1);
state.configuredTypes.push(type);
// Avoid too keep looping over a spliced array
return;
}
}
},
setBaseExtraFormTypes: function (state, types) {
state.baseTypes = types;
},
setConfiguredExtraFormTypes: function (state, types) {
state.configuredTypes = types;
}
};
| Java |
FROM gliderlabs/alpine:latest
MAINTAINER Carlos León <mail@carlosleon.info>
RUN apk-install darkhttpd
EXPOSE 80
ENTRYPOINT ["/usr/bin/darkhttpd"]
CMD ["/var/www", "--chroot"]
| Java |
### 实现元素拖拽功能:
- EventUtil 封装跨浏览器时间处理对象
- EventTarget 自定义事件对象
- dragdrop 在其中实现元素拖拽
关键点:
**被拖拽元素使用 绝对定位absolute 或 相对定位relative**,在mousemove事件中,重新设置left 及 top值
添加mousedown/mouseup事件
修缮拖动:鼠标点击位置与元素顶端位置差异 | Java |
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "PAS_fNotas_Credito"
'-------------------------------------------------------------------------------------------'
Partial Class PAS_fNotas_Credito
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim loConsulta As New StringBuilder()
loConsulta.AppendLine("SELECT Clientes.Nom_Cli,")
loConsulta.AppendLine(" Clientes.Rif,")
loConsulta.AppendLine(" Clientes.Nit,")
loConsulta.AppendLine(" Clientes.Dir_Fis,")
loConsulta.AppendLine(" Clientes.Telefonos,")
loConsulta.AppendLine(" Clientes.Fax,")
loConsulta.AppendLine(" Cuentas_Cobrar.Documento,")
loConsulta.AppendLine(" CASE WHEN DAY(Cuentas_Cobrar.Fec_Ini) < 10")
loConsulta.AppendLine(" THEN CONCAT('0', DAY(Cuentas_Cobrar.Fec_Ini))")
loConsulta.AppendLine(" ELSE DAY(Cuentas_Cobrar.Fec_Ini)")
loConsulta.AppendLine(" END AS Dia,")
loConsulta.AppendLine(" CASE WHEN MONTH(Cuentas_Cobrar.Fec_Ini) < 10 ")
loConsulta.AppendLine(" THEN CONCAT('0', MONTH(Cuentas_Cobrar.Fec_Ini))")
loConsulta.AppendLine(" ELSE MONTH(Cuentas_Cobrar.Fec_Ini)")
loConsulta.AppendLine(" END AS Mes,")
loConsulta.AppendLine(" YEAR(Cuentas_Cobrar.Fec_Ini) AS Anio,")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Bru AS Mon_Bru, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Imp1 AS Mon_Imp1, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Por_Imp1 AS Por_Imp1, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Net AS Mon_Net,")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Sal AS Mon_Sal,")
loConsulta.AppendLine(" Cuentas_Cobrar.Por_Des AS Por_Des, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Des AS Mon_Des, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Comentario,")
loConsulta.AppendLine(" Cuentas_Cobrar.Referencia,")
loConsulta.AppendLine(" Renglones_Documentos.Can_Art,")
loConsulta.AppendLine(" Renglones_Documentos.Cod_Uni,")
loConsulta.AppendLine(" Renglones_Documentos.Precio1,")
loConsulta.AppendLine(" Renglones_Documentos.Precio2,")
loConsulta.AppendLine(" Renglones_Documentos.Mon_Net AS Neto,")
loConsulta.AppendLine(" Renglones_Documentos.Comentario AS Com_Renglon,")
loConsulta.AppendLine(" Renglones_Documentos.Notas,")
loConsulta.AppendLine(" Articulos.Nom_Art")
loConsulta.AppendLine("FROM Cuentas_Cobrar")
loConsulta.AppendLine(" JOIN Clientes ")
loConsulta.AppendLine(" ON Cuentas_Cobrar.Cod_Cli = Clientes.Cod_Cli")
loConsulta.AppendLine(" JOIN Renglones_Documentos ")
loConsulta.AppendLine(" ON Cuentas_Cobrar.Documento = Renglones_Documentos.Documento")
loConsulta.AppendLine(" AND Renglones_Documentos.Cod_Tip = 'N/CR'")
loConsulta.AppendLine(" JOIN Articulos ")
loConsulta.AppendLine(" ON Renglones_Documentos.Cod_Art = Articulos.Cod_Art")
loConsulta.AppendLine(" ")
loConsulta.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
Dim loServicios As New cusDatos.goDatos()
' Me.mEscribirConsulta(loConsulta.ToString())
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString(), "curReportes")
'Dim lcXml As String = "<impuesto></impuesto>"
'Dim lcPorcentajesImpueto As String
'Dim loImpuestos As New System.Xml.XmlDocument()
'lcPorcentajesImpueto = "("
''Recorre cada renglon de la tabla
'For lnNumeroFila As Integer = 0 To laDatosReporte.Tables(0).Rows.Count - 1
' lcXml = laDatosReporte.Tables(0).Rows(lnNumeroFila).Item("dis_imp")
' If String.IsNullOrEmpty(lcXml.Trim()) Then
' Continue For
' End If
' loImpuestos.LoadXml(lcXml)
' 'En cada renglón lee el contenido de la distribució de impuestos
' For Each loImpuesto As System.Xml.XmlNode In loImpuestos.SelectNodes("impuestos/impuesto")
' If lnNumeroFila = laDatosReporte.Tables(0).Rows.Count - 1 Then
' If CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) <> 0 Then
' lcPorcentajesImpueto = lcPorcentajesImpueto & ", " & CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) & "%"
' End If
' End If
' Next loImpuesto
'Next lnNumeroFila
'lcPorcentajesImpueto = lcPorcentajesImpueto & ")"
'lcPorcentajesImpueto = lcPorcentajesImpueto.Replace("(,", "(")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("PAS_fNotas_Credito", laDatosReporte)
'lcPorcentajesImpueto = lcPorcentajesImpueto.Replace(".", ",")
'CType(loObjetoReporte.ReportDefinition.ReportObjects("Text1"), CrystalDecisions.CrystalReports.Engine.TextObject).Text = lcPorcentajesImpueto.ToString
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvPAS_fNotas_Credito.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' GMO: 16/08/08: Codigo inicial. '
'-------------------------------------------------------------------------------------------'
' JJD: 08/11/08: Ajustes al select. '
'-------------------------------------------------------------------------------------------'
' RJG: 01/09/09: Agregado código para mostrar unidad segundaria. '
'-------------------------------------------------------------------------------------------'
' CMS: 10/09/09: Se ajusto el nombre del articulo para los casos de aquellos articulos gen. '
'-------------------------------------------------------------------------------------------'
' JJD: 09/01/10: Se cambio para que leyera los datos genericos de la Factura cuando aplique.'
'-------------------------------------------------------------------------------------------'
' CMS: 18/03/10: Se aplicaron los metodos carga de imagen y validacion de registro cero. '
'-------------------------------------------------------------------------------------------'
' CMS: 19/03/10: Se a justo la logica para determinar el nombre del cliente '
' (Clientes.Generico = 0 ) a (Clientes.Generico = 0 AND Cuentas_Cobrar.Nom_Cli = '') '
'-------------------------------------------------------------------------------------------'
' MAT: 23/02/11: Se programo la distribución de impuestos para mostrarlo en el formato. '
'-------------------------------------------------------------------------------------------'
' MAT: 19/04/11 : Ajuste de la vista de diseño. '
'-------------------------------------------------------------------------------------------'
' RJG: 06/02/14 : Ajuste de la formato (comentario, indentación...) de código y SQL. '
'-------------------------------------------------------------------------------------------'
| Java |
.PHONY: build clean
build: .obj/chilon_sql_to_source
clean:
rm -rf .obj
.obj/%: %.cpp
@mkdir -p .obj
${CXX} -std=c++0x $^ -o $@ -I ../..
ifeq ($(wildcard .obj/*),)
install:
else
install:
@mkdir -p ${DESTDIR}/${prefix}/bin
@strip .obj/*
@cp .obj/* ${DESTDIR}/${prefix}/bin
endif
| Java |
package com.korpisystems.SimpleANN
import org.scalatest.FunSuite
class ANNTest extends FunSuite {
test("ANN learns non-linear XOR properly") {
val inputs: ExpectedValues = List(
List(1, 1)
, List(0, 1)
, List(1, 0)
, List(0, 0)
)
val expected_out: ExpectedValues = List(
List(0)
, List(1)
, List(1)
, List(0)
)
val ann = new ANN(List(2, 4, 1), 1.0)
ann.train(inputs, expected_out, iter=5000)
val xor_1_1 = ann.getOutput(inputs(0))(0)
assert(xor_1_1 < 0.04)
val xor_0_1 = ann.getOutput(inputs(1))(0)
assert(xor_0_1 > 0.96)
val xor_1_0 = ann.getOutput(inputs(2))(0)
assert(xor_1_0 > 0.96)
val xor_0_0 = ann.getOutput(inputs(3))(0)
assert(xor_0_0 < 0.04)
}
test("ANN learns XOR with multiple hidden layers") {
val inputs: ExpectedValues = List(
List(1, 1)
, List(0, 1)
, List(1, 0)
, List(0, 0)
)
val expected_out: ExpectedValues = List(
List(0)
, List(1)
, List(1)
, List(0)
)
val ann = new ANN(List(2, 4, 3, 1), 1.0)
ann.train(inputs, expected_out, iter=5000)
val xor_1_1 = ann.getOutput(inputs(0))(0)
assert(xor_1_1 < 0.04)
val xor_0_1 = ann.getOutput(inputs(1))(0)
assert(xor_0_1 > 0.96)
val xor_1_0 = ann.getOutput(inputs(2))(0)
assert(xor_1_0 > 0.96)
val xor_0_0 = ann.getOutput(inputs(3))(0)
assert(xor_0_0 < 0.04)
}
test("ANN learns first input is output") {
val inputs: ExpectedValues = List(
List(1, 1)
, List(0, 1)
, List(1, 0)
, List(0, 0)
)
val expected_out: ExpectedValues = List(
List(1)
, List(0)
, List(1)
, List(0)
)
val ann = new ANN(List(2, 4, 1), 1.0)
ann.train(inputs, expected_out, iter=5000)
val first_1_1 = ann.getOutput(inputs(0))(0)
assert(first_1_1 > 0.96)
val first_0_1 = ann.getOutput(inputs(1))(0)
assert(first_0_1 < 0.04)
val first_1_0 = ann.getOutput(inputs(2))(0)
assert(first_1_0 > 0.96)
val first_0_0 = ann.getOutput(inputs(3))(0)
assert(first_0_0 < 0.04)
}
test("ANN learns second input is output") {
val inputs: ExpectedValues = List(
List(1, 1)
, List(0, 1)
, List(1, 0)
, List(0, 0)
)
val expected_out: ExpectedValues = List(
List(1)
, List(1)
, List(0)
, List(0)
)
val ann = new ANN(List(2, 4, 1), 1.0)
ann.train(inputs, expected_out, iter=5000)
val first_1_1 = ann.getOutput(inputs(0))(0)
assert(first_1_1 > 0.96)
val first_0_1 = ann.getOutput(inputs(1))(0)
assert(first_0_1 > 0.96)
val first_1_0 = ann.getOutput(inputs(2))(0)
assert(first_1_0 < 0.04)
val first_0_0 = ann.getOutput(inputs(3))(0)
assert(first_0_0 < 0.04)
}
test("UnevenTrainingInstanceLists thrown properly") {
val inputs: ExpectedValues = List(
List(1, 1)
, List(0, 1)
, List(1, 0)
, List(0, 0)
)
val expected_out: ExpectedValues = List(
List(1)
, List(0)
, List(1)
)
val ann = new ANN(List(2, 4, 1), 1.0)
intercept[Exceptions.UnevenTrainingInstanceLists] {
ann.train(inputs, expected_out, iter=5000)
}
}
}
| Java |
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
| Java |
/**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /*
@author Axel Anceau - 2014
Package api contains general tools
*/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/
package api
import (
"fmt"
"github.com/revel/revel"
"runtime/debug"
)
/**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /*
PanicFilter renders a panic as JSON
@see revel/panic.go
*/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/
func PanicFilter(c *revel.Controller, fc []revel.Filter) {
defer func() {
if err := recover(); err != nil && err != "HttpException" {
error := revel.NewErrorFromPanic(err)
if error == nil {
revel.ERROR.Print(err, "\n", string(debug.Stack()))
c.Response.Out.WriteHeader(500)
c.Response.Out.Write(debug.Stack())
return
}
revel.ERROR.Print(err, "\n", error.Stack)
c.Result = HttpException(c, 500, fmt.Sprint(err))
}
}()
fc[0](c, fc[1:])
}
| Java |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tree View</title>
<link href="01.tree-view.css" rel="stylesheet" />
</head>
<body>
<nav>
<ul class="first">
<li>
<a href="#">List Item</a>
<ul>
<li>
<a href="#">Sublist item</a>
</li>
<li>
<a href="#">Sublist item</a>
</li>
<li>
<a href="#">Sublist item</a>
</li>
<li>
<a href="#">Sublist item</a>
</li>
</ul>
</li>
<li>
<a href="#">List Item</a>
<ul>
<li>
<a href="#">Sublist item</a>
</li>
<li>
<a href="#">Sublist item</a>
</li>
</ul>
</li>
<li>
<a href="#">List Item</a>
<ul>
<li>
<a href="#">Sublist item</a>
</li>
<li>
<a href="#">Sublist item</a>
</li>
<li>
<a href="#">Sublist item</a>
</li>
</ul>
</li>
<li>
<a href="#">List Item</a>
<ul>
<li>
<a href="#">Sublist item</a>
</li>
</ul>
</li>
</ul>
</nav>
</body>
</html>
| Java |
---
layout: post
author: nurahill
title: "Nura's Clicky turtle excercise"
---
Here is my code for option 1:
<iframe src="https://trinket.io/embed/python/3c8744a1ac" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
On option one, as usual, it took me a bit to come up with an idea of a program for this one. I ended up deciding to draw a ground and sky. on lines 38-46 i created my clicky funtion. I made it so if tinas y coordinate of the place you click on is greater than -152 it would draw a star (on the sky), and if it was less than it would draw a flower (on the ground). My helper functions are the star and flower.
Here is my code for option 2:
<iframe src="https://trinket.io/embed/python/b8a6b80918" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
I wasnt able to get to do a whole lot with option two. I bascially was just able to make it work, as it took me sometime to get it working properly. I created the list of colors so by clicking on shift, the turle color would change to different colors. Below is where i was able to use randint to make it choose a random color. where it says [randint(0,len(color)-1)] it means that I want it to pick a random color (randint) from 0 to the length of color, -1 (-1 makes sure that it never picks a color out of range)
```
# Define a function to change the color
def color_change():
tina.color(colors[randint(0,len(colors)-1)])
```
I feel like this excersice was a good foundation to build on futher in the future. Its pretty cool to able to manipulate the turtle with the keyboard and make it draw things. I particularly like that penup and pendown part that i created (wich you can turn on or off by clicking 'u') becaue that gave me the ability to draw things (like a square, triabgle, etc.). Th e penup/pendown was my something creative!
| Java |
<?php
namespace SCL\ZF2\Currency\Form\Fieldset;
use Zend\Form\Fieldset;
class TaxedPrice extends Fieldset
{
const AMOUNT_LABEL = 'Amount';
const TAX_LABEL = 'Tax';
public function init()
{
$this->add([
'name' => 'amount',
'type' => 'text',
'options' => [
'label' => self::AMOUNT_LABEL,
]
]);
$this->add([
'name' => 'tax',
'type' => 'text',
'options' => [
'label' => self::TAX_LABEL,
]
]);
}
}
| Java |
var indexController = require('./controllers/cIndex');
var usuarioController = require('./controllers/cUsuario');
var clientesController = require('./controllers/cCliente');
var adminController = require('./controllers/cAdmin');
var umedController = require('./controllers/cUmed');
var matepController = require('./controllers/cMatep');
var empleController = require('./controllers/cEmple');
var accesosController = require('./controllers/cAccesos');
var cargoController = require('./controllers/cCargos');
var reactoController = require('./controllers/cReacto');
var lineasController = require('./controllers/cLineas');
var prodController = require('./controllers/cProd');
var envasesController = require('./controllers/cEnvases');
var tanquesController = require('./controllers/cTanques');
var ubicaController = require('./controllers/cUbica');
var recetaController = require('./controllers/cReceta');
var remitosController = require('./controllers/cRemitos');
var progController = require('./controllers/cProgramacion');
var FormEnReactorController = require('./controllers/cFormEnReactor');
var labController = require('./controllers/cLab');
var formController = require('./controllers/cFormulados');
var mEventos = require('./models/mEventos');
var consuController = require('./controllers/cConsumibles');
var produccionController = require('./controllers/cProduccion');
var fraccionadoController = require('./controllers/cFraccionado');
var aprobacionController = require('./controllers/cAprobacion');
var navesController = require('./controllers/cNaves');
var mapaController = require('./controllers/cMapa');
function logout (req, res) {
fecha = new Date();
day = fecha.getDate();
month = fecha.getMonth();
if (day<10)
day = "0" + day;
if (month<10)
month = "0" + month;
fecha = fecha.getFullYear() + "/"+month+"/"+day+" "+fecha.getHours()+":"+fecha.getMinutes()
mEventos.add(req.session.user.unica, fecha, "Logout", "", function(){
});
req.session = null;
return res.redirect('/');
}
// Verifica que este logueado
function auth (req, res, next) {
if (req.session.auth) {
return next();
} else {
console.log("dentro del else del auth ")
return res.redirect('/')
}
}
module.exports = function(app) {
app.get('/', adminController.getLogin);
app.get('/login', adminController.getLogin)
app.post('/login', adminController.postLogin);
app.get('/logout', logout);
app.get('/inicio', auth, indexController.getInicio);
app.get('/error', indexController.getError);
//ayuda
app.get('/ayuda', indexController.getAyuda);
app.get('/ayudaver/:id', indexController.AyudaVer);
//novedades
app.get('/listanovedades', indexController.getNovedades);
//usuarios
app.get('/usuarioslista', auth, usuarioController.getUsuarios);
app.get('/usuariosalta', auth, usuarioController.getUsuariosAlta);
app.post('/usuariosalta', auth, usuarioController.putUsuario);
app.get('/usuariosmodificar/:id', auth, usuarioController.getUsuarioModificar);
app.post('/usuariosmodificar', auth, usuarioController.postUsuarioModificar);
app.get('/usuariosborrar/:id', auth, usuarioController.getDelUsuario);
//configurar accesos
app.get('/accesoslista/:id', auth, accesosController.getAccesos);
app.post('/accesoslista', auth, accesosController.postAccesos);
//clientes
app.get('/clienteslista', auth, clientesController.getClientes);
app.get('/clientesalta', auth, clientesController.getClientesAlta);
app.post('/clientesalta', auth, clientesController.putCliente);
app.get('/clientesmodificar/:id', auth, clientesController.getClienteModificar);
app.post('/clientesmodificar', auth, clientesController.postClienteModificar);
app.get('/clientesborrar/:id', auth, clientesController.getDelCliente);
app.get('/:cliente/materiasprimas', auth, clientesController.getMatep);
//unidades de medida "umed"
app.get('/umedlista', auth, umedController.getAllUmed);
app.get('/umedalta', auth, umedController.getAlta);
app.post('/umedalta', auth, umedController.postAlta);
app.get('/umedmodificar/:id', auth, umedController.getModificar);
app.post('/umedactualizar', auth, umedController.postModificar);
app.get('/umedborrar/:id', auth, umedController.getDelUmed);
//materias primas por cliente
app.get('/mateplista/:cdcliente', auth, matepController.getAllMatepPorCliente);
app.get('/matepalta/:cdcliente', auth, matepController.getAlta);
app.post('/matepalta', auth, matepController.postAlta);
app.get('/matepmodificar/:id', auth, matepController.getModificar);
app.post('/matepmodificar', auth, matepController.postModificar);
app.get('/matepborrar/:id', auth, matepController.getDelMatep);
//cantidad maxima en tanque por matep
app.get('/formenreactor/:id', auth, FormEnReactorController.getFormEnReactor);
app.get('/formenreactoralta/:idform', auth, FormEnReactorController.getAlta);
app.post('/formenreactoralta', auth, FormEnReactorController.postAlta);
app.get('/formenreactormodificar/:id', auth, FormEnReactorController.getModificar);
app.post('/formenreactormodificar', auth, FormEnReactorController.postModificar);
app.get('/formenreactorborrar/:id', auth, FormEnReactorController.del);
//producto por clientereactor
app.get('/prodlista/:cdcliente', auth, prodController.getAllProdPorCliente);
app.get('/prodalta/:cdcliente', auth, prodController.getAlta);
app.post('/prodalta', auth, prodController.postAlta);
app.get('/prodmodificar/:id', auth, prodController.getModificar);
app.post('/prodmodificar', auth, prodController.postModificar);
app.get('/prodborrar/:id', auth, prodController.getDelProd);
app.get('/:idprod/ablote', auth, prodController.getAbLote);
//empleados
app.get('/emplelista', auth, empleController.getEmpleados);
app.get('/emplealta', auth, empleController.getAlta);
app.post('/emplealta', auth, empleController.postAlta);
app.get('/emplemodificar/:codigo', auth, empleController.getModificar);
app.post('/emplemodificar', auth, empleController.postModificar);
app.get('/empleborrar/:codigo', auth, empleController.getDelEmple);
//cargos de empleados
app.get('/cargoslista', auth, cargoController.getAllCargos);
app.get('/cargosalta', auth, cargoController.getAlta);
app.post('/cargosalta', auth, cargoController.postAlta);
app.get('/cargosmodificar/:id', auth, cargoController.getModificar);
app.post('/cargosmodificar', auth, cargoController.postModificar);
app.get('/cargosborrar/:id', auth, cargoController.getDelCargo);
//reactores
app.get('/reactolista', auth, reactoController.getAll);
app.get('/reactoalta', auth, reactoController.getAlta);
app.post('/reactoalta', auth, reactoController.postAlta);
app.get('/reactomodificar/:id', auth, reactoController.getModificar);
app.post('/reactomodificar', auth, reactoController.postModificar);
app.get('/reactoborrar/:id', auth, reactoController.getDel);
//lineas
app.get('/lineaslista', auth, lineasController.getAll);
app.get('/lineasalta', auth, lineasController.getAlta);
app.post('/lineasalta', auth, lineasController.postAlta);
app.get('/lineasmodificar/:id', auth, lineasController.getModificar);
app.post('/lineasmodificar', auth, lineasController.postModificar);
app.get('/lineasborrar/:id', auth, lineasController.getDel);
//envases
app.get('/envaseslista', auth, envasesController.getAll);
app.get('/envasesalta', auth, envasesController.getAlta);
app.post('/envasesalta', auth, envasesController.postAlta);
app.get('/envasesmodificar/:id', auth, envasesController.getModificar);
app.post('/envasesmodificar', auth, envasesController.postModificar);
app.get('/envasesborrar/:id', auth, envasesController.getDel);
app.get('/capacidadenvase/:id', auth, envasesController.getCapacidad);
//tanques
app.get('/tanqueslista', auth, tanquesController.getAll);
app.get('/tanquesalta', auth, tanquesController.getAlta);
app.post('/tanquesalta', auth, tanquesController.postAlta);
app.get('/tanquesmodificar/:id', auth, tanquesController.getModificar);
app.post('/tanquesmodificar', auth, tanquesController.postModificar);
app.get('/tanquesborrar/:id', auth, tanquesController.getDel);
//ubicaciones "ubica"
app.get('/ubicalista', auth, ubicaController.getAll);
app.get('/ubicaalta', auth, ubicaController.getAlta);
app.post('/ubicaalta', auth, ubicaController.postAlta);
app.get('/ubicamodificar/:id', auth, ubicaController.getModificar);
app.post('/ubicamodificar', auth, ubicaController.postModificar);
app.get('/ubicaborrar/:id', auth, ubicaController.getDel);
//recetas
app.get('/recetalista/:id', auth, recetaController.getRecetaPorFormulado);
app.get('/recetaalta/:id', auth, recetaController.getAlta);
app.post('/recetaalta', auth, recetaController.postAlta);
app.get('/recetaborrar/:id', auth, recetaController.getDel);
app.get('/recetamodificar/:id', auth, recetaController.getModificar);
app.post('/recetamodificar', auth, recetaController.postModificar);
//remitos
app.get('/remitoslista', auth, remitosController.getAll);
app.get('/remitosalta', auth, remitosController.getAlta);
app.post('/remitosalta', auth, remitosController.postAlta);
app.get('/remitosmodificar/:id', auth, remitosController.getModificar);
app.post('/remitosmodificar', auth, remitosController.postModificar);
app.get('/remitosborrar/:id', auth, remitosController.getDel);
app.get('/buscarremito/:finicio/:ffin', auth, remitosController.getRemitos);
//programacion
app.get('/prog1lista', auth, progController.getAll);
app.get('/prog1alta', auth, progController.getAlta);
app.post('/prog1alta', auth, progController.postAlta);
app.get('/prog2lista', auth, progController.getLista);
app.get('/prog1alta2/:idprog', auth, progController.getAlta2);
app.post('/prog1alta2', auth, progController.postAlta2);
app.get('/prog1/:lote/:anio/:clienteid/:prodid', auth, progController.getCodigo);
app.get('/prog1borrar/:id', auth, progController.getDel);
app.get('/refrescaremito/:idcliente/:idmatep', auth, progController.getRemitos);
app.get('/traerpa/:idform', auth, progController.getPA);
app.get('/buscarprogramaciones/:fecha', auth, progController.getProgramaciones);
app.get('/produccionborrarprogram/:id', auth, progController.getDelProgram);
//laboratorio
app.get('/lab/:idremito', auth, labController.getLab);
app.post('/lab', auth, labController.postLab);
//formulados
app.get('/formuladoalta/:cdcliente', auth, formController.getAlta);
app.post('/formuladoalta', auth, formController.postAlta);
app.get('/formuladolista/:cdcliente', auth, formController.getAllFormuladoPorCliente);
app.get('/formuladomodificar/:id', auth, formController.getModificar);
app.post('/formuladomodificar', auth, formController.postModificar);
app.get('/formuladoborrar/:id', auth, formController.getDelFormulado);
app.get('/:id/formulados', auth, formController.getForms);
app.get('/:idform/ablotee', auth, formController.getAbLote);
//consumibles
app.get('/consumibleslista/:idprod', auth, consuController.getAll);
app.get('/consumiblesalta/:idprod', auth, consuController.getAlta);
app.post('/consumiblesalta', auth, consuController.postAlta);
app.get('/consumiblesborrar/:id', auth, consuController.getDel);
//produccion
app.get('/produccionlista', auth, produccionController.getLista);
app.get('/buscarprogramaciones2/:fi/:ff', auth, produccionController.getProgramaciones);
app.get('/produccionver/:id', auth, produccionController.getVerFormulado);
app.post('/produccionver', auth, produccionController.postDatosFormulado);
app.get('/produccionimprimir/:id', auth, produccionController.getImprimir);
//borrar
//fraccionado
app.get('/fraccionadolista', auth, fraccionadoController.getLista);
app.get('/fraccionadoalta/:id', auth, fraccionadoController.getAlta);
app.post('/fraccionadoalta', auth, fraccionadoController.postAlta);
app.get('/fraccionadomodificar/:id', auth, fraccionadoController.getModificar);
app.post('/fraccionadomodificar', auth, fraccionadoController.postModificar);
//borrar?
//aprobacion
app.get('/aprobacionlista', auth, aprobacionController.getLista);
app.get('/aprobacionver/:id', auth, aprobacionController.getVer);
app.post('/aprobacionver', auth, aprobacionController.postVer);
app.get('/aprobacionimprimir/:id', auth, aprobacionController.getImprimir);
//naves
app.get('/naveslista', auth, navesController.getLista);
//mapa
app.get('/mapaver', auth, mapaController.getMapa);
}; | Java |
<?php
/**
* Created by PhpStorm.
* User: tfg
* Date: 25/08/15
* Time: 20:03
*/
namespace AppBundle\Behat;
use Sylius\Bundle\ResourceBundle\Behat\DefaultContext;
class BrowserContext extends DefaultContext
{
/**
* @Given estoy autenticado como :username con :password
*/
public function iAmAuthenticated($username, $password)
{
$this->getSession()->visit($this->generateUrl('fos_user_security_login', [], true));
$this->fillField('_username', $username);
$this->fillField('_password', $password);
$this->pressButton('_submit');
}
/**
* @Then /^presiono "([^"]*)" con clase "([^"]*)"$/
*
* @param string $text
* @param string $class
*/
public function iFollowLinkWithClass($text, $class)
{
$link = $this->getSession()->getPage()->find(
'xpath', sprintf("//*[@class='%s' and contains(., '%s')]", $class, $text)
);
if (!$link) {
throw new ExpectationException(sprintf('Unable to follow the link with class: %s and text: %s', $class, $text), $this->getSession());
}
$link->click();
}
} | Java |
## Close
### What is the value of the first triangle number to have over five hundred divisors?
print max([len(m) for m in map(lambda k: [n for n in range(1,(k+1)) if k%n == 0], [sum(range(n)) for n in range(1,1000)])]) | Java |
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("Autos4Sale.Data.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Autos4Sale.Data.Models")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("280798cb-7923-404f-90bb-e890b732d781")]
// 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")]
| Java |
from errors import *
from manager import SchemaManager
| Java |
<?php
namespace Syrma\WebContainer;
/**
*
*/
interface ServerInterface
{
/**
* Start the server.
*
* @param ServerContextInterface $context
* @param RequestHandlerInterface $requestHandler
*/
public function start(ServerContextInterface $context, RequestHandlerInterface $requestHandler);
/**
* Stop the server.
*/
public function stop();
/**
* The server is avaiable.
*
* Here check requirements
*
* @return bool
*/
public static function isAvaiable();
}
| Java |
# Architecture
When you are developing a new feature that requires architectural design, or if
you are changing the fundamental design of an existing feature, make sure it is
discussed with one of the Frontend Architecture Experts.
A Frontend Architect is an expert who makes high-level Frontend design decisions
and decides on technical standards, including coding standards and frameworks.
Architectural decisions should be accessible to everyone, so please document
them in the relevant Merge Request discussion or by updating our documentation
when appropriate.
You can find the Frontend Architecture experts on the [team page](https://about.gitlab.com/team).
## Examples
You can find documentation about the desired architecture for a new feature
built with Vue.js [here](vue.md).
| Java |
module Mailchimp
class API
include HTTParty
format :plain
default_timeout 30
attr_accessor :api_key, :timeout, :throws_exceptions
def initialize(api_key = nil, extra_params = {})
@api_key = api_key || ENV['MAILCHIMP_API_KEY'] || self.class.api_key
@default_params = {:apikey => @api_key}.merge(extra_params)
@throws_exceptions = false
end
def api_key=(value)
@api_key = value
@default_params = @default_params.merge({:apikey => @api_key})
end
def base_api_url
"https://#{dc_from_api_key}api.mailchimp.com/1.3/?method="
end
def valid_api_key?(*args)
"Everything's Chimpy!" == call("ping")
end
protected
def call(method, params = {})
api_url = base_api_url + method
params = @default_params.merge(params)
timeout = params.delete(:timeout) || @timeout
response = self.class.post(api_url, :body => CGI::escape(params.to_json), :timeout => timeout)
begin
response = JSON.parse(response.body)
rescue
response = JSON.parse('['+response.body+']').first
end
if @throws_exceptions && response.is_a?(Hash) && response["error"]
raise "Error from MailChimp API: #{response["error"]} (code #{response["code"]})"
end
response
end
def method_missing(method, *args)
method = method.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } #Thanks for the gsub, Rails
method = method[0].chr.downcase + method[1..-1].gsub(/aim$/i, 'AIM')
call(method, *args)
end
class << self
attr_accessor :api_key
def method_missing(sym, *args, &block)
new(self.api_key).send(sym, *args, &block)
end
end
def dc_from_api_key
(@api_key.nil? || @api_key.length == 0 || @api_key !~ /-/) ? '' : "#{@api_key.split("-").last}."
end
end
end
| Java |
Ti=Ownership
sec=All {_Confidential_Information} furnished to {_the_Consultant} by {_the_Client} is the sole and exclusive property of {_the_Client} or its suppliers or customers.
=[G/Z/ol/0]
| Java |
/*
Print.cpp - Base class that provides print() and println()
Copyright (c) 2008 David A. Mellis. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 23 November 2006 by David A. Mellis
Modified 20 Aug 2014 by MediaTek Inc.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "Arduino.h"
#include "Print.h"
// Public Methods //////////////////////////////////////////////////////////////
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while (size--) {
n += write(*buffer++);
}
return n;
}
size_t Print::print(const __FlashStringHelper *ifsh)
{
return print(reinterpret_cast<const char *>(ifsh));
}
size_t Print::print(const String &s)
{
return write(s.c_str(), s.length());
}
size_t Print::print(const char str[])
{
return write(str);
}
size_t Print::print(char c)
{
return write(c);
}
size_t Print::print(unsigned char b, int base)
{
return print((unsigned long) b, base);
}
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
size_t Print::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t Print::print(long n, int base)
{
if (base == 0) {
return write(n);
} else if (base == 10) {
if (n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t Print::print(unsigned long n, int base)
{
if (base == 0) return write(n);
else return printNumber(n, base);
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t Print::println(const __FlashStringHelper *ifsh)
{
size_t n = print(ifsh);
n += println();
return n;
}
size_t Print::print(const Printable& x)
{
return x.printTo(*this);
}
size_t Print::println(void)
{
size_t n = print('\r');
n += print('\n');
return n;
}
size_t Print::println(const String &s)
{
size_t n = print(s);
n += println();
return n;
}
size_t Print::println(const char c[])
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t Print::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n;
}
size_t Print::println(const Printable& x)
{
size_t n = print(x);
n += println();
return n;
}
#include <stdarg.h>
size_t Print::printf(const char *fmt, ...)
{
va_list args;
char buf[256] = {0};
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
return write(buf, strlen(buf));
}
// Private Methods /////////////////////////////////////////////////////////////
size_t Print::printNumber(unsigned long n, uint8_t base) {
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if (base < 2) base = 10;
do {
unsigned long m = n;
n /= base;
char c = m - base * n;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return write(str);
}
size_t Print::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if (isnan(number)) return print("nan");
if (isinf(number)) return print("inf");
if (number > 4294967040.0) return print ("ovf"); // constant determined empirically
if (number <-4294967040.0) return print ("ovf"); // constant determined empirically
// Handle negative numbers
if (number < 0.0)
{
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i=0; i<digits; ++i)
rounding /= 10.0;
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0) {
n += print(".");
}
// Extract digits from the remainder one at a time
while (digits-- > 0)
{
remainder *= 10.0;
int toPrint = int(remainder);
n += print(toPrint);
remainder -= toPrint;
}
return n;
}
| Java |
import { Injectable } from '@angular/core';
/**
* Created by AAAA on 3/21/2017.
*/
//http://stackoverflow.com/questions/9671995/javascript-custom-event-listener
//http://www.typescriptlang.org/play/
class MyEvent{
private context:Object;
private cbs: Function[] = [];
constructor(context: Object){
this.context = context;
}
public addListener(cb: Function){
this.cbs.push(cb);
}
public removeListener(cb: Function){
let i = this.cbs.indexOf(cb);
if (i >-1) {
this.cbs.splice(i, 1);
}
}
public removeAllListeners(){
this.cbs=[];
}
public trigger(...args){
this.cbs.forEach(cb => cb.apply(this.context, args))
};
}
class EventContainer{
private events: MyEvent[]= [];
public createEvent(context:Object):MyEvent{
let myEvent = new MyEvent(context);
this.events.push(myEvent);
return myEvent;
}
public removeEvent(myEvent:MyEvent):void{
let i = this.events.indexOf(myEvent);
if (i >-1) {
this.events.splice(i, 1);
}
};
public trigger(...args):void{
this.events.forEach(event => event.trigger(args));
};
}
class LoginEvent extends EventContainer{}
class LogoutEvent extends EventContainer{}
@Injectable()
export class EventsService {
private _loginEvent:LoginEvent;
private _logoutEvent:LogoutEvent;
constructor() {}
get loginEvent():LoginEvent{
if(!this._loginEvent) {
this._loginEvent = new LoginEvent();
}
return this._loginEvent;
}
get logoutEvent():LogoutEvent{
if(!this._logoutEvent) {
this._logoutEvent = new LogoutEvent();
}
return this._logoutEvent;
}
}
| Java |
import random
from datetime import datetime
from multiprocessing import Pool
import numpy as np
from scipy.optimize import minimize
def worker_func(args):
self = args[0]
m = args[1]
k = args[2]
r = args[3]
return (self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) ** 2
def optimized_func_i_der(args):
"""
The derivative of the optimized function with respect to the
ith component of the vector r
"""
self = args[0]
r = args[1]
i = args[2]
result = 0
M = len(self.data)
for m in range(M):
Nm = self.data[m].shape[0] - 1
for k in range(Nm + 1):
result += ((self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) * 2 *
self.eval_func_der(m, k, r, i))
return result
def worker_func_der(args):
self = args[0]
m = args[1]
k = args[2]
r = args[3]
i = args[4]
return ((self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) * 2 *
self.eval_func_der(m, k, r, i))
class Agent:
num_features = 22
def __init__(self):
self.lf = 0.2 # Learning factor lambda
self.data = [] # The features' values for all the games
self.rewards = [] # Reward values for moving from 1 state to the next
self.rt = np.array([])
self.max_iter = 50
def set_learning_factor(self, learning_factor):
assert(learning_factor >= 0 and learning_factor <= 1)
self.lf = learning_factor
def set_rt(self, rt):
assert(len(rt) == self.num_features)
self.rt = rt
def set_iter(self, max_iter):
self.max_iter = max_iter
def set_data(self, data):
self.data = []
self.rewards = []
for game in data:
game = np.vstack((game, np.zeros(self.num_features + 1)))
self.data.append(game[:, :-1])
self.rewards.append(game[:, -1:])
def eval_func(self, m, k, r):
"""
The evaluation function value for the set of weights (vector) r
at the mth game and kth board state """
return np.dot(r, self.data[m][k])
def eval_func_der(self, m, k, r, i):
"""
Find the derivative of the evaluation function with respect
to the ith component of the vector r
"""
return self.data[m][k][i]
def get_reward(self, m, s):
"""
Get reward for moving from state s to state (s + 1)
"""
return self.rewards[m][s + 1][0]
def temporal_diff(self, m, s):
"""
The temporal diffence value for state s to state (s+1) in the mth game
"""
return (self.get_reward(m, s) + self.eval_func(m, s + 1, self.rt) -
self.eval_func(m, s, self.rt))
def temporal_diff_sum(self, m, k):
Nm = self.data[m].shape[0] - 1
result = 0
for s in range(k, Nm):
result += self.lf**(s - k) * self.temporal_diff(m, s)
return result
def optimized_func(self, r):
result = 0
M = len(self.data)
pool = Pool(processes=4)
for m in range(M):
Nm = self.data[m].shape[0] - 1
k_args = range(Nm + 1)
self_args = [self] * len(k_args)
m_args = [m] * len(k_args)
r_args = [r] * len(k_args)
result += sum(pool.map(worker_func,
zip(self_args, m_args, k_args, r_args)))
return result
def optimized_func_i_der(self, r, i):
"""
The derivative of the optimized function with respect to the
ith component of the vector r
"""
result = 0
M = len(self.data)
for m in range(M):
Nm = self.data[m].shape[0] - 1
for k in range(Nm + 1):
result += ((self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) * 2 *
self.eval_func_der(m, k, r, i))
return result
def optimized_func_der(self, r):
p = Pool(processes=4)
self_args = [self] * len(r)
i_args = range(len(r))
r_args = [r] * len(r)
return np.array(p.map(optimized_func_i_der,
zip(self_args, r_args, i_args)))
def callback(self, r):
print("Iteration %d completed at %s" %
(self.cur_iter, datetime.now().strftime("%d/%m/%Y %H:%M:%S")))
self.cur_iter += 1
def compute_next_rt(self):
print("Start computing at %s" %
(datetime.now().strftime("%d/%m/%Y %H:%M:%S")))
self.cur_iter = 1
r0 = np.array([random.randint(-10, 10)
for i in range(self.num_features)])
res = minimize(self.optimized_func, r0, method='BFGS',
jac=self.optimized_func_der,
options={'maxiter': self.max_iter, 'disp': True},
callback=self.callback)
return res.x
| Java |
RSpec.describe Porch::ProcStepDecorator do
describe ".decorates?" do
it "returns true if the step is a proc" do
expect(described_class).to be_decorates Proc.new {}
end
it "returns true if the step is a lambda" do
expect(described_class).to be_decorates lambda {}
end
it "returns false if the step is a class" do
expect(described_class).to_not be_decorates Object
end
end
describe "#execute" do
let(:context) { Hash.new }
let(:organizer) { double(:organizer) }
let(:step) { Proc.new {} }
subject { described_class.new step, organizer }
it "calls the proc with the context" do
expect(step).to receive(:call).with(context)
subject.execute context
end
end
end
| Java |
<?php
declare(strict_types=1);
namespace Symplify\MultiCodingStandard\Tests\PhpCsFixer\Factory;
use PhpCsFixer\Fixer\FixerInterface;
use PHPUnit\Framework\TestCase;
use Symplify\MultiCodingStandard\PhpCsFixer\Factory\FixerFactory;
final class FixerFactoryTest extends TestCase
{
/**
* @var FixerFactory
*/
private $fixerFactory;
protected function setUp()
{
$this->fixerFactory = new FixerFactory();
}
/**
* @dataProvider provideCreateData
*/
public function testResolveFixerLevels(
array $fixerLevels,
array $fixers,
array $excludedFixers,
int $expectedFixerCount
) {
$fixers = $this->fixerFactory->createFromLevelsFixersAndExcludedFixers($fixerLevels, $fixers, $excludedFixers);
$this->assertCount($expectedFixerCount, $fixers);
if (count($fixers)) {
$fixer = $fixers[0];
$this->assertInstanceOf(FixerInterface::class, $fixer);
}
}
public function provideCreateData() : array
{
return [
[[], [], [], 0],
[[], ['no_whitespace_before_comma_in_array'], [], 1],
[['psr1'], [], [], 2],
[['psr2'], [], [], 24],
[['psr2'], [], ['visibility'], 24],
[['psr1', 'psr2'], [], [], 26],
[['psr1', 'psr2'], [], ['visibility'], 26],
];
}
}
| Java |
# -*- coding: utf-8 -*-
""""
ProjectName: pydemi
Repo: https://github.com/chrisenytc/pydemi
Copyright (c) 2014 Christopher EnyTC
Licensed under the MIT license.
"""
# Dependencies
import uuid
from api import app
from hashlib import sha1
from flask import request
from flask import jsonify as JSON
from api.models.user import User
from cors import cors
@app.route('/signup', methods=['POST'])
@cors(origin='*', methods=['POST'])
def signup():
# Create new user
new_user = User()
new_user.name = request.form['name']
new_user.email = request.form['email']
new_user.password = sha1(request.form['password']).hexdigest()
new_user.token = str(uuid.uuid4())
new_user.save()
return JSON(message='User created successfully')
@app.route('/signin', methods=['POST'])
@cors(origin='*', methods=['POST'])
def signin():
# Retorna a user data
user_info = User.objects(email=request.form['email'], password=sha1(
request.form['password']).hexdigest())
if user_info.count():
return JSON(token=user_info.get().token, roles=user_info.get().roles)
else:
return JSON(message='User not found')
| Java |
'use strict';
const buildType = process.config.target_defaults.default_configuration;
const assert = require('assert');
if (process.argv[2] === 'fatal') {
const binding = require(process.argv[3]);
binding.error.throwFatalError();
return;
}
test(`./build/${buildType}/binding.node`);
test(`./build/${buildType}/binding_noexcept.node`);
function test(bindingPath) {
const binding = require(bindingPath);
assert.throws(() => binding.error.throwApiError('test'), function(err) {
return err instanceof Error && err.message.includes('Invalid');
});
assert.throws(() => binding.error.throwJSError('test'), function(err) {
return err instanceof Error && err.message === 'test';
});
assert.throws(() => binding.error.throwTypeError('test'), function(err) {
return err instanceof TypeError && err.message === 'test';
});
assert.throws(() => binding.error.throwRangeError('test'), function(err) {
return err instanceof RangeError && err.message === 'test';
});
assert.throws(
() => binding.error.doNotCatch(
() => {
throw new TypeError('test');
}),
function(err) {
return err instanceof TypeError && err.message === 'test' && !err.caught;
});
assert.throws(
() => binding.error.catchAndRethrowError(
() => {
throw new TypeError('test');
}),
function(err) {
return err instanceof TypeError && err.message === 'test' && err.caught;
});
const err = binding.error.catchError(
() => { throw new TypeError('test'); });
assert(err instanceof TypeError);
assert.strictEqual(err.message, 'test');
const msg = binding.error.catchErrorMessage(
() => { throw new TypeError('test'); });
assert.strictEqual(msg, 'test');
assert.throws(() => binding.error.throwErrorThatEscapesScope('test'), function(err) {
return err instanceof Error && err.message === 'test';
});
assert.throws(() => binding.error.catchAndRethrowErrorThatEscapesScope('test'), function(err) {
return err instanceof Error && err.message === 'test' && err.caught;
});
const p = require('./napi_child').spawnSync(
process.execPath, [ __filename, 'fatal', bindingPath ]);
assert.ifError(p.error);
assert.ok(p.stderr.toString().includes(
'FATAL ERROR: Error::ThrowFatalError This is a fatal error'));
}
| Java |
using System.Web;
using System.Web.Optimization;
namespace WebAPI.Boilerplate.Api
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| Java |
//
// YYBaseLib.h
// YYBaseLib
//
// Created by 银羽网络 on 16/7/19.
// Copyright © 2016年 银羽网络. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppConfig.h"
#import "BaseViewController.h"
#import "CommonTool.h"
#import "DataVerify.h"
#import "FSMediaPicker.h"
#import "MBProgressHUD+MBProgressHUD_Category.h"
#import "EnumModel.h"
#import "UsersModel.h"
#import "NSDataAdditions.h"
#import "NSDate_Extensions.h"
#import "NSDictionary_Extensions.h"
#import "NSObject_Extensions.h"
#import "NSString_Extensions.h"
#import "UIImageExtentions.h"
#import "UILabel_Extensions.h"
#import "PopupBaseView.h"
#import "SDCycleScrollView.h"
#import "UIButton+FillColor.h"
#import "UIColor_Extensions.h"
#import "UIImage+UIImage.h"
#import "UIImage+UIImageScale.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UITextView+Placeholder.h"
#import "UIView+extensions.h"
#import "UIView+Masonry.h"
#import "AuthService.h"
#import "AppManager.h"
#import "ApiService.h"
#import "GTMBase64.h"
#import "GTMDefines.h"
#import "ConsultGradeModel.h"
#import "CategoryModel.h"
#import "CityModel.h"
#import "MenuModel.h"
//! Project version number for YYBaseLib.
FOUNDATION_EXPORT double YYBaseLibVersionNumber;
//! Project version string for YYBaseLib.
FOUNDATION_EXPORT const unsigned char YYBaseLibVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <YYBaseLib/PublicHeader.h>
| Java |
<table id="member_table" class="mainTable padTable" style="width:100%;" cellspacing="0" cellpadding="0" border="0">
<thead>
<tr>
<th style="width:3%;" ><?=$lang_id?></th>
<th style="width:22%;"><?=$lang_name?></th>
<th style="width:15%;"><?=$lang_total_friends?></th>
<th style="width:15%;"><?=$lang_total_reciprocal_friends?></th>
<th style="width:15%;"><?=$lang_total_blocked_friends?></th>
<th style="width:15%;"><?=$lang_friends_groups_public?></th>
<th style="width:15%;"><?=$lang_friends_groups_private?></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><?=$member['member_id']?></td>
<td><?=$member['screen_name']?></td>
<td><?=$member['total_friends']?></td>
<td><?=$member['total_reciprocal_friends']?></td>
<td><?=$member['total_blocked_friends']?></td>
<td><?=$member['friends_groups_public']?></td>
<td><?=$member['friends_groups_private']?></td>
</tr>
</tbody>
</table>
<?php if ( count( $friends ) == 0 ) : ?>
<p><span class="notice"><?=$member['screen_name']?><?=$lang__added_no_friends_yet?></span></p>
<?php else: ?>
<form action="<?=$form_uri?>" method="post" id="delete_friend_form">
<input type="hidden" name="XID" value="<?=$XID_SECURE_HASH?>" />
<input type="hidden" name="member_id" value="<?=$member['member_id']?>" />
<table class="mainTable padTable magicCheckboxTable"
style="width:100%;" cellspacing="0" cellpadding="0" border="0">
<thead>
<tr>
<th style="width:3%;"> </th>
<th style="width:7%;">
<input class="checkbox" type="checkbox"
name="toggle_all_checkboxes" value="" /> <?=$lang_delete?>
</th>
<th style="width:30%;"><?=$lang_name?></th>
<th style="width:20%;"><?=$lang_date?></th>
<th style="width:15%;"><?=$lang_reciprocal?></th>
<th style="width:15%;"><?=$lang_blocked?></th>
<th style="width:10%;"><?=$lang_total_friends?></th>
</tr>
</thead>
<tbody>
<?php foreach ( $friends as $key => $val ) :
$key = $key + 1 + $row_count;
$switch = $this->cycle('odd', 'even'); ?>
<tr class="<?=$switch?>">
<td><?=$key?></td>
<td>
<input class="checkbox" type="checkbox"
name="toggle[]" value="<?=$val['entry_id']?>" id="delete_box_<?=$key?>" />
</td>
<td>
<a href="<?=$val['friend_uri']?>"
title="<?=$lang_view_friends_of_?><?=$val['screen_name']?>">
<?=$val['screen_name']; ?></a>
</td>
<td><?=$val['date']?></td>
<td><?=$val['reciprocal']?></td>
<td><?=$val['block']?></td>
<td><?=$val['total_friends']?></td>
</tr>
<?php endforeach; ?>
<?php $switch = $this->cycle('odd', 'even'); ?>
<tr class="<?=$switch?>">
<td> </td>
<td colspan="6">
<input class="checkbox" type="checkbox"
name="toggle_all_checkboxes" value="" /> <strong><?=$lang_delete?></strong>
</td>
</tr>
<?php if ( $paginate !== '' ) : ?>
<?php $switch = $this->cycle('odd', 'even'); ?>
<tr class="<?=$switch?>">
<td colspan="7">
<?=$paginate?>
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<p><input type="submit" class="submit" value="<?=$lang_delete?>" /></p>
</form>
<?php endif; ?> | Java |
package redes3.proyecto.nagiosalert;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class InfoServiceActivity extends Activity {
String nombre;
int status;
String duracion;
String revision;
String info;
ImageView image ;
TextView tvNombre ;
TextView tvStatus ;
TextView tvDuracion ;
TextView tvRevision ;
TextView tvInfo ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_service);
nombre = new String();
status = 0 ;
duracion = new String();
revision = new String();
info = new String();
image = (ImageView) findViewById(R.id.image);
tvNombre = (TextView)this.findViewById(R.id.tvNombreServicio);
tvStatus = (TextView)this.findViewById(R.id.status);
tvDuracion = (TextView)this.findViewById(R.id.duracion);
tvRevision = (TextView)this.findViewById(R.id.revision);
tvInfo = (TextView)this.findViewById(R.id.info);
Bundle extras = getIntent().getExtras();
nombre = extras.getString("nombre");
status = extras.getInt("status");
duracion = extras.getString("duracion");
revision = extras.getString("revision");
info = extras.getString("info");
tvNombre.setText(nombre);
tvDuracion.setText("Duracion : \n"+duracion);
tvRevision.setText("Revision : \n"+revision);
tvInfo.setText("Descripción : \n"+info);
if(status== 0){
tvStatus.setText("Estado : \nOk");
image.setImageResource(R.drawable.fine);
}else if(status== 1){
tvStatus.setText("Estado : \nFail");
image.setImageResource(R.drawable.fail);
}if(status== 2){
tvStatus.setText("Estado : \nWarning");
image.setImageResource(R.drawable.warning);
}if(status== 3){
tvStatus.setText("Estado : \nUnknown");
image.setImageResource(R.drawable.unknown);
}
}
} | Java |
---
layout: post
title: !binary |-
Rm9vbOKAmXMgV29ybGQgTWFw
tags:
- micrographic
---
Hoy me he encontrado en Microsiervos y en Halón disparado una cosa realmente curiosa, una revisión freakie del mapa del mundo! Se trata de un mapa donde los países están colocados donde la gente (yanquis, claro) cree que están. El resultado es impagable, de verdad.
| Java |
#include "MultiSelection.h"
#include "ofxCogEngine.h"
#include "EnumConverter.h"
#include "Node.h"
namespace Cog {
void MultiSelection::Load(Setting& setting) {
string group = setting.GetItemVal("selection_group");
if (group.empty()) CogLogError("MultiSelection", "Error while loading MultiSelection behavior: expected parameter selection_group");
this->selectionGroup = StrId(group);
// load all attributes
string defaultImg = setting.GetItemVal("default_img");
string selectedImg = setting.GetItemVal("selected_img");
if (!defaultImg.empty() && !selectedImg.empty()) {
this->defaultImg = CogGet2DImage(defaultImg);
this->selectedImg = CogGet2DImage(selectedImg);
}
else {
string defaultColorStr = setting.GetItemVal("default_color");
string selectedColorStr = setting.GetItemVal("selected_color");
if (!defaultColorStr.empty() && !selectedColorStr.empty()) {
this->defaultColor = EnumConverter::StrToColor(defaultColorStr);
this->selectedColor = EnumConverter::StrToColor(selectedColorStr);
}
}
}
void MultiSelection::OnInit() {
SubscribeForMessages(ACT_OBJECT_HIT_ENDED, ACT_STATE_CHANGED);
}
void MultiSelection::OnStart() {
CheckState();
owner->SetGroup(selectionGroup);
}
void MultiSelection::OnMessage(Msg& msg) {
if (msg.HasAction(ACT_OBJECT_HIT_ENDED) && msg.GetContextNode()->IsInGroup(selectionGroup)) {
// check if the object has been clicked (user could hit a different area and release touch over the button)
auto evt = msg.GetDataPtr<InputEvent>();
if (evt->input->handlerNodeId == msg.GetContextNode()->GetId()) {
ProcessHit(msg, false);
}
}
else if (msg.HasAction(ACT_STATE_CHANGED) && msg.GetContextNode()->IsInGroup(selectionGroup)) {
ProcessHit(msg, true); // set directly, because STATE_CHANGED event has been already invoked
}
}
void MultiSelection::ProcessHit(Msg& msg, bool setDirectly) {
if (msg.GetContextNode()->GetId() == owner->GetId()) {
// selected actual node
if (!owner->HasState(selectedState)) {
if (setDirectly) owner->GetStates().SetState(selectedState);
else owner->SetState(selectedState);
SendMessage(ACT_OBJECT_SELECTED);
CheckState();
}
else {
CheckState();
}
}
else {
if (owner->HasState(selectedState)) {
if (setDirectly) owner->GetStates().ResetState(selectedState);
else owner->ResetState(selectedState);
CheckState();
}
}
}
void MultiSelection::CheckState() {
if (owner->HasState(selectedState)) {
if (selectedImg) {
owner->GetMesh<Image>()->SetImage(selectedImg);
}
else {
owner->GetMesh()->SetColor(selectedColor);
}
}
else if (!owner->HasState(selectedState)) {
if (defaultImg) {
owner->GetMesh<Image>()->SetImage(defaultImg);
}
else {
owner->GetMesh()->SetColor(defaultColor);
}
}
}
}// namespace | Java |
// The MIT License (MIT)
//
// Copyright (c) 2016 Tim Jones
//
// 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.
package io.github.jonestimd.finance.file;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import io.github.jonestimd.finance.domain.transaction.Transaction;
import io.github.jonestimd.finance.swing.transaction.TransactionTableModel;
import static io.github.jonestimd.util.JavaPredicates.*;
public class Reconciler {
private final TransactionTableModel tableModel;
private final List<Transaction> uncleared;
public Reconciler(TransactionTableModel tableModel) {
this.tableModel = tableModel;
this.uncleared = tableModel.getBeans().stream()
.filter(not(Transaction::isCleared)).filter(not(Transaction::isNew))
.collect(Collectors.toList());
}
public void reconcile(Collection<Transaction> transactions) {
transactions.forEach(this::reconcile);
}
private void reconcile(Transaction transaction) {
Transaction toClear = select(transaction);
if (toClear.isNew()) {
toClear.setCleared(true);
tableModel.queueAdd(tableModel.getBeanCount()-1, toClear);
}
else {
tableModel.setValueAt(true, tableModel.rowIndexOf(toClear), tableModel.getClearedColumn());
}
}
private Transaction select(Transaction transaction) {
return uncleared.stream().filter(sameProperties(transaction)).min(nearestDate(transaction)).orElse(transaction);
}
private Predicate<Transaction> sameProperties(Transaction transaction) {
return t2 -> transaction.getAmount().compareTo(t2.getAmount()) == 0
&& transaction.getAssetQuantity().compareTo(t2.getAssetQuantity()) == 0
&& Objects.equals(transaction.getPayee(), t2.getPayee())
&& Objects.equals(transaction.getSecurity(), t2.getSecurity());
}
private Comparator<Transaction> nearestDate(Transaction transaction) {
return Comparator.comparingInt(t -> transaction.getDate().compareTo(t.getDate()));
}
}
| Java |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class AddTemplatesToEvents extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('events', function (Blueprint $table) {
$table->string('template')->default('show');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('events', function ($table) {
$table->dropColumn('template');
});
}
}
| Java |
package plugin_test
import (
"path/filepath"
"code.cloudfoundry.org/cli/utils/testhelpers/pluginbuilder"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestPlugin(t *testing.T) {
RegisterFailHandler(Fail)
pluginbuilder.BuildTestBinary(filepath.Join("..", "fixtures", "plugins"), "test_1")
RunSpecs(t, "Plugin Suite")
}
| Java |
var express = require('express'),
compression = require('compression'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
session = require('express-session'),
flash = require('connect-flash'),
moment = require('moment'),
mongoose = require('mongoose'),
MongoStore = require('connect-mongo')(session),
Pclog = require('./models/pclog.js'),
configDB = require('./config/database.js');
mongoose.Promise = global.Promise = require('bluebird');
mongoose.connect(configDB.uri);
var routes = require('./routes/index'),
reports = require('./routes/reports'),
statistics = require('./routes/statistics'),
charts = require('./routes/charts'),
logs = require('./routes/logs'),
organization = require('./routes/organization'),
users = require('./routes/users');
var app = express();
//var rootFolder = __dirname;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compression());
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'safe_session_cat',
resave: true,
rolling: true,
saveUninitialized: false,
cookie: {secure: false, maxAge: 900000},
store: new MongoStore({ url: configDB.uri })
}));
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', function(req,res,next){
app.locals.currentUrl = req.path;
app.locals.moment = moment;
res.locals.messages = require('express-messages')(req, res);
if(req.session & req.session.user){
app.locals.user = req.session.user;
}
console.log(app.locals.user);
next();
});
app.use('/', routes);
app.use('/reports', reports);
app.use('/statistics', statistics);
app.use('/charts', charts);
app.use('/logs', logs);
app.use('/organization', organization);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Page Not Found.');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
// if (app.get('env') === 'development') {
// app.use(function(err, req, res, next) {
// res.status(err.status || 500);
// res.render('error', {
// message: err.message,
// error: err
// });
// });
// }
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
if(err.status){
res.status(err.status);
}else{
err.status = 500;
err.message = "Internal Server Error."
res.status(500);
}
res.render('404', {error: err});
});
module.exports = app;
| Java |
/**
* CircularLinkedList implementation
* @author Tyler Smith
* @version 1.0
*/
public class CircularLinkedList<T> implements LinkedListInterface<T> {
private Node<T> head = null, tail = head;
private int size = 0;
@Override
public void addAtIndex(int index, T data) {
if (index < 0 || index > this.size()) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
this.addToFront(data);
} else if (index == this.size()) {
this.addToBack(data);
} else {
Node<T> current = head;
if (index == 1) {
current.setNext(new Node<T>(data, current.getNext()));
} else {
for (int i = 0; i < index - 1; i++) {
current = current.getNext();
}
Node<T> temp = current;
current = new Node<T>(data, temp);
}
size++;
}
}
@Override
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
Node<T> current = head;
for (int i = 0; i < index; i++) {
current = current.getNext();
}
return current.getData();
}
@Override
public T removeAtIndex(int index) {
if (index < 0 || index >= this.size()) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
T data = head.getData();
head = head.getNext();
tail.setNext(head);
size--;
return data;
} else {
Node<T> before = tail;
Node<T> current = head;
for (int i = 0; i < index; i++) {
before = current;
current = current.getNext();
}
T data = current.getData();
before.setNext(current.getNext());
size--;
return data;
}
}
@Override
public void addToFront(T t) {
if (this.isEmpty()) {
head = new Node<T>(t, tail);
tail = head;
tail.setNext(head);
size++;
return;
}
Node<T> node = new Node<T>(t, head);
head = node;
tail.setNext(head);
size++;
}
@Override
public void addToBack(T t) {
if (this.isEmpty()) {
tail = new Node<T>(t);
head = tail;
tail.setNext(head);
head.setNext(tail);
size++;
} else {
Node<T> temp = tail;
tail = new Node<T>(t, head);
temp.setNext(tail);
size++;
}
}
@Override
public T removeFromFront() {
if (this.isEmpty()) {
return null;
}
Node<T> ret = head;
head = head.getNext();
tail.setNext(head);
size--;
return ret.getData();
}
@Override
public T removeFromBack() {
if (this.isEmpty()) {
return null;
}
Node<T> iterate = head;
while (iterate.getNext() != tail) {
iterate = iterate.getNext();
}
iterate.setNext(head);
Node<T> ret = tail;
tail = iterate;
size--;
return ret.getData();
}
@SuppressWarnings("unchecked")
@Override
public T[] toList() {
Object[] list = new Object[this.size()];
int i = 0;
Node<T> current = head;
while (i < this.size()) {
list[i] = current.getData();
current = current.getNext();
i++;
}
return ((T[]) list);
}
@Override
public boolean isEmpty() {
return (this.size() == 0);
}
@Override
public int size() {
return size;
}
@Override
public void clear() {
head = null;
tail = null;
size = 0;
}
/**
* Reference to the head node of the linked list.
* Normally, you would not do this, but we need it
* for grading your work.
*
* @return Node representing the head of the linked list
*/
public Node<T> getHead() {
return head;
}
/**
* Reference to the tail node of the linked list.
* Normally, you would not do this, but we need it
* for grading your work.
*
* @return Node representing the tail of the linked list
*/
public Node<T> getTail() {
return tail;
}
/**
* This method is for your testing purposes.
* You may choose to implement it if you wish.
*/
@Override
public String toString() {
return "";
}
}
| Java |
---
name: Bug上报
about: 提交Bug让框架更加健壮
title: ''
labels: bug
assignees: ''
---
🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶
😁为了能够更好地复现问题和修复问题, 请提供 Demo 和详细的 bug 重现步骤😭
🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶
> 记得删除以上内容
**描述bug**
清晰简单地描述这个bug是啥
**必现/偶发?**
必现
**怎么样重现这个bug**
1. 显示哪个页面
2. 点击哪个位置
3. 滚动到哪个位置
4. 发生了什么错误
**你期望的结果是什么?**
你本来期望得到的正确结果是怎样的?就是解决bug之后的结果
**截图**
如果有必要的话,请上传几张截图
**运行环境**
- iPhone6
- iOS8.1
- Xcode10
**额外的**
最好能提供出现bug的Demo
| Java |
import { Component, OnInit } from '@angular/core';
// import { TreeModule, TreeNode } from "primeng/primeng";
import { BlogPostService } from '../shared/blog-post.service';
import { BlogPostDetails } from '../shared/blog-post.model';
@Component({
selector: 'ejc-blog-archive',
templateUrl: './blog-archive.component.html',
styleUrls: ['./blog-archive.component.scss']
})
export class BlogArchiveComponent implements OnInit {
constructor(
// private postService: BlogPostService
) { }
ngOnInit() {
}
// // it would be best if the data in the blog post details file was already organized into tree nodes
// private buildTreeNodes(): TreeNode[] {}
}
| Java |
require 'active_record'
module ActiveRecord
class Migration
def migrate_with_multidb(direction)
if defined? self.class::DATABASE_NAME
ActiveRecord::Base.establish_connection(self.class::DATABASE_NAME.to_sym)
migrate_without_multidb(direction)
ActiveRecord::Base.establish_connection(Rails.env.to_sym)
else
migrate_without_multidb(direction)
end
end
alias_method_chain :migrate, :multidb
end
end
| Java |
const os = require("os");
const fs = require("fs");
const config = {
}
let libs;
switch (os.platform()) {
case "darwin": {
libs = [
"out/Debug_x64/libpvpkcs11.dylib",
"out/Debug/libpvpkcs11.dylib",
"out/Release_x64/libpvpkcs11.dylib",
"out/Release/libpvpkcs11.dylib",
];
break;
}
case "win32": {
libs = [
"out/Debug_x64/pvpkcs11.dll",
"out/Debug/pvpkcs11.dll",
"out/Release_x64/pvpkcs11.dll",
"out/Release/pvpkcs11.dll",
];
break;
}
default:
throw new Error("Cannot get pvpkcs11 compiled library. Unsupported OS");
}
config.lib = libs.find(o => fs.existsSync(o));
if (!config.lib) {
throw new Error("config.lib is empty");
}
module.exports = config; | Java |
class RenameMembers < ActiveRecord::Migration[5.1]
def change
rename_table :members, :memberships
end
end
| Java |
using System;
using Xunit;
using System.Linq;
using hihapi.Models;
using hihapi.Controllers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.OData.Results;
using hihapi.test.common;
namespace hihapi.unittest.Finance
{
[Collection("HIHAPI_UnitTests#1")]
public class FinanceDocumentTypesControllerTest
{
private SqliteDatabaseFixture fixture = null;
public FinanceDocumentTypesControllerTest(SqliteDatabaseFixture fixture)
{
this.fixture = fixture;
}
[Theory]
[InlineData("")]
[InlineData(DataSetupUtility.UserA)]
public async Task TestCase_Read(string strusr)
{
var context = fixture.GetCurrentDataContext();
// 1. Read it without User assignment
var control = new FinanceDocumentTypesController(context);
if (String.IsNullOrEmpty(strusr))
{
var userclaim = DataSetupUtility.GetClaimForUser(strusr);
control.ControllerContext = new ControllerContext()
{
HttpContext = new DefaultHttpContext() { User = userclaim }
};
}
var getresult = control.Get();
Assert.NotNull(getresult);
var getokresult = Assert.IsType<OkObjectResult>(getresult);
var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value);
Assert.NotNull(getqueryresult);
if (String.IsNullOrEmpty(strusr))
{
var dbcategories = (from tt in context.FinDocumentTypes
where tt.HomeID == null
select tt).ToList<FinanceDocumentType>();
Assert.Equal(dbcategories.Count, getqueryresult.Count());
}
await context.DisposeAsync();
}
[Theory]
[InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, "Test 1")]
[InlineData(DataSetupUtility.UserB, DataSetupUtility.Home2ID, "Test 2")]
public async Task TestCase_CRUD(string currentUser, int hid, string name)
{
var context = fixture.GetCurrentDataContext();
// 1. Read it out before insert.
var control = new FinanceDocumentTypesController(context);
var userclaim = DataSetupUtility.GetClaimForUser(currentUser);
control.ControllerContext = new ControllerContext()
{
HttpContext = new DefaultHttpContext() { User = userclaim }
};
var getresult = control.Get();
Assert.NotNull(getresult);
var getokresult = Assert.IsType<OkObjectResult>(getresult);
var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value);
Assert.NotNull(getqueryresult);
// 2. Insert a new one.
FinanceDocumentType ctgy = new FinanceDocumentType();
ctgy.HomeID = hid;
ctgy.Name = name;
ctgy.Comment = name;
var postresult = await control.Post(ctgy);
var createdResult = Assert.IsType<CreatedODataResult<FinanceDocumentType>>(postresult);
Assert.NotNull(createdResult);
short nctgyid = createdResult.Entity.ID;
Assert.Equal(hid, createdResult.Entity.HomeID);
Assert.Equal(ctgy.Name, createdResult.Entity.Name);
Assert.Equal(ctgy.Comment, createdResult.Entity.Comment);
// 3. Read it out
var getsingleresult = control.Get(nctgyid);
Assert.NotNull(getsingleresult);
var getctgy = Assert.IsType<FinanceDocumentType>(getsingleresult);
Assert.Equal(hid, getctgy.HomeID);
Assert.Equal(ctgy.Name, getctgy.Name);
Assert.Equal(ctgy.Comment, getctgy.Comment);
// 4. Change it
getctgy.Comment += "Changed";
var putresult = control.Put(nctgyid, getctgy);
Assert.NotNull(putresult);
// 5. Delete it
var deleteresult = control.Delete(nctgyid);
Assert.NotNull(deleteresult);
await context.DisposeAsync();
}
}
}
| Java |
<?php
# MantisBT - a php based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* @package MantisBT
* @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright (C) 2002 - 2011 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*/
/**
* MantisBT Core API's
*/
require_once( 'core.php' );
require_once( 'email_api.php' );
form_security_validate( 'signup' );
$f_username = strip_tags( gpc_get_string( 'username' ) );
$f_email = strip_tags( gpc_get_string( 'email' ) );
$f_captcha = gpc_get_string( 'captcha', '' );
$f_public_key = gpc_get_int( 'public_key', '' );
$f_username = trim( $f_username );
$f_email = email_append_domain( trim( $f_email ) );
$f_captcha = utf8_strtolower( trim( $f_captcha ) );
# force logout on the current user if already authenticated
if( auth_is_user_authenticated() ) {
auth_logout();
}
# Check to see if signup is allowed
if ( OFF == config_get_global( 'allow_signup' ) ) {
print_header_redirect( 'login_page.php' );
exit;
}
if( ON == config_get( 'signup_use_captcha' ) && get_gd_version() > 0 &&
helper_call_custom_function( 'auth_can_change_password', array() ) ) {
# captcha image requires GD library and related option to ON
$t_key = utf8_strtolower( utf8_substr( md5( config_get( 'password_confirm_hash_magic_string' ) . $f_public_key ), 1, 5) );
if ( $t_key != $f_captcha ) {
trigger_error( ERROR_SIGNUP_NOT_MATCHING_CAPTCHA, ERROR );
}
}
email_ensure_not_disposable( $f_email );
# notify the selected group a new user has signed-up
if( user_signup( $f_username, $f_email ) ) {
email_notify_new_account( $f_username, $f_email );
}
form_security_purge( 'signup' );
html_page_top1();
html_page_top2a();
?>
<br />
<div align="center">
<table class="width50" cellspacing="1">
<tr>
<td class="center">
<b><?php echo lang_get( 'signup_done_title' ) ?></b><br />
<?php echo "[$f_username - $f_email] " ?>
</td>
</tr>
<tr>
<td>
<br />
<?php echo lang_get( 'password_emailed_msg' ) ?>
<br /><br />
<?php echo lang_get( 'no_reponse_msg') ?>
<br /><br />
</td>
</tr>
</table>
<br />
<?php print_bracket_link( 'login_page.php', lang_get( 'proceed' ) ); ?>
</div>
<?php
html_page_bottom1a( __FILE__ );
| Java |
team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Essendon",
"ME": "Melbourne",
"NM": "North Melbourne",
"PA": "Port Adelaide",
"BL": "Brisbane Lions",
"SK": "St Kilda"
}
def get_team_name(code):
return team_mapping[code]
def get_team_code(full_name):
for code, name in team_mapping.items():
if name == full_name:
return code
return full_name
def get_match_description(response):
match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0]
match_details = match_container.xpath(".//text()").extract()
return {
"round": match_details[1],
"venue": match_details[3],
"date": match_details[6],
"attendance": match_details[8],
"homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(),
"awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(),
"homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()),
"awayScore": int(response.xpath("//table[1]/tr[3]/td[5]/b/text()").extract_first())
}
def get_match_urls(response):
for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract():
yield response.urljoin(match) | Java |
from keras.applications import imagenet_utils
from keras.applications import mobilenet
def dummyPreprocessInput(image):
image -= 127.5
return image
def getPreprocessFunction(preprocessType):
if preprocessType == "dummy":
return dummyPreprocessInput
elif preprocessType == "mobilenet":
return mobilenet.preprocess_input
elif preprocessType == "imagenet":
return imagenet_utils.preprocess_input
else:
raise Exception(preprocessType + " not supported")
| Java |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace TheS.Runtime
{
internal class CallbackException : FatalException
{
public CallbackException()
{
}
public CallbackException(string message, Exception innerException) : base(message, innerException)
{
// This can't throw something like ArgumentException because that would be worse than
// throwing the callback exception that was requested.
Fx.Assert(innerException != null, "CallbackException requires an inner exception.");
Fx.Assert(!Fx.IsFatal(innerException), "CallbackException can't be used to wrap fatal exceptions.");
}
}
}
| Java |
<?php
namespace App\Http\Controllers;
use App\Jobs\GetInstance;
use App\Models\Build;
use App\Models\Commit;
use App\Models\Repository;
use App\RepositoryProviders\GitHub;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller
{
public function index()
{
$repositories = Repository::all();
$commits = Commit::select('branch', DB::raw('max(created_at) as created_at'))
->orderBy('created_at', 'desc')
->groupBy('branch')
->get();
$masterInfo = Commit::getBranchInfo('master');
$branches = [];
foreach ($commits as $commit) {
$info = Commit::getBranchInfo($commit->branch);
$branches[] = [
'branch' => $commit->branch,
'status' => $info['status'],
'label' => $info['label'],
'last_commit_id' => $info['last_commit_id'],
];
}
return view('dashboard', compact('repositories', 'branches', 'masterInfo'));
}
public function build(Commit $commit, $attempt = null)
{
$count = Build::where(['commit_id' => $commit->id])->count();
$query = Build::where(['commit_id' => $commit->id])
->orderBy('attempt', 'desc');
if ($attempt) {
$query->where(['attempt' => $attempt]);
}
$build = $query->first();
$logs = json_decode($build->log, true);
$next = $build->attempt < $count ? "/build/$build->id/" . ($build->attempt + 1) : null;
return view('build', compact('build', 'commit', 'attempt', 'logs', 'count', 'next'));
}
public function rebuild(Build $build)
{
$rebuild = new Build();
$rebuild->commit_id = $build->commit_id;
$rebuild->attempt = $build->attempt + 1;
$rebuild->status = 'QUEUED';
$rebuild->save();
$github = new GitHub(
$rebuild->commit->repository->name,
$rebuild->commit->commit_id,
env('PROJECT_URL') . '/build/' . $rebuild->commit_id
);
$github->notifyPendingBuild();
dispatch(new GetInstance($rebuild->id));
return redirect("/build/$rebuild->commit_id");
}
}
| Java |
#pragma once
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief OpenGL。
*/
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../types/types.h"
#pragma warning(pop)
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../actionbatching/actionbatching.h"
#pragma warning(pop)
/** include
*/
#include "./opengl_impl.h"
#include "./opengl_impl_include.h"
/** NBsys::NOpengl
*/
#if(BSYS_OPENGL_ENABLE)
#pragma warning(push)
#pragma warning(disable:4710)
namespace NBsys{namespace NOpengl
{
/** バーテックスバッファ作成。
*/
class Opengl_Impl_ActionBatching_Shader_Load : public NBsys::NActionBatching::ActionBatching_ActionItem_Base
{
private:
/** opengl_impl
*/
Opengl_Impl& opengl_impl;
/** shaderlayout
*/
sharedptr<Opengl_ShaderLayout> shaderlayout;
/** asyncresult
*/
AsyncResult<bool> asyncresult;
public:
/** constructor
*/
Opengl_Impl_ActionBatching_Shader_Load(Opengl_Impl& a_opengl_impl,const sharedptr<Opengl_ShaderLayout>& a_shaderlayout,AsyncResult<bool>& a_asyncresult)
:
opengl_impl(a_opengl_impl),
shaderlayout(a_shaderlayout),
asyncresult(a_asyncresult)
{
}
/** destructor
*/
virtual ~Opengl_Impl_ActionBatching_Shader_Load()
{
}
private:
/** copy constructor禁止。
*/
Opengl_Impl_ActionBatching_Shader_Load(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete;
/** コピー禁止。
*/
void operator =(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete;
public:
/** アクション開始。
*/
virtual void Start()
{
}
/** アクション中。
*/
virtual s32 Do(f32& a_delta,bool a_endrequest)
{
if(a_endrequest == true){
//中断。
}
if(this->shaderlayout->IsBusy() == true){
//継続。
a_delta -= 1.0f;
return 0;
}
//Render_LoadShader
this->opengl_impl.Render_LoadShader(this->shaderlayout);
//asyncresult
this->asyncresult.Set(true);
//成功。
return 1;
}
};
}}
#pragma warning(pop)
#endif
| Java |
<?php
namespace Vich\UploaderBundle\Mapping;
use Vich\UploaderBundle\Naming\NamerInterface;
/**
* PropertyMapping.
*
* @author Dustin Dobervich <ddobervich@gmail.com>
*/
class PropertyMapping
{
/**
* @var \ReflectionProperty $property
*/
protected $property;
/**
* @var \ReflectionProperty $fileNameProperty
*/
protected $fileNameProperty;
/**
* @var NamerInterface $namer
*/
protected $namer;
/**
* @var array $mapping
*/
protected $mapping;
/**
* @var string $mappingName
*/
protected $mappingName;
/**
* Gets the reflection property that represents the
* annotated property.
*
* @return \ReflectionProperty The property.
*/
public function getProperty()
{
return $this->property;
}
/**
* Sets the reflection property that represents the annotated
* property.
*
* @param \ReflectionProperty $property The reflection property.
*/
public function setProperty(\ReflectionProperty $property)
{
$this->property = $property;
$this->property->setAccessible(true);
}
/**
* Gets the reflection property that represents the property
* which holds the file name for the mapping.
*
* @return \ReflectionProperty The reflection property.
*/
public function getFileNameProperty()
{
return $this->fileNameProperty;
}
/**
* Sets the reflection property that represents the property
* which holds the file name for the mapping.
*
* @param \ReflectionProperty $fileNameProperty The reflection property.
*/
public function setFileNameProperty(\ReflectionProperty $fileNameProperty)
{
$this->fileNameProperty = $fileNameProperty;
$this->fileNameProperty->setAccessible(true);
}
/**
* Gets the configured namer.
*
* @return null|NamerInterface The namer.
*/
public function getNamer()
{
return $this->namer;
}
/**
* Sets the namer.
*
* @param \Vich\UploaderBundle\Naming\NamerInterface $namer The namer.
*/
public function setNamer(NamerInterface $namer)
{
$this->namer = $namer;
}
/**
* Determines if the mapping has a custom namer configured.
*
* @return bool True if has namer, false otherwise.
*/
public function hasNamer()
{
return null !== $this->namer;
}
/**
* Sets the configured configuration mapping.
*
* @param array $mapping The mapping;
*/
public function setMapping(array $mapping)
{
$this->mapping = $mapping;
}
/**
* Gets the configured configuration mapping name.
*
* @return string The mapping name.
*/
public function getMappingName()
{
return $this->mappingName;
}
/**
* Sets the configured configuration mapping name.
*
* @param $mappingName The mapping name.
*/
public function setMappingName($mappingName)
{
$this->mappingName = $mappingName;
}
/**
* Gets the name of the annotated property.
*
* @return string The name.
*/
public function getPropertyName()
{
return $this->property->getName();
}
/**
* Gets the value of the annotated property.
*
* @param object $obj The object.
* @return UploadedFile The file.
*/
public function getPropertyValue($obj)
{
return $this->property->getValue($obj);
}
/**
* Gets the configured file name property name.
*
* @return string The name.
*/
public function getFileNamePropertyName()
{
return $this->fileNameProperty->getName();
}
/**
* Gets the configured upload directory.
*
* @return string The configured upload directory.
*/
public function getUploadDir()
{
return $this->mapping['upload_dir'];
}
/**
* Determines if the file should be deleted upon removal of the
* entity.
*
* @return bool True if delete on remove, false otherwise.
*/
public function getDeleteOnRemove()
{
return $this->mapping['delete_on_remove'];
}
/**
* Determines if the uploadable field should be injected with a
* Symfony\Component\HttpFoundation\File\File instance when
* the object is loaded from the datastore.
*
* @return bool True if the field should be injected, false otherwise.
*/
public function getInjectOnLoad()
{
return $this->mapping['inject_on_load'];
}
}
| Java |
-------------------------------------------------------------------
-- The Long night
-- The night gives me black eyes, but I use it to find the light.
-- In 2017
-- 公共状态
-------------------------------------------------------------------
L_StatePublic = {}
setmetatable(L_StatePublic, {__index = _G})
local _this = L_StatePublic
_this.stateNone = function (o , eNtity)
local state = L_State.New(o , eNtity)
function state:Enter()
print("------进入None状态------")
end
function state:Execute(nTime)
--do thing
end
function state:Exit()
print("------退出None状态------")
end
return state
end
_this.stateLoad = function (o , eNtity)
local state = L_State.New(o , eNtity)
function state:Enter()
print("------进入Load状态------")
self.m_nTimer = 0
self.m_nTick = 0
end
function state:Execute(nTime)
--do thing
if 0 == self.m_nTick then
self.m_nTimer = self.m_nTimer + nTime
print(self.m_nTimer)
if self.m_nTimer > 3 then
self.m_eNtity:ChangeToState(self.m_eNtity.stateNone)
end
end
end
function state:Exit()
print("------退出Load状态------")
end
return state
end
_this.stateExit = function (o , eNtity)
local state = L_State.New(o , eNtity)
function state:Enter()
print("------进入Exit状态------")
self.m_nTimer = 0
self.m_nTick = 0
end
function state:Execute(nTime)
--do thing
if 0 == self.m_nTick then
self.m_nTimer = self.m_nTimer + nTime
print(self.m_nTimer)
if self.m_nTimer > 3 then
self.m_eNtity:ChangeToState(self.m_eNtity.stateNone)
end
end
end
function state:Exit()
print("------退出Exit状态------")
end
return state
end
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./ed6c3fe87a92e6b0939903db98d3209d32dcf2e96bee3586c1c6da3985c58ae4.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | Java |
personalprojects
================
A bunch of little things I made in my freetime
### PyPong
A simple pong game made in Python and Pygame.
**Changes Made**: Made the AI a bit (a lot) worse, you can actually win now.
### Maze Runner
A maze app that uses Deep Field Search (DFS) to make a perfect maze and then uses the same algorithm in reverse to solve. Requires PyGame.
**Usage**: Run it, enter your resolution, and let it run! Press "Escape" at anytime to quit.
**Changes Made**: Exits more elegantly, colors are more visible.
### Find the Cow
A joke of a game inspired by a conversation at dinner with friends. I challenged myself to keep it under 100 lines of code. Requires PyGame.
**Usage**: Click to guess where the cow is. The volume of the "moo" indicates how far away the cow is. Once the cow is found, press spacebar to go to the next level.
**ToDo**: Add a menu, although, I want to keep this under 100 lines of code.
### Binary Clock
Something I thought I would finish, but never had the initative. It was supposed to be a simple 5 row binary clock. Maybe someday it will get a life.
| Java |
// Copyright (c) 2020 The Firo Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef FIRO_ELYSIUM_SIGMAWALLETV0_H
#define FIRO_ELYSIUM_SIGMAWALLETV0_H
#include "sigmawallet.h"
namespace elysium {
class SigmaWalletV0 : public SigmaWallet
{
public:
SigmaWalletV0();
protected:
uint32_t BIP44ChangeIndex() const;
SigmaPrivateKey GeneratePrivateKey(uint512 const &seed);
class Database : public SigmaWallet::Database {
public:
Database();
public:
bool WriteMint(SigmaMintId const &id, SigmaMint const &mint, CWalletDB *db = nullptr);
bool ReadMint(SigmaMintId const &id, SigmaMint &mint, CWalletDB *db = nullptr) const;
bool EraseMint(SigmaMintId const &id, CWalletDB *db = nullptr);
bool HasMint(SigmaMintId const &id, CWalletDB *db = nullptr) const;
bool WriteMintId(uint160 const &hash, SigmaMintId const &mintId, CWalletDB *db = nullptr);
bool ReadMintId(uint160 const &hash, SigmaMintId &mintId, CWalletDB *db = nullptr) const;
bool EraseMintId(uint160 const &hash, CWalletDB *db = nullptr);
bool HasMintId(uint160 const &hash, CWalletDB *db = nullptr) const;
bool WriteMintPool(std::vector<MintPoolEntry> const &mints, CWalletDB *db = nullptr);
bool ReadMintPool(std::vector<MintPoolEntry> &mints, CWalletDB *db = nullptr);
void ListMints(std::function<void(SigmaMintId&, SigmaMint&)> const&, CWalletDB *db = nullptr);
};
public:
using SigmaWallet::GeneratePrivateKey;
};
}
#endif // FIRO_ELYSIUM_SIGMAWALLETV0_H | Java |
# Gears #
*Documentation may be outdated or incomplete as some URLs may no longer exist.*
*Warning! This codebase is deprecated and will no longer receive support; excluding critical issues.*
A PHP class that loads template files, binds variables to a single file or globally without the need for custom placeholders/variables, allows for parent-child hierarchy and parses the template structure.
Gear is a play on words for: Engine + Gears + Structure.
* Loads any type of file into the system
* Binds variables to a single file or to all files globally
* Template files DO NOT need custom markup and placeholders for variables
* Can access and use variables in a template just as you would a PHP file
* Allows for parent-child hierarchy
* Parse a parent template to parse all children, and their children, and so on
* Can destroy template indexes on the fly
* No eval() or security flaws
* And much more...
## Introduction ##
Most of the template systems today use a very robust setup where the template files contain no server-side code. Instead they use a system where they use custom variables and markup to get the job done. For example, in your template you may have a variable called {pageTitle} and in your code you assign that variable a value of "Welcome". This is all well and good, but to be able to parse this "system", it requires loads of regex and matching/replacing/looping which can be quite slow and cumbersome. It also requires you to learn a new markup language, specific for the system you are using. Why would you want to learn a new markup language and structure simply to do an if statement or go through a loop? In Gears, the goal is to remove all that custom code, separate your markup from your code, allow the use of standard PHP functions, loops, statements, etc within templates, and much more!
## Installation ##
Install by manually downloading the library or defining a [Composer dependency](http://getcomposer.org/).
```javascript
{
"require": {
"mjohnson/gears": "4.0.0"
}
}
```
Once available, instantiate the class and create template files.
```php
// index.php
$temp = new mjohnson\gears\Gears(dirname(__FILE__) . 'templates/');
$temp->setLayout('layouts/default');
// templates/layouts/default.tpl
<!DOCTYPE html>
<html>
<head>
<title><?php echo $pageTitle; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php echo $this->getContent(); ?>
</body>
</html>
```
Within the code block above I am initiating the class by calling `new mjohnson\gears\Gears($path)` (where `$path` is the path to your templates directory) and storing it within a `$temp` variable. Next I am setting the layout I want to use; a layout is the outer HTML that will wrap the inner content pages. Within a layout you can use `getContent()` which will output the inner HTML wherever you please.
## Binding Variables ##
It's now time to bind data to variables within your templates; to do this we use the `bind()` method. The bind method will take an array of key value pairs, or key value arguments.
```php
$temp->bind(array(
'pageTitle' => 'Gears - Template Engine',
'description' => 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.'
));
```
The way binding variables works is extremely easy to understand. In the data being binded, the key is the name of the variable within the template, and the value is what the variable will be output. For instance the variable pageTitle (Gears - Template Engine) above will be assigned to the variable `$pageTitle` within the `layouts/default.tpl`.
Variables are binded globally to all templates, includes and the layout.
## Displaying the Templates ##
To render templates, use the `display()` method. The display method takes two arguments, the name of the template you want to display and the key to use for caching.
```php
echo $temp->display('index');
```
The second argument defines the name of the key to use for caching. Generally it will be the same name as the template name, but you do have the option to name it whatever you please.
```php
echo $temp->display('index', 'index');
```
It's also possible to display templates within folders by separating the path with a forward slash.
```php
echo $temp->display('users/login');
```
## Opening a Template ##
To render a template within another template you would use the `open()` method. The `open()` method takes 3 arguments: the path to the template (relative to the templates folder), an array of key value pairs to define as custom scoped variables and an array of cache settings.
```php
echo $this->open('includes/footer', array('date' => date('Y'));
```
By default, includes are not cached but you can enable caching by passing true as the third argument or an array of settings. The viable settings are key and duration, where key is the name of the cached file (usually the path) and duration is the length of the cache.
```php
echo $this->open('includes/footer', array('date' => date('Y')), true);
// Custom settings
echo $this->open('includes/footer', array('date' => date('Y')), array(
'key' => 'cacheKey',
'duration' => '+10 minutes'
));
```
## Caching ##
Gears comes packaged with a basic caching mechanism. By default caching is disabled, but to enable caching you can use `setCaching()`. This method will take the cache location as its 1st argument (best to place it in the same templates folder) and the expiration duration as the 2nd argument (default +1 day).
```php
$temp->setCaching(dirname(__FILE__) . '/templates/cache/');
```
You can customize the duration by using the strtotime() format. You can also pass null as the first argument and the system will place the cache files within your template path.
```php
$temp->setCaching(null, '+15 minutes');
```
To clear all cached files, you can use `flush()`.
```php
$temp->flush();
```
For a better example of how to output cached data, refer to the tests folder within the Gears package.
| Java |
/*
* @Author: justinwebb
* @Date: 2015-09-24 21:08:23
* @Last Modified by: justinwebb
* @Last Modified time: 2015-09-24 22:19:45
*/
(function (window) {
'use strict';
window.JWLB = window.JWLB || {};
window.JWLB.View = window.JWLB.View || {};
//--------------------------------------------------------------------
// Event handling
//--------------------------------------------------------------------
var wallOnClick = function (event) {
if (event.target.tagName.toLowerCase() === 'img') {
var id = event.target.parentNode.dataset.id;
var selectedPhoto = this.photos.filter(function (photo) {
if (photo.id === id) {
photo.portrait.id = id;
return photo;
}
})[0];
this.sendEvent('gallery', selectedPhoto.portrait);
}
};
//--------------------------------------------------------------------
// View overrides
//--------------------------------------------------------------------
var addUIListeners = function () {
this.ui.wall.addEventListener('click', wallOnClick.bind(this));
};
var initUI = function () {
var isUIValid = false;
var comp = document.querySelector(this.selector);
this.ui.wall = comp;
if (this.ui.wall) {
this.reset();
isUIValid = true;
}
return isUIValid;
};
//--------------------------------------------------------------------
// Constructor
//--------------------------------------------------------------------
var Gallery = function (domId) {
// Overriden View class methods
this.initUI = initUI;
this.addUIListeners = addUIListeners;
this.name = 'Gallery';
// Instance properties
this.photos = [];
// Initialize View
JWLB.View.call(this, domId);
};
//--------------------------------------------------------------------
// Inheritance
//--------------------------------------------------------------------
Gallery.prototype = Object.create(JWLB.View.prototype);
Gallery.prototype.constructor = Gallery;
//--------------------------------------------------------------------
// Instance methods
//--------------------------------------------------------------------
Gallery.prototype.addThumb = function (data, id) {
// Store image data for future reference
var photo = {
id: id,
thumb: null,
portrait: data.size[0]
};
data.size.forEach(function (elem) {
if (elem.label === 'Square') {
photo.thumb = elem;
}
if (elem.height > photo.portrait.height) {
photo.portrait = elem;
}
});
this.photos.push(photo);
// Build thumbnail UI
var node = document.createElement('div');
node.setAttribute('data-id', id);
node.setAttribute('class', 'thumb');
var img = document.createElement('img');
img.setAttribute('src', photo.thumb.source);
img.setAttribute('title', 'id: '+ id);
node.appendChild(img);
this.ui.wall.querySelector('article[name=foobar]').appendChild(node);
};
Gallery.prototype.reset = function () {
if (this.ui.wall.children.length > 0) {
var article = this.ui.wall.children.item(0)
article.parentElement.removeChild(article);
}
var article = document.createElement('article');
article.setAttribute('name', 'foobar');
this.ui.wall.appendChild(article);
};
window.JWLB.View.Gallery = Gallery;
})(window);
| Java |
module InfinityTest
module Core
class Base
# Specify the Ruby Version Manager to run
cattr_accessor :strategy
# ==== Options
# * :rvm
# * :rbenv
# * :ruby_normal (Use when don't pass any rubies to run)
# * :auto_discover(defaults)
self.strategy = :auto_discover
# Specify Ruby version(s) to test against
#
# ==== Examples
# rubies = %w(ree jruby)
#
cattr_accessor :rubies
self.rubies = []
# Options to include in the command.
#
cattr_accessor :specific_options
self.specific_options = ''
# Test Framework to use Rspec, Bacon, Test::Unit or AutoDiscover(defaults)
# ==== Options
# * :rspec
# * :bacon
# * :test_unit (Test unit here apply to this two libs: test/unit and minitest)
# * :auto_discover(defaults)
#
# This will load a exactly a class constantize by name.
#
cattr_accessor :test_framework
self.test_framework = :auto_discover
# Framework to know the folders and files that need to monitoring by the observer.
#
# ==== Options
# * :rails
# * :rubygems
# * :auto_discover(defaults)
#
# This will load a exactly a class constantize by name.
#
cattr_accessor :framework
self.framework = :auto_discover
# Framework to observer watch the dirs.
#
# ==== Options
# * watchr
#
cattr_accessor :observer
self.observer = :watchr
# Ignore test files.
#
# ==== Examples
# ignore_test_files = [ 'spec/generators/controller_generator_spec.rb' ]
#
cattr_accessor :ignore_test_files
self.ignore_test_files = []
# Ignore test folders.
#
# ==== Examples
# # Imagine that you don't want to run integration specs.
# ignore_test_folders = [ 'spec/integration' ]
#
cattr_accessor :ignore_test_folders
self.ignore_test_folders = []
# Verbose Mode. Print commands before executing them.
#
cattr_accessor :verbose
self.verbose = true
# Set the notification framework to use with Infinity Test.
#
# ==== Options
# * :growl
# * :lib_notify
# * :auto_discover(defaults)
#
# This will load a exactly a class constantize by name.
#
cattr_writer :notifications
self.notifications = :auto_discover
# You can set directory to show images matched by the convention names.
# => http://github.com/tomas-stefano/infinity_test/tree/master/images/ )
#
# Infinity test will work on these names in the notification framework:
#
# * success (png, gif, jpeg)
# * failure (png, gif, jpeg)
# * pending (png, gif, jpeg)
#
cattr_accessor :mode
#
# => This will show images in the folder:
# http://github.com/tomas-stefano/infinity_test/tree/master/images/simpson
#
self.mode = :simpson
# Success Image to show after the tests run.
#
cattr_accessor :success_image
# Pending Image to show after the tests run.
#
cattr_accessor :pending_image
# Failure Image to show after the tests run.
#
cattr_accessor :failure_image
# Use a specific gemset for each ruby.
# OBS.: This only will work for RVM strategy.
#
cattr_accessor :gemset
# InfinityTest try to use bundler if Gemfile is present.
# Set to false if you don't want use bundler.
#
cattr_accessor :bundler
self.bundler = true
# Callbacks accessor to handle before or after all run and for each ruby!
cattr_accessor :callbacks
self.callbacks = []
# Run the observer to monitor files.
# If set to false will just <b>Run tests and exit</b>.
# Defaults to true: run tests and monitoring the files.
#
cattr_accessor :infinity_and_beyond
self.infinity_and_beyond = true
# The extension files that Infinity Test will search.
# You can observe python, erlang, etc files.
#
cattr_accessor :extension
self.extension = :rb
# Setup Infinity Test passing the ruby versions and others setting.
# <b>See the class accessors for more information.</b>
#
# ==== Examples
#
# InfinityTest::Base.setup do |config|
# config.strategy = :rbenv
# config.rubies = %w(ree jruby rbx 1.9.2)
# end
#
def self.setup
yield self
end
# Receives a object that quacks like InfinityTest::Options and do the merge with self(Base class).
#
def self.merge!(options)
ConfigurationMerge.new(self, options).merge!
end
def self.start_continuous_test_server
continuous_test_server.start
end
def self.continuous_test_server
@continuous_test_server ||= ContinuousTestServer.new(self)
end
# Just a shortcut to bundler class accessor.
#
def self.using_bundler?
bundler
end
# Just a shortcut to bundler class accessor.
#
def self.verbose?
verbose
end
# Callback method to handle before all run and for each ruby too!
#
# ==== Examples
#
# before(:all) do
# # ...
# end
#
# before(:each_ruby) do |environment|
# # ...
# end
#
# before do # if you pass not then will use :all option
# # ...
# end
#
def self.before(scope, &block)
# setting_callback(Callbacks::BeforeCallback, scope, &block)
end
# Callback method to handle after all run and for each ruby too!
#
# ==== Examples
#
# after(:all) do
# # ...
# end
#
# after(:each_ruby) do
# # ...
# end
#
# after do # if you pass not then will use :all option
# # ...
# end
#
def self.after(scope, &block)
# setting_callback(Callbacks::AfterCallback, scope, &block)
end
# Clear the terminal (Useful in the before callback)
#
def self.clear_terminal
system('clear')
end
###### This methods will be removed in the Infinity Test v2.0.1 or 2.0.2 ######
# <b>DEPRECATED:</b> Please use <tt>.notification=</tt> instead.
#
def self.notifications(notification_name = nil, &block)
if notification_name.blank?
self.class_variable_get(:@@notifications)
else
message = <<-MESSAGE
.notifications is DEPRECATED.
Use this instead:
InfinityTest.setup do |config|
config.notifications = :growl
end
MESSAGE
ActiveSupport::Deprecation.warn(message)
self.notifications = notification_name
self.instance_eval(&block) if block_given?
end
end
# <b>DEPRECATED:</b> Please use:
# <tt>success_image=</tt> or
# <tt>pending_image=</tt> or
# <tt>failure_image=</tt> or
# <tt>mode=</tt> instead.
#
def self.show_images(options)
message = <<-MESSAGE
.show_images is DEPRECATED.
Use this instead:
InfinityTest.setup do |config|
config.success_image = 'some_image.png'
config.pending_image = 'some_image.png'
config.failure_image = 'some_image.png'
config.mode = 'infinity_test_dir_that_contain_images'
end
MESSAGE
ActiveSupport::Deprecation.warn(message)
self.success_image = options[:success_image] || options[:sucess_image] if options[:success_image].present? || options[:sucess_image].present? # for fail typo in earlier versions.
self.pending_image = options[:pending_image] if options[:pending_image].present?
self.failure_image = options[:failure_image] if options[:failure_image].present?
self.mode = options[:mode] if options[:mode].present?
end
# <b>DEPRECATED:</b> Please use:
# .rubies = or
# .specific_options = or
# .test_framework = or
# .framework = or
# .verbose = or
# .gemset = instead
#
def self.use(options)
message = <<-MESSAGE
.use is DEPRECATED.
Use this instead:
InfinityTest.setup do |config|
config.rubies = %w(2.0 jruby)
config.specific_options = '-J'
config.test_framework = :rspec
config.framework = :padrino
config.verbose = true
config.gemset = :some_gemset
end
MESSAGE
ActiveSupport::Deprecation.warn(message)
self.rubies = options[:rubies] if options[:rubies].present?
self.specific_options = options[:specific_options] if options[:specific_options].present?
self.test_framework = options[:test_framework] if options[:test_framework].present?
self.framework = options[:app_framework] if options[:app_framework].present?
self.verbose = options[:verbose] unless options[:verbose].nil?
self.gemset = options[:gemset] if options[:gemset].present?
end
# <b>DEPRECATED:</b> Please use .clear_terminal instead.
#
def self.clear(option)
message = '.clear(:terminal) is DEPRECATED. Please use .clear_terminal instead.'
ActiveSupport::Deprecation.warn(message)
clear_terminal
end
def self.heuristics(&block)
# There is a spec pending.
end
def self.replace_patterns(&block)
# There is a spec pending.
end
private
# def self.setting_callback(callback_class, scope, &block)
# callback_instance = callback_class.new(scope, &block)
# self.callbacks.push(callback_instance)
# callback_instance
# end
end
end
end | Java |
<?php
session_start();
require_once('../php/conexion.php');
$conect = connect::conn();
$user = $_SESSION['usuario'];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "insert into cotidiano (dir_origen,dir_destino,semana,hora,usuario,estado) values (?,?,?,?,?,?);";
$favo = sqlsrv_query($conect,$sql,array($_POST['Dir_o'],$_POST['Dir_d'],$_POST['semana'],$_POST['reloj'],$user['usuario'],1));
if($favo){
echo 'Inserccion correcta';
}
else{
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
}else{
print "aqui la estabas cagando";
}
?>
| Java |
holiwish
========
| Java |
python -m unittest
| Java |
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.MSProjectApi.Enums
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863548(v=office.14).aspx </remarks>
[SupportByVersion("MSProject", 11,12,14)]
[EntityType(EntityType.IsEnum)]
public enum PjMonthLabel
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>57</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm = 57,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>86</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm_yy = 86,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>85</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm_yyy = 85,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>11</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_m = 11,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>10</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmm = 10,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>8</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmm_yyy = 8,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>9</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmmm = 9,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>7</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmmm_yyyy = 7,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>59</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_mm = 59,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>58</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_Mmm = 58,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>45</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_Month_mm = 45,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>61</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_mm = 61,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>60</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_Mmm = 60,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>44</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_Month_mm = 44,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>35</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelNoDateFormat = 35
}
} | Java |
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("CircleAreaAndCircumference")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CircleAreaAndCircumference")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("24a850d9-a2e2-4979-a7f8-47602b439978")]
// 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")]
| Java |
//#define USE_TOUCH_SCRIPT
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
/*
* ドラッグ操作でのカメラの移動コントロールクラス
* マウス&タッチ対応
*/
namespace GarageKit
{
[RequireComponent(typeof(Camera))]
public class FlyThroughCamera : MonoBehaviour
{
public static bool winTouch = false;
public static bool updateEnable = true;
// フライスルーのコントロールタイプ
public enum FLYTHROUGH_CONTROLL_TYPE
{
DRAG = 0,
DRAG_HOLD
}
public FLYTHROUGH_CONTROLL_TYPE controllType;
// 移動軸の方向
public enum FLYTHROUGH_MOVE_TYPE
{
XZ = 0,
XY
}
public FLYTHROUGH_MOVE_TYPE moveType;
public Collider groundCollider;
public Collider limitAreaCollider;
public bool useLimitArea = false;
public float moveBias = 1.0f;
public float moveSmoothTime = 0.1f;
public bool dragInvertX = false;
public bool dragInvertY = false;
public float rotateBias = 1.0f;
public float rotateSmoothTime = 0.1f;
public bool rotateInvert = false;
public OrbitCamera combinationOrbitCamera;
private GameObject flyThroughRoot;
public GameObject FlyThroughRoot { get{ return flyThroughRoot; } }
private GameObject shiftTransformRoot;
public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } }
private bool inputLock;
public bool IsInputLock { get{ return inputLock; } }
private object lockObject;
private Vector3 defaultPos;
private Quaternion defaultRot;
private bool isFirstTouch;
private Vector3 oldScrTouchPos;
private Vector3 dragDelta;
private Vector3 velocitySmoothPos;
private Vector3 dampDragDelta = Vector3.zero;
private Vector3 pushMoveDelta = Vector3.zero;
private float velocitySmoothRot;
private float dampRotateDelta = 0.0f;
private float pushRotateDelta = 0.0f;
public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } }
public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } }
void Awake()
{
}
void Start()
{
// 設定ファイルより入力タイプを取得
if(!ApplicationSetting.Instance.GetBool("UseMouse"))
winTouch = true;
inputLock = false;
// 地面上視点位置に回転ルートを設定する
Ray ray = new Ray(this.transform.position, this.transform.forward);
RaycastHit hitInfo;
if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity))
{
flyThroughRoot = new GameObject(this.gameObject.name + " FlyThrough Root");
flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false);
flyThroughRoot.transform.position = hitInfo.point;
flyThroughRoot.transform.rotation = Quaternion.identity;
shiftTransformRoot = new GameObject(this.gameObject.name + " ShiftTransform Root");
shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true);
shiftTransformRoot.transform.localPosition = Vector3.zero;
shiftTransformRoot.transform.localRotation = Quaternion.identity;
this.gameObject.transform.SetParent(shiftTransformRoot.transform, true);
}
else
{
Debug.LogWarning("FlyThroughCamera :: not set the ground collider !!");
return;
}
// 初期値を保存
defaultPos = flyThroughRoot.transform.position;
defaultRot = flyThroughRoot.transform.rotation;
ResetInput();
}
void Update()
{
if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0)
GetInput();
else
ResetInput();
UpdateFlyThrough();
UpdateOrbitCombination();
}
private void ResetInput()
{
isFirstTouch = true;
oldScrTouchPos = Vector3.zero;
dragDelta = Vector3.zero;
}
private void GetInput()
{
// for Touch
if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.GetTouch(0).position;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#if UNITY_STANDALONE_WIN
else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch)
{
#if !USE_TOUCH_SCRIPT
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.touches[0].position;
#else
if(TouchScript.TouchManager.Instance.PressedPointersCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position;
#endif
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#endif
// for Mouse
else
{
if(Input.GetMouseButton(0))
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.mousePosition;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
}
/// <summary>
/// Input更新のLock
/// </summary>
public void LockInput(object sender)
{
if(!inputLock)
{
lockObject = sender;
inputLock = true;
}
}
/// <summary>
/// Input更新のUnLock
/// </summary>
public void UnlockInput(object sender)
{
if(inputLock && lockObject == sender)
inputLock = false;
}
/// <summary>
/// フライスルーを更新
/// </summary>
private void UpdateFlyThrough()
{
if(!FlyThroughCamera.updateEnable || flyThroughRoot == null)
return;
// 位置
float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f);
float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
flyThroughRoot.transform.Translate(dampDragDelta, Space.Self);
pushMoveDelta = Vector3.zero;
if(useLimitArea)
{
// 移動範囲限界を設定
if(limitAreaCollider != null)
{
Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z);
flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ);
}
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y);
flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z);
}
}
}
// 方向
dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self);
pushRotateDelta = 0.0f;
}
private void UpdateOrbitCombination()
{
// 連携機能
if(combinationOrbitCamera != null && combinationOrbitCamera.OrbitRoot != null)
{
Vector3 lookPoint = combinationOrbitCamera.OrbitRoot.transform.position;
Transform orbitParent = combinationOrbitCamera.OrbitRoot.transform.parent;
combinationOrbitCamera.OrbitRoot.transform.parent = null;
flyThroughRoot.transform.LookAt(lookPoint, Vector3.up);
flyThroughRoot.transform.rotation = Quaternion.Euler(
0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f);
combinationOrbitCamera.OrbitRoot.transform.parent = orbitParent;
}
}
/// <summary>
/// 目標位置にカメラを移動させる
/// </summary>
public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.DOMove(targetPosition, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 指定値でカメラを移動させる
/// </summary>
public void TranslateToFlyThrough(Vector3 move)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.Translate(move, Space.Self);
}
/// <summary>
/// 目標方向にカメラを回転させる
/// </summary>
public void RotateToFlyThrough(float targetAngle, float time = 1.0f)
{
dampRotateDelta = 0.0f;
Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles;
targetEulerAngles.y = targetAngle;
flyThroughRoot.transform.DORotate(targetEulerAngles, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 外部トリガーで移動させる
/// </summary>
public void PushMove(Vector3 move)
{
pushMoveDelta = move;
}
/// <summary>
/// 外部トリガーでカメラ方向を回転させる
/// </summary>
public void PushRotate(float rotate)
{
pushRotateDelta = rotate;
}
/// <summary>
/// フライスルーを初期化
/// </summary>
public void ResetFlyThrough()
{
ResetInput();
MoveToFlyThrough(defaultPos);
RotateToFlyThrough(defaultRot.eulerAngles.y);
}
}
}
| Java |
"use strict";
const readdir = require("../../");
const dir = require("../utils/dir");
const { expect } = require("chai");
const through2 = require("through2");
const fs = require("fs");
let nodeVersion = parseFloat(process.version.substr(1));
describe("Stream API", () => {
it("should be able to pipe to other streams as a Buffer", done => {
let allData = [];
readdir.stream("test/dir")
.pipe(through2((data, enc, next) => {
try {
// By default, the data is streamed as a Buffer
expect(data).to.be.an.instanceOf(Buffer);
// Buffer.toString() returns the file name
allData.push(data.toString());
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", err => {
done(err);
});
});
it('should be able to pipe to other streams in "object mode"', done => {
let allData = [];
readdir.stream("test/dir")
.pipe(through2({ objectMode: true }, (data, enc, next) => {
try {
// In "object mode", the data is a string
expect(data).to.be.a("string");
allData.push(data);
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", err => {
done(err);
});
});
it('should be able to pipe fs.Stats to other streams in "object mode"', done => {
let allData = [];
readdir.stream("test/dir", { stats: true })
.pipe(through2({ objectMode: true }, (data, enc, next) => {
try {
// The data is an fs.Stats object
expect(data).to.be.an("object");
expect(data).to.be.an.instanceOf(fs.Stats);
allData.push(data.path);
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", done);
});
it("should be able to pause & resume the stream", done => {
let allData = [];
let stream = readdir.stream("test/dir")
.on("data", data => {
allData.push(data);
// The stream should not be paused
expect(stream.isPaused()).to.equal(false);
if (allData.length === 3) {
// Pause for one second
stream.pause();
setTimeout(() => {
try {
// The stream should still be paused
expect(stream.isPaused()).to.equal(true);
// The array should still only contain 3 items
expect(allData).to.have.lengthOf(3);
// Read the rest of the stream
stream.resume();
}
catch (e) {
done(e);
}
}, 1000);
}
})
.on("end", () => {
expect(allData).to.have.same.members(dir.shallow.data);
done();
})
.on("error", done);
});
it('should be able to use "readable" and "read"', done => {
let allData = [];
let nullCount = 0;
let stream = readdir.stream("test/dir")
.on("readable", () => {
// Manually read the next chunk of data
let data = stream.read();
while (true) { // eslint-disable-line
if (data === null) {
// The stream is done
nullCount++;
break;
}
else {
// The data should be a string (the file name)
expect(data).to.be.a("string").with.length.of.at.least(1);
allData.push(data);
data = stream.read();
}
}
})
.on("end", () => {
if (nodeVersion >= 12) {
// In Node >= 12, the "readable" event fires twice,
// and stream.read() returns null twice
expect(nullCount).to.equal(2);
}
else if (nodeVersion >= 10) {
// In Node >= 10, the "readable" event only fires once,
// and stream.read() only returns null once
expect(nullCount).to.equal(1);
}
else {
// In Node < 10, the "readable" event fires 13 times (once per file),
// and stream.read() returns null each time
expect(nullCount).to.equal(13);
}
expect(allData).to.have.same.members(dir.shallow.data);
done();
})
.on("error", done);
});
it('should be able to subscribe to custom events instead of "data"', done => {
let allFiles = [];
let allSubdirs = [];
let stream = readdir.stream("test/dir");
// Calling "resume" is required, since we're not handling the "data" event
stream.resume();
stream
.on("file", filename => {
expect(filename).to.be.a("string").with.length.of.at.least(1);
allFiles.push(filename);
})
.on("directory", subdir => {
expect(subdir).to.be.a("string").with.length.of.at.least(1);
allSubdirs.push(subdir);
})
.on("end", () => {
expect(allFiles).to.have.same.members(dir.shallow.files);
expect(allSubdirs).to.have.same.members(dir.shallow.dirs);
done();
})
.on("error", done);
});
it('should handle errors that occur in the "data" event listener', done => {
testErrorHandling("data", dir.shallow.data, 7, done);
});
it('should handle errors that occur in the "file" event listener', done => {
testErrorHandling("file", dir.shallow.files, 3, done);
});
it('should handle errors that occur in the "directory" event listener', done => {
testErrorHandling("directory", dir.shallow.dirs, 2, done);
});
it('should handle errors that occur in the "symlink" event listener', done => {
testErrorHandling("symlink", dir.shallow.symlinks, 5, done);
});
function testErrorHandling (eventName, expected, expectedErrors, done) {
let errors = [], data = [];
let stream = readdir.stream("test/dir");
// Capture all errors
stream.on("error", error => {
errors.push(error);
});
stream.on(eventName, path => {
data.push(path);
if (path.indexOf(".txt") >= 0 || path.indexOf("dir-") >= 0) {
throw new Error("Epic Fail!!!");
}
else {
return true;
}
});
stream.on("end", () => {
try {
// Make sure the correct number of errors were thrown
expect(errors).to.have.lengthOf(expectedErrors);
for (let error of errors) {
expect(error.message).to.equal("Epic Fail!!!");
}
// All of the events should have still been emitted, despite the errors
expect(data).to.have.same.members(expected);
done();
}
catch (e) {
done(e);
}
});
stream.resume();
}
});
| Java |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Font;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class PreferredSubfamily extends AbstractTag
{
protected $Id = 17;
protected $Name = 'PreferredSubfamily';
protected $FullName = 'Font::Name';
protected $GroupName = 'Font';
protected $g0 = 'Font';
protected $g1 = 'Font';
protected $g2 = 'Document';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Preferred Subfamily';
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (10.0.2) on Fri Sep 21 22:00:31 PDT 2018 -->
<title>U-Index</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-09-21">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
<script type="text/javascript" src="../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="U-Index";
}
}
catch(err) {
}
//-->
var pathtoroot = "../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../main/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../main/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li>Next Letter</li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li>
<li><a href="index-2.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
<div class="contentContainer"><a href="index-1.html">M</a> <a href="index-2.html">U</a> <a name="I:U">
<!-- -->
</a>
<h2 class="title">U</h2>
<dl>
<dt><a href="../main/UsingTheGridLayout.html" title="class in main"><span class="typeNameLink">UsingTheGridLayout</span></a> - Class in <a href="../main/package-summary.html">main</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../main/UsingTheGridLayout.html#UsingTheGridLayout--">UsingTheGridLayout()</a></span> - Constructor for class main.<a href="../main/UsingTheGridLayout.html" title="class in main">UsingTheGridLayout</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">M</a> <a href="index-2.html">U</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../main/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../main/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li>Next Letter</li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li>
<li><a href="index-2.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
/**
* 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.
*/
package com.microsoft.azure.management.synapse.v2019_06_01_preview;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for IntegrationRuntimeState.
*/
public final class IntegrationRuntimeState extends ExpandableStringEnum<IntegrationRuntimeState> {
/** Static value Initial for IntegrationRuntimeState. */
public static final IntegrationRuntimeState INITIAL = fromString("Initial");
/** Static value Stopped for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STOPPED = fromString("Stopped");
/** Static value Started for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STARTED = fromString("Started");
/** Static value Starting for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STARTING = fromString("Starting");
/** Static value Stopping for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STOPPING = fromString("Stopping");
/** Static value NeedRegistration for IntegrationRuntimeState. */
public static final IntegrationRuntimeState NEED_REGISTRATION = fromString("NeedRegistration");
/** Static value Online for IntegrationRuntimeState. */
public static final IntegrationRuntimeState ONLINE = fromString("Online");
/** Static value Limited for IntegrationRuntimeState. */
public static final IntegrationRuntimeState LIMITED = fromString("Limited");
/** Static value Offline for IntegrationRuntimeState. */
public static final IntegrationRuntimeState OFFLINE = fromString("Offline");
/** Static value AccessDenied for IntegrationRuntimeState. */
public static final IntegrationRuntimeState ACCESS_DENIED = fromString("AccessDenied");
/**
* Creates or finds a IntegrationRuntimeState from its string representation.
* @param name a name to look for
* @return the corresponding IntegrationRuntimeState
*/
@JsonCreator
public static IntegrationRuntimeState fromString(String name) {
return fromString(name, IntegrationRuntimeState.class);
}
/**
* @return known IntegrationRuntimeState values
*/
public static Collection<IntegrationRuntimeState> values() {
return values(IntegrationRuntimeState.class);
}
}
| Java |
// Copyright 2015 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
// Base class for a module. Stores the environment and handles magic such as route annotations.
export class Module {
constructor(env) {
this.env_ = env;
let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_;
if (!decoratedRoutes)
return;
decoratedRoutes.forEach(route => {
env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]);
});
}
};
// Annotation that can be used on modules to indicate that the annotated method is the request
// handler for a |method| (GET, POST) request for |route_path|.
export function route(method, route_path) {
return (target, handler) => {
if (!target.hasOwnProperty('decoratedRoutes_'))
target.decoratedRoutes_ = [];
target.decoratedRoutes_.push({ method, route_path, handler });
};
}
| Java |
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Roland Franssen <franssen.roland@gmail.com>
*/
final class PhpUnitFqcnAnnotationFixer extends AbstractFixer
{
/**
* {@inheritdoc}
*/
public function getDefinition()
{
return new FixerDefinition(
'PHPUnit annotations should be a FQCNs including a root namespace.',
array(new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
* @covers Project\NameSpace\Something
* @coversDefaultClass Project\Default
* @uses Project\Test\Util
*/
public function testSomeTest()
{
}
}
'
))
);
}
/**
* {@inheritdoc}
*/
public function getPriority()
{
// should be run before NoUnusedImportsFixer
return -9;
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $token) {
if ($token->isGivenKind(T_DOC_COMMENT)) {
$token->setContent(preg_replace(
'~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(\w.*)$~m', '$1\\\\$2',
$token->getContent()
));
}
}
}
}
| Java |
---
layout: post
title: "从头学算法(二、搞算法你必须知道的OJ)"
date: 2016-12-20 11:36:52
categories: 数据结构及算法
tags: OJ algorithms
mathjax: true
---
在没接触算法之前,我从没听说过OJ这个缩写,没关系,现在开始认识还来得及。等你真正开始研究算法,你才发现你又进入了一个新的世界。
这个世界,你不关注它的时候,它好像并不存在,而一旦你关注它了,每一个花草都让你叹为观止。
来看看百度百科是怎么说的吧:
OJ是Online Judge系统的简称,用来在线检测程序源代码的正确性。著名的OJ有TYVJ、RQNOJ、URAL等。国内著名的题库有北京大学题库、浙江大学题库、电子科技大学题库、杭州电子科技大学等。国外的题库包括乌拉尔大学、瓦拉杜利德大学题库等。
而作为程序员,你必须知道Leetcode这个OJ,相比起国内各大著名高校的OJ,为什么我更推荐程序员们选择LeetCode OJ呢?原因有两点:
第一,大学OJ上的题目一般都是为ACM选手做准备的,难度大,属于竞技范畴;LeetCode的题相对简单,更为实用,更适合以后从事开发等岗位的程序员们。
第二,LeetCode非常流行,用户的量级几乎要比其他OJ高出将近三到五个级别。大量的活跃用户,将会为我们提供数不清的经验交流和可供参考的GitHub源代码。
刷LeetCode不是为了学会某些牛逼的算法,也不是为了突破某道难题而可能获得的智趣上的快感。学习和练习正确的思考方法,锻炼考虑各种条件的能力,在代码实现前就已经尽可能避免大多数常见错误带来的bug,养成简洁代码的审美习惯。
通过OJ刷题,配合算法的相关书籍进行理解,对算法的学习是很有帮助的,作为一个程序员,不刷几道LeetCode,真的说不过去。
最后LeetCode网址:https://leetcode.com/
接下来注册开始搞吧!
![image_1bf90k08d19p01391i8pfvkqhbm.png-65.6kB][1]
![image_1bf90orko1ccn1opj29j93cc7f13.png-91.4kB][2]
LeetCode刷过一阵子之后,发现很多都是收费的,这就很不友好了。本着方便大家的原则,向大家推荐lintcode,题目相对也很全,支持中、英双语,最重要是免费。
[1]: http://static.zybuluo.com/coldxiangyu/j2xlu88omsuprk7c7qinubug/image_1bf90k08d19p01391i8pfvkqhbm.png
[2]: http://static.zybuluo.com/coldxiangyu/fztippzc74u7j9ww7av2vvn3/image_1bf90orko1ccn1opj29j93cc7f13.png
| Java |
package com.timotheteus.raincontrol.handlers;
import com.timotheteus.raincontrol.tileentities.IGUITile;
import com.timotheteus.raincontrol.tileentities.TileEntityInventoryBase;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.network.NetworkHooks;
import javax.annotation.Nullable;
public class GuiHandler implements IGuiHandler {
public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) {
BlockPos pos = openContainer.getAdditionalData().readBlockPos();
// new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos));
TileEntityInventoryBase te = (TileEntityInventoryBase) Minecraft.getInstance().world.getTileEntity(pos);
if (te != null) {
return te.createGui(Minecraft.getInstance().player);
}
return null;
}
//TODO can remove these, I think
@Nullable
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity te = world.getTileEntity(pos);
if (te instanceof IGUITile) {
return ((IGUITile) te).createContainer(player);
}
return null;
}
@Nullable
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity te = world.getTileEntity(pos);
if (te instanceof IGUITile) {
return ((IGUITile) te).createGui(player);
}
return null;
}
}
| Java |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* 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.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*---------------------------------------------------------------
*
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* NOTE: If you change these, also change the error_reporting() code below
*/
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
switch (ENVIRONMENT) {
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>=')) {
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
} else {
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
/*
*---------------------------------------------------------------
* SYSTEM FOLDER NAME
*---------------------------------------------------------------
*
* This variable must contain the name of your "system" folder.
* Include the path if the folder is not in the same directory
* as this file.
*/
$system_path = 'system';
/*
*---------------------------------------------------------------
* APPLICATION FOLDER NAME
*---------------------------------------------------------------
*
* If you want this front controller to use a different "application"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path. For more info please see the user guide:
* http://codeigniter.com/user_guide/general/managing_apps.html
*
* NO TRAILING SLASH!
*/
$application_folder = 'application';
/*
*---------------------------------------------------------------
* VIEW FOLDER NAME
*---------------------------------------------------------------
*
* If you want to move the view folder out of the application
* folder set the path to the folder here. The folder can be renamed
* and relocated anywhere on your server. If blank, it will default
* to the standard location inside your application folder. If you
* do move this, use the full server path to this folder.
*
* NO TRAILING SLASH!
*/
$view_folder = '';
$templates = $view_folder . '/templates/';
/*
* --------------------------------------------------------------------
* DEFAULT CONTROLLER
* --------------------------------------------------------------------
*
* Normally you will set your default controller in the routes.php file.
* You can, however, force a custom routing by hard-coding a
* specific controller class/function here. For most applications, you
* WILL NOT set your routing here, but it's an option for those
* special instances where you might want to override the standard
* routing in a specific front controller that shares a common CI installation.
*
* IMPORTANT: If you set the routing here, NO OTHER controller will be
* callable. In essence, this preference limits your application to ONE
* specific controller. Leave the function name blank if you need
* to call functions dynamically via the URI.
*
* Un-comment the $routing array below to use this feature
*/
// The directory name, relative to the "controllers" folder. Leave blank
// if your controller is not in a sub-folder within the "controllers" folder
// $routing['directory'] = '';
// The controller class file name. Example: mycontroller
// $routing['controller'] = '';
// The controller function you wish to be called.
// $routing['function'] = '';
/*
* -------------------------------------------------------------------
* CUSTOM CONFIG VALUES
* -------------------------------------------------------------------
*
* The $assign_to_config array below will be passed dynamically to the
* config class when initialized. This allows you to set custom config
* items or override any default config values found in the config.php file.
* This can be handy as it permits you to share one application between
* multiple front controller files, with each file containing different
* config values.
*
* Un-comment the $assign_to_config array below to use this feature
*/
// $assign_to_config['name_of_config_item'] = 'value of config item';
// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------
/*
* ---------------------------------------------------------------
* Resolve the system path for increased reliability
* ---------------------------------------------------------------
*/
// Set the current directory correctly for CLI requests
if (defined('STDIN')) {
chdir(dirname(__FILE__));
}
if (($_temp = realpath($system_path)) !== FALSE) {
$system_path = $_temp . '/';
} else {
// Ensure there's a trailing slash
$system_path = rtrim($system_path, '/') . '/';
}
// Is the system path correct?
if (!is_dir($system_path)) {
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: ' . pathinfo(__FILE__, PATHINFO_BASENAME);
exit(3); // EXIT_CONFIG
}
/*
* -------------------------------------------------------------------
* Now that we know the path, set the main path constants
* -------------------------------------------------------------------
*/
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// Path to the system folder
define('BASEPATH', str_replace('\\', '/', $system_path));
// Path to the front controller (this file)
define('FCPATH', dirname(__FILE__) . '/');
// Name of the "system folder"
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));
// The path to the "application" folder
if (is_dir($application_folder)) {
if (($_temp = realpath($application_folder)) !== FALSE) {
$application_folder = $_temp;
}
define('APPPATH', $application_folder . DIRECTORY_SEPARATOR);
} else {
if (!is_dir(BASEPATH . $application_folder . DIRECTORY_SEPARATOR)) {
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF;
exit(3); // EXIT_CONFIG
}
define('APPPATH', BASEPATH . $application_folder . DIRECTORY_SEPARATOR);
}
// The path to the "views" folder
if (!is_dir($view_folder)) {
if (!empty($view_folder) && is_dir(APPPATH . $view_folder . DIRECTORY_SEPARATOR)) {
$view_folder = APPPATH . $view_folder;
} elseif (!is_dir(APPPATH . 'views' . DIRECTORY_SEPARATOR)) {
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF;
exit(3); // EXIT_CONFIG
} else {
$view_folder = APPPATH . 'views';
}
}
if (($_temp = realpath($view_folder)) !== FALSE) {
$view_folder = $_temp . DIRECTORY_SEPARATOR;
} else {
$view_folder = rtrim($view_folder, '/\\') . DIRECTORY_SEPARATOR;
}
define('VIEWPATH', $view_folder);
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*/
require_once BASEPATH . 'core/CodeIgniter.php'; | Java |
version https://git-lfs.github.com/spec/v1
oid sha256:be847f24aac166b803f1ff5ccc7e4d7bc3fb5d960543e35f779068a754294c94
size 1312
| Java |
<?php
namespace Matthimatiker\CommandLockingBundle\Locking;
use Symfony\Component\Filesystem\LockHandler;
/**
* Uses files to create locks.
*
* @see \Symfony\Component\Filesystem\LockHandler
* @see http://symfony.com/doc/current/components/filesystem/lock_handler.html
*/
class FileLockManager implements LockManagerInterface
{
/**
* The directory that contains the lock files.
*
* @var string
*/
private $lockDirectory = null;
/**
* Contains the locks that are currently active.
*
* The name of the lock is used as key.
*
* @var array<string, LockHandler>
*/
private $activeLocksByName = array();
/**
* @param string $lockDirectory Path to the directory that contains the locks.
*/
public function __construct($lockDirectory)
{
$this->lockDirectory = $lockDirectory;
}
/**
* Obtains a lock for the provided name.
*
* The lock must be released before it can be obtained again.
*
* @param string $name
* @return boolean True if the lock was obtained, false otherwise.
*/
public function lock($name)
{
if ($this->isLocked($name)) {
return false;
}
$lock = new LockHandler($name . '.lock', $this->lockDirectory);
if ($lock->lock()) {
// Obtained lock.
$this->activeLocksByName[$name] = $lock;
return true;
}
return false;
}
/**
* Releases the lock with the provided name.
*
* If the lock does not exist, then this method will do nothing.
*
* @param string $name
*/
public function release($name)
{
if (!$this->isLocked($name)) {
return;
}
/* @var $lock LockHandler */
$lock = $this->activeLocksByName[$name];
$lock->release();
unset($this->activeLocksByName[$name]);
}
/**
* Checks if a lock with the given name is active.
*
* @param string $name
* @return boolean
*/
private function isLocked($name)
{
return isset($this->activeLocksByName[$name]);
}
}
| Java |
// Core is a collection of helpers
// Nothing specific to the emultor application
"use strict";
// all code is defined in this namespace
window.te = window.te || {};
// te.provide creates a namespace if not previously defined.
// Levels are seperated by a `.` Each level is a generic JS object.
// Example:
// te.provide("my.name.space");
// my.name.foo = function(){};
// my.name.space.bar = function(){};
te.provide = function(ns /*string*/ , root) {
var parts = ns.split('.');
var lastLevel = root || window;
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
if (!lastLevel[p]) {
lastLevel = lastLevel[p] = {};
} else if (typeof lastLevel[p] !== 'object') {
throw new Error('Error creating namespace.');
} else {
lastLevel = lastLevel[p];
}
}
};
// A simple UID generator. Returned UIDs are guaranteed to be unique to the page load
te.Uid = (function() {
var id = 1;
function next() {
return id++;
}
return {
next: next
};
})();
// defaultOptionParse is a helper for functions that expect an options
// var passed in. This merges the passed in options with a set of defaults.
// Example:
// foo function(options) {
// tf.defaultOptionParse(options, {bar:true, fizz:"xyz"});
// }
te.defaultOptionParse = function(src, defaults) {
src = src || {};
var keys = Object.keys(defaults);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (src[k] === undefined) {
src[k] = defaults[k];
}
}
return src;
};
// Simple string replacement, eg:
// tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar
te.sprintf = function(str) {
for (var i = 1; i < arguments.length; i++) {
var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
str = str.replace(re, arguments[i]);
}
return str;
}; | Java |
##
# Backup v4.x Configuration
#
# Documentation: http://meskyanichi.github.io/backup
# Issue Tracker: https://github.com/meskyanichi/backup/issues
##
# Config Options
#
# The options here may be overridden on the command line, but the result
# will depend on the use of --root-path on the command line.
#
# If --root-path is used on the command line, then all paths set here
# will be overridden. If a path (like --tmp-path) is not given along with
# --root-path, that path will use it's default location _relative to --root-path_.
#
# If --root-path is not used on the command line, a path option (like --tmp-path)
# given on the command line will override the tmp_path set here, but all other
# paths set here will be used.
#
# Note that relative paths given on the command line without --root-path
# are relative to the current directory. The root_path set here only applies
# to relative paths set here.
#
# ---
#
# Sets the root path for all relative paths, including default paths.
# May be an absolute path, or relative to the current working directory.
#
# root_path 'my/root'
#
# Sets the path where backups are processed until they're stored.
# This must have enough free space to hold apx. 2 backups.
# May be an absolute path, or relative to the current directory or +root_path+.
#
# tmp_path 'my/tmp'
#
# Sets the path where backup stores persistent information.
# When Backup's Cycler is used, small YAML files are stored here.
# May be an absolute path, or relative to the current directory or +root_path+.
#
# data_path 'my/data'
##
# Utilities
#
# If you need to use a utility other than the one Backup detects,
# or a utility can not be found in your $PATH.
#
# Utilities.configure do
# tar '/usr/bin/gnutar'
# redis_cli '/opt/redis/redis-cli'
# end
##
# Logging
#
# Logging options may be set on the command line, but certain settings
# may only be configured here.
#
# Logger.configure do
# console.quiet = true # Same as command line: --quiet
# logfile.max_bytes = 2_000_000 # Default: 500_000
# syslog.enabled = true # Same as command line: --syslog
# syslog.ident = 'my_app_backup' # Default: 'backup'
# end
#
# Command line options will override those set here.
# For example, the following would override the example settings above
# to disable syslog and enable console output.
# backup perform --trigger my_backup --no-syslog --no-quiet
##
# Component Defaults
#
# Set default options to be applied to components in all models.
# Options set within a model will override those set here.
#
# Storage::S3.defaults do |s3|
# s3.access_key_id = "my_access_key_id"
# s3.secret_access_key = "my_secret_access_key"
# end
#
# Notifier::Mail.defaults do |mail|
# mail.from = 'sender@email.com'
# mail.to = 'receiver@email.com'
# mail.address = 'smtp.gmail.com'
# mail.port = 587
# mail.domain = 'your.host.name'
# mail.user_name = 'sender@email.com'
# mail.password = 'my_password'
# mail.authentication = 'plain'
# mail.encryption = :starttls
# end
##
# Preconfigured Models
#
# Create custom models with preconfigured components.
# Components added within the model definition will
# +add to+ the preconfigured components.
#
# preconfigure 'MyModel' do
# archive :user_pictures do |archive|
# archive.add '~/pictures'
# end
#
# notify_by Mail do |mail|
# mail.to = 'admin@email.com'
# end
# end
#
# MyModel.new(:john_smith, 'John Smith Backup') do
# archive :user_music do |archive|
# archive.add '~/music'
# end
#
# notify_by Mail do |mail|
# mail.to = 'john.smith@email.com'
# end
# end
| Java |
import Ember from 'ember';
let __TRANSLATION_MAP__ = {};
export default Ember.Service.extend({ map: __TRANSLATION_MAP__ });
| Java |
import React from 'react';
<<<<<<< HEAD
import { Switch, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Blog from './Blog';
import Resume from './Resume';
import Error404 from './Error404';
=======
// import GithubForm from './forms/github/GithubForm';
import GithubRecent from './forms/github/RecentList';
import './Content.css';
>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a
class Content extends React.Component {
render() {
return (
<div className="app-content">
<<<<<<< HEAD
<Switch>
<Route exact path="/" component={Home} />
{/* <Route exact path="/about" component={About} /> */}
<Route component={Error404} />
</Switch>
=======
<div className="content-description">
<br />College Student. Love Coding. Interested in Web and Machine Learning.
</div>
<hr />
<div className="content-list">
<div className="list-projects">
<h3>Recent Projects</h3>
{/* <GithubRecent userName="slkjse9" standardDate={5259492000} /> */}
<GithubRecent userName="hejuby" standardDate={3.154e+10} />
{/* <h2>Activity</h2> */}
<h3>Experience</h3>
<h3>Education</h3>
<ul>
<li><h4>Computer Science</h4>Colorado State University, Fort Collins (2017 -)</li>
</ul>
<br />
</div>
</div>
{/* <div className="content-home-github-recent-title">
<h2>Recent Works</h2>
<h3>updated in 2 months</h3>
</div> */}
{/* <h3>Recent</h3>
<GithubForm contentType="recent"/> */}
{/* <h3>Lifetime</h3>
{/* <GithubForm contentType="life"/> */}
{/* <div className="content-home-blog-recent-title">
<h2>Recent Posts</h2>
<h3>written in 2 months</h3>
</div>
<BlogRecent /> */}
>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a
</div>
);
}
}
export default Content;
| Java |
package cmd
import (
"github.com/fatih/color"
out "github.com/plouc/go-gitlab-client/cli/output"
"github.com/spf13/cobra"
)
func init() {
getCmd.AddCommand(getProjectVarCmd)
}
var getProjectVarCmd = &cobra.Command{
Use: resourceCmd("project-var", "project-var"),
Aliases: []string{"pv"},
Short: "Get the details of a project's specific variable",
RunE: func(cmd *cobra.Command, args []string) error {
ids, err := config.aliasIdsOrArgs(currentAlias, "project-var", args)
if err != nil {
return err
}
color.Yellow("Fetching project variable (id: %s, key: %s)…", ids["project_id"], ids["var_key"])
loader.Start()
variable, meta, err := client.ProjectVariable(ids["project_id"], ids["var_key"])
loader.Stop()
if err != nil {
return err
}
out.Variable(output, outputFormat, variable)
printMeta(meta, false)
return nil
},
}
| Java |
export interface IContact {
id?: number;
email: string;
listName: string;
name: string;
}
| Java |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Interop
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct ExternalMemoryImageCreateInfo
{
/// <summary>
/// The type of this structure.
/// </summary>
public SharpVk.StructureType SType;
/// <summary>
/// Null or an extension-specific structure.
/// </summary>
public void* Next;
/// <summary>
///
/// </summary>
public SharpVk.ExternalMemoryHandleTypeFlags HandleTypes;
}
}
| Java |
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance;
import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterCreditException;
import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance;
import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord;
import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord;
import static com.googlecode.catchexception.CatchException.catchException;
import static com.googlecode.catchexception.CatchException.caughtException;
import static org.fest.assertions.api.Assertions.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
/**
* Created by jorgegonzalez on 2015.07.14..
*/
@RunWith(MockitoJUnitRunner.class)
public class CreditTest {
@Mock
private Database mockDatabase;
@Mock
private DatabaseTable mockWalletTable;
@Mock
private DatabaseTable mockBalanceTable;
@Mock
private DatabaseTransaction mockTransaction;
private List<DatabaseTableRecord> mockRecords;
private DatabaseTableRecord mockBalanceRecord;
private DatabaseTableRecord mockWalletRecord;
private BitcoinWalletTransactionRecord mockTransactionRecord;
private BitcoinWalletBasicWalletAvailableBalance testBalance;
@Before
public void setUpMocks(){
mockTransactionRecord = new MockBitcoinWalletTransactionRecord();
mockBalanceRecord = new MockDatabaseTableRecord();
mockWalletRecord = new MockDatabaseTableRecord();
mockRecords = new ArrayList<>();
mockRecords.add(mockBalanceRecord);
setUpMockitoRules();
}
public void setUpMockitoRules(){
when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable);
when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable);
when(mockBalanceTable.getRecords()).thenReturn(mockRecords);
when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord);
when(mockDatabase.newTransaction()).thenReturn(mockTransaction);
}
@Before
public void setUpAvailableBalance(){
testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase);
}
@Test
public void Credit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException()).isNull();
}
@Test
public void Credit_OpenDatabaseCantOpenDatabase_ThrowsCantRegisterCreditException() throws Exception{
doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase();
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
@Test
public void Credit_OpenDatabaseDatabaseNotFound_ThrowsCantRegisterCreditException() throws Exception{
doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase();
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
@Test
public void Credit_DaoCantCalculateBalanceException_ThrowsCantRegisterCreditException() throws Exception{
doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory();
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
@Test
public void Credit_GeneralException_ThrowsCantRegisterCreditException() throws Exception{
when(mockBalanceTable.getRecords()).thenReturn(null);
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
}
| Java |
using System;
namespace Sherlock
{
/// <summary>
/// A reader than can read values from a pipe.
/// </summary>
/// <typeparam name="T">The type of value to read.</typeparam>
public interface IPipeReader<T> : IDisposable
{
/// <summary>
/// Attempts to read a value from the pipe.
/// </summary>
/// <param name="item">The read value.</param>
/// <returns>A value indicating success.</returns>
bool Read(out T item);
/// <summary>
/// Closes the reader.
/// </summary>
void Close();
/// <summary>
/// Gets a value indicating whether the reader is closed.
/// </summary>
bool IsClosed { get; }
}
}
| Java |
# Nitrogen 2.0 New Features
### New Elements, Actions, and API functions
* wf:wire can now act upon CSS classes or full JQuery Paths, not just Nitrogen elements. For example, wf:wire(".people > .address", Actions) will wire actions to any HTML elements with an "address" class underneath a "people" class. Anything on http://api.jquery.com/category/selectors/ is supported
* Added wf:replace(ID, Elements), remove an element from the page, put new elements in their place.
* Added wf:remove(ID), remove an element from the page.
* New #api{} action allows you to define a javascript method that takes parameters and will trigger a postback. Javascript parameters are automatically translated to Erlang, allowing for pattern matching.
* New #grid{} element provides a Nitrogen interface to the 960 Grid System (http://960.gs) for page layouts.
* The #upload{} event callbacks have changed. Event fires both on start of upload and when upload finishes.
* Upload callbacks take a Node parameter so that file uploads work even when a postback hits a different node.
* Many methods that used to be in 'nitrogen.erl' are now in 'wf.erl'. Also, some method signatures in wf.erl have changed.
* wf:get_page_module changed to wf:page_module
* wf:q(ID) no longer returns a list, just the value.
* wf:qs(ID) returns a list.
* wf:depickle(Data, TTL) returns undefined if expired.
### Comet Pools
* Behind the scenes, combined logic for comet and continue events. This now all goes through the same channel. You can switch async mode between comet and intervalled polling by calling wf:switch_to_comet() or wf:switch_to_polling(IntervalMS), respectively.
* Comet processes can now register in a local pool (for a specific session) or a global pool (across the entire Nitrogen cluster). All other processes in the pool are alerted when a process joins or leaves. The first process in a pool gets a special init message.
* Use wf:send(Pool, Message) or wf:send_global(Pool, Message) to broadcast a message to the entire pool.
* wf:comet_flush() is now wf:flush()
### Architectural Changes
* Nitrogen now runs _under_ other web frameworks (inets, mochiweb, yaws, misultin) using simple_bridge. In other words, you hook into the other frameworks like normal (mochiweb loop, yaws appmod, etc.) and then call nitrogen:run() from within that process.
* Handlers are the new mechanism to extend the inner parts of Nitrogen, such as session storage, authentication, etc.
* New route handler code means that pages can exist in any namespace, don't have to start with /web/... (see dynamic_route_handler and named_route_handler)
* Changed interface to elements and actions, any custom elements and actions will need tweaks.
* sync:go() recompiles any changed files more intelligently by scanning for Emakefiles.
* New ability to package Nitrogen projects as self-contained directories using rebar.
# Nitrogen 1.0 Changelog
2009-05-02
- Added changes and bugfixes by Tom McNulty.
2009-04-05
- Added a templateroot setting in .app file, courtesy of Ville Koivula.
2009-03-28
- Added file upload support.
2009-03-22
- Added alt text support to #image elements by Robert Schonberger.
- Fixed bug, 'nitrogen create (PROJECT)' now does a recursive copy of the Nitrogen support files, by Jay Doane.
- Added radio button support courtesy of Benjamin Nortier and Tom McNulty.
2009-03-16
- Added .app configuration setting to bind Nitrogen to a specific IP address, by Tom McNulty.
2009-03-08
- Added DatePicker element by Torbjorn Tornkvist.
- Upgrade to JQuery 1.3.2 and JQuery UI 1.7.
- Created initial VERSIONS file.
- Added code from Tom McNulty to expose Mochiweb loop.
- Added coverage code from Michael Mullis, including lib/coverize submodule.
- Added wf_platform:get_peername/0 code from Marius A. Eriksen.
2009-03-07
- Added code by Torbjorn Tornkvist: Basic Authentication, Hostname settings, access to HTTP Headers, and a Max Length validator.
2009-01-26
- Added Gravatar support by Dan Bravender.
2009-01-24
- Add code-level documentation around comet.
- Fix bug where comet functions would continue running after a user left the page.
- Apply patch by Tom McNulty to allow request object access within the route/1 function.
- Apply patch by Tom McNulty to correctly bind binaries.
- Apply patch by Tom McNulty for wf_tags library to correctly handle binaries.
2009-01-16
- Clean up code around timeout events. (Events that will start running after X seconds on the browser.)
2009-01-08
- Apply changes by Jon Gretar to support 'nitrogen create PROJECT' and 'nitrogen page /web/page' scripts.
- Finish putting all properties into .app file. Put request/1 into application module file.
- Add ability to route through route/1 in application module file.
- Remove need for wf_global.erl
- Start Yaws process underneath the main Nitrogen supervisor. (Used to be separate.)
2009-01-06
- Make Nitrogen a supervised OTP application, startable and stoppable via nitrogen:start() and nitrogen:stop().
- Apply changes by Dave Peticolas to fix session bugs and turn sessions into supervised processes.
2009-01-04
- Update sync module, add mirror module. These tools allow you to deploy and start applications on a bare remote node.
2009-01-03
- Allow Nitrogen to be run as an OTP application. See Quickstart project for example.
- Apply Tom McNulty's patch to create and implement wf_tags library. Emit html tags more cleanly.
- Change templates to allow multiple callbacks, and use first one that is defined. Basic idea and starter code by Tom McNulty.
- Apply Martin Scholl's patch to optimize copy_to_baserecord in wf_utils.
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.