text
stringlengths 12
215k
|
|---|
b'What is the value of (-7 + -14 + 7 - -41) + -10?\n'
|
// FoalTS
import { FileSystem } from '../../file-system';
export function createVSCodeConfig() {
new FileSystem()
// TODO: test this line
.cdProjectRootDir()
.ensureDir('.vscode')
.cd('.vscode')
.copy('vscode-config/launch.json', 'launch.json')
.copy('vscode-config/tasks.json', 'tasks.json');
}
|
Dockermail - Email Core
==========
This image provides a secure, minimal mail server based on 'postfix' and 'dovecot'.
All incoming mail to your domains is accepted.
For outgoing mail, only authenticated (logged in with username and password) clients can send messages via STARTTLS.
## Setup
You will need 2 folder on your host, one to store your configuration and another one to store your email. For example:
* `/opt/dockermail/settings`
* `/opt/dockermail/vmail`
These will be mounted into container and store settings and email on host.
All the configuration is done through a single `config.json` file, extra files (eg. SSL keys) will be stored in the settings directory for backup.
There is an example file in `config/example` to get you started.
#### Remember to restart your container if you update the settings!
---
### config.json
```json
{
"settings": {
"myhostname": "mail.example.com"
},
"domains": {
"example.com" :
[
{
"email": "[email protected]",
"password": "{PLAIN}SuperSecure123",
"aliases": ["@example.com"]
},
{
"email": "[email protected]",
"password": "{SHA256-CRYPT}$5$ojXGqoxOAygN91er$VQD/8dDyCYOaLl2yLJlRFXgl.NSrB3seZGXBRMdZAr6"
}
]
}
}
```
The hash within *config.json* contains 2 primary keys: `domains` and `settings`.
##### settings
* `myhostname` - should be the fully qualified domain of the server hosting email. Although optional you will have problems with EHLO commands and `amavis` without it.
#### domains
Each domain has an array of account objects, each account has the following keys:
* `email` - email address of the account. Will also be used as the login.
* `password` - password for the account. See below for details.
* `aliases` - (Optional) Array of aliases to redirect to this account. For a catch-all use your domain with no account, eg: `@example.com`.
##### Generating passwords
Passwords have to be in a dovecot format.
A plain-text password looks like this: `{PLAIN}SuperSecure123`.
To get more secure hash values, you need to start the container and run:
```bash
docker exec -it [email_core_container_name] doveadm pw -s [scheme-name]
```
This will attach to a running container, prompt you for a password and provide a hash. For example:
```bash
> docker exec -it dockermail_core_1 doveadm pw -s SHA512-CRYPT
Enter new password:
Retype new password:
{SHA512-CRYPT}$6$OA/BzvLzf7C9uohz$a9B0kCihcHsfnK.x4xJWHs9V7.eR5crVtSUn6hoe6p03oea34.uxkozRUw7RYu13z26xNniY3M1kZu4CgSVaB/
```
See [Dovecot Wiki](http://wiki.dovecot.org/Authentication/PasswordSchemes) for more details on different schemes.
## Run
Using the pre-built image from docker hub, you can start your email by running:
```bash
docker run -name dockermail -d \
-p 25:25 -p 587:587 -p 143:143 -p 993:993 \
-v /opt/dockermail/settings:/mail_settings \
-v /opt/dockermail/vmail:/vmail \
adaline/dockermail-core
```
This will connect SMTP ports 25/587 and IMAP port 143/993 to host and mount the folders as per examples given above.
## SSL
Container will produce own SSL keys and back these up into the settings folder. These files are:
```
ssl-cert-snakeoil.key
ssl-cert-snakeoil.pem
```
On boot it will use these if present. You can replace these backup keys with your own, just restart the container.
|
b'What is 14 + 1 + (20 - (-2 - (-8 - 12)))?\n'
|
b'What is (-1 - -8) + 2 + -9?\n'
|
b'-6 - (1 - (-7 + -5 - -20))\n'
|
/**
*
* Modelo de Login usando MCV
* Desenvolvido por Ricardo Hirashiki
* Publicado em: http://www.sitedoricardo.com.br
* Data: Ago/2011
*
* Baseado na extensao criada por Wemerson Januario
* http://code.google.com/p/login-window/
*
*/
Ext.define('Siccad.view.authentication.CapsWarningTooltip', {
extend : 'Ext.tip.QuickTip',
alias : 'widget.capswarningtooltip',
target : 'authentication-login',
id : 'toolcaps',
anchor : 'left',
anchorOffset : 60,
width : 305,
dismissDelay : 0,
autoHide : false,
disabled : false,
title : '<b>Caps Lock está ativada</b>',
html : '<div>Se Caps lock estiver ativado, isso pode fazer com que você</div>' +
'<div>digite a senha incorretamente.</div><br/>' +
'<div>Você deve pressionar a tecla Caps lock para desativá-la</div>' +
'<div>antes de digitar a senha.</div>'
});
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ninject.Modules;
using Ninject.Extensions.Conventions;
namespace SongManager.Web.NinjectSupport
{
/// <summary>
/// Automatically loads all Boot Modules and puts them into the Ninject Dependency Resolver
/// </summary>
public class DependencyBindingsModule : NinjectModule
{
public override void Load()
{
// Bind all BootModules
Kernel.Bind( i => i.FromAssembliesMatching( "SongManager.Web.dll", "SongManager.Web.Core.dll", "SongManager.Web.Data.dll", "SongManager.Core.dll" )
.SelectAllClasses()
.InheritedFrom( typeof( SongManager.Core.Boot.IBootModule ) )
.BindSingleInterface()
);
}
}
}
|
/*!
* DASSL solver library description
*/
#include "libinfo.h"
extern void _start()
{
_library_ident("DAE solver library");
_library_task("interfaces to generic IVP solver");
_library_task("operations on data for included solvers");
_library_task("DASSL solver backend");
_library_task("RADAU solver backend");
_library_task("MEBDFI solver backend");
_exit(0);
}
|
b'What is the value of 15 + 4 - (6 + -8 - 6 - 0)?\n'
|
b'What is the value of -35 + (-72 - -46 - -80)?\n'
|
/**
* The MIT License Copyright (c) 2015 Teal Cube Games
*
* 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 land.face.strife.managers;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import land.face.strife.StrifePlugin;
import land.face.strife.data.champion.Champion;
import land.face.strife.data.champion.LifeSkillType;
import org.bukkit.entity.Player;
public class CombatStatusManager {
private final StrifePlugin plugin;
private final Map<Player, Integer> tickMap = new ConcurrentHashMap<>();
private static final int SECONDS_TILL_EXPIRY = 8;
public CombatStatusManager(StrifePlugin plugin) {
this.plugin = plugin;
}
public boolean isInCombat(Player player) {
return tickMap.containsKey(player);
}
public void addPlayer(Player player) {
tickMap.put(player, SECONDS_TILL_EXPIRY);
}
public void tickCombat() {
for (Player player : tickMap.keySet()) {
if (!player.isOnline() || !player.isValid()) {
tickMap.remove(player);
continue;
}
int ticksLeft = tickMap.get(player);
if (ticksLeft < 1) {
doExitCombat(player);
tickMap.remove(player);
continue;
}
tickMap.put(player, ticksLeft - 1);
}
}
public void doExitCombat(Player player) {
if (!tickMap.containsKey(player)) {
return;
}
Champion champion = plugin.getChampionManager().getChampion(player);
if (champion.getDetailsContainer().getExpValues() == null) {
return;
}
for (LifeSkillType type : champion.getDetailsContainer().getExpValues().keySet()) {
plugin.getSkillExperienceManager().addExperience(player, type,
champion.getDetailsContainer().getExpValues().get(type), false, false);
}
champion.getDetailsContainer().clearAll();
}
}
|
b'What is the value of -3 - (2 - 24 - (-19 + 12)) - 4?\n'
|
b'Evaluate (12 - 12) + 8 - (1 + (0 - 20)).\n'
|
b'What is the value of 3 + (47 - 52) + (11 - 0)?\n'
|
b'What is the value of 34 + -13 + 6 + -1 + -3?\n'
|
b'What is (9 - 10) + -7 - (-9 - 3)?\n'
|
b'-13 - (-5 - (-14 + 14))\n'
|
<?php
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use Spatie\Backup\FileHelpers\FileSelector;
class FileSelectorTest extends Orchestra\Testbench\TestCase
{
protected $path;
protected $disk;
protected $root;
protected $testFilesPath;
protected $fileSelector;
public function setUp()
{
parent::setUp();
$this->root = realpath('tests/_data/disk/root');
$this->path = 'backups';
$this->testFilesPath = realpath($this->root.'/'.$this->path);
//make sure all files in our testdirectory are 5 days old
foreach (scandir($this->testFilesPath) as $file) {
touch($this->testFilesPath.'/'.$file, time() - (60 * 60 * 24 * 5));
}
$this->disk = new Illuminate\Filesystem\FilesystemAdapter(new Filesystem(new Local($this->root)));
$this->fileSelector = new FileSelector($this->disk, $this->path);
}
/**
* @test
*/
public function it_returns_only_files_with_the_specified_extensions()
{
$oldFiles = $this->fileSelector->getFilesOlderThan(new DateTime(), ['zip']);
$this->assertNotEmpty($oldFiles);
$this->assertFalse(in_array('MariahCarey.php', $oldFiles));
}
/**
* @test
*/
public function it_returns_an_empty_array_if_no_extensions_are_specified()
{
$oldFiles = $this->fileSelector->getFilesOlderThan(new DateTime(), ['']);
$this->assertEmpty($oldFiles);
}
/**
* @test
*/
public function it_gets_files_older_than_the_given_date()
{
$testFileName = 'test_it_gets_files_older_than_the_given_date.zip';
touch($this->testFilesPath.'/'.$testFileName, time() - (60 * 60 * 24 * 10) + 60); //create a file that is 10 days and a minute old
$oldFiles = $this->fileSelector->getFilesOlderThan((new DateTime())->sub(new DateInterval('P9D')), ['zip']);
$this->assertTrue(in_array($this->path.'/'.$testFileName, $oldFiles));
$oldFiles = $this->fileSelector->getFilesOlderThan((new DateTime())->sub(new DateInterval('P10D')), ['zip']);
$this->assertFalse(in_array($this->path.'/'.$testFileName, $oldFiles));
$oldFiles = $this->fileSelector->getFilesOlderThan((new DateTime())->sub(new DateInterval('P11D')), ['zip']);
$this->assertFalse(in_array($this->path.'/'.$testFileName, $oldFiles));
}
/**
* @test
*/
public function it_excludes_files_outside_given_path()
{
$files = $this->fileSelector->getFilesOlderThan(new DateTime(), ['zip']);
touch(realpath('tests/_data/disk/root/TomJones.zip'), time() - (60 * 60 * 24 * 10) + 60);
$this->assertFalse(in_array($this->path.'/'.'TomJones.zip', $files));
$this->assertTrue(in_array($this->path.'/'.'test.zip', $files));
}
/**
* Call artisan command and return code.
*
* @param string $command
* @param array $parameters
*
* @return int
*/
public function artisan($command, $parameters = [])
{
}
}
|
b'Evaluate 30 - (3 + (31 - 15)).\n'
|
name 'google_app_engine'
description 'A cookbook to download and install the google app engine SDK on a Linux system.'
version '1.0.0'
maintainer 'Bernd Hoffmann'
maintainer_email '[email protected]'
license 'MIT'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
|
b'What is the value of (-15 - -13 - 17) + (0 - -4 - -4)?\n'
|
b'Calculate (51 - 12) + -30 - (-5 + 2).\n'
|
b'Calculate (5 - ((-1 - -1) + -3)) + (-27 - -7).\n'
|
b'What is (-2 - 7) + 15 + -27 + 10?\n'
|
b'Calculate (-10 - 0) + (-1 + 1 - (26 + -41)).\n'
|
b'Evaluate 10 - (-1 - 4 - -16) - 11.\n'
|
/*
* database.hpp
*
* Created on: Sep 22, 2016
* Author: dan
*/
#ifndef SRC_TURBO_BROCCOLI_DATABASE_HPP_
#define SRC_TURBO_BROCCOLI_DATABASE_HPP_
#include <boost/filesystem.hpp>
#include <turbo_broccoli/type/key.hpp>
#include <turbo_broccoli/type/value.hpp>
#include <turbo_broccoli/type/blob.hpp>
#include <turbo_broccoli/type/tags.hpp>
#include <turbo_broccoli/type/tagged_records.hpp>
#include <turbo_broccoli/type/result_find.hpp>
#include <turbo_broccoli/type/result_key.hpp>
#include <turbo_broccoli/detail/utils.hpp>
namespace turbo_broccoli {
using types::blob;
using types::db_key;
using types::result_key;
using types::result_find;
struct database {
database(const std::string& path) : path_(path) {
namespace fs = boost::filesystem;
if(!fs::exists(path_) ) {
if(!fs::create_directories(path_)) {
throw std::runtime_error("cannot open db, cannot create directory: " + path_.generic_string());
}
}
else {
if(!fs::is_directory(path_)) {
throw std::runtime_error("cannot open db, is not a directory: " + path_.generic_string());
}
}
}
result_find find(const std::string& key) {
return find(detail::calculate_key(key));
}
result_find find(const db_key& key) {
result_find result{};
result.success = false;
if(!record_exists(key)) {
std::cout << "no record with key" << types::to_string(key) << std::endl;
return result;
}
auto record = read_record(key);
if( is_blob(record)) {
result.success = true;
result.results.push_back(detail::deserialize<blob>(record.data));
}
if(is_tag_list(record)) {
auto records = detail::deserialize<types::tagged_records>(record.data);
for(auto& t : records.keys) {
auto k = types::string_to_key(t);
if(record_exists(k)) {
auto r = read_record(k);
if( is_blob(r)) {
result.success = true;
result.results.push_back(detail::deserialize<blob>(r.data));
}
else {
std::cout << "inconsistent: record is not blob " << t << std::endl;
}
}
else {
std::cout << "inconsistent no record from tag list " << t << std::endl;
}
}
}
return result;
}
result_key store(const blob& new_blob) {
static const result_key failed_result{false, turbo_broccoli::types::nil_key() };
if(record_exists(new_blob)) {
/*
* read all tags and update them!
*/
auto r = read_record(new_blob.key_hash());
auto old_blob = detail::deserialize<blob>(r.data);
types::tag_list::list_type to_delete = diff( old_blob.tags().tags, new_blob.tags().tags);
types::tag_list::list_type to_add = diff( new_blob.tags().tags, old_blob.tags().tags);
for(auto& t : to_add ) {
update_tag_add(t, types::to_string(new_blob.key_hash()));
}
for(auto& t : to_delete ) {
update_tag_remove(t, types::to_string(new_blob.key_hash()));
}
}
else {
detail::create_folder(path_, new_blob.key_hash());
for(auto& t : new_blob.tags().tags ) {
update_tag_add(t, types::to_string(new_blob.key_hash()));
}
}
write_blob(new_blob);
return {true, new_blob.key_hash()};
return failed_result;
}
private:
inline bool record_exists(const blob& b) {
namespace fs = boost::filesystem;
return fs::exists(detail::to_filename(path_, b.key_hash()));
}
inline bool record_exists(const db_key& k) {
namespace fs = boost::filesystem;
return fs::exists(detail::to_filename(path_, k));
}
inline void write_blob(const blob& b) {
namespace fs = boost::filesystem;
types::value_t v;
v.data = detail::serialize(b);
v.reccord_type = types::value_type::blob;
v.key = b.key();
detail::create_folder(path_, b.key_hash());
detail::write_file(detail::to_filename(path_, b.key_hash()).generic_string(), detail::serialize(v));
}
inline types::value_t read_record(const db_key& k) {
namespace fs = boost::filesystem;
auto tmp = detail::read_file(detail::to_filename(path_, k).generic_string() );
return detail::deserialize<types::value_t>(tmp);
}
inline void update_tag_add(const std::string& tag_name, const std::string& record_key) {
auto tag_key = detail::calculate_key(tag_name);
types::value_t v;
types::tagged_records records;
if(record_exists(tag_key)) {
v = read_record(tag_key);
if(types::is_tag_list(v)) {
records = detail::deserialize<types::tagged_records>(v.data);
for(auto& r : records.keys) {
if(record_key.compare(r) == 0) {
return;
}
}
records.keys.push_back(record_key);
}
else {
throw std::runtime_error("record exissts and is not a tagged_list: " + tag_name);
}
}
else {
records.keys.push_back(record_key);
v.key = tag_name;
v.reccord_type = types::value_type::tag_list;
v.data = detail::serialize(records);
detail::create_folder(path_, tag_key);
}
v.data = detail::serialize(records);
detail::write_file(detail::to_filename(path_, tag_key).generic_string(), detail::serialize(v));
}
inline void update_tag_remove(const std::string& tag_name, const std::string& record_key) {
auto tag_key = detail::calculate_key(tag_name);
types::value_t v = read_record(tag_key);
if(types::is_tag_list(v)) {
types::tagged_records records = detail::deserialize<types::tagged_records>(v.data);
records.keys.erase(std::remove(records.keys.begin(), records.keys.end(), record_key), records.keys.end());
v.data = detail::serialize(records);
detail::write_file(detail::to_filename(path_, tag_key).generic_string(), detail::serialize(v));
}
}
/*
* \brief return list of all elements that are only in a
* a{0, 1, 2, 3, 4}
* b{3, 4, 5, 6, 7}
* d{0, 1, 2}
*/
inline std::vector<std::string> diff(const std::vector<std::string>& a, const std::vector<std::string>& b) {
std::vector<std::string> d;
for(auto& a_i : a) {
bool contains_b_i{false};
for(auto& b_i : b) {
if(a_i.compare(b_i) == 0) {
contains_b_i = true;
break;
}
}
if(!contains_b_i) {
d.push_back(a_i);
}
}
return d;
}
using path_t = boost::filesystem::path;
path_t path_;
};
}
#endif /* SRC_TURBO_BROCCOLI_DATABASE_HPP_ */
|
b'What is the value of (-39 + 15 - -19) + (34 - (-7 - -4))?\n'
|
//
// URBSegmentedControl.h
// URBSegmentedControlDemo
//
// Created by Nicholas Shipes on 2/1/13.
// Copyright (c) 2013 Urban10 Interactive. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, URBSegmentedControlOrientation) {
URBSegmentedControlOrientationHorizontal = 0,
URBSegmentedControlOrientationVertical
};
typedef NS_ENUM(NSUInteger, URBSegmentViewLayout) {
URBSegmentViewLayoutDefault = 0,
URBSegmentViewLayoutVertical
};
typedef NS_ENUM(NSUInteger, URBSegmentImagePosition) {
URBSegmentImagePositionLeft = 0,
URBSegmentImagePositionRight
};
@interface URBSegmentedControl : UISegmentedControl <UIAppearance>
typedef void (^URBSegmentedControlBlock)(NSInteger index, URBSegmentedControl *segmentedControl);
/**
Layout behavior for the segments (row or columns).
*/
@property (nonatomic) URBSegmentedControlOrientation layoutOrientation;
/**
Layout behavior of the segment contents.
*/
@property (nonatomic) URBSegmentViewLayout segmentViewLayout;
/**
* Position of the image when placed horizontally next to a segment label. Not used for controls containing only text or images.
*/
@property (nonatomic, assign) URBSegmentImagePosition imagePosition;
/**
Block handle called when the selected segment has changed.
*/
@property (nonatomic, copy) URBSegmentedControlBlock controlEventBlock;
/**
Background color for the base container view.
*/
@property (nonatomic, strong) UIColor *baseColor;
@property (nonatomic, strong) UIColor *baseGradient;
/**
Stroke color used around the base container view.
*/
@property (nonatomic, strong) UIColor *strokeColor;
/**
Stroke width for the base container view.
*/
@property (nonatomic, assign) CGFloat strokeWidth;
/**
Corner radius for the base container view.
*/
@property (nonatomic) CGFloat cornerRadius;
/**
Whether or not a gradient should be automatically applied to the base and segment backgrounds based on the defined base colors.
*/
@property (nonatomic, assign) BOOL showsGradient;
/**
Padding between the segments and the base container view.
*/
@property (nonatomic, assign) UIEdgeInsets segmentEdgeInsets;
///----------------------------
/// @name Segment Customization
///----------------------------
@property (nonatomic, strong) UIColor *segmentBackgroundColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIColor *segmentBackgroundGradient UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIColor *imageColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIColor *selectedImageColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) UIEdgeInsets contentEdgeInsets;
@property (nonatomic, assign) UIEdgeInsets titleEdgeInsets;
@property (nonatomic, assign) UIEdgeInsets imageEdgeInsets;
- (id)initWithTitles:(NSArray *)titles;
- (id)initWithIcons:(NSArray *)icons;
- (id)initWithTitles:(NSArray *)titles icons:(NSArray *)icons;
- (void)insertSegmentWithTitle:(NSString *)title image:(UIImage *)image atIndex:(NSUInteger)segment animated:(BOOL)animated;
- (void)setSegmentBackgroundColor:(UIColor *)segmentBackgroundColor atIndex:(NSUInteger)segment;
- (void)setImageColor:(UIColor *)imageColor forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setSegmentBackgroundColor:(UIColor *)segmentBackgroundColor UI_APPEARANCE_SELECTOR;
- (void)setControlEventBlock:(URBSegmentedControlBlock)controlEventBlock;
@end
@interface UIImage (URBSegmentedControl)
- (UIImage *)imageTintedWithColor:(UIColor *)color;
@end
|
b'Calculate (-4 - (-7 + -5 - -28)) + 3.\n'
|
{% from "components/table.html" import list_table, field, right_aligned_field_heading, row_heading, notification_status_field %}
{% from "components/page-footer.html" import page_footer %}
<div class="ajax-block-container" aria-labelledby='pill-selected-item'>
<div class="dashboard-table bottom-gutter-3-2">
{% call(item, row_number) list_table(
[notification],
caption=None,
caption_visible=False,
empty_message=None,
field_headings=[
'Recipient',
'Status'
],
field_headings_visible=False
) %}
{% call row_heading() %}
<p class="govuk-body">{{ item.to }}</p>
{% endcall %}
{{ notification_status_field(item) }}
{% endcall %}
{% if more_than_one_page %}
<p class="table-show-more-link">
Only showing the first 50 rows
</p>
{% endif %}
</div>
</div>
|
typedef struct { f_t x, y; } vec_t, *vec;
//inline
f_t cross(vec a, vec b)
{
return a->x * b->y - a->y * b->x;
}
//inline
vec vsub(vec a, vec b, vec res)
{
res->x = a->x - b->x;
res->y = a->y - b->y;
}
// Does point c lie on the left side of directed edge a->b?
// 1 if left, -1 if right, 0 if on the line
int c_left_of_ab(vec a, vec b, vec c)
{
vec_t tmp1, tmp2;
f_t x;
vsub(b, a, &tmp1);
vsub(c, b, &tmp2);
x = cross(&tmp1, &tmp2);
return x < 0 ? -1 : x > 0;
}
|
---
layout: page_home
title: Home
headerline: Design Club at IIIT-Delhi
headerlinelink: /about/
newslink: /news/
projectslink: /projects/
---
|
/*
The MIT License (MIT)
Copyright (c) 2014 Mehmetali Shaqiri ([email protected])
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 System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using openvpn.api.common.domain;
using openvpn.api.core.controllers;
using openvpn.api.shared;
using Raven.Client;
using openvpn.api.core.auth;
namespace openvpn.api.Controllers
{
public class UsersController : RavenDbApiController
{
/// <summary>
/// Get requested user by email
/// </summary>
[Route("api/users/{email}")]
public async Task<User> Get(string email)
{
return await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == email);
}
/// <summary>
/// Get all users
/// </summary>
[Route("api/users/all")]
public async Task<IEnumerable<User>> Get()
{
var query = Session.Query<User>().OrderBy(u => u.Firstname).ToListAsync();
return await query;
}
[HttpPost]
public async Task<ApiStatusCode> Post([FromBody]User userModel)
{
var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == userModel.Email);
if (ModelState.IsValid)
{
if (user != null)
return ApiStatusCode.Exists;
await Session.StoreAsync(userModel);
return ApiStatusCode.Saved;
}
return ApiStatusCode.Error;
}
[HttpDelete]
[Route("api/users/{email}")]
public async Task<ApiStatusCode> Delete(string email)
{
var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == email);
if (user == null)
return ApiStatusCode.Error;
Session.Delete<User>(user);
return ApiStatusCode.Deleted;
}
[HttpPut]
public async Task<ApiStatusCode> Put(User userModel)
{
var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == userModel.Email);
if (user != null)
{
user.Firstname = userModel.Firstname;
user.Lastname = userModel.Lastname;
user.Certificates = userModel.Certificates;
await Session.SaveChangesAsync();
return ApiStatusCode.Saved;
}
return ApiStatusCode.Error;
}
}
}
|
function LetterProps(o, sw, sc, fc, m, p) {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
}
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
this._mdf.o = false;
this._mdf.sw = false;
this._mdf.sc = false;
this._mdf.fc = false;
this._mdf.m = false;
this._mdf.p = false;
var updated = false;
if (this.o !== o) {
this.o = o;
this._mdf.o = true;
updated = true;
}
if (this.sw !== sw) {
this.sw = sw;
this._mdf.sw = true;
updated = true;
}
if (this.sc !== sc) {
this.sc = sc;
this._mdf.sc = true;
updated = true;
}
if (this.fc !== fc) {
this.fc = fc;
this._mdf.fc = true;
updated = true;
}
if (this.m !== m) {
this.m = m;
this._mdf.m = true;
updated = true;
}
if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) {
this.p = p;
this._mdf.p = true;
updated = true;
}
return updated;
};
|
<?php
namespace PHPAuth;
class Auth
{
protected $dbh;
public $config;
public $lang;
public function __construct(\PDO $dbh, $config, $language = "en_GB")
{
$this->dbh = $dbh;
$this->config = $config;
if (version_compare(phpversion(), '5.5.0', '<')) {
die('PHP 5.5.0 required for Auth engine!');
}
// Load language
require "languages/{$language}.php";
$this->lang = $lang;
date_default_timezone_set($this->config->site_timezone);
}
public function login($email, $password, $remember = 0, $captcha = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if ($block_status == "verify") {
$return['message'] = $this->lang["user_verify_failed"];
return $return;
}
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
$validateEmail = $this->validateEmail($email);
$validatePassword = $this->validatePassword($password);
if ($validateEmail['error'] == 1) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_invalid"];
return $return;
} elseif ($validatePassword['error'] == 1) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_invalid"];
return $return;
} elseif ($remember != 0 && $remember != 1) {
$this->addAttempt();
$return['message'] = $this->lang["remember_me_invalid"];
return $return;
}
$uid = $this->getUID(strtolower($email));
if (!$uid) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_incorrect"];
return $return;
}
$user = $this->getBaseUser($uid);
if (!password_verify($password, $user['password'])) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_incorrect"];
return $return;
}
if ($user['isactive'] != 1) {
$this->addAttempt();
$return['message'] = $this->lang["account_inactive"];
return $return;
}
$sessiondata = $this->addSession($user['uid'], $remember);
if ($sessiondata == false) {
$return['message'] = $this->lang["system_error"] . " #01";
return $return;
}
$return['error'] = false;
$return['message'] = $this->lang["logged_in"];
$return['hash'] = $sessiondata['hash'];
$return['expire'] = $sessiondata['expiretime'];
$return['cookie_name'] = $this->config->cookie_name;
return $return;
}
public function isEmailTaken($email)
{
$query = $this->dbh->prepare("SELECT count(*) FROM {$this->config->table_users} WHERE email = ?");
$query->execute(array($email));
if ($query->fetchColumn() == 0) {
return false;
}
return true;
}
protected function addUser($email, $password, $params = array(), &$sendmail)
{
$return['error'] = true;
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_users} (isactive) VALUES (0)");
if (!$query->execute()) {
$return['message'] = $this->lang["system_error"] . " #03";
return $return;
}
$uid = $this->dbh->lastInsertId("{$this->config->table_users}_id_seq");
$email = htmlentities(strtolower($email));
$isactive = 1;
$password = $this->getHash($password);
if (is_array($params)&& count($params) > 0) {
$customParamsQueryArray = Array();
foreach($params as $paramKey => $paramValue) {
$customParamsQueryArray[] = array('value' => $paramKey . ' = ?');
}
$setParams = ', ' . implode(', ', array_map(function ($entry) {
return $entry['value'];
}, $customParamsQueryArray));
} else { $setParams = ''; }
$query = $this->dbh->prepare("UPDATE {$this->config->table_users} SET email = ?, password = ?, isactive = ? {$setParams} WHERE id = ?");
$bindParams = array_values(array_merge(array($email, $password, $isactive), $params, array($uid)));
if (!$query->execute($bindParams)) {
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
$return['message'] = $this->lang["system_error"] . " #04";
return $return;
}
$return['error'] = false;
return $return;
}
public function getHash($password)
{
return password_hash($password, PASSWORD_BCRYPT, ['cost' => $this->config->bcrypt_cost]);
}
public function getUID($email)
{
$query = $this->dbh->prepare("SELECT id FROM {$this->config->table_users} WHERE email = ?");
$query->execute(array($email));
if(!$row = $query->fetch(\PDO::FETCH_ASSOC)) {
return false;
}
return $row['id'];
}
public function isLogged()
{
return (isset($_COOKIE[$this->config->cookie_name]) && $this->checkSession($_COOKIE[$this->config->cookie_name]));
}
public function getSessionHash()
{
return $_COOKIE[$this->config->cookie_name];
}
protected function getBaseUser($uid)
{
$query = $this->dbh->prepare("SELECT email, password, isactive FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
$data = $query->fetch(\PDO::FETCH_ASSOC);
if (!$data) {
return false;
}
$data['uid'] = $uid;
return $data;
}
protected function addSession($uid, $remember)
{
$ip = $this->getIp();
$user = $this->getBaseUser($uid);
if (!$user) {
return false;
}
$data['hash'] = sha1($this->config->site_key . microtime());
$agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$this->deleteExistingSessions($uid);
if ($remember == true) {
$data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_remember));
$data['expiretime'] = strtotime($data['expire']);
} else {
$data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_forget));
$data['expiretime'] = 0;
}
$data['cookie_crc'] = sha1($data['hash'] . $this->config->site_key);
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_sessions} (uid, hash, expiredate, ip, agent, cookie_crc) VALUES (?, ?, ?, ?, ?, ?)");
if (!$query->execute(array($uid, $data['hash'], $data['expire'], $ip, $agent, $data['cookie_crc']))) {
return false;
}
$data['expire'] = strtotime($data['expire']);
return $data;
}
protected function deleteSession($hash)
{
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
return $query->rowCount() == 1;
}
public function checkSession($hash)
{
$ip = $this->getIp();
$block_status = $this->isBlocked();
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return false;
}
if (strlen($hash) != 40) {
return false;
}
$query = $this->dbh->prepare("SELECT id, uid, expiredate, ip, agent, cookie_crc FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
if (!$row = $query->fetch(\PDO::FETCH_ASSOC)) {
return false;
}
$sid = $row['id'];
$uid = $row['uid'];
$expiredate = strtotime($row['expiredate']);
$currentdate = strtotime(date("Y-m-d H:i:s"));
$db_ip = $row['ip'];
$db_agent = $row['agent'];
$db_cookie = $row['cookie_crc'];
if ($currentdate > $expiredate) {
$this->deleteExistingSessions($uid);
return false;
}
if ($ip != $db_ip) {
return false;
}
if ($db_cookie == sha1($hash . $this->config->site_key)) {
return true;
}
return false;
}
public function getSessionUID($hash)
{
$query = $this->dbh->prepare("SELECT uid FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
if (!$row = $query->fetch(\PDO::FETCH_ASSOC)) {
return false;
}
return $row['uid'];
}
protected function deleteExistingSessions($uid)
{
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE uid = ?");
$query->execute(array($uid));
return $query->rowCount() == 1;
}
public function register($email, $password, $repeatpassword, $params = Array(), $captcha = NULL, $sendmail = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if ($block_status == "verify") {
//if ($this->checkCaptcha($captcha) == false) {
$return['message'] = $this->lang["user_verify_failed"];
return $return;
//}
}
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
if ($password !== $repeatpassword) {
$return['message'] = $this->lang["password_nomatch"];
return $return;
}
// Validate email
$validateEmail = $this->validateEmail($email);
if ($validateEmail['error'] == 1) {
$return['message'] = $validateEmail['message'];
return $return;
}
// Validate password
$validatePassword = $this->validatePassword($password);
if ($validatePassword['error'] == 1) {
$return['message'] = $validatePassword['message'];
return $return;
}
/*$zxcvbn = new Zxcvbn();
if ($zxcvbn->passwordStrength($password)['score'] < intval($this->config->password_min_score)) {
$return['message'] = $this->lang['password_weak'];
return $return;
}*/
if ($this->isEmailTaken($email)) {
$this->addAttempt();
$return['message'] = $this->lang["email_taken"];
return $return;
}
$addUser = $this->addUser($email, $password, $params, $sendmail);
if ($addUser['error'] != 0) {
$return['message'] = $addUser['message'];
return $return;
}
$return['error'] = false;
$return['message'] = ($sendmail == true ? $this->lang["register_success"] : $this->lang['register_success_emailmessage_suppressed'] );
return $return;
}
public function logout($hash)
{
if (strlen($hash) != 40) {
return false;
}
return $this->deleteSession($hash);
}
protected function validatePassword($password)
{
$return['error'] = true;
if (strlen($password) < (int)$this->config->verify_password_min_length ) {
$return['message'] = $this->lang["password_short"];
return $return;
}
$return['error'] = false;
return $return;
}
protected function validateEmail($email)
{
$return['error'] = true;
if (strlen($email) < (int)$this->config->verify_email_min_length ) {
$return['message'] = $this->lang["email_short"];
return $return;
} elseif (strlen($email) > (int)$this->config->verify_email_max_length ) {
$return['message'] = $this->lang["email_long"];
return $return;
}/* elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$return['message'] = $this->lang["email_invalid"];
return $return;
}
if ( (int)$this->config->verify_email_use_banlist ) {
$bannedEmails = json_decode(file_get_contents(__DIR__ . "/files/domains.json"));
if (in_array(strtolower(explode('@', $email)[1]), $bannedEmails)) {
$return['message'] = $this->lang["email_banned"];
return $return;
}
}*/
$return['error'] = false;
return $return;
}
public function isBlocked()
{
$ip = $this->getIp();
$this->deleteAttempts($ip, false);
$query = $this->dbh->prepare("SELECT count(*) FROM {$this->config->table_attempts} WHERE ip = ?");
$query->execute(array($ip));
$attempts = $query->fetchColumn();
if ($attempts < intval($this->config->attempts_before_verify)) {
return "allow";
}
if ($attempts < intval($this->config->attempts_before_ban)) {
//return "verify";
return "block";
}
return "block";
}
protected function addAttempt()
{
$ip = $this->getIp();
$attempt_expiredate = date("Y-m-d H:i:s", strtotime($this->config->attack_mitigation_time));
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_attempts} (ip, expiredate) VALUES (?, ?)");
return $query->execute(array($ip, $attempt_expiredate));
}
protected function deleteAttempts($ip, $all = false)
{
if ($all==true) {
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_attempts} WHERE ip = ?");
return $query->execute(array($ip));
}
$query = $this->dbh->prepare("SELECT id, expiredate FROM {$this->config->table_attempts} WHERE ip = ?");
$query->execute(array($ip));
while ($row = $query->fetch(\PDO::FETCH_ASSOC)) {
$expiredate = strtotime($row['expiredate']);
$currentdate = strtotime(date("Y-m-d H:i:s"));
if ($currentdate > $expiredate) {
$queryDel = $this->dbh->prepare("DELETE FROM {$this->config->table_attempts} WHERE id = ?");
$queryDel->execute(array($row['id']));
}
}
}
protected function getIp()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
}
|
b'What is 26 + -12 - 15 - (-2 + -4)?\n'
|
b'Evaluate 9 - 13 - (-10 + 13) - -3.\n'
|
b'5 + -1 + 2 - (15 - -4 - -11)\n'
|
#if false
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LionFire.Behaviors
{
public class Coroutine
{
}
}
#endif
|
b'-94 + -5 + 54 - -15\n'
|
b'What is 1 + 9 + (5 + -10 - 2) + 6?\n'
|
b'Evaluate -16 + (-6 - 1 - -22 - 24).\n'
|
b'-1 + (-2 + 3 - (-3 + 15))\n'
|
b'Evaluate 4 - (-3 + -1 + (16 - 15) + 8).\n'
|
b'What is the value of -6 + (0 - 5) + 17?\n'
|
b'Evaluate (7 - -13) + -67 + 59.\n'
|
b'Evaluate 13 + 5 + -12 + 12.\n'
|
b'Evaluate (-41 - -15) + 18 - (-9 + (3 - 2)).\n'
|
b'Calculate (-7 - ((6 - 2) + -16)) + (0 - 4).\n'
|
# Dreedi
To start your this app:
1. Install dependencies with `mix deps.get`
2. Create and migrate your database with `mix ecto.create && mix ecto.migrate`
3. Start Phoenix endpoint with `mix phoenix.server`
Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
|
b'What is -34 + -1 + 25 + 17?\n'
|
<?php
/**
* File: SimpleImage.php
* Author: Simon Jarvis
* Modified by: Miguel Fermín
* Based in: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*/
class Image_compression_helper {
public $image;
public $image_type;
public function __construct($filename = null) {
if (!empty($filename)) {
$this->load($filename);
}
}
public function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if ($this->image_type == IMAGETYPE_JPEG) {
$this->image = imagecreatefromjpeg($filename);
} elseif ($this->image_type == IMAGETYPE_GIF) {
$this->image = imagecreatefromgif($filename);
} elseif ($this->image_type == IMAGETYPE_PNG) {
$this->image = imagecreatefrompng($filename);
} else {
throw new Exception("The file you're trying to open is not supported");
}
}
public function example($url) {
// Usage:
// Load the original image
$image = new SimpleImage($url);
// Resize the image to 600px width and the proportional height
$image->resizeToWidth(600);
$image->save('lemon_resized.jpg');
// Create a squared version of the image
$image->square(200);
$image->save('lemon_squared.jpg');
// Scales the image to 75%
$image->scale(75);
$image->save('lemon_scaled.jpg');
// Resize the image to specific width and height
$image->resize(80, 60);
$image->save('lemon_resized2.jpg');
// Resize the canvas and fill the empty space with a color of your choice
$image->maxareafill(600, 400, 32, 39, 240);
$image->save('lemon_filled.jpg');
// Output the image to the browser:
$image->output();
}
public function save($filename, $image_type = IMAGETYPE_JPEG, $compression = 75, $permissions = null) {
if ($image_type == IMAGETYPE_JPEG) {
imagejpeg($this->image, $filename, $compression);
} elseif ($image_type == IMAGETYPE_GIF) {
imagegif($this->image, $filename);
} elseif ($image_type == IMAGETYPE_PNG) {
imagepng($this->image, $filename);
}
if ($permissions != null) {
chmod($filename, $permissions);
}
}
public function output($image_type = IMAGETYPE_JPEG, $quality = 80) {
if ($image_type == IMAGETYPE_JPEG) {
header("Content-type: image/jpeg");
imagejpeg($this->image, null, $quality);
} elseif ($image_type == IMAGETYPE_GIF) {
header("Content-type: image/gif");
imagegif($this->image);
} elseif ($image_type == IMAGETYPE_PNG) {
header("Content-type: image/png");
imagepng($this->image);
}
}
public function getWidth() {
return imagesx($this->image);
}
public function getHeight() {
return imagesy($this->image);
}
public function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = round($this->getWidth() * $ratio);
$this->resize($width, $height);
}
public function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = round($this->getHeight() * $ratio);
$this->resize($width, $height);
}
public function square($size) {
$new_image = imagecreatetruecolor($size, $size);
if ($this->getWidth() > $this->getHeight()) {
$this->resizeToHeight($size);
imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0));
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
imagecopy($new_image, $this->image, 0, 0, ($this->getWidth() - $size) / 2, 0, $size, $size);
} else {
$this->resizeToWidth($size);
imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0));
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
imagecopy($new_image, $this->image, 0, 0, 0, ($this->getHeight() - $size) / 2, $size, $size);
}
$this->image = $new_image;
}
public function scale($scale) {
$width = $this->getWidth() * $scale / 100;
$height = $this->getHeight() * $scale / 100;
$this->resize($width, $height);
}
public function resize($width, $height) {
$new_image = imagecreatetruecolor($width, $height);
imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0));
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
public function cut($x, $y, $width, $height) {
$new_image = imagecreatetruecolor($width, $height);
imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0));
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
imagecopy($new_image, $this->image, 0, 0, $x, $y, $width, $height);
$this->image = $new_image;
}
public function maxarea($width, $height = null) {
$height = $height ? $height : $width;
if ($this->getWidth() > $width) {
$this->resizeToWidth($width);
}
if ($this->getHeight() > $height) {
$this->resizeToheight($height);
}
}
public function minarea($width, $height = null) {
$height = $height ? $height : $width;
if ($this->getWidth() < $width) {
$this->resizeToWidth($width);
}
if ($this->getHeight() < $height) {
$this->resizeToheight($height);
}
}
public function cutFromCenter($width, $height) {
if ($width < $this->getWidth() && $width > $height) {
$this->resizeToWidth($width);
}
if ($height < $this->getHeight() && $width < $height) {
$this->resizeToHeight($height);
}
$x = ($this->getWidth() / 2) - ($width / 2);
$y = ($this->getHeight() / 2) - ($height / 2);
return $this->cut($x, $y, $width, $height);
}
public function maxareafill($width, $height, $red = 0, $green = 0, $blue = 0) {
$this->maxarea($width, $height);
$new_image = imagecreatetruecolor($width, $height);
$color_fill = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color_fill);
imagecopyresampled($new_image, $this->image, floor(($width - $this->getWidth()) / 2), floor(($height - $this->getHeight()) / 2), 0, 0, $this->getWidth(), $this->getHeight(), $this->getWidth(), $this->getHeight()
);
$this->image = $new_image;
}
}
|
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d;
int sum=1080;
while(cin>>a>>b>>c>>d)
{
if(a==0&&b==0&&c==0&&d==0)
break;
if(a>b)
{
sum=(a-b)*9+sum;
}
else if(a<b)
{
sum=((40-b)+a)*9+sum;
}
if(c>b)
{
sum=(c-b)*9+sum;
}
else if(c<b)
{
sum=((40-b)+c)*9+sum;
}
if(c>d)
{
sum=(c-d)*9+sum;
}
else if(c<d)
{
sum=((40-d)+c)*9+sum;
}
cout<<sum<<endl;
sum=1080;
}
return 0;
}
|
b'Calculate -325 + 317 + (-2 + 2 - 0).\n'
|
b'Calculate -32 - -1 - (-8 + (-17 - (-14 - 3))).\n'
|
b'Evaluate -3 + -9 + 9 - 2 - 16.\n'
|
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_petitioneer_session'
|
b'Evaluate 13 - ((-8 - -19) + -23).\n'
|
b'Evaluate -11 - (-21 + 16) - (-1 + 12).\n'
|
<?php
class Neostrada
{
const API_HOST = 'https://api.neostrada.nl/';
private $_key;
private $_secret;
public function __construct($key, $secret)
{
$this->_key = $key;
$this->_secret = $secret;
}
public function domain($domain)
{
return new Neostrada_Domain($this, $domain);
}
public function save(Neostrada_Domain $domain)
{
$data = [];
foreach ($domain->getRecords() as $record)
{
$data[$record->neostradaDnsId] = $record->toNeostradaFormat();
}
$this->request($domain, 'dns', [
'dnsdata' => serialize($data),
]);
return $this;
}
public function request(Neostrada_Domain $domain, $action, array $rawParams = [])
{
$params = [
'domain' => $domain->getName(),
'extension' => $domain->getExtension(),
] + $rawParams;
$params['api_sig'] = $this->_calculateSignature($action, $params);
$params['action'] = $action;
$params['api_key'] = $this->_key;
$url = self::API_HOST . '?' . http_build_query($params, '', '&');
$c = curl_init();
if ($c === false)
{
throw new \RuntimeException('Could not initialize cURL');
}
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_HEADER, 0);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$rawData = curl_exec($c);
if ($rawData === false)
{
throw new \RuntimeException('Could not complete cURL request: ' . curl_error($c));
}
curl_close($c);
$oldUseErrors = libxml_use_internal_errors(true);
$xml = simplexml_load_string($rawData);
if ($xml === false)
{
$message = libxml_get_errors()[0]->message;
libxml_use_internal_errors($oldUseErrors);
throw new \RuntimeException('Invalid XML: ' . $message);
}
libxml_use_internal_errors($oldUseErrors);
$this->_validateResponse($xml);
return $xml;
}
private function _validateResponse(SimpleXMLElement $xml)
{
if ((string) $xml->code !== '200')
{
throw new \UnexpectedValueException('Request failed [' . $xml->code . ']: ' . $xml->description);
}
}
private function _calculateSignature($action, array $params = [])
{
$signature = $this->_secret . $this->_key . 'action' . $action;
foreach ($params as $key => $value)
{
$signature .= $key . $value;
}
return md5($signature);
}
}
|
// rd_route.c
// Copyright (c) 2014-2015 Dmitry Rodionov
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include <stdlib.h> // realloc()
#include <libgen.h> // basename()
#include <assert.h> // assert()
#include <stdio.h> // fprintf()
#include <dlfcn.h> // dladdr()
#include "TargetConditionals.h"
#if defined(__i386__) || defined(__x86_64__)
#if !(TARGET_IPHONE_SIMULATOR)
#include <mach/mach_vm.h> // mach_vm_*
#else
#include <mach/vm_map.h> // vm_*
#define mach_vm_address_t vm_address_t
#define mach_vm_size_t vm_size_t
#define mach_vm_allocate vm_allocate
#define mach_vm_deallocate vm_deallocate
#define mach_vm_write vm_write
#define mach_vm_remap vm_remap
#define mach_vm_protect vm_protect
#define NSLookupSymbolInImage(...) ((void)0)
#define NSAddressOfSymbol(...) ((void)0)
#endif
#else
#endif
#include <mach-o/dyld.h> // _dyld_*
#include <mach-o/nlist.h> // nlist/nlist_64
#include <mach/mach_init.h> // mach_task_self()
#include "rd_route.h"
#define RDErrorLog(format, ...) fprintf(stderr, "%s:%d:\n\terror: "format"\n", \
__FILE__, __LINE__, ##__VA_ARGS__)
#if defined(__x86_64__)
typedef struct mach_header_64 mach_header_t;
typedef struct segment_command_64 segment_command_t;
#define LC_SEGMENT_ARCH_INDEPENDENT LC_SEGMENT_64
typedef struct nlist_64 nlist_t;
#else
typedef struct mach_header mach_header_t;
typedef struct segment_command segment_command_t;
#define LC_SEGMENT_ARCH_INDEPENDENT LC_SEGMENT
typedef struct nlist nlist_t;
#endif
typedef struct rd_injection {
mach_vm_address_t injected_mach_header;
mach_vm_address_t target_address;
} rd_injection_t;
static void* _function_ptr_within_image(const char *function_name, void *macho_image_header, uintptr_t vm_image_slide);
void* function_ptr_from_name(const char *function_name)
{
assert(function_name);
for (uint32_t i = 0; i < _dyld_image_count(); i++) {
void *header = (void *)_dyld_get_image_header(i);
uintptr_t vmaddr_slide = _dyld_get_image_vmaddr_slide(i);
void *ptr = _function_ptr_within_image(function_name, header, vmaddr_slide);
if (ptr) { return ptr; }
}
RDErrorLog("Failed to find symbol `%s` in the current address space.", function_name);
return NULL;
}
static void* _function_ptr_within_image(const char *function_name, void *macho_image_header, uintptr_t vmaddr_slide)
{
assert(function_name);
assert(macho_image_header);
/**
* Try the system NSLookup API to find out the function's pointer withing the specifed header.
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
void *pointer_via_NSLookup = ({
NSSymbol symbol = NSLookupSymbolInImage(macho_image_header, function_name,
NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
NSAddressOfSymbol(symbol);
});
#pragma clang diagnostic pop
if (pointer_via_NSLookup) return pointer_via_NSLookup;
return NULL;
}
|
b'Evaluate 0 + 20 + -8 + -5 + -15 + 3.\n'
|
b'What is 97 - 64 - (11 - 3)?\n'
|
b'Calculate -33 + (-43 - -99) - (-1 + 0).\n'
|
b'What is 3 + (29 - 23) + (4 - 2) + 0?\n'
|
b'What is the value of (0 - (-10 + 17)) + 20?\n'
|
b'Calculate -4 + (-24 + 3 - -43).\n'
|
# Toady 1.0
Wickedly extensible IRC bot written in Node.js. Load and reload mods without reconnecting.
## Please pay attention: This master branch is merged with version 1.x from Toady and got extended afterwards!
## Download. Install. Fly.
If you don't already have Node.js, [get it](http://nodejs.org). It's awesome.
And also required.
Then, grab Toady from Github by using the [download link](https://github.com/TomFrost/Toady/archive/master.zip),
or if you're dev-minded and like to stay updated, clone it on the command line:
git clone [email protected]:TomFrost/Toady.git
Get into that folder on the command line and install:
npm install
## Configure it. Just a little bit.
Copy config/default.yaml.sample to config/default.yaml. Enter your server
settings, change Toady's name, and pay extra careful attention to the section
marked with
## !!IMPORTANT!! ##
Because four exclamation points means business, son.
## You turn Toady on.
To launch (from the Toady directory) on any non-Windows machine, or Cygwin:
./ribbit start
If you're on Windows, it's:
ribbit.cmd start
Need to launch it on more than one server? Just copy config/default.yaml to
config/myotherserver.yaml, edit it for the new server, and launch
Toady like this:
./ribbit start myotherserver
When he's in your channel, do this in IRC for more info:
/msg Toady help
## Teach Toady new tricks.
Toady can be extended through simple mods, and mods can make Toady do
practially anything. Mods can be searched for, installed, and uninstalled
through ribbit.
**IMPORTANT NOTE: This section shows you how to install third-party mods.
These are not moderated, maintained, guaranteed, or otherwise vetted by
Toady's author. Install at your own risk, as mods are capable of anything!**
List all Toady mods:
./ribbit search
# Or in IRC: /msg Toady ribbit search
List only mods that deal with typos:
./ribbit search typo
# Or in IRC: /msg Toady ribbit search typo
Install a mod:
./ribbit install typofix
# Or in IRC, just say: !ribbit install typofix
Uninstall a mod:
./ribbit uninstall typofix
# Or in IRC, just say: !ribbit uninstall typofix
Did I mention you can search, download, and install mods into a running Toady
instance directly from IRC? Yeah. Toady's like that.
## Write your own mods! (It's easy)
Mods for Toady are standard Node.js modules. They can have their own
node_modules folder with dependencies set up in a package.json, they can
require() whatever they need, they can open new ports, and they can interact
with the entire Toady framework including other mods. Toady mods have no
limitations.
### Make a basic mod
For your first mod, make a folder in Toady's 'mods' folder called 'test'.
That makes 'test' your mod's 'id' -- no other mod can be loaded with the same
id. Inside of mods/test, create index.js and paste in the following. This is
the most basic form of a mod:
/**
* Creates a new Test mod
*
* @param {Object} config Contains config fields specific to this mod
* @param {Object} client The connected IRC client powering the bot
* @param {Object} modMan A reference to the ModManager object,
* responsible for loading/unloading mods and commands.
* @returns {Object} The new Test mod
*/
module.exports = function(config, client, modMan) {
return {
name: "My Test Mod",
version: "0.1.0",
author: "Me, Myself, and I",
desc: "I just made this to screw around",
commands: {
greet: {
handler: function(from, to, target, args) {
client.say(target, "Hi " + from + "!");
},
desc: "Makes the bot say Hi to you.",
help: [
"Format: {cmd} [#channel]",
"Examples:",
" /msg {nick} {cmd} #room",
" {!}{cmd}",
" {!}{cmd} #otherRoomImIn",
" ",
"If this is said in a channel, I'll greet you on the" +
"same channel if no other is specified."
],
targetChannel: true
}
}
};
};
If Toady isn't running yet, this mod will be loaded automatically when you
start him up. If he *is* currently running, just say this:
!loadmod test
And now you can try out your new `!greet` command. Any time you make a change
to this mod and want Toady to update to the latest version, just say:
!reloadmod test
For a list of these and other mod-related commands, type
!viewmod modcontrol
### Structure of a mod
The object literal that the exported function returns has the following
properties:
#### name: string
The name given to your mod when it's listed with `!help` or `!viewmod`.
#### version: string
The version of your mod. This should follow the semantic versioning guidelines
at [semver.org](http://semver.org). **You can omit this if your mod has a
package.json file with a version! Toady will pull it from there instead.**
#### author: string
Your name! You can optionally specify your E-mail address, in the format
`Your Name <[email protected]>`. **You can omit this if your mod has a
package.json file with an author! Toady will pull it from there instead.**
#### desc: string
A very brief, one-liner description of what your mod does. This will show
up in the `!viewmod` output. **You can omit this if your mod has a
package.json file with a description! Toady will pull it from there instead.**
#### unload: function() *(optional)*
A function that will be called immediately before unloading this module in the
ModManager. **If any event listeners have been placed on the ModManager
or the IRC client object, they MUST BE REMOVED by this function!** Toady cannot
enforce this, so it is up to you, the mod author, to make sure. Toady will
have unexpected and unstable behavior if this function does not remove all
the mod's listeners.
#### configItems: object *(optional)*
A mapping of configuration keys to objects defining that key. The object
has the following properties, all of which are optional:
{
desc: "Describe what this option means in a one-liner",
type: "number", // Either string, boolean, or number.
validate: function(value) { return true; }
}
These items will be made available to be changed by the 'config' core module.
If a type is specified, the user input will be cast to that type. If validate
is specified, the value will be passed to it and the function can return one
of three things:
- {Error} If validation failed and an error message should be provided
to the user
- {boolean} false if validation failed and a generic error message
should be provided to the user
- {boolean} true if validation passed
#### blockReload: boolean *(optional, default false)*
If true, this will stop your mod from being reloaded with the `!reloadmod`
command. While this can be convenient to stop the mod's "memory" from being
wiped by an unsuspecting Owner or SuperUser, this is *extremely bad practice*.
Use the config object to save changes rather than blocking your mod from
being reloaded.
#### blockUnload: boolean *(optional, default false)*
If true, this will stop your mod from being unloaded with the `!unloadmod`
command, but *not* through the `!reloadmod` command. **This should only
ever be used for mods that are core to the function of the bot**
#### commands
An object literal that maps command names (whatever you would msg Toady or
say in a room with the fantasy char) to command objects. Those are defined
below. *This field is optional; not all mods have user-callabe commands.*
### Structure of a Command
Commands are managed by the Toady framework to prevent name overlaps, ensure
users have the appropriate permissions, etc. If your mod just needs to listen
for IRC events and react to them, no commands are necessary. But if you want
someone to be able to say `!somecommand`, here's how:
#### handler: function(from, to, target, args, inChan)
The function that executes when the function is called. The arguments are:
- *from* - The nick of the user calling the command
- *to* - The bot's name if this was sent in a private message, or the channel the command was spoken in if not.
- *target* - The channel or nick targeted for the command. This is configured below.
- *args* - An array containing the arguments to this command. If no *pattern* is specified below, this will have just one element: The entire string following the command or target.
- *inChan* - True if the command was said in a channel (and thus 'to' is a channel name); false if the command was messaged privately (and this 'to' is the bot's nick).
#### desc: string
A brief one-liner description of what the command does. Shown in `!help`.
#### help: array
An array of strings to be sent in the `!help` command. Each string will be
sent in its own IRC NOTICE, so this can be utilized to control line breaks.
The following placeholders will be automatically replaced with the appropriate
contents:
- **{!}** - The configured fantasy character
- **{cmd}** - The name of the command
- **{mod}** - The name of the mod (specified in the mod's `name` field)
- **{modId}** - The id of the mod (usually, its folder name in the mods folder)
- **{nick}** - The nickname of the bot
- **{version}** - The version number of the mod
#### minPermission: string *(optional)*
The permission character of the lowest permission allowed to call this command.
If omitted, the command won't be restricted by permission. Toady recognizes
the following permissions, in order from most to least privileged:
- **O** - Owner. Full access to all commands, cannot be revoked.
- **S** - SuperUser. Full access to all commands, except those which may impact other Owners or SuperUsers.
- **P** - PowerUser. Limited access to global command set.
- **~** - Channel founder
- **&** - Channel admin
- **@** - Channel op
- **%** - Channel half-op
- **+** - Voice
- **''** - (Empty string) A user in a channel
The **O**, **S**, and **P** permissions are Toady-specfic and can be set with
the `!adduser` and `!updateuser` commands. All others come directly from IRC.
#### pattern: RexExp *(optional)*
The regex pattern that the command arguments must match in order for the
function to be called. If specified, the `args` argument in the handler
function will be the result of the match -- so index 0 will be the entire
string, 1 will be the first paranthetical match, 2 will be the second, and so
on. If targetChannel or targetNick is specified as described below, this
pattern will *NOT* be applied to the target argument.
#### targetChannel: boolean *(optional, default false)*
Setting this to `true` will require that the first argument to the command
is a channel name, prefixed with `#` or `&`. If the command is said in a
channel using the fantasy char, the channel can be omitted and it will be
assumed that the target is the same channel. This value will be passed in the
handler's `target` argument.
#### targetNick: boolean *(optional, default false)*
Setting this to `true` will require that the first argument to the command
is a user's nick. **Note that this will *not* ensure that the nick is real
or connected -- it just assumes the first argument is the target nick**.
This value will be passed in the handler's `target` argument.
#### hidden: boolean *(optional, default false)*
Setting this to `true` will cause this command to be omitted from `!help`.
This can be useful in games where certain commands would only make sense to
users if the game is currently running. The "hidden" flag can be turned on
and off dynamically as needed. It should **never** be used to exercise
any form of security through obscurity. Use *minPermission* to restrict
access to commands.
### Config
The `config` argument passed to each mod is an object literal containing
configuration fields. The fields are loaded in the following order, with
each step overwriting any existing fields from previous steps:
- The mod's own module.exports.configDefaults object, if one exists
- The mod_MODNAME-HERE section from the .yaml config file currently in use, if it exists
- The config/CONFNAME-mod_MODNAME.json file, if it exists
So if a mod named "test" is written with this at the bottom:
module.exports.configDefaults = {
delay: 12,
message: 'Hello!',
name: 'Ted'
};
And **config/default.yaml** contains this block:
mod_test:
delay: 5
And the file **config/default-mod_test.json** contains this:
{
"message": "Yo!"
}
Then the config object passed into the 'test' mod when it's loaded will be:
{
delay: 5,
message: "Yo!",
name: "Ted"
}
Why the complexity?
- module.exports.configDefaults allows you to define the default values your mod will be instantiated with, so that no error checking for nonexistant config values is necessary
- The block in the .yaml file allows the bot owner to easily specify new config options
- The .json file is what the config object itself saves when config.save() is called.
Note that any mod can access any other mod's config object to read, write, and
save with the following call. This should be used sparingly and only when
absolutely necessary, as the target mod may not be prepared to handle dynamic
changes in its config:
var otherModConfig = modMan.getMod('otherModId').config;
#### config.save(_\[{Array} properties\]_, _\[{Function} callback\]_)
The 'save' function is the only value that Toady itself adds to your config
object, and it is non-enumable -- so iterating over your config values will not
show 'save' as a property. It's there, though, and calling it will write the
file config/default-mod_MODNAME.json, where "default" is the name of the .yaml
file currently in use. Any saved config will be provided back to the mod if
it's reloaded, or the bot is restarted.
If _properties_ is omitted, all enumerable properties on the config object will
be saved. But _properties_ can be set to an array of strings representing
the only config keys that should be saved in the resulting file.
The optional callback function will be called with an Error object from
_fs.writeFile_ if the write fails, or with no error upon success.
### Client
The IRC client provided to each mod is an instance of martynsmith's
fantastic [node-irc](https://github.com/martynsmith/node-irc) client, unaltered
in any way except for configuring and connecting it according to the options
defined in the configuration yaml file.
The client object allows the bot to send messages, join, part, quit, change
nicks, etc -- anything you would expect an IRC client to do. It also tracks
the bot's nick as well as the users and their permissions in the channels the
bot is in, and exposes many events you can hook to be notified of new messages,
nick changes, parts, and more. Just skim [the node-irc documentation site](https://node-irc.readthedocs.org/en/latest/API.html)
for details.
Here are a few examples of how easy the client is to use:
client.say('#myChan', "HI GUYS! MY NAME IS " + client.nick + "!!!");
function nickHandler(oldnick, newnick, channels) {
channels.forEach(function(channel) {
client.say(channel, "Stop changing your name, " + newnick);
});
}
client.on('nick', nickHandler);
// And your mod's 'unload' function MUST contain this line
// if you do the above:
// client.removeListener('nick', nickHandler);
### ModManager
The ModManager instance that gets passed to each mod on load is a singleton
responsible for loading/unloading all mods, collecting command objects, and
providing all of these things to other mods on request. In addition to
returning official mod properties in the resulting object literal, arbitrary
properties can be added for other mods to take advantage of. For example,
the 'users' mod includes functions for finding and checking user permissions.
If your mod needs to do that, you could call:
var usersMod = modMan.getMod('users');
client.say(channel, "You have the permission: " + usersMod.getPermission(nick));
The ModManager also emits events for when mods and commands are
loaded/unloaded, so if your mod needs to modify all new commands as they load
(maybe your mod's goal is to remove permission requirements from all comamnds?),
listening for those events is extremely easy.
Since the use cases for accessing the ModManager are fairly rare, I'll refer to
the very thorough in-code documentation in app/modmanager/ModManager.js to
guide you to the different events and function calls.
### Mod Metadata
Toady mods all assign module.exports to a function. However, some features
can be impacted before the mod is fully loaded by assigning other properties
to module.exports as well.
#### module.exports.configDefaults = {Object}
A mapping of config keys to their default value, which will be passed in the
module's _'config'_ argument at load time unless a key or keys have been
overridden through other means. See **Config** above for details.
#### module.exports.minToadyVersion = {String}
The minimum version of Toady with which this mod is compatible. Toady will
refuse to load the mod if this value is greater than Toady's own version.
### Examples
Learn faster from looking at code than reading docs? Nearly all of Toady's
functionality happens in mods -- from the help commands, to finding and
verifying user permissions, to even detecting and executing commands
themselves. All of these core mods are very thoroughly documented in the
app/coremods folder.
## Distribute your mods on ribbit
To get your mods on ribbit, all you need to do is publish your mod to NPM
under the following name:
toady-mod_name_here
So if your mod is named 'typofix', your mod's package.json should contain
this line:
"name": "toady-typofix"
Don't have a package.json yet? Just type `npm init` in your mod's directory
and follow the prompts, giving it the "toady-" prefixed name when it asks.
If you haven't already done it, run `npm adduser` to log in (or make an
account) on NPM, and then run `npm publish` to give your mod to the world.
It should show up in ribbit searches within a few minutes.
## Toady has a lawyer
Toady is distributed under the BSD license. See the 'LICENSE.txt' file for the
legalese. It's friendly and open, I promise.
## Toady has a purpose in life
I wrote Toady in 2013 to help manage my dev team's IRC room. There are other
bots, but this is the magical mix of features that few of the others had:
- Written in Javascript, so practically anyone can extend it
- Dead-simple command framework, so new commands are no more than a few lines of code away
- Can develop on it and test mods without restarting (/msg Toady viewmod modcontrol)
- Can restrict its commands by its own global permissions as well as channel and NickServ permissions on the IRC server itself
- Since it's Node.js, making mods do crazy stuff like hosting websites to view channel logs right within Toady is as simple as `npm install express`
## Obligatory Copyright
Toady is Copyright ©2013 Tom Frost.
|
---
name: Dreadnought
type: AV
speed: 15cm
armour: 3+
cc: 4+
ff: 4+
special_rules:
- walker
notes:
|
Armed with either a Missile Launcher and Twin Lascannon, or an Assault Cannon and Power Fist.
weapons:
-
id: missile-launcher
multiplier: 0–1
-
id: twin-lascannon
multiplier: 0–1
-
id: assault-cannon
multiplier: 0–1
-
id: power-fist
multiplier: 0–1
---
|
require "spec_helper"
module Smsru
describe API do
shared_context "shared configuration", need_values: 'configuration' do
before :each do
Smsru.configure do |conf|
conf.api_id = 'your-api-id'
conf.from = 'sender-name'
conf.test = test
conf.format = format
end
end
subject { Smsru::API }
end
shared_examples 'send_sms' do
it { expect(VCR.use_cassette(cassette) { subject.send_sms(phone, text) }).to eq(response) }
end
shared_examples 'send_group_sms' do
it { expect(VCR.use_cassette(cassette) { subject.group_send(phone, text) }).to eq(response) }
end
let(:text) { 'Sample of text that will have sended inside sms.' }
let(:phone) { '+79050000000' }
context 'test', need_values: 'configuration' do
let(:test) { true }
describe 'format = false' do
it_behaves_like "send_sms" do
let(:response) { "100\n000-00000" }
let(:cassette) { 'api/send_sms' }
let(:format) { false }
end
end
describe 'error message' do
let(:phone) { '0000' }
let(:raw_response) { "202\n0000" }
it_behaves_like "send_sms" do
let(:response) { raw_response }
let(:cassette) { 'api/error_sms' }
let(:format) { false }
end
it_behaves_like "send_sms" do
let(:response) { Smsru::Response.new(phone, raw_response) }
let(:cassette) { 'api/error_sms' }
let(:format) { true }
end
end
describe 'group send sms' do
let(:raw_response) { "100\n000-00000\n000-00000" }
let(:phone) { ['+79050000000', '+79060000000'] }
let(:cassette) { 'api/group_sms' }
describe 'format = true' do
it_behaves_like "send_group_sms" do
let(:response_phone) { '+79050000000,+79060000000' }
let(:response) { [Smsru::Response.new(response_phone, raw_response)] }
let(:format) { true }
end
end
describe 'format = false' do
it_behaves_like "send_group_sms" do
let(:response) { [raw_response] }
let(:format) { false }
end
end
end
end
context 'production', need_values: 'configuration' do
let(:test) { false }
describe 'send sms' do
let(:raw_response) { "100\n000-00000\nbalance=1000" }
let(:cassette) { 'api/send_sms_production' }
describe 'format = false' do
it_behaves_like "send_sms" do
let(:response) { raw_response }
let(:format) { false }
end
end
describe 'format = true' do
it_behaves_like "send_sms" do
let(:response) { Smsru::Response.new(phone, raw_response) }
let(:format) { true }
end
end
end
describe 'group send sms' do
let(:raw_response) { "100\n000-00000\n000-00000\nbalance=1000" }
let(:cassette) { 'api/group_sms_production' }
let(:phone) { ['+79050000000', '+79060000000'] }
let(:response_phone) { '+79050000000,+79060000000' }
describe 'format = true' do
it_behaves_like "send_group_sms" do
let(:response) { [Smsru::Response.new(response_phone, raw_response)] }
let(:format) { true }
end
end
describe 'format = false' do
it_behaves_like "send_group_sms" do
let(:response) { [raw_response] }
let(:format) { false }
end
end
end
end
end
end
|
describe("Dragable Row Directive ", function () {
var scope, container, element, html, compiled, compile;
beforeEach(module("app", function ($provide) { $provide.value("authService", {}) }));
beforeEach(inject(function ($compile, $rootScope) {
html = '<div id="element-id" data-draggable-row=""'
+ ' data-draggable-elem-selector=".draggable"'
+ ' data-drop-area-selector=".drop-area">'
+ '<div class="draggable"></div>'
+ '<div class="drop-area" style="display: none;"></div>'
+ '</div>';
scope = $rootScope.$new();
compile = $compile;
}));
function prepareDirective(s) {
container = angular.element(html);
compiled = compile(container);
element = compiled(s);
s.$digest();
}
/***********************************************************************************************************************/
it('should add draggable attribute to draggable element, when initialise', function () {
prepareDirective(scope);
expect(element.find('.draggable').attr('draggable')).toBe('true');
});
it('should prevent default, when dragging over allowed element', function () {
prepareDirective(scope);
var event = $.Event('dragover');
event.preventDefault = window.jasmine.createSpy('preventDefault');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.trigger(event);
expect(event.preventDefault).toHaveBeenCalled();
});
it('should show drop area, when drag enter allowed element', function () {
prepareDirective(scope);
var event = $.Event('dragenter');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.trigger(event);
expect(element.find('.drop-area').css('display')).not.toEqual('none');
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
});
it('should call scope onDragEnd, when dragging ends', function () {
prepareDirective(scope);
var event = $.Event('dragend');
var isolateScope = element.isolateScope();
spyOn(isolateScope, 'onDragEnd');
element.trigger(event);
expect(isolateScope.onDragEnd).toHaveBeenCalled();
});
it('should set drag data and call scope onDrag, when drag starts', function () {
prepareDirective(scope);
var event = $.Event('dragstart');
event.originalEvent = {
dataTransfer: {
setData: window.jasmine.createSpy('setData')
}
};
var isolateScope = element.isolateScope();
spyOn(isolateScope, 'onDrag');
element.find('.draggable').trigger(event);
expect(isolateScope.onDrag).toHaveBeenCalled();
expect(event.originalEvent.dataTransfer.setData).toHaveBeenCalledWith('draggedRow', 'element-id');
});
it('should prevent default, when dragging over allowed drop area', function () {
prepareDirective(scope);
var event = $.Event('dragover');
event.preventDefault = window.jasmine.createSpy('preventDefault');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.find('.drop-area').trigger(event);
expect(event.preventDefault).toHaveBeenCalled();
});
it('should show drop area, when drag enter allowed drop area', function () {
prepareDirective(scope);
var event = $.Event('dragenter');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.find('.drop-area').trigger(event);
expect(element.find('.drop-area').css('display')).not.toEqual('none');
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
});
it('should hide drop area, when drag leave drop area', function () {
prepareDirective(scope);
var event = $.Event('dragleave');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.find('.drop-area').trigger(event);
expect(element.find('.drop-area').css('display')).toEqual('none');
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
});
it('should hide drop area and call scope onDrop, when drop on drop area', function () {
prepareDirective(scope);
var event = $.Event('drop');
event.preventDefault = window.jasmine.createSpy('preventDefault');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
var isolateScope = element.isolateScope();
spyOn(isolateScope, 'onDrop');
element.find('.drop-area').trigger(event);
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
expect(event.preventDefault).toHaveBeenCalled();
expect(element.find('.drop-area').css('display')).toEqual('none');
expect(isolateScope.onDrop).toHaveBeenCalled();
});
});
|
/**
* Created by Keerthikan on 29-Apr-17.
*/
export {expenseSpyFactory} from './expense-spy-factory';
export {compensationSpyFactory} from './compensation-spy-factory';
|
b'Calculate (217 - 193) + (-4 - -12).\n'
|
<?php
/*
Safe sample
input : get the field UserData from the variable $_POST
sanitize : use of ternary condition
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = $_POST['UserData'];
$tainted = $tainted == 'safe1' ? 'safe1' : 'safe2';
$var = http_redirect("pages/'". $tainted . "'.php");
?>
|
import m from 'mithril';
import _ from 'underscore';
import postgrest from 'mithril-postgrest';
import models from '../models';
import h from '../h';
import projectDashboardMenu from '../c/project-dashboard-menu';
import projectContributionReportHeader from '../c/project-contribution-report-header';
import projectContributionReportContent from '../c/project-contribution-report-content';
import projectsContributionReportVM from '../vms/projects-contribution-report-vm';
import FilterMain from '../c/filter-main';
import FilterDropdown from '../c/filter-dropdown';
import InfoProjectContributionLegend from '../c/info-project-contribution-legend';
import ProjectContributionStateLegendModal from '../c/project-contribution-state-legend-modal';
import ProjectContributionDeliveryLegendModal from '../c/project-contribution-delivery-legend-modal';
const projectContributionReport = {
controller(args) {
const listVM = postgrest.paginationVM(models.projectContribution, 'id.desc', {
Prefer: 'count=exact'
}),
filterVM = projectsContributionReportVM,
project = m.prop([{}]),
rewards = m.prop([]),
contributionStateOptions = m.prop([]),
reloadSelectOptions = (projectState) => {
let opts = [{
value: '',
option: 'Todos'
}];
const optionsMap = {
online: [{
value: 'paid',
option: 'Confirmado'
},
{
value: 'pending',
option: 'Iniciado'
},
{
value: 'refunded,chargeback,deleted,pending_refund',
option: 'Contestado'
},
],
waiting_funds: [{
value: 'paid',
option: 'Confirmado'
},
{
value: 'pending',
option: 'Iniciado'
},
{
value: 'refunded,chargeback,deleted,pending_refund',
option: 'Contestado'
},
],
failed: [{
value: 'pending_refund',
option: 'Reembolso em andamento'
},
{
value: 'refunded',
option: 'Reembolsado'
},
{
value: 'paid',
option: 'Reembolso não iniciado'
},
],
successful: [{
value: 'paid',
option: 'Confirmado'
},
{
value: 'refunded,chargeback,deleted,pending_refund',
option: 'Contestado'
},
]
};
opts = opts.concat(optionsMap[projectState] || []);
contributionStateOptions(opts);
},
submit = () => {
if (filterVM.reward_id() === 'null') {
listVM.firstPage(filterVM.withNullParameters()).then(null);
} else {
listVM.firstPage(filterVM.parameters()).then(null);
}
return false;
},
filterBuilder = [{
component: FilterMain,
data: {
inputWrapperClass: '.w-input.text-field',
btnClass: '.btn.btn-medium',
vm: filterVM.full_text_index,
placeholder: 'Busque por nome ou email do apoiador'
}
},
{
label: 'reward_filter',
component: FilterDropdown,
data: {
label: 'Recompensa selecionada',
onchange: submit,
name: 'reward_id',
vm: filterVM.reward_id,
wrapper_class: '.w-sub-col.w-col.w-col-4',
options: []
}
},
{
label: 'delivery_filter',
component: FilterDropdown,
data: {
custom_label: [InfoProjectContributionLegend, {
content: [ProjectContributionDeliveryLegendModal],
text: 'Status da entrega'
}],
onchange: submit,
name: 'delivery_status',
vm: filterVM.delivery_status,
wrapper_class: '.w-col.w-col-4',
options: [{
value: '',
option: 'Todos'
},
{
value: 'undelivered',
option: 'Não enviada'
},
{
value: 'delivered',
option: 'Enviada'
},
{
value: 'error',
option: 'Erro no envio'
},
{
value: 'received',
option: 'Recebida'
}
]
}
},
{
label: 'payment_state',
component: FilterDropdown,
data: {
custom_label: [InfoProjectContributionLegend, {
text: 'Status do apoio',
content: [ProjectContributionStateLegendModal, {
project
}]
}],
name: 'state',
onchange: submit,
vm: filterVM.state,
wrapper_class: '.w-sub-col.w-col.w-col-4',
options: contributionStateOptions
}
}
];
filterVM.project_id(args.root.getAttribute('data-id'));
const lReward = postgrest.loaderWithToken(models.rewardDetail.getPageOptions({
project_id: `eq.${filterVM.project_id()}`
}));
const lProject = postgrest.loaderWithToken(models.projectDetail.getPageOptions({
project_id: `eq.${filterVM.project_id()}`
}));
lReward.load().then(rewards);
lProject.load().then((data) => {
project(data);
reloadSelectOptions(_.first(data).state);
});
const mapRewardsToOptions = () => {
let options = [];
if (!lReward()) {
options = _.map(rewards(), r => ({
value: r.id,
option: `R$ ${h.formatNumber(r.minimum_value, 2, 3)} - ${r.description.substring(0, 20)}`
}));
}
options.unshift({
value: null,
option: 'Sem recompensa'
});
options.unshift({
value: '',
option: 'Todas'
});
return options;
};
if (!listVM.collection().length) {
listVM.firstPage(filterVM.parameters());
}
return {
listVM,
filterVM,
filterBuilder,
submit,
lReward,
lProject,
rewards,
project,
mapRewardsToOptions
};
},
view(ctrl) {
const list = ctrl.listVM;
if (!ctrl.lProject()) {
return [
m.component(projectDashboardMenu, {
project: m.prop(_.first(ctrl.project()))
}),
m.component(projectContributionReportHeader, {
submit: ctrl.submit,
filterBuilder: ctrl.filterBuilder,
form: ctrl.filterVM.formDescriber,
mapRewardsToOptions: ctrl.mapRewardsToOptions,
filterVM: ctrl.filterVM
}),
m('.divider.u-margintop-30'),
m.component(projectContributionReportContent, {
submit: ctrl.submit,
list,
filterVM: ctrl.filterVM,
project: m.prop(_.first(ctrl.project()))
})
];
}
return h.loader();
}
};
export default projectContributionReport;
|
b'6 - 4 - -5 - (-20 - -31)\n'
|
import { Component, OnInit, HostListener, ElementRef } from '@angular/core';
import { Router, NavigationEnd, NavigationExtras } from '@angular/router';
import { AuthService } from '../../services/auth.service';
@Component({
selector: 'app-nav',
templateUrl: 'app-nav.component.html'
})
export class AppNavComponent implements OnInit {
loggedIn: boolean;
menuDropped: boolean;
searchKeyword: string;
constructor(
public auth: AuthService,
private router: Router,
private elementRef: ElementRef
) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.menuDropped = false;
this.searchKeyword = '';
}
});
this.searchKeyword = '';
}
ngOnInit() {
this.auth.checkLogin();
}
toggleMenu() {
this.menuDropped = !this.menuDropped;
}
logout(): void {
this.auth.logout();
this.menuDropped = false;
}
searchPackages(e: Event): void {
e.preventDefault();
const navigationExtras: NavigationExtras = {
queryParams: { 'keyword': this.searchKeyword }
};
this.router.navigate(['search'], navigationExtras);
}
@HostListener('document:click', ['$event'])
onBlur(e: MouseEvent) {
if (!this.menuDropped) {
return;
}
let toggleBtn = this.elementRef.nativeElement.querySelector('.drop-menu-act');
if (e.target === toggleBtn || toggleBtn.contains(<any>e.target)) {
return;
}
let dropMenu: HTMLElement = this.elementRef.nativeElement.querySelector('.nav-dropdown');
if (dropMenu && dropMenu !== e.target && !dropMenu.contains((<any>e.target))) {
this.menuDropped = false;
}
}
}
|
---
layout: page
title: Webb Basic Financial Party
date: 2016-05-24
author: Kenneth Schroeder
tags: weekly links, java
status: published
summary: Aliquam erat volutpat. Pellentesque tincidunt luctus neque, ac.
banner: images/banner/leisure-02.jpg
booking:
startDate: 01/03/2017
endDate: 01/07/2017
ctyhocn: MGMDNHX
groupCode: WBFP
published: true
---
Maecenas semper augue vel velit volutpat, eu tempor mi volutpat. Curabitur sed lobortis justo. Ut diam turpis, efficitur eu est in, malesuada faucibus orci. Suspendisse eget lacinia tellus. In malesuada enim mi, ac convallis mi placerat ac. Nunc laoreet, leo ut vestibulum mollis, nisi leo volutpat lorem, lacinia condimentum tortor nisl vitae ligula. Mauris vitae leo porttitor, porta nunc nec, rutrum nulla.
Proin maximus ullamcorper risus, non sodales eros viverra eu. Nam tempus consequat sem, eu porttitor nisl egestas at. In eget efficitur felis. Duis eu vulputate ligula. Phasellus vel augue eget urna imperdiet cursus et sed risus. Integer dignissim imperdiet diam, id feugiat leo. Mauris id leo nunc. Suspendisse potenti. Sed vel dolor diam. Ut eget ornare mauris. Phasellus porta tortor vel sapien dignissim feugiat. Pellentesque vel imperdiet tellus.
* Praesent eu nibh vel eros convallis eleifend eget eu tortor
* Aenean nec neque eu felis efficitur interdum nec nec arcu.
Integer ac eleifend risus, eget finibus erat. Ut sollicitudin pellentesque ipsum id pellentesque. Phasellus condimentum congue porttitor. Vestibulum neque nisl, ultricies at aliquet a, efficitur non felis. Quisque ut rutrum magna. Integer semper pretium nibh, in suscipit tortor ornare vel. Integer egestas feugiat blandit. Sed non consequat magna. Cras scelerisque tristique neque nec hendrerit.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras gravida ligula non aliquet lacinia. Maecenas eu ipsum sapien. Suspendisse quis ornare tortor. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam ac vulputate ipsum. Etiam scelerisque lacinia lacus id pretium. Phasellus ultrices condimentum ex.
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace Umbraco.Core.Models.EntityBase
{
/// <summary>
/// A base class for use to implement IRememberBeingDirty/ICanBeDirty
/// </summary>
public abstract class TracksChangesEntityBase : IRememberBeingDirty
{
/// <summary>
/// Tracks the properties that have changed
/// </summary>
private readonly IDictionary<string, bool> _propertyChangedInfo = new Dictionary<string, bool>();
/// <summary>
/// Tracks the properties that we're changed before the last commit (or last call to ResetDirtyProperties)
/// </summary>
private IDictionary<string, bool> _lastPropertyChangedInfo = null;
/// <summary>
/// Property changed event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Method to call on a property setter.
/// </summary>
/// <param name="propertyInfo">The property info.</param>
protected virtual void OnPropertyChanged(PropertyInfo propertyInfo)
{
_propertyChangedInfo[propertyInfo.Name] = true;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyInfo.Name));
}
}
/// <summary>
/// Indicates whether a specific property on the current entity is dirty.
/// </summary>
/// <param name="propertyName">Name of the property to check</param>
/// <returns>True if Property is dirty, otherwise False</returns>
public virtual bool IsPropertyDirty(string propertyName)
{
return _propertyChangedInfo.Any(x => x.Key == propertyName);
}
/// <summary>
/// Indicates whether the current entity is dirty.
/// </summary>
/// <returns>True if entity is dirty, otherwise False</returns>
public virtual bool IsDirty()
{
return _propertyChangedInfo.Any();
}
/// <summary>
/// Indicates that the entity had been changed and the changes were committed
/// </summary>
/// <returns></returns>
public bool WasDirty()
{
return _lastPropertyChangedInfo != null && _lastPropertyChangedInfo.Any();
}
/// <summary>
/// Indicates whether a specific property on the current entity was changed and the changes were committed
/// </summary>
/// <param name="propertyName">Name of the property to check</param>
/// <returns>True if Property was changed, otherwise False. Returns false if the entity had not been previously changed.</returns>
public virtual bool WasPropertyDirty(string propertyName)
{
return WasDirty() && _lastPropertyChangedInfo.Any(x => x.Key == propertyName);
}
/// <summary>
/// Resets the remembered dirty properties from before the last commit
/// </summary>
public void ForgetPreviouslyDirtyProperties()
{
_lastPropertyChangedInfo.Clear();
}
/// <summary>
/// Resets dirty properties by clearing the dictionary used to track changes.
/// </summary>
/// <remarks>
/// Please note that resetting the dirty properties could potentially
/// obstruct the saving of a new or updated entity.
/// </remarks>
public virtual void ResetDirtyProperties()
{
ResetDirtyProperties(true);
}
/// <summary>
/// Resets dirty properties by clearing the dictionary used to track changes.
/// </summary>
/// <param name="rememberPreviouslyChangedProperties">
/// true if we are to remember the last changes made after resetting
/// </param>
/// <remarks>
/// Please note that resetting the dirty properties could potentially
/// obstruct the saving of a new or updated entity.
/// </remarks>
public virtual void ResetDirtyProperties(bool rememberPreviouslyChangedProperties)
{
if (rememberPreviouslyChangedProperties)
{
//copy the changed properties to the last changed properties
_lastPropertyChangedInfo = _propertyChangedInfo.ToDictionary(v => v.Key, v => v.Value);
}
_propertyChangedInfo.Clear();
}
/// <summary>
/// Used by inheritors to set the value of properties, this will detect if the property value actually changed and if it did
/// it will ensure that the property has a dirty flag set.
/// </summary>
/// <param name="setValue"></param>
/// <param name="value"></param>
/// <param name="propertySelector"></param>
/// <returns>returns true if the value changed</returns>
/// <remarks>
/// This is required because we don't want a property to show up as "dirty" if the value is the same. For example, when we
/// save a document type, nearly all properties are flagged as dirty just because we've 'reset' them, but they are all set
/// to the same value, so it's really not dirty.
/// </remarks>
internal bool SetPropertyValueAndDetectChanges<T>(Func<T, T> setValue, T value, PropertyInfo propertySelector)
{
var initVal = value;
var newVal = setValue(value);
if (!Equals(initVal, newVal))
{
OnPropertyChanged(propertySelector);
return true;
}
return false;
}
}
}
|
b'Calculate (-13 - (15 + -8)) + 34.\n'
|
b'Evaluate -20 + 3 + 23 + -14 + -15.\n'
|
b'Calculate 22 - (-5 + 17 - 0).\n'
|
b'Calculate -3 + 0 + (-5 - (-8 - 2)) + 0.\n'
|
export function wedgeYZ(a, b) {
return a.y * b.z - a.z * b.y;
}
export function wedgeZX(a, b) {
return a.z * b.x - a.x * b.z;
}
export function wedgeXY(a, b) {
return a.x * b.y - a.y * b.x;
}
|
b'(-16 - (0 - 14)) + 7 + -3\n'
|
b'What is (8 + -7 - (2 + -1)) + -12 + 4?\n'
|
# baites.github.io
# Installation
* Cloning and creating docker image
**NOTE**: This installation requires installed docker server.
```bash
$ git clone git clone https://github.com/baites/baites.github.io.git
$ cd baites.github.io
$ docker build -t jekyll -f jekyll.dockerfile .
...
Successfully tagged jekyll:latest
```
* Creating container
```bash
$ USER_ID=$(id -u)
$ USER_NAME=$(id -un)
$ GROUP_ID=$(id -g)
$ GROUP_NAME=$(id -gn)
$ docker create \
--name jekyll-$USER_NAME \
--mount type=bind,source=$PWD,target=/home/$USER_NAME/baites.github.io \
--mount type=bind,source=$HOME/.ssh,target=/home/$USER_NAME/.ssh \
--workdir /home/$USER_NAME/baites.github.io \
-t -p 4000:4000 jekyll
$ docker start jekyll-$USER_NAME
```
* Mirror user and group to the container
```bash
$ CMD="useradd -u $USER_ID -N $USER_NAME && \
groupadd -g $GROUP_ID $GROUP_NAME && \
usermod -g $GROUP_NAME $USER_NAME &&\
echo '$USER_NAME ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/$USER_NAME &&\
chown -R $USER_NAME:$GROUP_NAME /home/$USER_NAME"
docker exec jekyll-$USER_NAME /bin/bash -c "$CMD"
```
* Entering in the container install gihub pages
```bash
$ docker exec -it -u $USER_NAME jekyll-$USER_NAME /bin/bash
$USER_NAME@bcfa7ea7eb52 baites.github.io$ export PATH="/home/baites/.gem/ruby/2.7.0/bin:$PATH"
$USER_NAME@bcfa7ea7eb52 baites.github.io$ gem install bundler
...
$USER_NAME@bcfa7ea7eb52 baites.github.io$ bundle exec jekyll serve -I --future --host 0.0.0.0
...
```
* Open browser at http://localhost:4000/
|
b'-14 + 83 + -34 + -39\n'
|
<div class="col-xs-7">
<div class="box">
<div class="box-header">
<h3 class="box-title">Order Table</h3>
<div class="box-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="search" class="light-table-filter form-control pull-right" data-table="order-table" placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover order-table">
<thead>
<tr>
<th>Product</th>
<th>Customer</th>
<th>Date</th>
<th>Status</th>
<th>Price</th>
<th>Phone</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($order as $item):
if($item->status == 0){
?>
<tr>
<td><?php echo $item->product; ?></td>
<td><?php echo $item->username; ?></td>
<td><?php echo $item->datereceive; ?></td>
<td><?php if($item->status == 0){
echo "Watting access...";
}
else{
echo "Ok";
}
?></td>
<td><?php echo $item->price ?></td>
<td><?php echo $item->phone ?></td>
<td>
<?php echo Html::anchor('admin/order/'.$item->id, 'Click to Complete', array('onclick' => "return confirm('Are you sure?')")); ?>
</td>
</tr>
<?php
}
endforeach; ?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<div class="col-xs-1"></div>
<div class="col-xs-4">
<div class="box">
<div class="box-header">
<h3 class="box-title">Order Sussess</h3>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<?php if ($order): ?>
<table class="table table-hover">
<tbody><tr>
<th>Product</th>
<th>Date</th>
<th>Status</th>
<th>Customer</th>
</tr>
<?php foreach ($order as $item):
if($item->status == 1){
?>
<tr>
<td><?php echo $item->product; ?></td>
<td><?php echo $item->datereceive; ?></td>
<td><?php echo $item->username; ?></td>
<td><?php if($item->status == 0){
echo "Watting access...";
}
else{
echo "Ok";
}
?></td>
</tr>
<?php
}
?>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- /.box-body -->
</div>
</div>
|
b'What is the value of (0 - 5 - -19) + (29 + -10 - 12)?\n'
|
b'(0 + -6 - (244 - 238)) + -2\n'
|
b'Calculate 9 - (-4 - (4 - 13)).\n'
|
import unittest
from katas.beta.what_color_is_your_name import string_color
class StringColorTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(string_color('Jack'), '79CAE5')
def test_equal_2(self):
self.assertEqual(string_color('Joshua'), '6A10D6')
def test_equal_3(self):
self.assertEqual(string_color('Joshua Smith'), '8F00FB')
def test_equal_4(self):
self.assertEqual(string_color('Hayden Smith'), '7E00EE')
def test_equal_5(self):
self.assertEqual(string_color('Mathew Smith'), '8B00F1')
def test_is_none_1(self):
self.assertIsNone(string_color('a'))
|
#pragma config(Sensor, in1, linefollower, sensorLineFollower)
#pragma config(Sensor, dgtl5, OutputBeltSonar, sensorSONAR_mm)
#pragma config(Motor, port6, WhipCreamMotor, tmotorVex393, openLoop)
#pragma config(Motor, port7, InputBeltMotor, tmotorServoContinuousRotation, openLoop)
#pragma config(Motor, port8, ElevatorMotor, tmotorServoContinuousRotation, openLoop)
#pragma config(Motor, port9, OutputBeltMotor, tmotorServoContinuousRotation, openLoop)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
/*
Project Title: Cookie Maker
Team Members: Patrick Kubiak
Date:
Section:
Task Description: Control cookie maker machine
Pseudocode:
Move input conveior belt set distance
Move elevator set distance
Move output conveior belt until whip cream
Press whip cream
Reset whip cream
Move output conveior belt to end
Reset elevator
*/
task main()
{ //Program begins, insert code within curly braces
while (true)
{
//Input Conveior Belt
startMotor(InputBeltMotor, 127);
wait(2.5);
stopMotor(InputBeltMotor);
//Elevator
startMotor(ElevatorMotor, 127);
wait(1.5);
stopMotor(ElevatorMotor);
//Move Cookie To line follower
do
{
startMotor(OutputBeltMotor, -127);
}
while(SensorValue(linefollower) > 2900);
stopMotor(OutputBeltMotor);
//Reset Elevator
startMotor(ElevatorMotor, -127);
wait(2);
stopMotor(ElevatorMotor);
//Move Cookie To Whip Cream
startMotor(OutputBeltMotor, -127);
wait(0.4);
stopMotor(OutputBeltMotor);
//Whip Cream Press
startMotor(WhipCreamMotor, -127);
wait(1);
stopMotor(WhipCreamMotor);
//Whip Cream Reset
startMotor(WhipCreamMotor, 127);
wait(0.9);
stopMotor(WhipCreamMotor);
//Output Conveior Belt
startMotor(OutputBeltMotor, -127);
wait(2);
}
}
|
b'Calculate 352 + -392 + (2 - -51).\n'
|
{% extends "layout.html" %}
{% block body %}
<title>All Events - Media Services</title>
<form id="adminForm" action="" method=post>
<div class="container">
<table class="table">
<thead>
<td>
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link active" href="#">Upcoming Events</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('past') }}">Past Events</a>
</li>
</ul>
</td>
<td>
<button type="button" class="btn btn-outline-secondary" onclick="toggleSignUps()">
<span id="signUpText" class="text-muted"> Please Wait...</span>
</button>
</td>
<td style="text-align:right">
<a href="{{ url_for('new') }}" class="btn btn-success">
<i class="fa fa-plus" aria-hidden="true"></i> New Event
</a>
</td>
</thead>
</table>
<table class="table table-hover">
{% block events %}{% endblock %}
</table>
<!-- bottom buttons -->
</div>
</form>
<script>
currentPage = "edit";
$(window).on('load', function(){ socket.emit("getSignUps") })
function lockEvent(event) {
socket.emit("lockEvent", String(event));
document.getElementById("lock_"+event).innerHTML = "Please Wait...";
}
function toggleSignUps() {
socket.emit("toggleSignUps");
document.getElementById("signUpText").innerHTML = "Please Wait...";
}
socket.on('eventLock', function(data) {
if (data.locked) {
document.getElementById("lock_"+data.event).setAttribute("class", "btn btn-sm btn-danger");
document.getElementById("lock_"+data.event).innerHTML = "<i class=\"fa fa-lock\"> </i> Locked";
}
else {
document.getElementById("lock_"+data.event).setAttribute("class", "btn btn-sm btn-default");
document.getElementById("lock_"+data.event).innerHTML = "<i class=\"fa fa-unlock\"> </i> Unlocked";
}
});
socket.on('signUpsAvailable', function(data) {
if (data.available) {
document.getElementById("signUpText").setAttribute("class", "text-success");
document.getElementById("signUpText").innerHTML = "<i id=\"signUpIcon\" class=\"fa fa-toggle-on\" aria-hidden=\"true\"></i> Sign-Ups Open";
}
else {
document.getElementById("signUpText").setAttribute("class", "text-danger");
document.getElementById("signUpText").innerHTML = "<i id=\"signUpIcon\" class=\"fa fa-toggle-off\" aria-hidden=\"true\"></i> Sign-Ups Closed";
}
});
</script>
{% endblock %}
|
b'What is -6 + 2 + 10 + -2 + -30?\n'
|
print("hello!!!!")
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 22