code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
class JudgeTask
@queue = :judge
def self.perform(id)
submission = Submission.find(id)
code = submission.code
log = Logger.new 'log/resque.log'
compile_output = `gcc #{submission.source_path} -o #{submission.exec_path} #{Settings.compiler_options} 2>&1`
if $?.success?
problem = submission.problem
log.debug "#{submission.id} | #{compile_output}"
msg = `#{Settings.sandbox_path} -i #{problem.input_path} -o #{submission.out_path} -t #{problem.time_limit} -m #{problem.mem_limit} #{submission.exec_path}`
case msg.strip
when /(\d+) (\d+) (\d+)/
submission.time_cost = $2.to_i
submission.status = self.output_eql?(submission.out_path, problem.ans_path) ? :ac : :wa;
when 'Time Limit Exceeded'
submission.status = :tle
submission.msg = msg
when 'Memory Limit Exceeded'
submission.status = :re
submission.msg = msg
when 'Program Killed'
submission.status = :re
submission.msg = msg
end
FileUtils.rm_f(submission.exec_path)
FileUtils.rm_f(submission.out_path)
else
submission.status = :ce
submission.msg = compile_output.gsub(submission.source_path, 'Your code')
end
submission.save
end
private
def self.output_eql?(exec_out, ans_path)
a = IO.readlines(exec_out).map { |s| s.strip }
b = IO.readlines(ans_path).map { |s| s.strip }
a == b
end
end | ciffel/judgement | app/workers/judge_task.rb | Ruby | mit | 1,444 |
package bhgomes.jaql.logging;
import java.util.logging.StreamHandler;
/**
* Singleton object for System.out as a StreamHandler
*
* @author Brandon Gomes (bhgomes)
*/
public final class STDOUT extends StreamHandler {
/**
* Singleton instance
*/
private static final STDOUT instance = new STDOUT();
/**
* Default constructor of the singleton instance
*/
private STDOUT() {
this.setOutputStream(System.out);
}
/**
* @return instance of the singleton
*/
public static final STDOUT getInstance() {
return STDOUT.instance;
}
}
| bhgomes/jaql | src/main/java/bhgomes/jaql/logging/STDOUT.java | Java | mit | 608 |
package com.venky.core.security;
import com.venky.core.util.ObjectUtil;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import java.util.Base64;
public class SignatureComputer {
public static void main(String[] args) throws Exception{
Options options = new Options();
Option help = new Option("h","help",false, "print this message");
Option url = new Option("u","url", true,"Url called");
url.setRequired(true);
Option privateKey = new Option("b64pvk","base64privatekey", true,"Private Key to Sign with");
privateKey.setRequired(true);
Option data = new Option("d","data", true,"Data posted to the url");
options.addOption(help);
options.addOption(url);
options.addOption(privateKey);
options.addOption(data);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options,args);
}catch (Exception ex){
formatter.printHelp(SignatureComputer.class.getName(),options);
System.exit(1);
}
StringBuilder payload = new StringBuilder();
String sUrl = cmd.getOptionValue("url");
if (sUrl.startsWith("http://")){
sUrl = sUrl.substring("http://".length());
sUrl = sUrl.substring(sUrl.indexOf("/"));
}
payload.append(sUrl);
String sData = cmd.getOptionValue("data");
if (!ObjectUtil.isVoid(sData)){
payload.append("|");
payload.append(sData);
}
String sign = Crypt.getInstance().generateSignature(Base64.getEncoder().encodeToString(payload.toString().getBytes()),Crypt.SIGNATURE_ALGO,
Crypt.getInstance().getPrivateKey(Crypt.KEY_ALGO,cmd.getOptionValue("base64privatekey")));
System.out.println(sign);
}
}
| venkatramanm/common | src/main/java/com/venky/core/security/SignatureComputer.java | Java | mit | 2,127 |
SwaggerYard::Rails::Engine.routes.draw do
get '/doc', to: 'swagger#doc'
scope default: {format: 'json'} do
get '/swagger', to: 'swagger#index'
get '/openapi', to: 'swagger#openapi'
get '/api', to: 'swagger#index'
end
end
| tpitale/swagger_yard-rails | config/routes.rb | Ruby | mit | 240 |
window.PerfHelpers = window.PerfHelpers || {};
;(function(PerfHelpers) {
var timers = {};
PerfHelpers = window.performance || {};
PerfHelpers.now = PerfHelpers.now || function () {};
if ((!console) || (!console.time)) {
console.time = function() {};
console.timeEnd = function() {};
}
var consoleTime = console.time.bind(window.console);
var consoleTimeEnd = console.timeEnd.bind(window.console);
console.time = function(key) {
var phTimeKey = '[PHTime]' + key;
timers[phTimeKey + '_start'] = PerfHelpers.now();
var _startDate = (new Date().toLocaleString());
timers[phTimeKey + '_startDate'] = _startDate;
//console.log(phTimeKey + '[STARTED]: ' + _startDate);
consoleTime(phTimeKey);
};
console.timeEnd = function (key) {
var phTimeKey = '[PHTime]' + key;
var _startTime = timers[phTimeKey + '_start'];
if (_startTime) {
var _endDate = (new Date().toLocaleString());
var _endTime = PerfHelpers.now();
var _totalTime = _endTime - _startTime;
delete timers[phTimeKey + '_start'];
delete timers[phTimeKey + '_startDate'];
//console.log(phTimeKey + '[ENDED]: ' + _endDate);
consoleTimeEnd(phTimeKey);
if ('ga' in window) {
var alKey = 'ACT_' + key;
var _roundedTime = Math.round(_totalTime);
ga('send', 'timing', 'web-performance', alKey, _roundedTime, 'Total Time');
ga('send', {
hitType: 'event',
eventCategory: 'web-performance',
eventAction: alKey,
eventLabel: _endDate,
eventValue: _roundedTime
});
// console.debug('[GA][timing]:', 'send', 'event', 'web-performance', alKey, _endDate, _roundedTime);
}
return _totalTime;
} else {
return undefined;
}
};
})(window.PerfHelpers);
| WebPolymerLabs/PolyBills | scripts/time-perf-helper.js | JavaScript | mit | 1,825 |
# frozen_string_literal: true
class Awarding < ApplicationRecord
belongs_to :award
belongs_to :recipient
belongs_to :group
validates :award, presence: true
validates :recipient, presence: true
# group should be present if there is no default group
validates :group, presence: true, if: proc { |a| a.award.nil? || a.award.group.nil? }
# award name override should be present iff the award is an 'other award'
validates :award_name, presence: true, if: proc { |a| a.award.nil? || a.award.other_award? }
validates :award_name, absence: true, if: proc { |a| a.award && !a.award.other_award? }
# returns overriden value if present, otherwise falls back to award
def override_attr(attr, own_attr_val)
return own_attr_val if own_attr_val
award.send(attr) if award
end
# returns override award name if one exists, otherwise the default group
def group
override_attr(:group, super)
end
# returns award name or display name (if other award) along with granting group (if not the default)
def display_name
override_attr(:name, award_name) + (group == award.group ? '' : " (#{group})")
end
def to_s
display_name
end
def received
return super if super
'(Unknown)'
end
end
| aelkiss/cynnabar-rails | app/models/awarding.rb | Ruby | mit | 1,241 |
<?php
/*
* This file is part of Hifone.
*
* (c) Hifone.com <hifone@hifone.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Hifone\Http\Controllers\Auth;
use AltThree\Validator\ValidationException;
use Hifone\Commands\Identity\AddIdentityCommand;
use Hifone\Events\User\UserWasAddedEvent;
use Hifone\Events\User\UserWasLoggedinEvent;
use Hifone\Hashing\PasswordHasher;
use Hifone\Http\Controllers\Controller;
use Hifone\Models\Identity;
use Hifone\Models\Provider;
use Hifone\Models\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str;
use Input;
use Laravel\Socialite\Two\InvalidStateException;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
//注册后返回主页
protected $redirectPath = '/';
protected $hasher;
public function __construct(PasswordHasher $hasher)
{
$this->hasher = $hasher;
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
public function getLogin()
{
$providers = Provider::orderBy('created_at', 'desc')->get();
return $this->view('auth.login')
->withCaptcha(route('captcha', ['random' => time()]))
->withConnectData(Session::get('connect_data'))
->withProviders($providers)
->withPageTitle(trans('dashboard.login.login'));
}
public function landing()
{
return $this->view('auth.landing')
->withConnectData(Session::get('connect_data'))
->withPageTitle('');
}
/**
* Logs the user in.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function postLogin()
{
$loginData = Input::only(['login', 'password', 'verifycode']);
if (!Config::get('setting.site_captcha_login_disabled')) {
$verifycode = array_pull($loginData, 'verifycode');
if ($verifycode != Session::get('phrase')) {
// instructions if user phrase is good
return Redirect::to('auth/login')
->withInput(Input::except('password'))
->withError(trans('hifone.captcha.failure'));
}
}
// Login with username or email.
$loginKey = Str::contains($loginData['login'], '@') ? 'email' : 'username';
$loginData[$loginKey] = array_pull($loginData, 'login');
// Validate login credentials.
if (Auth::validate($loginData)) {
// We probably want to add support for "Remember me" here.
Auth::attempt($loginData, false);
if (Session::has('connect_data')) {
$connect_data = Session::get('connect_data');
dispatch(new AddIdentityCommand(Auth::user()->id, $connect_data));
}
event(new UserWasLoggedinEvent(Auth::user()));
return Redirect::intended('/')
->withSuccess(sprintf('%s %s', trans('hifone.awesome'), trans('hifone.login.success')));
}
return redirect('/auth/login')
->withInput(Input::except('password'))
->withError(trans('hifone.login.invalid'));
}
public function getRegister()
{
$connect_data = Session::get('connect_data');
return $this->view('auth.register')
->withCaptcha(route('captcha', ['random' => time()]))
->withConnectData($connect_data)
->withPageTitle(trans('dashboard.login.login'));
}
public function postRegister()
{
// Auto register
$connect_data = Session::get('connect_data');
$from = '';
if ($connect_data && isset($connect_data['extern_uid'])) {
$registerData = [
'username' => $connect_data['nickname'].'_'.$connect_data['provider_id'],
'nickname' => $connect_data['nickname'],
'password' => $this->hashPassword(str_random(8), ''),
'email' => $connect_data['extern_uid'].'@'.$connect_data['provider_id'],
'salt' => '',
];
$from = 'provider';
} else {
$registerData = Input::only(['username', 'email', 'password', 'password_confirmation', 'verifycode']);
if ($registerData['verifycode'] != Session::get('phrase') && Config::get('setting.site_captcha_reg_disabled')) {
return Redirect::to('auth/register')
->withTitle(sprintf('%s %s', trans('hifone.whoops'), trans('dashboard.users.add.failure')))
->withInput(Input::all())
->withErrors([trans('hifone.captcha.failure')]);
}
}
try {
$user = $this->create($registerData);
} catch (ValidationException $e) {
return Redirect::to('auth/register')
->withTitle(sprintf('%s %s', trans('hifone.whoops'), trans('dashboard.users.add.failure')))
->withInput(Input::all())
->withErrors($e->getMessageBag());
}
if ($from == 'provider') {
dispatch(new AddIdentityCommand($user->id, $connect_data));
}
event(new UserWasAddedEvent($user));
Auth::guard($this->getGuard())->login($user);
return redirect($this->redirectPath());
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
*
* @return User
*/
protected function create(array $data)
{
$salt = $this->generateSalt();
$password = $this->hashPassword($data['password'], $salt);
$user = User::create([
'username' => $data['username'],
'email' => $data['email'],
'salt' => $salt,
'password' => $password,
]);
return $user;
}
/**
* hash user's raw password.
*
* @param string $password plain text form of user's password
* @param string $salt salt
*
* @return string hashed password
*/
private function hashPassword($password, $salt)
{
return $this->hasher->make($password, ['salt' => $salt]);
}
/**
* generate salt for hashing password.
*
* @return string
*/
private function generateSalt()
{
return str_random(16);
}
public function provider($slug)
{
return \Socialite::with($slug)->redirect();
}
public function callback($slug)
{
if (Input::has('code')) {
$provider = Provider::where('slug', '=', $slug)->firstOrFail();
try {
$extern_user = \Socialite::with($slug)->user();
} catch (InvalidStateException $e) {
return Redirect::to('/auth/landing')
->withErrors(['授权失效']);
}
//检查是否已经连接过
$identity = Identity::where('provider_id', '=', $provider->id)->where('extern_uid', '=', $extern_user->id)->first();
if (is_null($identity)) {
Session::put('connect_data', ['provider_id' => $provider->id, 'extern_uid' => $extern_user->id, 'nickname' => $extern_user->nickname]);
return Redirect::to('/auth/landing');
}
//已经连接过,找出user_id, 直接登录
$user = User::find($identity->user_id);
if (!Auth::check()) {
Auth::login($user, true);
}
return Redirect::to('/')
->withSuccess(sprintf('%s %s', trans('hifone.awesome'), trans('hifone.login.success')));
}
}
public function userBanned()
{
if (Auth::check() && !Auth::user()->is_banned) {
return redirect(route('home'));
}
//force logout
Auth::logout();
return Redirect::to('/');
}
// 用户屏蔽
public function userIsBanned($user)
{
return Redirect::route('user-banned');
}
}
| abbychau/Hifone | app/Http/Controllers/Auth/AuthController.php | PHP | mit | 8,814 |
using Hanafuda.OpenApi.Entities;
using Hanafuda.OpenApi.Enums;
using Hanafuda.OpenApi.Expressions;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Hanafuda.OpenApi.Extensions
{
/// <summary>
/// Extensions for Enumerable
/// </summary>
public static class EnumerableExtension
{
/// <summary>
/// Return a Shuffled enumerable of this enumerable
/// </summary>
/// <typeparam name="T">T type</typeparam>
/// <param name="enumerable">Enumerable extend</param>
/// <returns>Shuffled enumerable</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> enumerable)
{
return enumerable.OrderBy(x => Guid.NewGuid()).ToList();
}
/// <summary>
/// Draw a random item
/// </summary>
/// <typeparam name="T">T type</typeparam>
/// <param name="enumerable">Enumerable extend</param>
/// <returns>Item draw</returns>
public static T Draw<T>(this IEnumerable<T> enumerable)
{
return enumerable.Shuffle().First();
}
/// <summary>
/// True if a card enumeration has a Teshi, otherwise false
/// </summary>
/// <param name="cards">IEnumarable extends</param>
/// <param name="month">Month</param>
/// <returns>True if a card enumeration has a Teshi, otherwise false</returns>
public static bool HasTeshi(this IEnumerable<Card> cards, MonthEnum month)
{
return cards.Count(x => x.Month == month) == 4;
}
/// <summary>
/// True if a card enumeration has a Kuttsuki, otherwise false
/// </summary>
/// <param name="cards">IEnumarable extends</param>
/// <returns>True if a card enumeration has a Kuttsuki, otherwise false</returns>
public static bool HasKuttsuki(this IEnumerable<Card> cards)
{
var cardArray = cards as Card[] ?? cards.ToArray();
//4 month pair
return cardArray.Select(x => x.Month).Distinct().Count(m => cardArray.Count(x => x.Month == m) == 2) == 4;
}
/// <summary>
/// Return all Yakus find in a collection of cards.
/// </summary>
/// <param name="cards">Cards</param>
/// <param name="currentMonth">Current month</param>
/// <returns>Enumerable of YakuEnum</returns>
public static IEnumerable<YakuEnum> GetYakus(this IEnumerable<Card> cards, MonthEnum currentMonth)
{
var cardArray = cards as Card[] ?? cards.ToArray();
var yakus = new List<YakuEnum>();
//SANKO
if (cardArray.Count(YakuLambda.NoRainMan) == 3)
yakus.Add(YakuEnum.Sanko);
//SHIKO
if (cardArray.Count(YakuLambda.NoRainMan) == 4)
{
yakus.Remove(YakuEnum.Sanko);
yakus.Add(YakuEnum.Shiko);
}
//AME_SHIKO
if (cardArray.Count(YakuLambda.NoRainMan) == 3 && cardArray.Any(YakuLambda.RainMan))
{
yakus.Remove(YakuEnum.Sanko);
yakus.Add(YakuEnum.AmeShiko);
}
//GOKO
if (cardArray.Count(YakuLambda.Special) == 5)
{
yakus.Remove(YakuEnum.Shiko);
yakus.Add(YakuEnum.Goko);
}
//INOSHIKACHO
if (cardArray.Count(YakuLambda.Inoshikacho) == 3)
yakus.Add(YakuEnum.Inoshikacho);
//TANE
if (cardArray.Count(YakuLambda.Animal) >= 5)
yakus.Add(YakuEnum.Tane);
//AKATAN
if (cardArray.Count(YakuLambda.Poem) == 3)
yakus.Add(YakuEnum.Akatan);
//AOTAN
if (cardArray.Count(YakuLambda.Blue) == 3)
yakus.Add(YakuEnum.Aotan);
//AKATAN_AOTAN_NO_CHOFUKU
if(yakus.Contains(YakuEnum.Akatan) && yakus.Contains(YakuEnum.Aotan))
yakus.Add(YakuEnum.AkatanAotanNoChofuku);
//TAN
if (cardArray.Count(YakuLambda.Ribbon) >= 5)
yakus.Add(YakuEnum.Tan);
//TSUKIMI
if (cardArray.Any(YakuLambda.Moon) && cardArray.Any(YakuLambda.SakeCup))
yakus.Add(YakuEnum.TsukimiZake);
//HANAMI
if (cardArray.Any(YakuLambda.Curtain) && cardArray.Any(YakuLambda.SakeCup))
yakus.Add(YakuEnum.HanamiZake);
//KASU
if (cardArray.Count(YakuLambda.Normal) >= 10)
yakus.Add(YakuEnum.Kasu);
//BAKE_FUDA
if (cardArray.Count(YakuLambda.Normal) == 9 && cardArray.Any(YakuLambda.SakeCup))
{
yakus.Add(YakuEnum.BakeFuda);
}
//TSUKI_FUDA
if (cardArray.Count(x => x.Month == currentMonth) == 4)
yakus.Add(YakuEnum.TsukiFuda);
return yakus;
}
}
}
| Vtek/Hanafuda.OpenApi | Hanafuda.OpenApi/Extensions/EnumerableExtension.cs | C# | mit | 5,031 |
import { NgModule } from '@angular/core';
import { RouterModule, Routes, PreloadAllModules } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { I18nComponent } from './i18n/i18n.component';
import { ValidationComponent } from './validation/validation.component';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'i18n', component: I18nComponent },
{
path: 'list', loadChildren: () => import('./list/list.module').then(m => m.ListModule)
},
{ path: 'validation', component: ValidationComponent },
{ path: '**', redirectTo: 'home' }
];
@NgModule({
imports: [
RouterModule.forRoot(routes, {
useHash: true,
preloadingStrategy: PreloadAllModules
})
],
exports: [RouterModule]
})
export class AppRoutingModule { }
| robisim74/angular-l10n-sample | src/app/app-routing.module.ts | TypeScript | mit | 917 |
package com.bitdecay.game.ui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction;
import com.bitdecay.game.util.Quest;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.util.Optional;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.moveTo;
public class Tray extends Group {
protected Logger log = LogManager.getLogger(this.getClass());
public TrayCard taskCard;
public ConversationDialog dialog;
private TaskList taskList;
private boolean isHidden = false;
public Tray(TaskList taskList) {
super();
this.taskList = taskList;
Vector2 screenSize = new Vector2(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Group taskCardGroup = new Group();
taskCard = new TrayCard();
taskCard.setPosition(0, 0);
taskCardGroup.addActor(taskCard);
taskCardGroup.setScale(0.7f);
addActor(taskCardGroup);
dialog = new ConversationDialog();
dialog.setPosition(screenSize.x * 0.2125f, 0);
addActor(dialog);
}
@Override
public void act(float delta) {
super.act(delta);
Optional<Quest> curQuest = taskList.currentQuest();
if (curQuest.isPresent()){
Quest q = curQuest.get();
if (q != taskCard.quest) {
taskCard.quest = q;
showTray();
}
} else if (!isHidden) hideTray();
}
public void showTray(){
log.info("Show tray");
MoveToAction move = moveTo(getX(), Gdx.graphics.getHeight() * 1.01f);
move.setDuration(0.25f);
addAction(Actions.sequence(Actions.run(()-> {
if(taskCard.quest != null && taskCard.quest.currentZone().isPresent()) {
taskCard.quest.currentZone().ifPresent(zone -> {
dialog.setPersonName(taskCard.quest.personName);
dialog.setText(zone.flavorText);
});
} else {
dialog.setPersonName(null);
dialog.setText("");
}
}), move));
isHidden = false;
}
public void hideTray(){
log.info("Hide tray");
MoveToAction move = moveTo(getX(), 0);
move.setDuration(0.25f);
addAction(Actions.sequence(move, Actions.run(()-> taskCard.quest = null)));
isHidden = true;
}
public void toggle(){
if (isHidden) showTray();
else hideTray();
}
}
| bitDecayGames/LudumDare38 | src/main/java/com/bitdecay/game/ui/Tray.java | Java | mit | 2,669 |
module.exports = function(locker) {
/*
locker.add(function(callback) {
//Return content in format:
callback({
name: "Vehicle Speed",
type: "metric",
content: {
x: 0,
y: 0,
xtitle: "Time",
ytitle: "Speed"
},
tags: ["vehicle", "speed", "velocity", "car"]
});
});
locker.add(function(callback) {
//Return content in format:
callback({
name: "Vehicle RPM",
type: "metric",
content: {
x: 0,
y: 0,
xtitle: "Time",
ytitle: "Revolutions Per Minute"
},
tags: ["vehicle", "rpm", "revolutions", "car"]
});
});
locker.add(function(callback) {
callback({
name: "Image test",
type: "image",
content: {
url: "http://24.media.tumblr.com/tumblr_mc6vgcDUEK1qmbg8bo1_500.jpg"
},
tags: ["vehicle", "rpm", "revolutions", "car"]
});
});
*/
}
| pushchris/locker | adapters/demo.js | JavaScript | mit | 1,276 |
package app;
import java.util.ResourceBundle;
import control.MainController;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* Main class for Logoquiz app.
*/
public class LogoquizMainApp extends Application {
/**
* Root layout of the application.
*/
private VBox rootLayout;
/**
* Primary Stage.
*/
private Stage primaryStage;
/**
* main() method.
* @param args arguments
*/
public static final void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
primaryStage = stage;
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/fxml/rootLayout.fxml"));
loader.setResources(ResourceBundle.getBundle("i18n/message"));
rootLayout = loader.load();
MainController controller = loader.getController();
controller.setMainApp(this);
primaryStage.setTitle("Logoquiz");
primaryStage.setScene(new Scene(rootLayout));
primaryStage.show();
}
/**
* Getter for primaryStage.
*
* @return primaryStage
*/
public Stage getPrimaryStage() {
return primaryStage;
}
}
| lcmatrix/logoquiz | src/main/java/app/LogoquizMainApp.java | Java | mit | 1,350 |
{
it("returns a key", () => {
var nativeEvent = new KeyboardEvent("keypress", {
key: "f"
});
expect(getEventKey(nativeEvent)).toBe("f");
});
}
| stas-vilchik/bdd-ml | data/7503.js | JavaScript | mit | 165 |
<?php
/* @WebProfiler/Icon/close.svg */
class __TwigTemplate_6bdd9e9862db24b9d9ca3b9811419338c5925f8e0c5dd2898e11b045839a13fd extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_a0af381be0a0e30ade6543694a1930767aff1d9dfe92cf56a41f9cee6dc77806 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_a0af381be0a0e30ade6543694a1930767aff1d9dfe92cf56a41f9cee6dc77806->enter($__internal_a0af381be0a0e30ade6543694a1930767aff1d9dfe92cf56a41f9cee6dc77806_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@WebProfiler/Icon/close.svg"));
// line 1
echo "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" x=\"0px\" y=\"0px\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" enable-background=\"new 0 0 24 24\" xml:space=\"preserve\">
<path fill=\"#AAAAAA\" d=\"M21.1,18.3c0.8,0.8,0.8,2,0,2.8c-0.4,0.4-0.9,0.6-1.4,0.6s-1-0.2-1.4-0.6L12,14.8l-6.3,6.3
c-0.4,0.4-0.9,0.6-1.4,0.6s-1-0.2-1.4-0.6c-0.8-0.8-0.8-2,0-2.8L9.2,12L2.9,5.7c-0.8-0.8-0.8-2,0-2.8c0.8-0.8,2-0.8,2.8,0L12,9.2
l6.3-6.3c0.8-0.8,2-0.8,2.8,0c0.8,0.8,0.8,2,0,2.8L14.8,12L21.1,18.3z\"/>
</svg>
";
$__internal_a0af381be0a0e30ade6543694a1930767aff1d9dfe92cf56a41f9cee6dc77806->leave($__internal_a0af381be0a0e30ade6543694a1930767aff1d9dfe92cf56a41f9cee6dc77806_prof);
}
public function getTemplateName()
{
return "@WebProfiler/Icon/close.svg";
}
public function getDebugInfo()
{
return array ( 22 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" x=\"0px\" y=\"0px\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" enable-background=\"new 0 0 24 24\" xml:space=\"preserve\">
<path fill=\"#AAAAAA\" d=\"M21.1,18.3c0.8,0.8,0.8,2,0,2.8c-0.4,0.4-0.9,0.6-1.4,0.6s-1-0.2-1.4-0.6L12,14.8l-6.3,6.3
c-0.4,0.4-0.9,0.6-1.4,0.6s-1-0.2-1.4-0.6c-0.8-0.8-0.8-2,0-2.8L9.2,12L2.9,5.7c-0.8-0.8-0.8-2,0-2.8c0.8-0.8,2-0.8,2.8,0L12,9.2
l6.3-6.3c0.8-0.8,2-0.8,2.8,0c0.8,0.8,0.8,2,0,2.8L14.8,12L21.1,18.3z\"/>
</svg>
", "@WebProfiler/Icon/close.svg", "C:\\wamp\\www\\ws\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\WebProfilerBundle\\Resources\\views\\Icon\\close.svg");
}
}
| mickael-matelli/ws | app/cache/dev/twig/87/871a3ea9034aec0720ad691ccb20d167d406b23c012ff297190fd9c58f83774a.php | PHP | mit | 2,883 |
/**
* A 32-bit unsigned bitfield that describes an entity's classification(s)
* @typedef {number} EntityClass
*/
/**
* Enumerate entity classes
*/
const ENTITY = {
NULL: 0x00,
// Base celestial classes
ASTEROID: 0x01, // floating rock in space, orbits star
COMET: 0x02, // an asteroid with a highly-eccentric orbit
PLANET: 0x04, // a large celestial that orbits a star
MOON: 0x08, // something that orbits a celestial that is not a star
STAR: 0x10, // a luminous sphere of plasma, typically the center of a solar system
BLACKHOLE: 0x20, // a object dense enough to maintain an event horizon
// Celestial modifiers
GAS: 0x40, // is a gas giant / gas world
ICE: 0x80, // is an ice giant / ice world
DESERT: 0x100, // is a desert world
DWARF: 0x200, // is a "dwarf" in its category
GIANT: 0x400, // is a "giant" in its category
NEUTRON: 0x800, // is a composed of "neutronium" (ie neutron stars)
// Empire Units
VESSEL: 0x1000, // a vessel is any empire-made object, manned or unmanned
SHIP: 0x2000, // a ship is a manned vessel equipped with engines
DRONE: 0x4000, // a drone is an unmanned vessel equipped with engines
STATION: 0x8000, // a station is a large habitable vessel with reduced maneuverability (if any) - can be orbital or ground-based
MILITARY: 0x10000, // a military vessel belongs to an empire's military
COLONY: 0x20000 // a colony is a ground-based civilian population
};
/**
* An Entity is any object representing something in the game world. This may include: planets, stars, starships,
* cultures, empires, etc.
*/
class Entity {
/**
* Entity constructor method
* @param {string} [name]
* Defines the name of this entity
* @param {Coord} [coords]
* Defines the default coordinates of this entity
* @param {EntityClass} [eClass]
* Defines this entity's eClass
*/
constructor(name, coords, eClass) {
/** The entity's non-unique name */
this.name = name || "";
/** The entity's class */
this.eClass = eClass || ENTITY.NULL;
if(coords) {
// Set this entity's location
this.setPos(coords.xPos, coords.yPos, coords.system);
}
// Register this entity to LogicM
LogicM.addEntity(this);
}
/**
*
* @param {number} [xPos=0]
* The new x coordinate
* @param {number} [yPos=0]
* The new y coordinate
* @param {string} [system]
* The name of the star system
*/
setPos(xPos=0, yPos=0, system) {
this.xPos = xPos;
this.yPos = yPos;
this.system = system || this.system;
}
}
/**
* A table describing an entity's display properties
*
* @typedef {Object} DisplayProperties
* @property {number} radius - The entity's real radius, in km
* @property {number} [minRadius=0] - The entity's minimum draw radius, in pixels
* @property {string} [color=#ffffff] - The entity's draw color
*/
/**
* A RenderEntity is an entity that structures render data. It can be drawn onto the screen.
* @extends Entity
*/
class RenderEntity extends Entity {
/**
* RenderEntity constructor method
* @param {string} name
* Defines the name of this entity
* @param {Coord} coords
* Defines the default coordinates of this entity
* @param {DisplayProperties} displayProps
* Defines the default display properties
* @param {EntityClass} [eClass]
* Defines this entity's eClass
*/
constructor(name, coords, displayProps, eClass) {
super(name, coords, eClass);
/** Set to true if this entity can be rendered */
this.canRender = true;
/** Entity's draw radius */
this.radius = displayProps.radius || 0;
/** Entity's minimum radius */
this.minRadius = displayProps.minRadius || 0;
/** Entity's draw color */
this.color = displayProps.color || 'white';
// Register this visible entity to the Logic Module
if(LogicM.getViewingSystem() == coords.system) {
RenderM.addRenderEntity(this);
}
}
} | Doohl/Sourcebound | core/entities/Entity.js | JavaScript | mit | 4,061 |
# -*- coding: utf-8 -*-
"""
flask.ext.babelex
~~~~~~~~~~~~~~~~~
Implements i18n/l10n support for Flask applications based on Babel.
:copyright: (c) 2013 by Serge S. Koval, Armin Ronacher and contributors.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import os
# this is a workaround for a snow leopard bug that babel does not
# work around :)
if os.environ.get('LC_CTYPE', '').lower() == 'utf-8':
os.environ['LC_CTYPE'] = 'en_US.utf-8'
from datetime import datetime
from flask import _request_ctx_stack
from babel import dates, numbers, support, Locale
from babel.support import NullTranslations
from werkzeug import ImmutableDict
try:
from pytz.gae import pytz
except ImportError:
from pytz import timezone, UTC
else:
timezone = pytz.timezone
UTC = pytz.UTC
from flask_babelex._compat import string_types
_DEFAULT_LOCALE = Locale.parse('en')
class Babel(object):
"""Central controller class that can be used to configure how
Flask-Babel behaves. Each application that wants to use Flask-Babel
has to create, or run :meth:`init_app` on, an instance of this class
after the configuration was initialized.
"""
default_date_formats = ImmutableDict({
'time': 'medium',
'date': 'medium',
'datetime': 'medium',
'time.short': None,
'time.medium': None,
'time.full': None,
'time.long': None,
'date.short': None,
'date.medium': None,
'date.full': None,
'date.long': None,
'datetime.short': None,
'datetime.medium': None,
'datetime.full': None,
'datetime.long': None,
})
def __init__(self, app=None, default_locale='en', default_timezone='UTC',
date_formats=None, configure_jinja=True, default_domain=None):
self._default_locale = default_locale
self._default_timezone = default_timezone
self._date_formats = date_formats
self._configure_jinja = configure_jinja
self.app = app
self._locale_cache = dict()
if default_domain is None:
self._default_domain = Domain()
else:
self._default_domain = default_domain
self.locale_selector_func = None
self.timezone_selector_func = None
if app is not None:
self.init_app(app)
def init_app(self, app):
"""Set up this instance for use with *app*, if no app was passed to
the constructor.
"""
self.app = app
app.babel_instance = self
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['babel'] = self
app.config.setdefault('BABEL_DEFAULT_LOCALE', self._default_locale)
app.config.setdefault('BABEL_DEFAULT_TIMEZONE', self._default_timezone)
if self._date_formats is None:
self._date_formats = self.default_date_formats.copy()
#: a mapping of Babel datetime format strings that can be modified
#: to change the defaults. If you invoke :func:`format_datetime`
#: and do not provide any format string Flask-Babel will do the
#: following things:
#:
#: 1. look up ``date_formats['datetime']``. By default ``'medium'``
#: is returned to enforce medium length datetime formats.
#: 2. ``date_formats['datetime.medium'] (if ``'medium'`` was
#: returned in step one) is looked up. If the return value
#: is anything but `None` this is used as new format string.
#: otherwise the default for that language is used.
self.date_formats = self._date_formats
if self._configure_jinja:
app.jinja_env.filters.update(
datetimeformat=format_datetime,
dateformat=format_date,
timeformat=format_time,
timedeltaformat=format_timedelta,
numberformat=format_number,
decimalformat=format_decimal,
currencyformat=format_currency,
percentformat=format_percent,
scientificformat=format_scientific,
)
app.jinja_env.add_extension('jinja2.ext.i18n')
app.jinja_env.install_gettext_callables(
lambda x: get_domain().get_translations().ugettext(x),
lambda s, p, n: get_domain().get_translations().ungettext(s, p, n),
newstyle=True
)
def localeselector(self, f):
"""Registers a callback function for locale selection. The default
behaves as if a function was registered that returns `None` all the
time. If `None` is returned, the locale falls back to the one from
the configuration.
This has to return the locale as string (eg: ``'de_AT'``, ''`en_US`'')
"""
assert self.locale_selector_func is None, \
'a localeselector function is already registered'
self.locale_selector_func = f
return f
def timezoneselector(self, f):
"""Registers a callback function for timezone selection. The default
behaves as if a function was registered that returns `None` all the
time. If `None` is returned, the timezone falls back to the one from
the configuration.
This has to return the timezone as string (eg: ``'Europe/Vienna'``)
"""
assert self.timezone_selector_func is None, \
'a timezoneselector function is already registered'
self.timezone_selector_func = f
return f
def list_translations(self):
"""Returns a list of all the locales translations exist for. The
list returned will be filled with actual locale objects and not just
strings.
.. versionadded:: 0.6
"""
dirname = os.path.join(self.app.root_path, 'translations')
if not os.path.isdir(dirname):
return []
result = []
for folder in os.listdir(dirname):
locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES')
if not os.path.isdir(locale_dir):
continue
if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)):
result.append(Locale.parse(folder))
if not result:
result.append(Locale.parse(self._default_locale))
return result
@property
def default_locale(self):
"""The default locale from the configuration as instance of a
`babel.Locale` object.
"""
return self.load_locale(self.app.config['BABEL_DEFAULT_LOCALE'])
@property
def default_timezone(self):
"""The default timezone from the configuration as instance of a
`pytz.timezone` object.
"""
return timezone(self.app.config['BABEL_DEFAULT_TIMEZONE'])
def load_locale(self, locale):
"""Load locale by name and cache it. Returns instance of a `babel.Locale`
object.
"""
rv = self._locale_cache.get(locale)
if rv is None:
self._locale_cache[locale] = rv = Locale.parse(locale)
return rv
def get_locale():
"""Returns the locale that should be used for this request as
`babel.Locale` object. This returns `None` if used outside of
a request. If flask-babel was not attached to the Flask application,
will return 'en' locale.
"""
ctx = _request_ctx_stack.top
if ctx is None:
return None
locale = getattr(ctx, 'babel_locale', None)
if locale is None:
babel = ctx.app.extensions.get('babel')
if babel is None:
locale = _DEFAULT_LOCALE
else:
if babel.locale_selector_func is not None:
rv = babel.locale_selector_func()
if rv is None:
locale = babel.default_locale
else:
locale = babel.load_locale(rv)
else:
locale = babel.default_locale
ctx.babel_locale = locale
return locale
def get_timezone():
"""Returns the timezone that should be used for this request as
`pytz.timezone` object. This returns `None` if used outside of
a request. If flask-babel was not attached to application, will
return UTC timezone object.
"""
ctx = _request_ctx_stack.top
tzinfo = getattr(ctx, 'babel_tzinfo', None)
if tzinfo is None:
babel = ctx.app.extensions.get('babel')
if babel is None:
tzinfo = UTC
else:
if babel.timezone_selector_func is None:
tzinfo = babel.default_timezone
else:
rv = babel.timezone_selector_func()
if rv is None:
tzinfo = babel.default_timezone
else:
if isinstance(rv, string_types):
tzinfo = timezone(rv)
else:
tzinfo = rv
ctx.babel_tzinfo = tzinfo
return tzinfo
def refresh():
"""Refreshes the cached timezones and locale information. This can
be used to switch a translation between a request and if you want
the changes to take place immediately, not just with the next request::
user.timezone = request.form['timezone']
user.locale = request.form['locale']
refresh()
flash(gettext('Language was changed'))
Without that refresh, the :func:`~flask.flash` function would probably
return English text and a now German page.
"""
ctx = _request_ctx_stack.top
for key in 'babel_locale', 'babel_tzinfo':
if hasattr(ctx, key):
delattr(ctx, key)
def _get_format(key, format):
"""A small helper for the datetime formatting functions. Looks up
format defaults for different kinds.
"""
babel = _request_ctx_stack.top.app.extensions.get('babel')
if babel is not None:
formats = babel.date_formats
else:
formats = Babel.default_date_formats
if format is None:
format = formats[key]
if format in ('short', 'medium', 'full', 'long'):
rv = formats['%s.%s' % (key, format)]
if rv is not None:
format = rv
return format
def to_user_timezone(datetime):
"""Convert a datetime object to the user's timezone. This automatically
happens on all date formatting unless rebasing is disabled. If you need
to convert a :class:`datetime.datetime` object at any time to the user's
timezone (as returned by :func:`get_timezone` this function can be used).
"""
if datetime.tzinfo is None:
datetime = datetime.replace(tzinfo=UTC)
tzinfo = get_timezone()
return tzinfo.normalize(datetime.astimezone(tzinfo))
def to_utc(datetime):
"""Convert a datetime object to UTC and drop tzinfo. This is the
opposite operation to :func:`to_user_timezone`.
"""
if datetime.tzinfo is None:
datetime = get_timezone().localize(datetime)
return datetime.astimezone(UTC).replace(tzinfo=None)
def format_datetime(datetime=None, format=None, rebase=True):
"""Return a date formatted according to the given pattern. If no
:class:`~datetime.datetime` object is passed, the current time is
assumed. By default rebasing happens which causes the object to
be converted to the users's timezone (as returned by
:func:`to_user_timezone`). This function formats both date and
time.
The format parameter can either be ``'short'``, ``'medium'``,
``'long'`` or ``'full'`` (in which cause the language's default for
that setting is used, or the default from the :attr:`Babel.date_formats`
mapping is used) or a format string as documented by Babel.
This function is also available in the template context as filter
named `datetimeformat`.
"""
format = _get_format('datetime', format)
return _date_format(dates.format_datetime, datetime, format, rebase)
def format_date(date=None, format=None, rebase=True):
"""Return a date formatted according to the given pattern. If no
:class:`~datetime.datetime` or :class:`~datetime.date` object is passed,
the current time is assumed. By default rebasing happens which causes
the object to be converted to the users's timezone (as returned by
:func:`to_user_timezone`). This function only formats the date part
of a :class:`~datetime.datetime` object.
The format parameter can either be ``'short'``, ``'medium'``,
``'long'`` or ``'full'`` (in which cause the language's default for
that setting is used, or the default from the :attr:`Babel.date_formats`
mapping is used) or a format string as documented by Babel.
This function is also available in the template context as filter
named `dateformat`.
"""
if rebase and isinstance(date, datetime):
date = to_user_timezone(date)
format = _get_format('date', format)
return _date_format(dates.format_date, date, format, rebase)
def format_time(time=None, format=None, rebase=True):
"""Return a time formatted according to the given pattern. If no
:class:`~datetime.datetime` object is passed, the current time is
assumed. By default rebasing happens which causes the object to
be converted to the users's timezone (as returned by
:func:`to_user_timezone`). This function formats both date and
time.
The format parameter can either be ``'short'``, ``'medium'``,
``'long'`` or ``'full'`` (in which cause the language's default for
that setting is used, or the default from the :attr:`Babel.date_formats`
mapping is used) or a format string as documented by Babel.
This function is also available in the template context as filter
named `timeformat`.
"""
format = _get_format('time', format)
return _date_format(dates.format_time, time, format, rebase)
def format_timedelta(datetime_or_timedelta, granularity='second'):
"""Format the elapsed time from the given date to now or the given
timedelta. This currently requires an unreleased development
version of Babel.
This function is also available in the template context as filter
named `timedeltaformat`.
"""
if isinstance(datetime_or_timedelta, datetime):
datetime_or_timedelta = datetime.utcnow() - datetime_or_timedelta
return dates.format_timedelta(datetime_or_timedelta, granularity,
locale=get_locale())
def _date_format(formatter, obj, format, rebase, **extra):
"""Internal helper that formats the date."""
locale = get_locale()
extra = {}
if formatter is not dates.format_date and rebase:
extra['tzinfo'] = get_timezone()
return formatter(obj, format, locale=locale, **extra)
def format_number(number):
"""Return the given number formatted for the locale in request
:param number: the number to format
:return: the formatted number
:rtype: unicode
"""
locale = get_locale()
return numbers.format_number(number, locale=locale)
def format_decimal(number, format=None):
"""Return the given decimal number formatted for the locale in request
:param number: the number to format
:param format: the format to use
:return: the formatted number
:rtype: unicode
"""
locale = get_locale()
return numbers.format_decimal(number, format=format, locale=locale)
def format_currency(number, currency, format=None):
"""Return the given number formatted for the locale in request
:param number: the number to format
:param currency: the currency code
:param format: the format to use
:return: the formatted number
:rtype: unicode
"""
locale = get_locale()
return numbers.format_currency(
number, currency, format=format, locale=locale
)
def format_percent(number, format=None):
"""Return formatted percent value for the locale in request
:param number: the number to format
:param format: the format to use
:return: the formatted percent number
:rtype: unicode
"""
locale = get_locale()
return numbers.format_percent(number, format=format, locale=locale)
def format_scientific(number, format=None):
"""Return value formatted in scientific notation for the locale in request
:param number: the number to format
:param format: the format to use
:return: the formatted percent number
:rtype: unicode
"""
locale = get_locale()
return numbers.format_scientific(number, format=format, locale=locale)
class Domain(object):
"""Localization domain. By default will use look for tranlations in Flask application directory
and "messages" domain - all message catalogs should be called ``messages.mo``.
"""
def __init__(self, dirname=None, domain='messages'):
self.dirname = dirname
self.domain = domain
self.cache = dict()
def as_default(self):
"""Set this domain as default for the current request"""
ctx = _request_ctx_stack.top
if ctx is None:
raise RuntimeError("No request context")
ctx.babel_domain = self
def get_translations_cache(self, ctx):
"""Returns dictionary-like object for translation caching"""
return self.cache
def get_translations_path(self, ctx):
"""Returns translations directory path. Override if you want
to implement custom behavior.
"""
return self.dirname or os.path.join(ctx.app.root_path, 'translations')
def get_translations(self):
"""Returns the correct gettext translations that should be used for
this request. This will never fail and return a dummy translation
object if used outside of the request or if a translation cannot be
found.
"""
ctx = _request_ctx_stack.top
if ctx is None:
return NullTranslations()
locale = get_locale()
cache = self.get_translations_cache(ctx)
translations = cache.get(str(locale))
if translations is None:
dirname = self.get_translations_path(ctx)
translations = support.Translations.load(dirname,
locale,
domain=self.domain)
cache[str(locale)] = translations
return translations
def gettext(self, string, **variables):
"""Translates a string with the current locale and passes in the
given keyword arguments as mapping to a string formatting string.
::
gettext(u'Hello World!')
gettext(u'Hello %(name)s!', name='World')
"""
t = self.get_translations()
return t.ugettext(string) % variables
def ngettext(self, singular, plural, num, **variables):
"""Translates a string with the current locale and passes in the
given keyword arguments as mapping to a string formatting string.
The `num` parameter is used to dispatch between singular and various
plural forms of the message. It is available in the format string
as ``%(num)d`` or ``%(num)s``. The source language should be
English or a similar language which only has one plural form.
::
ngettext(u'%(num)d Apple', u'%(num)d Apples', num=len(apples))
"""
variables.setdefault('num', num)
t = self.get_translations()
return t.ungettext(singular, plural, num) % variables
def pgettext(self, context, string, **variables):
"""Like :func:`gettext` but with a context.
.. versionadded:: 0.7
"""
t = self.get_translations()
return t.upgettext(context, string) % variables
def npgettext(self, context, singular, plural, num, **variables):
"""Like :func:`ngettext` but with a context.
.. versionadded:: 0.7
"""
variables.setdefault('num', num)
t = self.get_translations()
return t.unpgettext(context, singular, plural, num) % variables
def lazy_gettext(self, string, **variables):
"""Like :func:`gettext` but the string returned is lazy which means
it will be translated when it is used as an actual string.
Example::
hello = lazy_gettext(u'Hello World')
@app.route('/')
def index():
return unicode(hello)
"""
from speaklater import make_lazy_string
return make_lazy_string(self.gettext, string, **variables)
def lazy_pgettext(self, context, string, **variables):
"""Like :func:`pgettext` but the string returned is lazy which means
it will be translated when it is used as an actual string.
.. versionadded:: 0.7
"""
from speaklater import make_lazy_string
return make_lazy_string(self.pgettext, context, string, **variables)
# This is the domain that will be used if there is no request context (and thus no app)
# or if the app isn't initialized for babel. Note that if there is no request context,
# then the standard Domain will use NullTranslations
domain = Domain()
def get_domain():
"""Return the correct translation domain that is used for this request.
This will return the default domain (e.g. "messages" in <approot>/translations")
if none is set for this request.
"""
ctx = _request_ctx_stack.top
if ctx is None:
return domain
try:
return ctx.babel_domain
except AttributeError:
pass
babel = ctx.app.extensions.get('babel')
if babel is not None:
d = babel._default_domain
else:
d = domain
ctx.babel_domain = d
return d
# Create shortcuts for the default Flask domain
def gettext(*args, **kwargs):
return get_domain().gettext(*args, **kwargs)
_ = gettext
def ngettext(*args, **kwargs):
return get_domain().ngettext(*args, **kwargs)
def pgettext(*args, **kwargs):
return get_domain().pgettext(*args, **kwargs)
def npgettext(*args, **kwargs):
return get_domain().npgettext(*args, **kwargs)
def lazy_gettext(*args, **kwargs):
return get_domain().lazy_gettext(*args, **kwargs)
def lazy_pgettext(*args, **kwargs):
return get_domain().lazy_pgettext(*args, **kwargs)
| initNirvana/Easyphotos | env/lib/python3.4/site-packages/flask_babelex/__init__.py | Python | mit | 22,503 |
<?php
Class Contact_model extends MY_Model
{
var $table = 'contact';
function get_list_contact()
{
$query = $this->db->get($this->table);
if ($query->result()) {
return $query->result();
} else {
return FALSE;
}
}
}
| cuongfpt/vp-card | application/models/Contact_model.php | PHP | mit | 295 |
var _; //globals
/* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/
"Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.
It's the tie to go along with jQuery's tux."
*/
describe("About Higher Order Functions", function () {
it("should use filter to return array items that meet a criteria", function () {
var numbers = [1,2,3];
var odd = _(numbers).filter(function (x) { return x % 2 !== 0 });
expect(odd).toEqual([1,3]);
expect(odd.length).toBe(2);
expect(numbers.length).toBe(3);
});
it("should use 'map' to transform each element", function () {
var numbers = [1, 2, 3];
var numbersPlus1 = _(numbers).map(function(x) { return x + 1 });
expect(numbersPlus1).toEqual([2,3,4]);
expect(numbers).toEqual([1,2,3]);
});
it("should use 'reduce' to update the same result on each iteration", function () {
var numbers = [1, 2, 3];
var reduction = _(numbers).reduce(
function(memo, x) {
//note: memo is the result from last call, and x is the current number
return memo + x;
},
/* initial */ 0
);
expect(reduction).toBe(6);
expect(numbers).toEqual([1,2,3]);
});
it("should use 'forEach' for simple iteration", function () {
var numbers = [1,2,3];
var msg = "";
var isEven = function (item) {
msg += (item % 2) === 0;
};
_(numbers).forEach(isEven);
expect(msg).toEqual('falsetruefalse');
expect(numbers).toEqual([1,2,3]);
});
it("should use 'all' to test whether all items pass condition", function () {
var onlyEven = [2,4,6];
var mixedBag = [2,4,5,6];
var isEven = function(x) { return x % 2 === 0 };
expect(_(onlyEven).all(isEven)).toBe(true);
expect(_(mixedBag).all(isEven)).toBe(false);
});
it("should use 'any' to test if any items passes condition" , function () {
var onlyEven = [2,4,6];
var mixedBag = [2,4,5,6];
var isEven = function(x) { return x % 2 === 0 };
expect(_(onlyEven).any(isEven)).toBe(true);
expect(_(mixedBag).any(isEven)).toBe(true);
});
it("should use range to generate an array", function() {
expect(_.range(3)).toEqual([0, 1, 2]);
expect(_.range(1, 4)).toEqual([1, 2, 3]);
expect(_.range(0, -4, -1)).toEqual([0, -1, -2, -3]);
});
it("should use flatten to make nested arrays easy to work with", function() {
expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual([1,2,3,4]);
});
it("should use chain() ... .value() to use multiple higher order functions", function() {
var result = _([ [0, 1], 2 ]).chain()
.flatten()
.map(function(x) { return x+1 } )
.reduce(function (sum, x) { return sum + x })
.value();
expect(result).toEqual(6);
});
});
| victorleungtw/javascript-koans | koans/AboutHigherOrderFunctions.js | JavaScript | mit | 3,035 |
<?php $error_id = uniqid('error', true); ?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title><?= esc($title) ?></title>
<style type="text/css">
<?= preg_replace('#[\r\n\t ]+#', ' ', file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.css')) ?>
</style>
<script type="text/javascript">
<?= file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.js') ?>
</script>
</head>
<body onload="init()">
<!-- Header -->
<div class="header">
<div class="container">
<h1><?= esc($title), esc($exception->getCode() ? ' #' . $exception->getCode() : '') ?></h1>
<p>
<?= nl2br(esc($exception->getMessage())) ?>
<a href="https://www.duckduckgo.com/?q=<?= urlencode($title . ' ' . preg_replace('#\'.*\'|".*"#Us', '', $exception->getMessage())) ?>"
rel="noreferrer" target="_blank">search →</a>
</p>
</div>
</div>
<!-- Source -->
<div class="container">
<p><b><?= esc(static::cleanPath($file, $line)) ?></b> at line <b><?= esc($line) ?></b></p>
<?php if (is_file($file)) : ?>
<div class="source">
<?= static::highlightFile($file, $line, 15); ?>
</div>
<?php endif; ?>
</div>
<div class="container">
<ul class="tabs" id="tabs">
<li><a href="#backtrace">Backtrace</a></li>
<li><a href="#server">Server</a></li>
<li><a href="#request">Request</a></li>
<li><a href="#response">Response</a></li>
<li><a href="#files">Files</a></li>
<li><a href="#memory">Memory</a></li>
</ul>
<div class="tab-content">
<!-- Backtrace -->
<div class="content" id="backtrace">
<ol class="trace">
<?php foreach ($trace as $index => $row) : ?>
<li>
<p>
<!-- Trace info -->
<?php if (isset($row['file']) && is_file($row['file'])) :?>
<?php
if (isset($row['function']) && in_array($row['function'], ['include', 'include_once', 'require', 'require_once'], true)) {
echo esc($row['function'] . ' ' . static::cleanPath($row['file']));
} else {
echo esc(static::cleanPath($row['file']) . ' : ' . $row['line']);
}
?>
<?php else : ?>
{PHP internal code}
<?php endif; ?>
<!-- Class/Method -->
<?php if (isset($row['class'])) : ?>
— <?= esc($row['class'] . $row['type'] . $row['function']) ?>
<?php if (! empty($row['args'])) : ?>
<?php $args_id = $error_id . 'args' . $index ?>
( <a href="#" onclick="return toggle('<?= esc($args_id, 'attr') ?>');">arguments</a> )
<div class="args" id="<?= esc($args_id, 'attr') ?>">
<table cellspacing="0">
<?php
$params = null;
// Reflection by name is not available for closure function
if (substr($row['function'], -1) !== '}') {
$mirror = isset($row['class']) ? new \ReflectionMethod($row['class'], $row['function']) : new \ReflectionFunction($row['function']);
$params = $mirror->getParameters();
}
foreach ($row['args'] as $key => $value) : ?>
<tr>
<td><code><?= esc(isset($params[$key]) ? '$' . $params[$key]->name : "#{$key}") ?></code></td>
<td><pre><?= esc(print_r($value, true)) ?></pre></td>
</tr>
<?php endforeach ?>
</table>
</div>
<?php else : ?>
()
<?php endif; ?>
<?php endif; ?>
<?php if (! isset($row['class']) && isset($row['function'])) : ?>
— <?= esc($row['function']) ?>()
<?php endif; ?>
</p>
<!-- Source? -->
<?php if (isset($row['file']) && is_file($row['file']) && isset($row['class'])) : ?>
<div class="source">
<?= static::highlightFile($row['file'], $row['line']) ?>
</div>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ol>
</div>
<!-- Server -->
<div class="content" id="server">
<?php foreach (['_SERVER', '_SESSION'] as $var) : ?>
<?php
if (empty($GLOBALS[$var]) || ! is_array($GLOBALS[$var])) {
continue;
} ?>
<h3>$<?= esc($var) ?></h3>
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($GLOBALS[$var] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endforeach ?>
<!-- Constants -->
<?php $constants = get_defined_constants(true); ?>
<?php if (! empty($constants['user'])) : ?>
<h3>Constants</h3>
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($constants['user'] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Request -->
<div class="content" id="request">
<?php $request = \Config\Services::request(); ?>
<table>
<tbody>
<tr>
<td style="width: 10em">Path</td>
<td><?= esc($request->uri) ?></td>
</tr>
<tr>
<td>HTTP Method</td>
<td><?= esc($request->getMethod(true)) ?></td>
</tr>
<tr>
<td>IP Address</td>
<td><?= esc($request->getIPAddress()) ?></td>
</tr>
<tr>
<td style="width: 10em">Is AJAX Request?</td>
<td><?= $request->isAJAX() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>Is CLI Request?</td>
<td><?= $request->isCLI() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>Is Secure Request?</td>
<td><?= $request->isSecure() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>User Agent</td>
<td><?= esc($request->getUserAgent()->getAgentString()) ?></td>
</tr>
</tbody>
</table>
<?php $empty = true; ?>
<?php foreach (['_GET', '_POST', '_COOKIE'] as $var) : ?>
<?php
if (empty($GLOBALS[$var]) || ! is_array($GLOBALS[$var])) {
continue;
} ?>
<?php $empty = false; ?>
<h3>$<?= esc($var) ?></h3>
<table style="width: 100%">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($GLOBALS[$var] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endforeach ?>
<?php if ($empty) : ?>
<div class="alert">
No $_GET, $_POST, or $_COOKIE Information to show.
</div>
<?php endif; ?>
<?php $headers = $request->getHeaders(); ?>
<?php if (! empty($headers)) : ?>
<h3>Headers</h3>
<table>
<thead>
<tr>
<th>Header</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($headers as $value) : ?>
<?php
if (empty($value)) {
continue;
}
if (! is_array($value)) {
$value = [$value];
} ?>
<?php foreach ($value as $h) : ?>
<tr>
<td><?= esc($h->getName(), 'html') ?></td>
<td><?= esc($h->getValueLine(), 'html') ?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Response -->
<?php
$response = \Config\Services::response();
$response->setStatusCode(http_response_code());
?>
<div class="content" id="response">
<table>
<tr>
<td style="width: 15em">Response Status</td>
<td><?= esc($response->getStatusCode() . ' - ' . $response->getReason()) ?></td>
</tr>
</table>
<?php $headers = $response->getHeaders(); ?>
<?php if (! empty($headers)) : ?>
<?php natsort($headers) ?>
<h3>Headers</h3>
<table>
<thead>
<tr>
<th>Header</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($headers as $name => $value) : ?>
<tr>
<td><?= esc($name, 'html') ?></td>
<td><?= esc($response->getHeaderLine($name), 'html') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Files -->
<div class="content" id="files">
<?php $files = get_included_files(); ?>
<ol>
<?php foreach ($files as $file) :?>
<li><?= esc(static::cleanPath($file)) ?></li>
<?php endforeach ?>
</ol>
</div>
<!-- Memory -->
<div class="content" id="memory">
<table>
<tbody>
<tr>
<td>Memory Usage</td>
<td><?= esc(static::describeMemory(memory_get_usage(true))) ?></td>
</tr>
<tr>
<td style="width: 12em">Peak Memory Usage:</td>
<td><?= esc(static::describeMemory(memory_get_peak_usage(true))) ?></td>
</tr>
<tr>
<td>Memory Limit:</td>
<td><?= esc(ini_get('memory_limit')) ?></td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /tab-content -->
</div> <!-- /container -->
<div class="footer">
<div class="container">
<p>
Displayed at <?= esc(date('H:i:sa')) ?> —
PHP: <?= esc(PHP_VERSION) ?> —
CodeIgniter: <?= esc(\CodeIgniter\CodeIgniter::CI_VERSION) ?>
</p>
</div>
</div>
</body>
</html>
| ytetsuro/CodeIgniter4 | app/Views/errors/html/error_exception.php | PHP | mit | 10,634 |
try:
from tornado.websocket import WebSocketHandler
import tornado.ioloop
tornadoAvailable = True
except ImportError:
class WebSocketHandler(object): pass
tornadoAvailable = False
from json import loads as fromJS, dumps as toJS
from threading import Thread
from Log import console
import Settings
from utils import *
PORT = Settings.PORT + 1
handlers = []
channels = {}
class WebSocket:
@staticmethod
def available():
return tornadoAvailable
@staticmethod
def start():
if WebSocket.available():
WSThread().start()
@staticmethod
def broadcast(data):
for handler in handlers:
handler.write_message(toJS(data))
@staticmethod
def sendChannel(channel, data):
if not 'channel' in data:
data['channel'] = channel
for handler in channels.get(channel, []):
handler.write_message(toJS(data))
class WSThread(Thread):
def __init__(self):
Thread.__init__(self)
self.name = 'websocket'
self.daemon = True
def run(self):
app = tornado.web.Application([('/', WSHandler)])
app.listen(PORT, '0.0.0.0')
tornado.ioloop.IOLoop.instance().start()
class WSHandler(WebSocketHandler):
def __init__(self, *args, **kw):
super(WSHandler, self).__init__(*args, **kw)
self.channels = set()
def check_origin(self, origin):
return True
def open(self):
handlers.append(self)
console('websocket', "Opened")
def on_message(self, message):
console('websocket', "Message received: %s" % message)
try:
data = fromJS(message)
except:
return
if 'subscribe' in data and isinstance(data['subscribe'], list):
addChannels = (set(data['subscribe']) - self.channels)
self.channels |= addChannels
for channel in addChannels:
if channel not in channels:
channels[channel] = set()
channels[channel].add(self)
if 'unsubscribe' in data and isinstance(data['unsubscribe'], list):
rmChannels = (self.channels & set(data['unsubscribe']))
self.channels -= rmChannels
for channel in rmChannels:
channels[channel].remove(self)
if len(channels[channel]) == 0:
del channels[channel]
def on_close(self):
for channel in self.channels:
channels[channel].remove(self)
if len(channels[channel]) == 0:
del channels[channel]
handlers.remove(self)
console('websocket', "Closed")
verbs = {
'status': "Status set",
'name': "Renamed",
'goal': "Goal set",
'assigned': "Reassigned",
'hours': "Hours updated",
}
from Event import EventHandler, addEventHandler
class ShareTaskChanges(EventHandler):
def newTask(self, handler, task):
WebSocket.sendChannel("backlog#%d" % task.sprint.id, {'type': 'new'}); #TODO
def taskUpdate(self, handler, task, field, value):
if field == 'assigned': # Convert set of Users to list of usernames
value = [user.username for user in value]
elif field == 'goal': # Convert Goal to goal ID
value = value.id if value else 0
description = ("%s by %s" % (verbs[field], task.creator)) if field in verbs else None
WebSocket.sendChannel("backlog#%d" % task.sprint.id, {'type': 'update', 'id': task.id, 'revision': task.revision, 'field': field, 'value': value, 'description': description, 'creator': task.creator.username})
addEventHandler(ShareTaskChanges())
| mrozekma/Sprint | WebSocket.py | Python | mit | 3,192 |
<?php
namespace Illuminate\Database\Query;
use Closure;
use BadMethodCallException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use InvalidArgumentException;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Database\Query\Processors\Processor;
class Builder
{
use Macroable {
__call as macroCall;
}
/**
* The database connection instance.
*
* @var \Illuminate\Database\Connection
*/
protected $connection;
/**
* The database query grammar instance.
*
* @var \Illuminate\Database\Query\Grammars\Grammar
*/
protected $grammar;
/**
* The database query post processor instance.
*
* @var \Illuminate\Database\Query\Processors\Processor
*/
protected $processor;
/**
* The current query value bindings.
*
* @var array
*/
protected $bindings = [
'select' => [],
'join' => [],
'where' => [],
'having' => [],
'order' => [],
'union' => [],
];
/**
* An aggregate function and column to be run.
*
* @var array
*/
public $aggregate;
/**
* The columns that should be returned.
*
* @var array
*/
public $columns;
/**
* Indicates if the query returns distinct results.
*
* @var bool
*/
public $distinct = false;
/**
* The table which the query is targeting.
*
* @var string
*/
public $from;
/**
* The table joins for the query.
*
* @var array
*/
public $joins;
/**
* The where constraints for the query.
*
* @var array
*/
public $wheres;
/**
* The groupings for the query.
*
* @var array
*/
public $groups;
/**
* The having constraints for the query.
*
* @var array
*/
public $havings;
/**
* The orderings for the query.
*
* @var array
*/
public $orders;
/**
* The maximum number of records to return.
*
* @var int
*/
public $limit;
/**
* The number of records to skip.
*
* @var int
*/
public $offset;
/**
* The query union statements.
*
* @var array
*/
public $unions;
/**
* The maximum number of union records to return.
*
* @var int
*/
public $unionLimit;
/**
* The number of union records to skip.
*
* @var int
*/
public $unionOffset;
/**
* The orderings for the union query.
*
* @var array
*/
public $unionOrders;
/**
* Indicates whether row locking is being used.
*
* @var string|bool
*/
public $lock;
/**
* The field backups currently in use.
*
* @var array
*/
protected $backups = [];
/**
* The binding backups currently in use.
*
* @var array
*/
protected $bindingBackups = [];
/**
* All of the available clause operators.
*
* @var array
*/
protected $operators = [
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'like binary', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
'~', '~*', '!~', '!~*', 'similar to',
'not similar to',
];
/**
* Whether use write pdo for select.
*
* @var bool
*/
protected $useWritePdo = false;
/**
* Create a new query builder instance.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param \Illuminate\Database\Query\Grammars\Grammar $grammar
* @param \Illuminate\Database\Query\Processors\Processor $processor
* @return void
*/
public function __construct(ConnectionInterface $connection,
Grammar $grammar,
Processor $processor)
{
$this->grammar = $grammar;
$this->processor = $processor;
$this->connection = $connection;
}
/**
* Set the columns to be selected.
*
* @param array|mixed $columns
* @return $this
*/
public function select($columns = ['*'])
{
$this->columns = is_array($columns) ? $columns : func_get_args();
return $this;
}
/**
* Add a new "raw" select expression to the query.
*
* @param string $expression
* @param array $bindings
* @return \Illuminate\Database\Query\Builder|static
*/
public function selectRaw($expression, array $bindings = [])
{
$this->addSelect(new Expression($expression));
if ($bindings) {
$this->addBinding($bindings, 'select');
}
return $this;
}
/**
* Add a subselect expression to the query.
*
* @param \Closure|\Illuminate\Database\Query\Builder|string $query
* @param string $as
* @return \Illuminate\Database\Query\Builder|static
*/
public function selectSub($query, $as)
{
if ($query instanceof Closure) {
$callback = $query;
$callback($query = $this->newQuery());
}
if ($query instanceof self) {
$bindings = $query->getBindings();
$query = $query->toSql();
} elseif (is_string($query)) {
$bindings = [];
} else {
throw new InvalidArgumentException;
}
return $this->selectRaw('('.$query.') as '.$this->grammar->wrap($as), $bindings);
}
/**
* Add a new select column to the query.
*
* @param array|mixed $column
* @return $this
*/
public function addSelect($column)
{
$column = is_array($column) ? $column : func_get_args();
$this->columns = array_merge((array) $this->columns, $column);
return $this;
}
/**
* Force the query to only return distinct results.
*
* @return $this
*/
public function distinct()
{
$this->distinct = true;
return $this;
}
/**
* Set the table which the query is targeting.
*
* @param string $table
* @return $this
*/
public function from($table)
{
$this->from = $table;
return $this;
}
/**
* Add a join clause to the query.
*
* @param string $table
* @param string $one
* @param string $operator
* @param string $two
* @param string $type
* @param bool $where
* @return $this
*/
public function join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)
{
// If the first "column" of the join is really a Closure instance the developer
// is trying to build a join with a complex "on" clause containing more than
// one condition, so we'll add the join and call a Closure with the query.
if ($one instanceof Closure) {
$join = new JoinClause($type, $table);
call_user_func($one, $join);
$this->joins[] = $join;
$this->addBinding($join->bindings, 'join');
}
// If the column is simply a string, we can assume the join simply has a basic
// "on" clause with a single condition. So we will just build the join with
// this simple join clauses attached to it. There is not a join callback.
else {
$join = new JoinClause($type, $table);
$this->joins[] = $join->on(
$one, $operator, $two, 'and', $where
);
$this->addBinding($join->bindings, 'join');
}
return $this;
}
/**
* Add a "join where" clause to the query.
*
* @param string $table
* @param string $one
* @param string $operator
* @param string $two
* @param string $type
* @return \Illuminate\Database\Query\Builder|static
*/
public function joinWhere($table, $one, $operator, $two, $type = 'inner')
{
return $this->join($table, $one, $operator, $two, $type, true);
}
/**
* Add a left join to the query.
*
* @param string $table
* @param string $first
* @param string $operator
* @param string $second
* @return \Illuminate\Database\Query\Builder|static
*/
public function leftJoin($table, $first, $operator = null, $second = null)
{
return $this->join($table, $first, $operator, $second, 'left');
}
/**
* Add a "join where" clause to the query.
*
* @param string $table
* @param string $one
* @param string $operator
* @param string $two
* @return \Illuminate\Database\Query\Builder|static
*/
public function leftJoinWhere($table, $one, $operator, $two)
{
return $this->joinWhere($table, $one, $operator, $two, 'left');
}
/**
* Add a right join to the query.
*
* @param string $table
* @param string $first
* @param string $operator
* @param string $second
* @return \Illuminate\Database\Query\Builder|static
*/
public function rightJoin($table, $first, $operator = null, $second = null)
{
return $this->join($table, $first, $operator, $second, 'right');
}
/**
* Add a "right join where" clause to the query.
*
* @param string $table
* @param string $one
* @param string $operator
* @param string $two
* @return \Illuminate\Database\Query\Builder|static
*/
public function rightJoinWhere($table, $one, $operator, $two)
{
return $this->joinWhere($table, $one, $operator, $two, 'right');
}
/**
* Add a basic where clause to the query.
*
* @param string|array|\Closure $column
* @param string $operator
* @param mixed $value
* @param string $boolean
* @return $this
*
* @throws \InvalidArgumentException
*/
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
// If the column is an array, we will assume it is an array of key-value pairs
// and can add them each as a where clause. We will maintain the boolean we
// received when the method was called and pass it into the nested where.
if (is_array($column)) {
return $this->whereNested(function ($query) use ($column) {
foreach ($column as $key => $value) {
$query->where($key, '=', $value);
}
}, $boolean);
}
// Here we will make some assumptions about the operator. If only 2 values are
// passed to the method, we will assume that the operator is an equals sign
// and keep going. Otherwise, we'll require the operator to be passed in.
if (func_num_args() == 2) {
list($value, $operator) = [$operator, '='];
} elseif ($this->invalidOperatorAndValue($operator, $value)) {
throw new InvalidArgumentException('Illegal operator and value combination.');
}
// If the columns is actually a Closure instance, we will assume the developer
// wants to begin a nested where statement which is wrapped in parenthesis.
// We'll add that Closure to the query then return back out immediately.
if ($column instanceof Closure) {
return $this->whereNested($column, $boolean);
}
// If the given operator is not found in the list of valid operators we will
// assume that the developer is just short-cutting the '=' operators and
// we will set the operators to '=' and set the values appropriately.
if (! in_array(strtolower($operator), $this->operators, true)) {
list($value, $operator) = [$operator, '='];
}
// If the value is a Closure, it means the developer is performing an entire
// sub-select within the query and we will need to compile the sub-select
// within the where clause to get the appropriate query record results.
if ($value instanceof Closure) {
return $this->whereSub($column, $operator, $value, $boolean);
}
// If the value is "null", we will just assume the developer wants to add a
// where null clause to the query. So, we will allow a short-cut here to
// that method for convenience so the developer doesn't have to check.
if (is_null($value)) {
return $this->whereNull($column, $boolean, $operator != '=');
}
// Now that we are working with just a simple query we can put the elements
// in our array and add the query binding to our array of bindings that
// will be bound to each SQL statements when it is finally executed.
$type = 'Basic';
$this->wheres[] = compact('type', 'column', 'operator', 'value', 'boolean');
if (! $value instanceof Expression) {
$this->addBinding($value, 'where');
}
return $this;
}
/**
* Add an "or where" clause to the query.
*
* @param string $column
* @param string $operator
* @param mixed $value
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhere($column, $operator = null, $value = null)
{
return $this->where($column, $operator, $value, 'or');
}
/**
* Determine if the given operator and value combination is legal.
*
* @param string $operator
* @param mixed $value
* @return bool
*/
protected function invalidOperatorAndValue($operator, $value)
{
$isOperator = in_array($operator, $this->operators);
return $isOperator && $operator != '=' && is_null($value);
}
/**
* Add a raw where clause to the query.
*
* @param string $sql
* @param array $bindings
* @param string $boolean
* @return $this
*/
public function whereRaw($sql, array $bindings = [], $boolean = 'and')
{
$type = 'raw';
$this->wheres[] = compact('type', 'sql', 'boolean');
$this->addBinding($bindings, 'where');
return $this;
}
/**
* Add a raw or where clause to the query.
*
* @param string $sql
* @param array $bindings
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereRaw($sql, array $bindings = [])
{
return $this->whereRaw($sql, $bindings, 'or');
}
/**
* Add a where between statement to the query.
*
* @param string $column
* @param array $values
* @param string $boolean
* @param bool $not
* @return $this
*/
public function whereBetween($column, array $values, $boolean = 'and', $not = false)
{
$type = 'between';
$this->wheres[] = compact('column', 'type', 'boolean', 'not');
$this->addBinding($values, 'where');
return $this;
}
/**
* Add an or where between statement to the query.
*
* @param string $column
* @param array $values
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereBetween($column, array $values)
{
return $this->whereBetween($column, $values, 'or');
}
/**
* Add a where not between statement to the query.
*
* @param string $column
* @param array $values
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereNotBetween($column, array $values, $boolean = 'and')
{
return $this->whereBetween($column, $values, $boolean, true);
}
/**
* Add an or where not between statement to the query.
*
* @param string $column
* @param array $values
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereNotBetween($column, array $values)
{
return $this->whereNotBetween($column, $values, 'or');
}
/**
* Add a nested where statement to the query.
*
* @param \Closure $callback
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereNested(Closure $callback, $boolean = 'and')
{
$query = $this->forNestedWhere();
call_user_func($callback, $query);
return $this->addNestedWhereQuery($query, $boolean);
}
/**
* Create a new query instance for nested where condition.
*
* @return \Illuminate\Database\Query\Builder
*/
public function forNestedWhere()
{
$query = $this->newQuery();
return $query->from($this->from);
}
/**
* Add another query builder as a nested where to the query builder.
*
* @param \Illuminate\Database\Query\Builder|static $query
* @param string $boolean
* @return $this
*/
public function addNestedWhereQuery($query, $boolean = 'and')
{
if (count($query->wheres)) {
$type = 'Nested';
$this->wheres[] = compact('type', 'query', 'boolean');
$this->addBinding($query->getBindings(), 'where');
}
return $this;
}
/**
* Add a full sub-select to the query.
*
* @param string $column
* @param string $operator
* @param \Closure $callback
* @param string $boolean
* @return $this
*/
protected function whereSub($column, $operator, Closure $callback, $boolean)
{
$type = 'Sub';
$query = $this->newQuery();
// Once we have the query instance we can simply execute it so it can add all
// of the sub-select's conditions to itself, and then we can cache it off
// in the array of where clauses for the "main" parent query instance.
call_user_func($callback, $query);
$this->wheres[] = compact('type', 'column', 'operator', 'query', 'boolean');
$this->addBinding($query->getBindings(), 'where');
return $this;
}
/**
* Add an exists clause to the query.
*
* @param \Closure $callback
* @param string $boolean
* @param bool $not
* @return $this
*/
public function whereExists(Closure $callback, $boolean = 'and', $not = false)
{
$type = $not ? 'NotExists' : 'Exists';
$query = $this->newQuery();
// Similar to the sub-select clause, we will create a new query instance so
// the developer may cleanly specify the entire exists query and we will
// compile the whole thing in the grammar and insert it into the SQL.
call_user_func($callback, $query);
$this->wheres[] = compact('type', 'operator', 'query', 'boolean');
$this->addBinding($query->getBindings(), 'where');
return $this;
}
/**
* Add an or exists clause to the query.
*
* @param \Closure $callback
* @param bool $not
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereExists(Closure $callback, $not = false)
{
return $this->whereExists($callback, 'or', $not);
}
/**
* Add a where not exists clause to the query.
*
* @param \Closure $callback
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereNotExists(Closure $callback, $boolean = 'and')
{
return $this->whereExists($callback, $boolean, true);
}
/**
* Add a where not exists clause to the query.
*
* @param \Closure $callback
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereNotExists(Closure $callback)
{
return $this->orWhereExists($callback, true);
}
/**
* Add a "where in" clause to the query.
*
* @param string $column
* @param mixed $values
* @param string $boolean
* @param bool $not
* @return $this
*/
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
$type = $not ? 'NotIn' : 'In';
// If the value of the where in clause is actually a Closure, we will assume that
// the developer is using a full sub-select for this "in" statement, and will
// execute those Closures, then we can re-construct the entire sub-selects.
if ($values instanceof Closure) {
return $this->whereInSub($column, $values, $boolean, $not);
}
if ($values instanceof Arrayable) {
$values = $values->toArray();
}
$this->wheres[] = compact('type', 'column', 'values', 'boolean');
$this->addBinding($values, 'where');
return $this;
}
/**
* Add an "or where in" clause to the query.
*
* @param string $column
* @param mixed $values
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereIn($column, $values)
{
return $this->whereIn($column, $values, 'or');
}
/**
* Add a "where not in" clause to the query.
*
* @param string $column
* @param mixed $values
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereNotIn($column, $values, $boolean = 'and')
{
return $this->whereIn($column, $values, $boolean, true);
}
/**
* Add an "or where not in" clause to the query.
*
* @param string $column
* @param mixed $values
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereNotIn($column, $values)
{
return $this->whereNotIn($column, $values, 'or');
}
/**
* Add a where in with a sub-select to the query.
*
* @param string $column
* @param \Closure $callback
* @param string $boolean
* @param bool $not
* @return $this
*/
protected function whereInSub($column, Closure $callback, $boolean, $not)
{
$type = $not ? 'NotInSub' : 'InSub';
// To create the exists sub-select, we will actually create a query and call the
// provided callback with the query so the developer may set any of the query
// conditions they want for the in clause, then we'll put it in this array.
call_user_func($callback, $query = $this->newQuery());
$this->wheres[] = compact('type', 'column', 'query', 'boolean');
$this->addBinding($query->getBindings(), 'where');
return $this;
}
/**
* Add a "where null" clause to the query.
*
* @param string $column
* @param string $boolean
* @param bool $not
* @return $this
*/
public function whereNull($column, $boolean = 'and', $not = false)
{
$type = $not ? 'NotNull' : 'Null';
$this->wheres[] = compact('type', 'column', 'boolean');
return $this;
}
/**
* Add an "or where null" clause to the query.
*
* @param string $column
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereNull($column)
{
return $this->whereNull($column, 'or');
}
/**
* Add a "where not null" clause to the query.
*
* @param string $column
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereNotNull($column, $boolean = 'and')
{
return $this->whereNull($column, $boolean, true);
}
/**
* Add an "or where not null" clause to the query.
*
* @param string $column
* @return \Illuminate\Database\Query\Builder|static
*/
public function orWhereNotNull($column)
{
return $this->whereNotNull($column, 'or');
}
/**
* Add a "where date" statement to the query.
*
* @param string $column
* @param string $operator
* @param int $value
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereDate($column, $operator, $value, $boolean = 'and')
{
return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean);
}
/**
* Add a "where day" statement to the query.
*
* @param string $column
* @param string $operator
* @param int $value
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereDay($column, $operator, $value, $boolean = 'and')
{
return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean);
}
/**
* Add a "where month" statement to the query.
*
* @param string $column
* @param string $operator
* @param int $value
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereMonth($column, $operator, $value, $boolean = 'and')
{
return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean);
}
/**
* Add a "where year" statement to the query.
*
* @param string $column
* @param string $operator
* @param int $value
* @param string $boolean
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereYear($column, $operator, $value, $boolean = 'and')
{
return $this->addDateBasedWhere('Year', $column, $operator, $value, $boolean);
}
/**
* Add a date based (year, month, day) statement to the query.
*
* @param string $type
* @param string $column
* @param string $operator
* @param int $value
* @param string $boolean
* @return $this
*/
protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and')
{
$this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value');
$this->addBinding($value, 'where');
return $this;
}
/**
* Handles dynamic "where" clauses to the query.
*
* @param string $method
* @param string $parameters
* @return $this
*/
public function dynamicWhere($method, $parameters)
{
$finder = substr($method, 5);
$segments = preg_split('/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);
// The connector variable will determine which connector will be used for the
// query condition. We will change it as we come across new boolean values
// in the dynamic method strings, which could contain a number of these.
$connector = 'and';
$index = 0;
foreach ($segments as $segment) {
// If the segment is not a boolean connector, we can assume it is a column's name
// and we will add it to the query as a new constraint as a where clause, then
// we can keep iterating through the dynamic method string's segments again.
if ($segment != 'And' && $segment != 'Or') {
$this->addDynamic($segment, $connector, $parameters, $index);
$index++;
}
// Otherwise, we will store the connector so we know how the next where clause we
// find in the query should be connected to the previous ones, meaning we will
// have the proper boolean connector to connect the next where clause found.
else {
$connector = $segment;
}
}
return $this;
}
/**
* Add a single dynamic where clause statement to the query.
*
* @param string $segment
* @param string $connector
* @param array $parameters
* @param int $index
* @return void
*/
protected function addDynamic($segment, $connector, $parameters, $index)
{
// Once we have parsed out the columns and formatted the boolean operators we
// are ready to add it to this query as a where clause just like any other
// clause on the query. Then we'll increment the parameter index values.
$bool = strtolower($connector);
$this->where(Str::snake($segment), '=', $parameters[$index], $bool);
}
/**
* Add a "group by" clause to the query.
*
* @param array|string $column,...
* @return $this
*/
public function groupBy()
{
foreach (func_get_args() as $arg) {
$this->groups = array_merge((array) $this->groups, is_array($arg) ? $arg : [$arg]);
}
return $this;
}
/**
* Add a "having" clause to the query.
*
* @param string $column
* @param string $operator
* @param string $value
* @param string $boolean
* @return $this
*/
public function having($column, $operator = null, $value = null, $boolean = 'and')
{
$type = 'basic';
$this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean');
if (! $value instanceof Expression) {
$this->addBinding($value, 'having');
}
return $this;
}
/**
* Add a "or having" clause to the query.
*
* @param string $column
* @param string $operator
* @param string $value
* @return \Illuminate\Database\Query\Builder|static
*/
public function orHaving($column, $operator = null, $value = null)
{
return $this->having($column, $operator, $value, 'or');
}
/**
* Add a raw having clause to the query.
*
* @param string $sql
* @param array $bindings
* @param string $boolean
* @return $this
*/
public function havingRaw($sql, array $bindings = [], $boolean = 'and')
{
$type = 'raw';
$this->havings[] = compact('type', 'sql', 'boolean');
$this->addBinding($bindings, 'having');
return $this;
}
/**
* Add a raw or having clause to the query.
*
* @param string $sql
* @param array $bindings
* @return \Illuminate\Database\Query\Builder|static
*/
public function orHavingRaw($sql, array $bindings = [])
{
return $this->havingRaw($sql, $bindings, 'or');
}
/**
* Add an "order by" clause to the query.
*
* @param string $column
* @param string $direction
* @return $this
*/
public function orderBy($column, $direction = 'asc')
{
$property = $this->unions ? 'unionOrders' : 'orders';
$direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';
$this->{$property}[] = compact('column', 'direction');
return $this;
}
/**
* Add an "order by" clause for a timestamp to the query.
*
* @param string $column
* @return \Illuminate\Database\Query\Builder|static
*/
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
/**
* Add an "order by" clause for a timestamp to the query.
*
* @param string $column
* @return \Illuminate\Database\Query\Builder|static
*/
public function oldest($column = 'created_at')
{
return $this->orderBy($column, 'asc');
}
/**
* Add a raw "order by" clause to the query.
*
* @param string $sql
* @param array $bindings
* @return $this
*/
public function orderByRaw($sql, $bindings = [])
{
$property = $this->unions ? 'unionOrders' : 'orders';
$type = 'raw';
$this->{$property}[] = compact('type', 'sql');
$this->addBinding($bindings, 'order');
return $this;
}
/**
* Set the "offset" value of the query.
*
* @param int $value
* @return $this
*/
public function offset($value)
{
$property = $this->unions ? 'unionOffset' : 'offset';
$this->$property = max(0, $value);
return $this;
}
/**
* Alias to set the "offset" value of the query.
*
* @param int $value
* @return \Illuminate\Database\Query\Builder|static
*/
public function skip($value)
{
return $this->offset($value);
}
/**
* Set the "limit" value of the query.
*
* @param int $value
* @return $this
*/
public function limit($value)
{
$property = $this->unions ? 'unionLimit' : 'limit';
if ($value >= 0) {
$this->$property = $value;
}
return $this;
}
/**
* Alias to set the "limit" value of the query.
*
* @param int $value
* @return \Illuminate\Database\Query\Builder|static
*/
public function take($value)
{
return $this->limit($value);
}
/**
* Set the limit and offset for a given page.
*
* @param int $page
* @param int $perPage
* @return \Illuminate\Database\Query\Builder|static
*/
public function forPage($page, $perPage = 15)
{
return $this->skip(($page - 1) * $perPage)->take($perPage);
}
/**
* Add a union statement to the query.
*
* @param \Illuminate\Database\Query\Builder|\Closure $query
* @param bool $all
* @return \Illuminate\Database\Query\Builder|static
*/
public function union($query, $all = false)
{
if ($query instanceof Closure) {
call_user_func($query, $query = $this->newQuery());
}
$this->unions[] = compact('query', 'all');
$this->addBinding($query->getBindings(), 'union');
return $this;
}
/**
* Add a union all statement to the query.
*
* @param \Illuminate\Database\Query\Builder|\Closure $query
* @return \Illuminate\Database\Query\Builder|static
*/
public function unionAll($query)
{
return $this->union($query, true);
}
/**
* Lock the selected rows in the table.
*
* @param bool $value
* @return $this
*/
public function lock($value = true)
{
$this->lock = $value;
if ($this->lock) {
$this->useWritePdo();
}
return $this;
}
/**
* Lock the selected rows in the table for updating.
*
* @return \Illuminate\Database\Query\Builder
*/
public function lockForUpdate()
{
return $this->lock(true);
}
/**
* Share lock the selected rows in the table.
*
* @return \Illuminate\Database\Query\Builder
*/
public function sharedLock()
{
return $this->lock(false);
}
/**
* Get the SQL representation of the query.
*
* @return string
*/
public function toSql()
{
return $this->grammar->compileSelect($this);
}
/**
* Execute a query for a single record by ID.
*
* @param int $id
* @param array $columns
* @return mixed|static
*/
public function find($id, $columns = ['*'])
{
return $this->where('id', '=', $id)->first($columns);
}
/**
* Get a single column's value from the first result of a query.
*
* @param string $column
* @return mixed
*/
public function value($column)
{
$result = (array) $this->first([$column]);
return count($result) > 0 ? reset($result) : null;
}
/**
* Execute the query and get the first result.
*
* @param array $columns
* @return mixed|static
*/
public function first($columns = ['*'])
{
$results = $this->take(1)->get($columns);
return count($results) > 0 ? reset($results) : null;
}
/**
* Execute the query as a "select" statement.
*
* @param array $columns
* @return array|static[]
*/
public function get($columns = ['*'])
{
$original = $this->columns;
if (is_null($original)) {
$this->columns = $columns;
}
$results = $this->processor->processSelect($this, $this->runSelect());
$this->columns = $original;
return $results;
}
/**
* Run the query as a "select" statement against the connection.
*
* @return array
*/
protected function runSelect()
{
return $this->connection->select($this->toSql(), $this->getBindings(), ! $this->useWritePdo);
}
/**
* Paginate the given query into a simple paginator.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
*/
public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$total = $this->getCountForPagination($columns);
$results = $this->forPage($page, $perPage)->get($columns);
return new LengthAwarePaginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Get a paginator only supporting simple next and previous links.
*
* This is more efficient on larger data-sets, etc.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @return \Illuminate\Contracts\Pagination\Paginator
*/
public function simplePaginate($perPage = 15, $columns = ['*'], $pageName = 'page')
{
$page = Paginator::resolveCurrentPage($pageName);
$this->skip(($page - 1) * $perPage)->take($perPage + 1);
return new Paginator($this->get($columns), $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Get the count of the total records for the paginator.
*
* @param array $columns
* @return int
*/
public function getCountForPagination($columns = ['*'])
{
$this->backupFieldsForCount();
$this->aggregate = ['function' => 'count', 'columns' => $this->clearSelectAliases($columns)];
$results = $this->get();
$this->aggregate = null;
$this->restoreFieldsForCount();
if (isset($this->groups)) {
return count($results);
}
return isset($results[0]) ? (int) array_change_key_case((array) $results[0])['aggregate'] : 0;
}
/**
* Backup some fields for the pagination count.
*
* @return void
*/
protected function backupFieldsForCount()
{
foreach (['orders', 'limit', 'offset', 'columns'] as $field) {
$this->backups[$field] = $this->{$field};
$this->{$field} = null;
}
foreach (['order', 'select'] as $key) {
$this->bindingBackups[$key] = $this->bindings[$key];
$this->bindings[$key] = [];
}
}
/**
* Remove the column aliases since they will break count queries.
*
* @param array $columns
* @return array
*/
protected function clearSelectAliases(array $columns)
{
return array_map(function ($column) {
return is_string($column) && ($aliasPosition = strpos(strtolower($column), ' as ')) !== false
? substr($column, 0, $aliasPosition) : $column;
}, $columns);
}
/**
* Restore some fields after the pagination count.
*
* @return void
*/
protected function restoreFieldsForCount()
{
foreach (['orders', 'limit', 'offset', 'columns'] as $field) {
$this->{$field} = $this->backups[$field];
}
foreach (['order', 'select'] as $key) {
$this->bindings[$key] = $this->bindingBackups[$key];
}
$this->backups = [];
$this->bindingBackups = [];
}
/**
* Chunk the results of the query.
*
* @param int $count
* @param callable $callback
* @return bool
*/
public function chunk($count, callable $callback)
{
$results = $this->forPage($page = 1, $count)->get();
while (count($results) > 0) {
// On each chunk result set, we will pass them to the callback and then let the
// developer take care of everything within the callback, which allows us to
// keep the memory low for spinning through large result sets for working.
if (call_user_func($callback, $results) === false) {
return false;
}
$page++;
$results = $this->forPage($page, $count)->get();
}
return true;
}
/**
* Get an array with the values of a given column.
*
* @param string $column
* @param string|null $key
* @return array
*/
public function pluck($column, $key = null)
{
$results = $this->get(is_null($key) ? [$column] : [$column, $key]);
// If the columns are qualified with a table or have an alias, we cannot use
// those directly in the "pluck" operations since the results from the DB
// are only keyed by the column itself. We'll strip the table out here.
return Arr::pluck(
$results,
$this->stripeTableForPluck($column),
$this->stripeTableForPluck($key)
);
}
/**
* Strip off the table name or alias from a column identifier.
*
* @param string $column
* @return string|null
*/
protected function stripeTableForPluck($column)
{
return is_null($column) ? $column : last(preg_split('~\.| ~', $column));
}
/**
* Concatenate values of a given column as a string.
*
* @param string $column
* @param string $glue
* @return string
*/
public function implode($column, $glue = '')
{
return implode($glue, $this->pluck($column));
}
/**
* Determine if any rows exist for the current query.
*
* @return bool
*/
public function exists()
{
$sql = $this->grammar->compileExists($this);
$results = $this->connection->select($sql, $this->getBindings(), ! $this->useWritePdo);
if (isset($results[0])) {
$results = (array) $results[0];
return (bool) $results['exists'];
}
return false;
}
/**
* Retrieve the "count" result of the query.
*
* @param string $columns
* @return int
*/
public function count($columns = '*')
{
if (! is_array($columns)) {
$columns = [$columns];
}
return (int) $this->aggregate(__FUNCTION__, $columns);
}
/**
* Retrieve the minimum value of a given column.
*
* @param string $column
* @return float|int
*/
public function min($column)
{
return $this->aggregate(__FUNCTION__, [$column]);
}
/**
* Retrieve the maximum value of a given column.
*
* @param string $column
* @return float|int
*/
public function max($column)
{
return $this->aggregate(__FUNCTION__, [$column]);
}
/**
* Retrieve the sum of the values of a given column.
*
* @param string $column
* @return float|int
*/
public function sum($column)
{
$result = $this->aggregate(__FUNCTION__, [$column]);
return $result ?: 0;
}
/**
* Retrieve the average of the values of a given column.
*
* @param string $column
* @return float|int
*/
public function avg($column)
{
return $this->aggregate(__FUNCTION__, [$column]);
}
/**
* Alias for the "avg" method.
*
* @param string $column
* @return float|int
*/
public function average($column)
{
return $this->avg($column);
}
/**
* Execute an aggregate function on the database.
*
* @param string $function
* @param array $columns
* @return float|int
*/
public function aggregate($function, $columns = ['*'])
{
$this->aggregate = compact('function', 'columns');
$previousColumns = $this->columns;
// We will also back up the select bindings since the select clause will be
// removed when performing the aggregate function. Once the query is run
// we will add the bindings back onto this query so they can get used.
$previousSelectBindings = $this->bindings['select'];
$this->bindings['select'] = [];
$results = $this->get($columns);
// Once we have executed the query, we will reset the aggregate property so
// that more select queries can be executed against the database without
// the aggregate value getting in the way when the grammar builds it.
$this->aggregate = null;
$this->columns = $previousColumns;
$this->bindings['select'] = $previousSelectBindings;
if (isset($results[0])) {
$result = array_change_key_case((array) $results[0]);
return $result['aggregate'];
}
}
/**
* Insert a new record into the database.
*
* @param array $values
* @return bool
*/
public function insert(array $values)
{
if (empty($values)) {
return true;
}
// Since every insert gets treated like a batch insert, we will make sure the
// bindings are structured in a way that is convenient for building these
// inserts statements by verifying the elements are actually an array.
if (! is_array(reset($values))) {
$values = [$values];
}
// Since every insert gets treated like a batch insert, we will make sure the
// bindings are structured in a way that is convenient for building these
// inserts statements by verifying the elements are actually an array.
else {
foreach ($values as $key => $value) {
ksort($value);
$values[$key] = $value;
}
}
// We'll treat every insert like a batch insert so we can easily insert each
// of the records into the database consistently. This will make it much
// easier on the grammars to just handle one type of record insertion.
$bindings = [];
foreach ($values as $record) {
foreach ($record as $value) {
$bindings[] = $value;
}
}
$sql = $this->grammar->compileInsert($this, $values);
// Once we have compiled the insert statement's SQL we can execute it on the
// connection and return a result as a boolean success indicator as that
// is the same type of result returned by the raw connection instance.
$bindings = $this->cleanBindings($bindings);
return $this->connection->insert($sql, $bindings);
}
/**
* Insert a new record and get the value of the primary key.
*
* @param array $values
* @param string $sequence
* @return int
*/
public function insertGetId(array $values, $sequence = null)
{
$sql = $this->grammar->compileInsertGetId($this, $values, $sequence);
$values = $this->cleanBindings($values);
return $this->processor->processInsertGetId($this, $sql, $values, $sequence);
}
/**
* Update a record in the database.
*
* @param array $values
* @return int
*/
public function update(array $values)
{
$bindings = array_values(array_merge($values, $this->getBindings()));
$sql = $this->grammar->compileUpdate($this, $values);
return $this->connection->update($sql, $this->cleanBindings($bindings));
}
/**
* Increment a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function increment($column, $amount = 1, array $extra = [])
{
$wrapped = $this->grammar->wrap($column);
$columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);
return $this->update($columns);
}
/**
* Decrement a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function decrement($column, $amount = 1, array $extra = [])
{
$wrapped = $this->grammar->wrap($column);
$columns = array_merge([$column => $this->raw("$wrapped - $amount")], $extra);
return $this->update($columns);
}
/**
* Delete a record from the database.
*
* @param mixed $id
* @return int
*/
public function delete($id = null)
{
// If an ID is passed to the method, we will set the where clause to check
// the ID to allow developers to simply and quickly remove a single row
// from their database without manually specifying the where clauses.
if (! is_null($id)) {
$this->where('id', '=', $id);
}
$sql = $this->grammar->compileDelete($this);
return $this->connection->delete($sql, $this->getBindings());
}
/**
* Run a truncate statement on the table.
*
* @return void
*/
public function truncate()
{
foreach ($this->grammar->compileTruncate($this) as $sql => $bindings) {
$this->connection->statement($sql, $bindings);
}
}
/**
* Get a new instance of the query builder.
*
* @return \Illuminate\Database\Query\Builder
*/
public function newQuery()
{
return new static($this->connection, $this->grammar, $this->processor);
}
/**
* Merge an array of where clauses and bindings.
*
* @param array $wheres
* @param array $bindings
* @return void
*/
public function mergeWheres($wheres, $bindings)
{
$this->wheres = array_merge((array) $this->wheres, (array) $wheres);
$this->bindings['where'] = array_values(array_merge($this->bindings['where'], (array) $bindings));
}
/**
* Remove all of the expressions from a list of bindings.
*
* @param array $bindings
* @return array
*/
protected function cleanBindings(array $bindings)
{
return array_values(array_filter($bindings, function ($binding) {
return ! $binding instanceof Expression;
}));
}
/**
* Create a raw database expression.
*
* @param mixed $value
* @return \Illuminate\Database\Query\Expression
*/
public function raw($value)
{
return $this->connection->raw($value);
}
/**
* Get the current query value bindings in a flattened array.
*
* @return array
*/
public function getBindings()
{
return Arr::flatten($this->bindings);
}
/**
* Get the raw array of bindings.
*
* @return array
*/
public function getRawBindings()
{
return $this->bindings;
}
/**
* Set the bindings on the query builder.
*
* @param array $bindings
* @param string $type
* @return $this
*
* @throws \InvalidArgumentException
*/
public function setBindings(array $bindings, $type = 'where')
{
if (! array_key_exists($type, $this->bindings)) {
throw new InvalidArgumentException("Invalid binding type: {$type}.");
}
$this->bindings[$type] = $bindings;
return $this;
}
/**
* Add a binding to the query.
*
* @param mixed $value
* @param string $type
* @return $this
*
* @throws \InvalidArgumentException
*/
public function addBinding($value, $type = 'where')
{
if (! array_key_exists($type, $this->bindings)) {
throw new InvalidArgumentException("Invalid binding type: {$type}.");
}
if (is_array($value)) {
$this->bindings[$type] = array_values(array_merge($this->bindings[$type], $value));
} else {
$this->bindings[$type][] = $value;
}
return $this;
}
/**
* Merge an array of bindings into our bindings.
*
* @param \Illuminate\Database\Query\Builder $query
* @return $this
*/
public function mergeBindings(Builder $query)
{
$this->bindings = array_merge_recursive($this->bindings, $query->bindings);
return $this;
}
/**
* Get the database connection instance.
*
* @return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get the database query processor instance.
*
* @return \Illuminate\Database\Query\Processors\Processor
*/
public function getProcessor()
{
return $this->processor;
}
/**
* Get the query grammar instance.
*
* @return \Illuminate\Database\Query\Grammars\Grammar
*/
public function getGrammar()
{
return $this->grammar;
}
/**
* Use the write pdo for query.
*
* @return $this
*/
public function useWritePdo()
{
$this->useWritePdo = true;
return $this;
}
/**
* Handle dynamic method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if (Str::startsWith($method, 'where')) {
return $this->dynamicWhere($method, $parameters);
}
$className = get_class($this);
throw new BadMethodCallException("Call to undefined method {$className}::{$method}()");
}
}
| DougSisk/framework | src/Illuminate/Database/Query/Builder.php | PHP | mit | 54,802 |
const autoAdjustOverflow = {
adjustX: 1,
adjustY: 1
}
const targetOffset = [0, 0]
export const placements = {
left: {
points: ['cr', 'cl'],
overflow: autoAdjustOverflow,
offset: [-3, 0],
targetOffset
},
right: {
points: ['cl', 'cr'],
overflow: autoAdjustOverflow,
offset: [3, 0],
targetOffset
},
top: {
points: ['bc', 'tc'],
overflow: autoAdjustOverflow,
offset: [0, -3],
targetOffset
},
bottom: {
points: ['tc', 'bc'],
overflow: autoAdjustOverflow,
offset: [0, 3],
targetOffset
},
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow,
offset: [0, -3],
targetOffset
},
leftTop: {
points: ['tr', 'tl'],
overflow: autoAdjustOverflow,
offset: [-3, 0],
targetOffset
},
topRight: {
points: ['br', 'tr'],
overflow: autoAdjustOverflow,
offset: [0, -3],
targetOffset
},
rightTop: {
points: ['tl', 'tr'],
overflow: autoAdjustOverflow,
offset: [3, 0],
targetOffset
},
bottomRight: {
points: ['tr', 'br'],
overflow: autoAdjustOverflow,
offset: [0, 3],
targetOffset
},
rightBottom: {
points: ['bl', 'br'],
overflow: autoAdjustOverflow,
offset: [3, 0],
targetOffset
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow,
offset: [0, 3],
targetOffset
},
leftBottom: {
points: ['br', 'bl'],
overflow: autoAdjustOverflow,
offset: [-3, 0],
targetOffset
}
}
export default placements
| okoala/vue-antd | components/base/tooltip/placements.js | JavaScript | mit | 1,536 |
<?php
namespace AdminBundle\Form;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CommentType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('author')
->add('content')
//->add('createAt')
->add('score')
/*->add('product', EntityType::class, [
'class' => 'AdminBundle\Entity\Product',
'choice_label' => 'title',
// pour avoir un champ vide au départ :
//'placeholder' => '',
'expanded' => true,
'multiple' => true
])*/
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AdminBundle\Entity\Comment'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'adminbundle_comment';
}
}
| jpitard/my_first_symfony | src/AdminBundle/Form/CommentType.php | PHP | mit | 1,270 |
#include "Common.h"
#include "Core.h"
#include "Event.h"
#include "Message.h"
#include "ProfilerServer.h"
#include "EventDescriptionBoard.h"
namespace Brofiler
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct MessageHeader
{
uint32 mark;
uint32 length;
static const uint32 MESSAGE_MARK = 0xB50FB50F;
bool IsValid() const { return mark == MESSAGE_MARK; }
MessageHeader() : mark(0), length(0) {}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class MessageFactory
{
typedef IMessage* (*MessageCreateFunction)(InputDataStream& str);
MessageCreateFunction factory[IMessage::COUNT];
template<class T>
void RegisterMessage()
{
factory[T::GetMessageType()] = T::Create;
}
MessageFactory()
{
memset(&factory[0], 0, sizeof(MessageCreateFunction));
RegisterMessage<StartMessage>();
RegisterMessage<StopMessage>();
RegisterMessage<TurnSamplingMessage>();
for (uint32 msg = 0; msg < IMessage::COUNT; ++msg)
{
BRO_ASSERT(factory[msg] != nullptr, "Message is not registered to factory");
}
}
public:
static MessageFactory& Get()
{
static MessageFactory instance;
return instance;
}
IMessage* Create(InputDataStream& str)
{
MessageHeader header;
str.Read(header);
size_t length = str.Length();
int32 messageType = IMessage::COUNT;
str >> messageType;
BRO_VERIFY(0 <= messageType && messageType < IMessage::COUNT && factory[messageType] != nullptr, "Unknown message type!", return nullptr)
IMessage* result = factory[messageType](str);
if (header.length + str.Length() != length)
{
BRO_FAILED("Message Stream is corrupted! Invalid Protocol?")
return nullptr;
}
return result;
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OutputDataStream& operator<<(OutputDataStream& os, const DataResponse& val)
{
return os << val.version << (uint32)val.type;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IMessage* IMessage::Create(InputDataStream& str)
{
MessageHeader header;
while (str.Peek(header))
{
if (header.IsValid())
{
if (str.Length() < header.length + sizeof(MessageHeader))
break; // Not enough data yet
return MessageFactory::Get().Create(str);
}
else
{
// Some garbage in the stream?
str.Skip(1);
}
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void StartMessage::Apply()
{
Core::Get().Activate(true);
if (EventDescriptionBoard::Get().HasSamplingEvents())
{
Core::Get().StartSampling();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IMessage* StartMessage::Create(InputDataStream&)
{
return new StartMessage();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void StopMessage::Apply()
{
Core& core = Core::Get();
core.Activate(false);
core.DumpFrames();
core.DumpSamplingData();
Server::Get().Send(DataResponse::NullFrame, OutputDataStream::Empty);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IMessage* StopMessage::Create(InputDataStream&)
{
return new StopMessage();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IMessage* TurnSamplingMessage::Create(InputDataStream& stream)
{
TurnSamplingMessage* msg = new TurnSamplingMessage();
stream >> msg->index;
stream >> msg->isSampling;
return msg;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TurnSamplingMessage::Apply()
{
EventDescriptionBoard::Get().SetSamplingFlag(index, isSampling != 0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | galek/brofiler | BrofilerCore/Message.cpp | C++ | mit | 4,559 |
'use strict';
function removeIndex(key, id, callback) {
var client = this._;
client.del(key + ':' + id + '@index', callback);
}
module.exports = removeIndex;
| meimisaki/pupa.moe | lib/db/node_modules/removeIndex.js | JavaScript | mit | 162 |
# __init__.py: Yet Another Bayes Net library
# Contact: Jacob Schreiber ( jmschreiber91@gmail.com )
"""
For detailed documentation and examples, see the README.
"""
# Make our dependencies explicit so compiled Cython code won't segfault trying
# to load them.
import networkx, matplotlib.pyplot, scipy
import numpy as np
import os
import pyximport
# Adapted from Cython docs https://github.com/cython/cython/wiki/
# InstallingOnWindows#mingw--numpy--pyximport-at-runtime
if os.name == 'nt':
if 'CPATH' in os.environ:
os.environ['CPATH'] = os.environ['CPATH'] + np.get_include()
else:
os.environ['CPATH'] = np.get_include()
# XXX: we're assuming that MinGW is installed in C:\MinGW (default)
if 'PATH' in os.environ:
os.environ['PATH'] = os.environ['PATH'] + ';C:\MinGW\bin'
else:
os.environ['PATH'] = 'C:\MinGW\bin'
mingw_setup_args = { 'options': { 'build_ext': { 'compiler': 'mingw32' } } }
pyximport.install(setup_args=mingw_setup_args)
elif os.name == 'posix':
if 'CFLAGS' in os.environ:
os.environ['CFLAGS'] = os.environ['CFLAGS'] + ' -I' + np.get_include()
else:
os.environ['CFLAGS'] = ' -I' + np.get_include()
pyximport.install()
from yabn import *
__version__ = '0.1.0' | jmschrei/yabn | yabn/__init__.py | Python | mit | 1,279 |
package ooo.purity.unwatermark.gui;
import ooo.purity.unwatermark.Mode;
import ooo.purity.unwatermark.ModeFactory;
import ooo.purity.unwatermark.mode.MFSA;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
class ViewFrame extends JFrame {
private static final long serialVersionUID = -908237280313491890L;
private final JFileChooser openChooser = new JFileChooser();
private final JFileChooser saveChooser = new JFileChooser();
private final ImagePanel imagePanel = new ImagePanel();
private final JScrollPane scrollPane = new JScrollPane(imagePanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
private final DefaultListModel<Document> listModel = new DefaultListModel<>();
final JList<Document> list = new JList<>(listModel);
private class Document {
private final File file;
private BufferedImage image;
private Mode mode = ModeFactory.create(MFSA.NAME);
private Document(final File file) throws IOException {
this.file = file;
image = mode.apply(file);
}
private void show() {
imagePanel.setName(file.getName());
imagePanel.setImage(image);
imagePanel.setBounds(0, 0,
scrollPane.getWidth() - scrollPane.getVerticalScrollBar().getWidth(),
scrollPane.getHeight() - scrollPane.getHorizontalScrollBar().getHeight());
imagePanel.setVisible(true);
imagePanel.repaint();
}
@Override
public String toString() {
return file.getName();
}
}
private class ViewTransferHandler extends TransferHandler {
private static final long serialVersionUID = 2695692501459052660L;
@Override
public boolean canImport(final TransferSupport support) {
if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
final boolean copySupported = (COPY & support.getSourceDropActions()) == COPY;
if (!copySupported) {
return false;
}
support.setDropAction(COPY);
return true;
}
@Override
@SuppressWarnings({"unchecked", "serial"})
public boolean importData(final TransferSupport support) {
if (!canImport(support)) {
return false;
}
final Transferable transferable = support.getTransferable();
try {
final java.util.List<File> fileList =
(java.util.List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
return unwatermark(fileList.toArray(new File[fileList.size()]));
} catch (final UnsupportedFlavorException | IOException e) {
return false;
}
}
}
ViewFrame() {
super("Unwatermark");
final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, list, scrollPane);
splitPane.setDividerLocation(120);
getContentPane().add(splitPane);
list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(e -> {
if (e.getValueIsAdjusting()) {
return;
}
final Document document = list.getSelectedValue();
if (document != null) {
document.show();
}
});
final TransferHandler transferHandler = new ViewTransferHandler();
setTransferHandler(transferHandler);
setBackground(Color.LIGHT_GRAY);
imagePanel.setTransferHandler(transferHandler);
imagePanel.setLayout(new BorderLayout());
imagePanel.setBackground(Color.LIGHT_GRAY);
scrollPane.setBackground(Color.LIGHT_GRAY);
scrollPane.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
imagePanel.setBounds(0, 0,
scrollPane.getWidth() - scrollPane.getVerticalScrollBar().getWidth(),
scrollPane.getHeight() - scrollPane.getHorizontalScrollBar().getHeight());
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
pack();
initialiseMenuBar();
openChooser.setMultiSelectionEnabled(true);
openChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
saveChooser.setMultiSelectionEnabled(false);
}
private void initialiseMenuBar() {
final JMenuBar menuBar = new JMenuBar();
JMenu menu;
menu = new JMenu("File");
menu.add(new JMenuItem("Open...")).addActionListener(e -> {
if (openChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
unwatermark(openChooser.getSelectedFiles());
}
});
menu.add(new JMenuItem("Save...")).addActionListener(e -> {
Document document = list.getSelectedValue();
if (null == document && listModel.size() > 0) {
document = listModel.getElementAt(0);
}
if (null == document) {
return;
}
saveChooser.setSelectedFile(document.file);
if (saveChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
unwatermark(document, saveChooser.getSelectedFile());
}
});
menu.add(new JMenuItem("Print")).addActionListener(e -> {
Document document = list.getSelectedValue();
if (null == document && listModel.size() > 0) {
document = listModel.getElementAt(0);
}
if (null == document) {
return;
}
try {
document.mode.print(document.file);
} catch (final IOException | PrinterException exc) {
displayException(exc);
}
});
menuBar.add(menu);
menu = new JMenu("Help");
menu.add(new JMenuItem("About")).addActionListener(e -> {
JOptionPane.showMessageDialog(imagePanel, "Unwatermark\nmattcg@gmail.com");
});
menuBar.add(menu);
setJMenuBar(menuBar);
}
private boolean unwatermark(final File... files) {
try {
Document document = null;
for (File file : files) {
document = new Document(file);
listModel.add(listModel.size(), document);
}
if (null != document) {
document.show();
}
} catch (final IOException e) {
displayException(e);
return false;
}
return true;
}
private void unwatermark(final Document input, final File output) {
try {
input.mode.apply(input.file, output);
} catch (final IOException e) {
displayException(e);
}
}
@SuppressWarnings("serial")
private void displayException(final Exception e) {
final JPanel panel = new JPanel();
final JPanel labelPanel = new JPanel(new BorderLayout());
final StringWriter writer = new StringWriter();
labelPanel.add(new JLabel("Unable to unwatermark."));
panel.add(labelPanel);
panel.add(Box.createVerticalStrut(10));
e.printStackTrace(new PrintWriter(writer));
panel.add(new JScrollPane(new JTextArea(writer.toString())){
@Override
public Dimension getPreferredSize() {
return new Dimension(480, 320);
}
});
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
JOptionPane.showMessageDialog(imagePanel, panel, "Error", JOptionPane.ERROR_MESSAGE);
}
}
| purityooo/unwatermark | src/main/java/ooo/purity/unwatermark/gui/ViewFrame.java | Java | mit | 7,117 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.21 at 09:18:55 AM CST
//
package ca.ieso.reports.schema.daareareserveconst;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.ieso.ca/schema}DocTitle"/>
* <element ref="{http://www.ieso.ca/schema}DocRevision"/>
* <element ref="{http://www.ieso.ca/schema}DocConfidentiality"/>
* <element ref="{http://www.ieso.ca/schema}CreatedAt"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"docTitle",
"docRevision",
"docConfidentiality",
"createdAt"
})
@XmlRootElement(name = "DocHeader")
public class DocHeader {
@XmlElement(name = "DocTitle", required = true)
protected String docTitle;
@XmlElement(name = "DocRevision", required = true)
protected BigInteger docRevision;
@XmlElement(name = "DocConfidentiality", required = true)
protected DocConfidentiality docConfidentiality;
@XmlElement(name = "CreatedAt", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar createdAt;
/**
* Gets the value of the docTitle property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDocTitle() {
return docTitle;
}
/**
* Sets the value of the docTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDocTitle(String value) {
this.docTitle = value;
}
/**
* Gets the value of the docRevision property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getDocRevision() {
return docRevision;
}
/**
* Sets the value of the docRevision property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setDocRevision(BigInteger value) {
this.docRevision = value;
}
/**
* Gets the value of the docConfidentiality property.
*
* @return
* possible object is
* {@link DocConfidentiality }
*
*/
public DocConfidentiality getDocConfidentiality() {
return docConfidentiality;
}
/**
* Sets the value of the docConfidentiality property.
*
* @param value
* allowed object is
* {@link DocConfidentiality }
*
*/
public void setDocConfidentiality(DocConfidentiality value) {
this.docConfidentiality = value;
}
/**
* Gets the value of the createdAt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getCreatedAt() {
return createdAt;
}
/**
* Sets the value of the createdAt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCreatedAt(XMLGregorianCalendar value) {
this.createdAt = value;
}
}
| r24mille/IesoPublicReportBindings | src/main/java/ca/ieso/reports/schema/daareareserveconst/DocHeader.java | Java | mit | 4,315 |
<?php
/**
* This file is part of FunctionInjector project.
* You are using it at your own risk and you are fully responsible for everything that code will do.
*
* Copyright (c) 2016 Grzegorz Zdanowski <grzegorz@noflash.pl>
*
* For the full copyright and license information, please view the LICENSE file distributed with this source code.
*/
namespace noFlash\FunctionsManipulator\Exception;
use Exception;
use noFlash\FunctionsManipulator\NameValidator;
class InvalidFunctionNameException extends \InvalidArgumentException
{
public function __construct($functionName, $reasonCode, Exception $previous = null)
{
$message = sprintf(
'Function name "%s" is invalid - %s.',
$functionName,
NameValidator::getErrorFromCode($reasonCode)
);
parent::__construct($message, 0, $previous);
}
}
| kiler129/FunctionInjector | src/Exception/InvalidFunctionNameException.php | PHP | mit | 866 |
using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("Colorful/Fast Vignette")]
public class CC_FastVignette : CC_Base
{
public Vector2 center = new Vector2(0.5f, 0.5f);
[Range(-100f, 100f)]
public float sharpness = 10f;
[Range(0f, 100f)]
public float darkness = 30f;
public bool desaturate = false;
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
material.SetVector("_Data", new Vector4(center.x, center.y, sharpness * 0.01f, darkness * 0.02f));
Graphics.Blit(source, destination, material, desaturate ? 1 : 0);
}
}
| esther5576/GEO | CODE/Assets/Plugins/Colorful/Components/CC_FastVignette.cs | C# | mit | 561 |
/* FTUI Plugin
* Copyright (c) 2016 Mario Stephan <mstephan@shared-files.de>
* Under MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/* global ftui:true, Modul_widget:true */
"use strict";
var Modul_medialist = function () {
$('head').append('<link rel="stylesheet" href="' + ftui.config.dir + '/../css/ftui_medialist.css" type="text/css" />');
function changedCurrent(elem, pos) {
elem.find('.media').each(function (index) {
$(this).removeClass('current');
});
var idx = elem.hasClass('index1') ? pos - 1 : pos;
var currentElem = elem.find('.media').eq(idx);
if (currentElem.length > 0) {
currentElem.addClass("current");
if (elem.hasClass("autoscroll")) {
elem.scrollTop(currentElem.offset().top - elem.offset().top + elem.scrollTop());
}
}
}
function init_attr(elem) {
elem.initData('get', 'STATE');
elem.initData('set', 'play');
elem.initData('pos', 'Pos');
elem.initData('cmd', 'set');
elem.initData('color', ftui.getClassColor(elem) || ftui.getStyle('.' + me.widgetname, 'color') || '#222');
elem.initData('background-color', ftui.getStyle('.' + me.widgetname, 'background-color') || 'transparent');
elem.initData('text-color', ftui.getStyle('.' + me.widgetname, 'text-color') || '#ddd');
elem.initData('width', '90%');
elem.initData('height', '80%');
me.addReading(elem, 'get');
me.addReading(elem, 'pos');
}
function init_ui(elem) {
// prepare container element
var width = elem.data('width');
var widthUnit = ($.isNumeric(width)) ? 'px' : '';
var height = elem.data('height');
var heightUnit = ($.isNumeric(height)) ? 'px' : '';
elem.html('')
.addClass('media-list')
.css({
width: width + widthUnit,
maxWidth: width + widthUnit,
height: height + heightUnit,
color: elem.mappedColor('text-color'),
backgroundColor: elem.mappedColor('background-color'),
});
elem.on('click', '.media', function (index) {
elem.data('value', elem.hasClass('index1') ? $(this).index() + 1 : $(this).index());
elem.transmitCommand();
});
}
function update(dev, par) {
// update medialist reading
me.elements.filterDeviceReading('get', dev, par)
.each(function (index) {
var elem = $(this);
var list = elem.getReading('get').val;
var pos = elem.getReading('pos').val;
if (ftui.isValid(list)) {
elem.html('');
var text = '';
try {
var collection = JSON.parse(list);
for (var idx in collection) {
var media = collection[idx];
text += '<div class="media">';
text += '<div class="media-image">';
text += '<img class="cover" src="' + media.Cover + '"/>';
text += '</div>';
text += '<div class="media-text">';
text += '<div class="title" data-track="' + media.Track + '">' + media.Title + '</div>';
text += '<div class="artist">' + media.Artist + '</div>';
text += '<div class="duration">' + ftui.durationFromSeconds(media.Time) + '</div>';
text += '</div></div>';
}
} catch (e) {
ftui.log(1, 'widget-' + me.widgetname + ': error:' + e);
ftui.log(1, list);
ftui.toast('<b>widget-' + me.widgetname + '</b><br>' + e, 'error');
}
elem.append(text).fadeIn();
}
if (pos) {
changedCurrent(elem, pos);
}
});
//extra reading for current position
me.elements.filterDeviceReading('pos', dev, par)
.each(function (idx) {
var elem = $(this);
var pos = elem.getReading('pos').val;
if (ftui.isValid(pos)){
changedCurrent(elem, pos);
}
});
}
// public
// inherit members from base class
var me = $.extend(new Modul_widget(), {
//override members
widgetname: 'medialist',
init_attr: init_attr,
init_ui: init_ui,
update: update,
});
return me;
}; | viegener/fhem-tablet-ui | www/tablet/js/widget_medialist.js | JavaScript | mit | 4,805 |
<?php
declare(strict_types=1);
/*
* This file is part of the RollerworksSearch package.
*
* (c) Sebastiaan Stok <s.stok@rollerscapes.net>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Rollerworks\Component\Search\Extension\Symfony\Validator\Tests;
use Rollerworks\Component\Search\ConditionErrorMessage;
use Rollerworks\Component\Search\ErrorList;
use Rollerworks\Component\Search\Extension\Core\Type\DateType;
use Rollerworks\Component\Search\Extension\Core\Type\IntegerType;
use Rollerworks\Component\Search\Extension\Core\Type\TextType;
use Rollerworks\Component\Search\Extension\Symfony\Validator\InputValidator;
use Rollerworks\Component\Search\Extension\Symfony\Validator\ValidatorExtension;
use Rollerworks\Component\Search\Test\SearchIntegrationTestCase;
use Rollerworks\Component\Search\Value\PatternMatch;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validation;
/**
* @internal
*/
final class InputValidatorTest extends SearchIntegrationTestCase
{
private $sfValidator;
/**
* @var InputValidator
*/
private $validator;
protected function setUp(): void
{
parent::setUp();
$validatorBuilder = Validation::createValidatorBuilder();
$validatorBuilder->disableAnnotationMapping();
$this->sfValidator = $validatorBuilder->getValidator();
$this->validator = new InputValidator($this->sfValidator);
}
protected function getFieldSet(bool $build = true)
{
$fieldSet = $this->getFactory()->createFieldSetBuilder();
$fieldSet->add('id', IntegerType::class, ['constraints' => new Assert\Range(['min' => 5])]);
$fieldSet->add('date', DateType::class, [
'constraints' => [
new Assert\Range(
['min' => new \DateTimeImmutable('2014-12-20 14:35:05 UTC')]
),
],
]);
$fieldSet->add('type', TextType::class);
return $build ? $fieldSet->getFieldSet() : $fieldSet;
}
protected function getExtensions(): array
{
return [new ValidatorExtension()];
}
/** @test */
public function it_validates_fields_with_constraints(): void
{
$fieldSet = $this->getFieldSet();
$errorList = new ErrorList();
$this->validator->initializeContext($fieldSet->get('id'), $errorList);
$this->validator->validate(10, 'simple', 10, 'simpleValues[0]');
$this->validator->validate(3, 'simple', 3, 'simpleValues[1]');
$this->validator->validate(4, 'simple', 4, 'simpleValues[2]');
$errorList2 = new ErrorList();
$this->validator->initializeContext($fieldSet->get('date'), $errorList2);
$this->validator->validate($d1 = new \DateTimeImmutable('2014-12-13 14:35:05 UTC'), 'simple', '2014-12-13 14:35:05', 'simpleValues[0]');
$this->validator->validate($d2 = new \DateTimeImmutable('2014-12-21 14:35:05 UTC'), 'simple', '2014-12-17 14:35:05', 'simpleValues[1]');
$this->validator->validate($d3 = new \DateTimeImmutable('2014-12-10 14:35:05 UTC'), 'simple', '2014-12-10 14:35:05', 'simpleValues[2]');
$errorList3 = new ErrorList();
$this->validator->initializeContext($fieldSet->get('type'), $errorList3);
$this->validator->validate('something', 'simple', 'something', 'simpleValues[0]');
$this->assertContainsErrors(
[
new ConditionErrorMessage('simpleValues[1]', 'This value should be 5 or more.', 'This value should be {{ limit }} or more.', ['{{ value }}' => '3', '{{ limit }}' => '5']),
new ConditionErrorMessage('simpleValues[2]', 'This value should be 5 or more.', 'This value should be {{ limit }} or more.', ['{{ value }}' => '4', '{{ limit }}' => '5']),
],
$errorList
);
$minDate = self::formatDateTime(new \DateTimeImmutable('2014-12-20 14:35:05 UTC'));
$this->assertContainsErrors(
[
new ConditionErrorMessage('simpleValues[0]', 'This value should be ' . $minDate . ' or more.', 'This value should be {{ limit }} or more.', ['{{ value }}' => self::formatDateTime($d1), '{{ limit }}' => $minDate]),
new ConditionErrorMessage('simpleValues[2]', 'This value should be ' . $minDate . ' or more.', 'This value should be {{ limit }} or more.', ['{{ value }}' => self::formatDateTime($d3), '{{ limit }}' => $minDate]),
],
$errorList2
);
self::assertEmpty($errorList3);
}
/** @test */
public function it_validates_matchers(): void
{
$fieldSet = $this->getFieldSet(false);
$fieldSet->add('username', TextType::class, ['constraints' => new Assert\NotBlank()]);
$fieldSet = $fieldSet->getFieldSet();
$errorList = new ErrorList();
$this->validator->initializeContext($fieldSet->get('username'), $errorList);
$this->validator->validate('foo', PatternMatch::class, 'foo', 'patternMatch[0].value');
$this->validator->validate('bar', PatternMatch::class, 'foo', 'patternMatch[1].value');
$this->validator->validate('', PatternMatch::class, 'foo', 'patternMatch[2].value');
$this->assertContainsErrors(
[
new ConditionErrorMessage('patternMatch[2].value', 'This value should not be blank.', 'This value should not be blank.', ['{{ value }}' => '""']),
],
$errorList
);
}
private function assertContainsErrors(array $expectedErrors, ErrorList $errors): void
{
foreach ($errors as $error) {
self::assertInstanceOf(ConstraintViolation::class, $error->cause);
// Remove cause to make assertion possible.
$error->cause = null;
}
self::assertEquals($expectedErrors, $errors->getArrayCopy());
}
/**
* @param \DateTimeImmutable $value
*
* @return string
*/
private static function formatDateTime($value)
{
if (\class_exists('IntlDateFormatter')) {
$locale = \Locale::getDefault();
$formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);
// neither the native nor the stub IntlDateFormatter support
// DateTimeImmutable as of yet
if (! $value instanceof \DateTime) {
$value = new \DateTime(
$value->format('Y-m-d H:i:s.u e'),
$value->getTimezone()
);
}
return $formatter->format($value);
}
return $value->format('Y-m-d H:i:s');
}
}
| rollerworks/search | lib/Symfony/Validator/Tests/InputValidatorTest.php | PHP | mit | 6,811 |
version https://git-lfs.github.com/spec/v1
oid sha256:2d79d4ce9f72e0b9db16aee949410ecd30bfcfb5205af39053f05ac39083e151
size 22425
| yogeshsaroya/new-cdnjs | ajax/libs/fancybox/2.1.4/jquery.fancybox.pack.min.js | JavaScript | mit | 130 |
//******************************************************************************************************
// CollectionEventArgs.cs - Gbtc
//
// Copyright © 2014, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 8/18/2012 - Steven E. Chisholm
// Generated original version of source code.
//
//
//******************************************************************************************************
using System;
namespace GSF.IO.Unmanaged
{
/// <summary>
/// Speifies how critical the collection of memory blocks is.
/// </summary>
public enum MemoryPoolCollectionMode
{
/// <summary>
/// This means no collection has to occur.
/// </summary>
None,
/// <summary>
/// This is the routine mode
/// </summary>
Normal,
/// <summary>
/// This means the engine is using more memory than desired
/// </summary>
Emergency,
/// <summary>
/// This means any memory that can be released should be released.
/// If no memory is released after this pass,
/// an out of memory exception will occur.
/// </summary>
Critical
}
/// <summary>
/// This contains information about the collection that is requested from the system.
/// </summary>
public class CollectionEventArgs : EventArgs
{
private readonly Action<int> m_releasePage;
/// <summary>
/// When <see cref="CollectionMode"/> is <see cref="MemoryPoolCollectionMode.Emergency"/> or
/// <see cref="MemoryPoolCollectionMode.Critical"/> this field contains the number of pages
/// that need to be released by all of the objects. This value will automatically decrement
/// every time a page has been released.
/// </summary>
public int DesiredPageReleaseCount
{
get;
private set;
}
/// <summary>
/// The mode for the collection
/// </summary>
public MemoryPoolCollectionMode CollectionMode
{
get;
private set;
}
/// <summary>
/// Creates a new <see cref="CollectionEventArgs"/>.
/// </summary>
/// <param name="releasePage"></param>
/// <param name="collectionMode"></param>
/// <param name="desiredPageReleaseCount"></param>
public CollectionEventArgs(Action<int> releasePage, MemoryPoolCollectionMode collectionMode, int desiredPageReleaseCount)
{
DesiredPageReleaseCount = desiredPageReleaseCount;
m_releasePage = releasePage;
CollectionMode = collectionMode;
}
/// <summary>
/// Releases an unused page.
/// </summary>
/// <param name="index">the index of the page</param>
public void ReleasePage(int index)
{
m_releasePage(index);
DesiredPageReleaseCount--;
}
}
} | GridProtectionAlliance/openHistorian | Source/Libraries/GSF.SortedTreeStore/IO/Unmanaged/CollectionEventArgs.cs | C# | mit | 3,877 |
/**
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.ast;
/**
* <h1>12 ECMAScript Language: Expressions</h1><br>
* <h2>12.1 Primary Expressions</h2><br>
* <h3>12.1.4 Array Initialiser</h3>
* <ul>
* <li>12.1.4.2 Array Comprehension
* </ul>
*/
public final class ComprehensionFor extends ComprehensionQualifier implements ScopedNode {
private BlockScope scope;
private Binding binding;
private Expression expression;
public ComprehensionFor(long beginPosition, long endPosition, BlockScope scope,
Binding binding, Expression expression) {
super(beginPosition, endPosition);
this.scope = scope;
this.binding = binding;
this.expression = expression;
}
@Override
public BlockScope getScope() {
return scope;
}
public Binding getBinding() {
return binding;
}
public Expression getExpression() {
return expression;
}
@Override
public <R, V> R accept(NodeVisitor<R, V> visitor, V value) {
return visitor.visit(this, value);
}
}
| rwaldron/es6draft | src/main/java/com/github/anba/es6draft/ast/ComprehensionFor.java | Java | mit | 1,224 |
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
requirejs: {
compile: {
options: {
shim: {
grape: {
exports: 'Grape'
}
},
paths:{
grape:'../../../../dist/grape.min'
},
baseUrl: "js",
name: "../node_modules/almond/almond",
include: ["pong"],
out: "build/pong.min.js",
optimize: 'uglify2',
logLevel: 3,
uglify2: {
output: {
beautify: true
},
compress: {
sequences: false
},
warnings: true,
mangle: false
}
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('default', ['requirejs']);
}; | zoltan-mihalyi/grape | examples/pong/required/Gruntfile.js | JavaScript | mit | 1,228 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using kinectApp.Utilities;
namespace kinectApp.Entities
{
public interface IScene
{
List<IEntity> Entities { get; }
string Name { get; }
void HandleKeys(InputHelper aInputHelper, ISceneManager aSceneManager);
}
/*
Defines a list of entities for the Entity Manager to load in when required.
Would define parts of game - Menu / Game / HighScores / GameOver etc
*/
public abstract class Scene : IScene
{
private string _name;
private List<IEntity> _entites;
public Scene(string aName)
{
_name = aName;
_entites = new List<IEntity>();
}
public List<IEntity> Entities { get { return _entites; } }
public string Name { get { return _name; } }
public abstract void HandleKeys(InputHelper aInputHelper, ISceneManager aSceneManager);
}
} | Sheepzez/yorkhill-kinect | kinectApp/kinectApp/kinectApp/Entities/Scene.cs | C# | mit | 1,016 |
class TokyoMetro::Factory::Convert::Customize::Api::TrainTimetable::RomanceCar::Info < TokyoMetro::Factory::Convert::Common::Api::MetaClass::TrainInfos::RomanceCar::Info
end
| osorubeki-fujita/odpt_tokyo_metro | lib/tokyo_metro/factory/convert/customize/api/train_timetable/romance_car/info.rb | Ruby | mit | 174 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make_loaddata.py
Convert ken_all.csv to loaddata
"""
import argparse
import csv
def merge_separated_line(args):
"""
yields line
yields a line.
if two (or more) lines has same postalcode,
merge them.
"""
def is_dup(line, buff):
""" lines is duplicated or not """
# same postalcode
if line[2] != buff[2]:
return False
# include choume and not
if line[11] != buff[11]:
return False
# line contains touten(kana)
if line[5].count(u'、') != 0:
return True
if buff[5].count(u'、') != 0:
return True
# line contains touten(kanji)
if line[8].count(u'、') != 0:
return True
if buff[8].count(u'、') != 0:
return True
return False
def merge(line, buff):
""" merge address of two lines """
new_buff = []
idx = 0
for element in line:
if element[:len(buff[idx])] != buff[idx]:
new_buff.append(u''.join([buff[idx], element]))
else:
new_buff.append(buff[idx])
idx += 1
return new_buff
line_buffer = []
ken_all = csv.reader(open(args.source))
for line in ken_all:
unicode_line = [unicode(s, 'utf8') for s in line]
if not(line_buffer):
line_buffer = unicode_line
continue
if is_dup(unicode_line, line_buffer):
line_buffer = merge(unicode_line, line_buffer)
else:
yield line_buffer
line_buffer = unicode_line
yield line_buffer
def parse_args():
# parse aruguments
Parser = argparse.ArgumentParser(description='Make loaddata of postalcode.')
Parser.add_argument('source', help='input file of converting')
Parser.add_argument('area', help='data file for area-code')
Parser.add_argument('net', help='data file of net-code')
return Parser.parse_args()
def main(args):
# converting main
Areadata = csv.writer(open(args.area, 'w'),
delimiter=',',
quoting=csv.QUOTE_NONE)
Netdata = csv.writer(open(args.net, 'w'),
delimiter=',',
quoting=csv.QUOTE_NONE)
for line in merge_separated_line(args):
zipcode = line[2]
if zipcode[5:7] != '00':
Areadata.writerow([s.encode('utf8') for s in line])
else:
Netdata.writerow([s.encode('utf8') for s in line])
if __name__ == '__main__':
args = parse_args()
main(args)
| morinatsu/ZipCode | bin/make_loaddata.py | Python | mit | 2,655 |
package main.java.srm149;
import java.util.HashSet;
import java.util.Set;
/*
* SRM 149 DIV I Level 2
* http://community.topcoder.com/stat?c=problem_statement&pm=1331
*/
public class MessageMess {
private Set<String> _dictionarySet = new HashSet<String>();
public String restore(String[] dictionary, String message) {
populateDictionarySet(dictionary);
int numAnswers = 0;
StringBuilder answer = findPossibleAnswer(0, message, "");
int ansLength = answer.length();
//Find answer
if (ansLength > 0 && ansLength < message.length()) {
answer = answer.deleteCharAt(ansLength - 1);
ansLength = answer.length();
answer = findPossibleAnswer(ansLength, message, answer.toString());
} else if ( ansLength > 0) {
//Find multiple answers
numAnswers++;
StringBuilder alternative = new StringBuilder(answer.substring(0, answer.indexOf(" ")));
ansLength = alternative.length();
alternative = findPossibleAnswer(ansLength, message, alternative.toString());
if (alternative.length() >= message.length()) {
numAnswers++;
}
}
if(numAnswers > 1) {
answer = new StringBuilder("AMBIGUOUS!");
} else if(answer.length() == 0 || answer.length() < message.length()) {
answer = new StringBuilder("IMPOSSIBLE!");
} else {
answer.deleteCharAt(answer.length() - 1);
}
return answer.toString();
}
private StringBuilder findPossibleAnswer(int startIndex, String message, String prefix) {
StringBuilder possibleWord = new StringBuilder(prefix);
StringBuilder answer = new StringBuilder();
for(int i = startIndex; i < message.length(); i++) {
possibleWord.append(message.charAt(i));
if(_dictionarySet.contains(possibleWord.toString())) {
answer.append(possibleWord).append(" ");
possibleWord.delete(0, possibleWord.length());
}
}
return answer;
}
private void populateDictionarySet(String[] array) {
for(int i = 0; i < array.length; i++) {
_dictionarySet.add(array[i]);
}
}
}
| revati1701/topcoder | src/main/java/srm149/MessageMess.java | Java | mit | 1,972 |
package seedu.taskboss.logic.commands;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Finds and lists all tasks in TaskBoss whose name contains any of the argument keywords.
* Keyword matching is case sensitive.
*/
public class FindCommand extends Command {
private static final String ALL_WHITESPACE = "\\s+";
public static final String COMMAND_WORD = "find";
public static final String COMMAND_WORD_SHORT = "f";
public static final String MESSAGE_USAGE = COMMAND_WORD + "/" + COMMAND_WORD_SHORT
+ ": Finds all tasks with names or information containing any of "
+ "the specified keywords (case-sensitive),\n"
+ " or with dates specified in any of following formats"
+ " e.g 28 / Feb / Feb 28 / Feb 28, 2017,\n"
+ " and displays them in a list.\n"
+ "Parameters: NAME AND INFORMATION KEYWORDS or sd/START_DATE or ed/END_DATE \n"
+ "Example: " + COMMAND_WORD + " meeting" + " || " + COMMAND_WORD_SHORT + " sd/march 19";
private static final String TYPE_KEYWORDS = "keywords";
private static final String TYPE_START_DATE = "startDate";
private static final String TYPE_END_DATE = "endDate";
private final String keywords;
private final String type;
//@@author A0147990R
public FindCommand(String type, String keywords) {
this.type = type;
this.keywords = keywords;
}
@Override
public CommandResult execute() {
switch(type) {
case TYPE_KEYWORDS:
String[] keywordsList = keywords.split(ALL_WHITESPACE);
final Set<String> keywordSet = new HashSet<String>(Arrays.asList(keywordsList));
model.updateFilteredTaskListByKeywords(keywordSet);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
case TYPE_START_DATE:
model.updateFilteredTaskListByStartDateTime(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
case TYPE_END_DATE:
model.updateFilteredTaskListByEndDateTime(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
default:
return null; //will never reach here
}
}
}
| CS2103JAN2017-W14-B2/main | src/main/java/seedu/taskboss/logic/commands/FindCommand.java | Java | mit | 2,391 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package autoescola.view;
import autoescola.controleDao.ControleLogin;
import autoescola.controleDao.ControleVeiculo;
import autoescola.modelo.bean.Veiculo;
/**
*
* @author felipe
*/
public class TelaCadastroVeiculo extends javax.swing.JDialog {
/**
* Creates new form TelaCadastroVeiculo
*/
private final ControleLogin controleLogin = new ControleLogin();
private final ControleVeiculo controleVeiculo = new ControleVeiculo();
public TelaCadastroVeiculo(java.awt.Frame parent, boolean modal, int id) {
super(parent, modal);
initComponents();
editar(id);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jtUsario = new javax.swing.JTabbedPane();
jPanel10 = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
txtPlaca = new javax.swing.JFormattedTextField();
txtAno = new javax.swing.JFormattedTextField();
bntCadastrarVeiculo = new javax.swing.JPanel();
lblCadastrarEditar = new javax.swing.JLabel();
jSCapacidade = new javax.swing.JSpinner();
txtModelo = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(144, 180, 242));
jLabel7.setFont(new java.awt.Font("Ubuntu", 1, 24)); // NOI18N
jLabel7.setForeground(new java.awt.Color(254, 254, 254));
jLabel7.setText("Veículo");
jtUsario.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jtUsarioMouseClicked(evt);
}
});
jPanel10.setBackground(new java.awt.Color(254, 254, 254));
jLabel11.setText("Placa");
jLabel16.setText("Modelo");
jLabel17.setText("Capacidade");
jLabel18.setText("Ano");
try {
txtPlaca.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("AAA-####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
try {
txtAno.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
bntCadastrarVeiculo.setBackground(new java.awt.Color(28, 181, 165));
bntCadastrarVeiculo.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
bntCadastrarVeiculo.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bntCadastrarVeiculoMouseClicked(evt);
}
});
lblCadastrarEditar.setBackground(new java.awt.Color(254, 254, 254));
lblCadastrarEditar.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
lblCadastrarEditar.setForeground(new java.awt.Color(254, 254, 254));
lblCadastrarEditar.setText("Cadastrar veiculo");
javax.swing.GroupLayout bntCadastrarVeiculoLayout = new javax.swing.GroupLayout(bntCadastrarVeiculo);
bntCadastrarVeiculo.setLayout(bntCadastrarVeiculoLayout);
bntCadastrarVeiculoLayout.setHorizontalGroup(
bntCadastrarVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bntCadastrarVeiculoLayout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(lblCadastrarEditar)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
bntCadastrarVeiculoLayout.setVerticalGroup(
bntCadastrarVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bntCadastrarVeiculoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblCadastrarEditar)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jSCapacidade.setModel(new javax.swing.SpinnerNumberModel(1, 1, null, 1));
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel10Layout.createSequentialGroup()
.addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(244, 244, 244))
.addComponent(txtPlaca)
.addComponent(jLabel11)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtAno, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addComponent(jLabel16)
.addGap(168, 168, 168))
.addComponent(txtModelo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17)
.addComponent(jSCapacidade, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel10Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bntCadastrarVeiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(jLabel17))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSCapacidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(25, 25, 25)
.addComponent(jLabel18)
.addGap(18, 18, 18)
.addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
.addComponent(bntCadastrarVeiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jtUsario.addTab("Dados do veiculo", jPanel10);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jtUsario))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jtUsario, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setBounds(0, 0, 713, 480);
}// </editor-fold>//GEN-END:initComponents
private void editar(int id) {
if (id != 0) {
Veiculo veiculo = controleVeiculo.getVeiculo(id);
txtPlaca.setText(veiculo.getPlaca());
jSCapacidade.setValue(veiculo.getCapacidade());
txtModelo.setText(veiculo.getModelo());
txtAno.setText(veiculo.getAno());
lblCadastrarEditar.setText("Editar veículo");
}
}
private void bntCadastrarVeiculoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntCadastrarVeiculoMouseClicked
Veiculo veiculo = new Veiculo();
veiculo.setPlaca(txtPlaca.getText());
float capacidade = Float.parseFloat(jSCapacidade.getValue().toString());
veiculo.setCapacidade(capacidade);
veiculo.setModelo(txtModelo.getText());
veiculo.setAno(txtAno.getText());
if (controleVeiculo.isEditar()) {
boolean res = controleVeiculo.editarVeiculo(veiculo);
if (res) {
lblCadastrarEditar.setText("Editar Veiculo");
//verificarTela();
}
} else {
veiculo.setStatus(true);
boolean res = controleVeiculo.cadastrarVeiculo(veiculo);
if (res) {
lblCadastrarEditar.setText("Editar Veiculo");
//verificarTela();
}
}
}//GEN-LAST:event_bntCadastrarVeiculoMouseClicked
private void jtUsarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtUsarioMouseClicked
}//GEN-LAST:event_jtUsarioMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TelaCadastroVeiculo dialog = new TelaCadastroVeiculo(new javax.swing.JFrame(), true, 0);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel bntCadastrarVeiculo;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JSpinner jSCapacidade;
private javax.swing.JTabbedPane jtUsario;
private javax.swing.JLabel lblCadastrarEditar;
private javax.swing.JFormattedTextField txtAno;
private javax.swing.JTextField txtModelo;
private javax.swing.JFormattedTextField txtPlaca;
// End of variables declaration//GEN-END:variables
}
| felipefsn-07/EasyDrive | autoEscola/src/autoescola/view/TelaCadastroVeiculo.java | Java | mit | 15,576 |
require File.dirname(__FILE__) + '/../spec_helper'
describe ProjectsController, "spam" do
let(:spammer_content) {
p = Project.make!
p.user.update_attributes(spammer: true)
p
}
let(:flagged_content) {
p = Project.make!
Flag.make!(flaggable: p, flag: Flag::SPAM)
p
}
it "should render 403 when the owner is a spammer" do
get :show, id: spammer_content.id
expect(response.response_code).to eq 403
end
it "should render 403 when content is flagged as spam" do
get :show, id: spammer_content.id
expect(response.response_code).to eq 403
end
end
describe ProjectsController, "add" do
let(:user) { User.make! }
let(:project_user) { ProjectUser.make!(user: user) }
let(:project) { project_user.project }
before do
sign_in user
end
it "should add to the project" do
o = Observation.make!(user: user)
post :add, id: project.id, observation_id: o.id
o.reload
expect( o.projects ).to include(project)
end
it "should set the project observation's user_id" do
o = Observation.make!(user: user)
post :add, id: project.id, observation_id: o.id
o.reload
expect( o.projects ).to include(project)
expect( o.project_observations.last.user_id ).to eq user.id
end
end
describe ProjectsController, "join" do
let(:user) { User.make! }
let(:project) { Project.make! }
before do
sign_in user
end
it "should create a project user" do
post :join, id: project.id
expect( project.project_users.where(user_id: user.id).count ).to eq 1
end
it "should accept project user parameters" do
post :join, id: project.id, project_user: {preferred_updates: false}
pu = project.project_users.where(user_id: user.id).first
expect( pu ).not_to be_prefers_updates
end
end
describe ProjectsController, "leave" do
let(:user) { User.make! }
let(:project) { Project.make! }
before do
sign_in user
end
it "should destroy the project user" do
pu = ProjectUser.make!(user: user, project: project)
delete :leave, id: project.id
expect( ProjectUser.find_by_id(pu.id) ).to be_blank
end
describe "routes" do
it "should accept DELETE requests" do
expect(delete: "/projects/#{project.slug}/leave").to be_routable
end
end
end
describe ProjectsController, "search" do
elastic_models( Project, Place )
describe "for site with a place" do
let(:place) { make_place_with_geom }
before { Site.default.update_attributes(place_id: place.id) }
it "should filter by place" do
with_place = Project.make!(place: place)
without_place = Project.make!(title: "#{with_place.title} without place")
response_json = <<-JSON
{
"results": [
{
"record": {
"id": #{with_place.id}
}
}
]
}
JSON
stub_request(:get, /#{INatAPIService::ENDPOINT}/).to_return(
status: 200,
body: response_json,
headers: { "Content-Type" => "application/json" }
)
get :search, q: with_place.title
expect( assigns(:projects) ).to include with_place
expect( assigns(:projects) ).not_to include without_place
end
it "should allow removal of the place filter" do
with_place = Project.make!(place: place)
without_place = Project.make!(title: "#{with_place.title} without place")
response_json = <<-JSON
{
"results": [
{
"record": {
"id": #{with_place.id}
}
},
{
"record": {
"id": #{without_place.id}
}
}
]
}
JSON
stub_request(:get, /#{INatAPIService::ENDPOINT}/).to_return(
status: 200,
body: response_json,
headers: { "Content-Type" => "application/json" }
)
get :search, q: with_place.title, everywhere: true
expect( assigns(:projects) ).to include with_place
expect( assigns(:projects) ).to include without_place
end
end
end
describe ProjectsController, "update" do
let(:project) { Project.make! }
let(:user) { project.user }
elastic_models( Observation )
before { sign_in user }
it "should work for the owner" do
put :update, id: project.id, project: {title: "the new title"}
project.reload
expect( project.title ).to eq "the new title"
end
it "allows bioblitz project to turn on aggregation" do
project.update_attributes(place: make_place_with_geom)
expect( project ).to be_aggregation_allowed
expect( project ).not_to be_prefers_aggregation
put :update, id: project.id, project: { prefers_aggregation: true }
project.reload
# still not allowed to aggregate since it's not a Bioblitz project
expect( project ).not_to be_prefers_aggregation
put :update, id: project.id, project: {
prefers_aggregation: true, project_type: Project::BIOBLITZ_TYPE,
start_time: 5.minutes.ago, end_time: Time.now }
project.reload
expect( project ).to be_prefers_aggregation
end
it "should not allow a non-curator to turn on observation aggregation" do
project.update_attributes(place: make_place_with_geom)
expect( project ).to be_aggregation_allowed
expect( project ).not_to be_prefers_aggregation
put :update, id: project.id, project: {prefers_aggregation: true}
project.reload
expect( project ).not_to be_prefers_aggregation
end
it "should not allow a non-curator to turn off observation aggregation" do
project.update_attributes(place: make_place_with_geom, prefers_aggregation: true)
expect( project ).to be_aggregation_allowed
expect( project ).to be_prefers_aggregation
put :update, id: project.id, project: {prefers_aggregation: false}
project.reload
expect( project ).to be_prefers_aggregation
end
end
describe ProjectsController, "destroy" do
let( :project ) { Project.make! }
before do
sign_in project.user
end
it "should not actually destroy the project" do
delete :destroy, id: project.id
expect( Project.find_by_id( project.id ) ).not_to be_blank
end
it "should queue a job to destroy the project" do
delete :destroy, id: project.id
expect( Delayed::Job.where("handler LIKE '%sane_destroy%'").count ).to eq 1
expect( Delayed::Job.where("unique_hash = '{:\"Project::sane_destroy\"=>#{project.id}}'").
count ).to eq 1
end
end
| pleary/inaturalist | spec/controllers/projects_controller_spec.rb | Ruby | mit | 6,463 |
const FeedParser = require("feedparser");
const request = require("request");
const Promise = require("bluebird");
const flatten = require("lodash").flatten;
const nodemailer = require("nodemailer");
const cfg = require("dotenv").config();
const readUrls = require("./urls.json");
const EMAIL_OPTIONS = {
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: cfg.EMAIL,
pass: cfg.APP_PASS
}
};
const urls = Object.keys(readUrls).filter((url) => readUrls[url]);
Promise.map(urls, (url) => {
return new Promise((resolve, reject) => {
const items = [];
const req = request(url);
const feeder = new FeedParser();
req.on("error", reject);
req.on('response', function (res) {
if (res.statusCode != 200) return reject(new Error("Something went wrong."));
res.pipe(feeder);
});
feeder.on("error", reject);
feeder.on("readable", function () {
let item;
while (item = this.read()) {
items.push(item);
}
});
feeder.on("end", () => {
return resolve(items.map((item) => {
return {
title: item.title,
link: item.link
};
}));
});
});
}).then(flatten).then(email).catch(console.error);
function email(items) {
const transporter = nodemailer.createTransport(EMAIL_OPTIONS);
const mail = {
from: cfg.EMAIL,
to: cfg.EMAIL,
subject: "New Craigslist Finds",
html: items.map((item) => `<a href=${item.link}>${item.title}</a>`).join("<br /><br />")
};
transporter.sendMail(mail, (err, info) => {
if (err) { return console.error(err); }
console.log("Mail Sent: " + info.response);
});
}
| zelein/craigbot | index.js | JavaScript | mit | 1,892 |
const {Scene, Sprite} = spritejs;
const container = document.getElementById('stage');
const scene = new Scene({
container,
width: 1200,
height: 600,
// contextType: '2d',
});
const layer = scene.layer();
(async function () {
const sprite = new Sprite({
anchor: 0.5,
bgcolor: 'red',
pos: [500, 300],
size: [200, 200],
borderRadius: 50,
});
layer.append(sprite);
await sprite.transition(2.0)
.attr({
bgcolor: 'green',
width: width => width + 100,
});
await sprite.transition(1.0)
.attr({
bgcolor: 'orange',
height: height => height + 100,
});
}()); | spritejs/spritejs | demos/doc/transition_basic/index.js | JavaScript | mit | 628 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoRest.Core;
using AutoRest.Core.ClientModel;
using AutoRest.Core.Utilities;
using AutoRest.Extensions;
using AutoRest.Ruby.TemplateModels;
using AutoRest.Ruby.Templates;
namespace AutoRest.Ruby
{
/// <summary>
/// A class with main code generation logic for Ruby.
/// </summary>
public class RubyCodeGenerator : CodeGenerator
{
/// <summary>
/// Name of the generated sub-folder inside ourput directory.
/// </summary>
private const string GeneratedFolderName = "generated";
/// <summary>
/// The name of the SDK. Determined in the following way:
/// if the parameter 'Name' is provided that it becomes the
/// name of the SDK, otherwise the name of input swagger is converted
/// into Ruby style and taken as name.
/// </summary>
protected readonly string sdkName;
/// <summary>
/// The name of the package version to be used in creating a version.rb file
/// </summary>
protected readonly string packageVersion;
/// <summary>
/// The name of the package name to be used in creating a version.rb file
/// </summary>
protected readonly string packageName;
/// <summary>
/// Relative path to produced SDK files.
/// </summary>
protected readonly string sdkPath;
/// <summary>
/// Relative path to produced SDK model files.
/// </summary>
protected readonly string modelsPath;
/// <summary>
/// A code namer instance (object which is responsible for correct files/variables naming).
/// </summary>
protected RubyCodeNamer CodeNamer { get; private set; }
/// <summary>
/// Initializes a new instance of the class RubyCodeGenerator.
/// </summary>
/// <param name="settings">The settings.</param>
public RubyCodeGenerator(Settings settings) : base(settings)
{
CodeNamer = new RubyCodeNamer();
this.packageVersion = Settings.PackageVersion;
this.packageName = Settings.PackageName;
if (Settings.CustomSettings.ContainsKey("Name"))
{
this.sdkName = Settings.CustomSettings["Name"].ToString();
}
if (sdkName == null)
{
this.sdkName = Path.GetFileNameWithoutExtension(Settings.Input);
}
if (sdkName == null)
{
sdkName = "client";
}
this.sdkName = RubyCodeNamer.UnderscoreCase(CodeNamer.RubyRemoveInvalidCharacters(this.sdkName));
this.sdkPath = this.packageName ?? this.sdkName;
this.modelsPath = Path.Combine(this.sdkPath, "models");
// AutoRest generated code for Ruby and Azure.Ruby generator will live inside "generated" sub-folder
settings.OutputDirectory = Path.Combine(settings.OutputDirectory, GeneratedFolderName);
}
/// <summary>
/// Gets the name of code generator.
/// </summary>
public override string Name
{
get { return "Ruby"; }
}
/// <summary>
/// Gets the brief description of the code generator.
/// </summary>
public override string Description
{
get { return "Generic Ruby code generator."; }
}
/// <summary>
/// Gets the brief instructions required to complete before using the code generator.
/// </summary>
public override string UsageInstructions
{
get { return "The \"gem 'ms_rest' ~> 0.6\" is required for working with generated code."; }
}
/// <summary>
/// Gets the file extension of the generated code files.
/// </summary>
public override string ImplementationFileExtension
{
get { return ".rb"; }
}
/// <summary>
/// Normalizes client model by updating names and types to be language specific.
/// </summary>
/// <param name="serviceClient"></param>
public override void NormalizeClientModel(ServiceClient serviceClient)
{
SwaggerExtensions.NormalizeClientModel(serviceClient, Settings);
PopulateAdditionalProperties(serviceClient);
CodeNamer.NormalizeClientModel(serviceClient);
CodeNamer.ResolveNameCollisions(serviceClient, Settings.Namespace,
Settings.Namespace + "::Models");
}
/// <summary>
/// Adds special properties to the service client (e.g. credentials).
/// </summary>
/// <param name="serviceClient">The service client.</param>
private void PopulateAdditionalProperties(ServiceClient serviceClient)
{
if (Settings.AddCredentials)
{
if (!serviceClient.Properties.Any(p => p.Type.IsPrimaryType(KnownPrimaryType.Credentials)))
{
serviceClient.Properties.Add(new Property
{
Name = "Credentials",
Type = new PrimaryType(KnownPrimaryType.Credentials),
IsRequired = true,
Documentation = "Subscription credentials which uniquely identify client subscription."
});
}
}
}
/// <summary>
/// Generates Ruby code for service client.
/// </summary>
/// <param name="serviceClient">The service client.</param>
/// <returns>Async task for generating SDK files.</returns>
public override async Task Generate(ServiceClient serviceClient)
{
// Service client
var serviceClientTemplate = new ServiceClientTemplate
{
Model = new ServiceClientTemplateModel(serviceClient),
};
await Write(serviceClientTemplate,
Path.Combine(sdkPath, RubyCodeNamer.UnderscoreCase(serviceClient.Name) + ImplementationFileExtension));
// Method groups
foreach (var group in serviceClient.MethodGroups)
{
var groupTemplate = new MethodGroupTemplate
{
Model = new MethodGroupTemplateModel(serviceClient, group),
};
await Write(groupTemplate,
Path.Combine(sdkPath, RubyCodeNamer.UnderscoreCase(group) + ImplementationFileExtension));
}
// Models
foreach (var model in serviceClient.ModelTypes)
{
var modelTemplate = new ModelTemplate
{
Model = new ModelTemplateModel(model, serviceClient.ModelTypes)
};
await Write(modelTemplate,
Path.Combine(modelsPath, RubyCodeNamer.UnderscoreCase(model.Name) + ImplementationFileExtension));
}
// Enums
foreach (var enumType in serviceClient.EnumTypes)
{
var enumTemplate = new EnumTemplate
{
Model = new EnumTemplateModel(enumType),
};
await Write(enumTemplate,
Path.Combine(modelsPath, RubyCodeNamer.UnderscoreCase(enumTemplate.Model.TypeDefinitionName) + ImplementationFileExtension));
}
// Requirements
var requirementsTemplate = new RequirementsTemplate
{
Model = new RequirementsTemplateModel(serviceClient, this.packageName ?? this.sdkName, this.ImplementationFileExtension, this.Settings.Namespace),
};
await Write(requirementsTemplate, RubyCodeNamer.UnderscoreCase(this.packageName ?? this.sdkName) + ImplementationFileExtension);
// Version File
if (!string.IsNullOrEmpty(this.packageVersion))
{
var versionTemplate = new VersionTemplate
{
Model = new VersionTemplateModel(packageVersion),
};
await Write(versionTemplate, Path.Combine(sdkPath, "version" + ImplementationFileExtension));
}
// Module Definition File
if (!string.IsNullOrEmpty(Settings.Namespace))
{
var modTemplate = new ModuleDefinitionTemplate
{
Model = new ModuleDefinitionTemplateModel(Settings.Namespace),
};
await Write(modTemplate, Path.Combine(sdkPath, "module_definition" + ImplementationFileExtension));
}
}
}
}
| fhoring/autorest | src/generator/AutoRest.Ruby/RubyCodeGenerator.cs | C# | mit | 8,978 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AcademyRPG
{
class Ninja:Character,IGatherer,IFighter
{
private int attackPointsCount;
public Ninja(string name, Point position,int owner)
: base(name, position, owner)
{
HitPoints = 1;
attackPointsCount = 0;
}
public int AttackPoints
{
get { return attackPointsCount; }
}
public int DefensePoints
{
get { return int.MaxValue; }
}
public int GetTargetIndex(List<WorldObject> availableTargets)
{
int maxHitPointsIndex = -1;
for (int i = 0; i < availableTargets.Count; i++)
{
if (availableTargets[i].Owner != this.Owner && availableTargets[i].Owner != 0)
{
if (maxHitPointsIndex == -1 || availableTargets[maxHitPointsIndex].HitPoints < availableTargets[i].HitPoints)
{
maxHitPointsIndex = i;
}
}
}
return maxHitPointsIndex;
}
public bool TryGather(IResource resource)
{
if (resource.Type == ResourceType.Stone)
{
attackPointsCount += resource.Quantity * 2;
}
else
{
attackPointsCount += resource.Quantity;
}
return true;
}
}
}
| LazarDL/TelerikHomeworks | OOP/TestPreparationOOp/academyTest/AcademyRPG-Skeleton/Ninja.cs | C# | mit | 1,551 |
require 'fn_space/utils'
describe FnSpace::Utils do
describe 'mod' do
it 'creates a object with assign function' do
res = FnSpace::Utils.mod.().assign(:q){50}.assign(:w){93}
expect(res.q).to eql(50)
expect(res.w).to eql(93)
end
end
describe 'struct' do
it 'creates a struct from a hash' do
res = FnSpace::Utils.struct.(a: 57, b: 6)
expect(res.a).to eql(57)
end
end
describe 'apply_send' do
it 'creates a lamda that sends a message with paramaters to the first argument' do
add_five = FnSpace::Utils.apply_send.(:+, 5)
expect(add_five.(9)).to eql(14)
end
end
describe 'chain' do
it 'creates a monad' do
x = 5
add_one = ->(v) { v + 1 }
side_effect = ->(v) { x += 3 }
res = FnSpace::Utils.chain.(4) >> add_one << side_effect | :value
expect(res).to eql(5)
expect(x).to eql(8)
end
end
end
| mushishi78/fn_space | spec/utils_spec.rb | Ruby | mit | 916 |
<?php
namespace Jasig;
/*
* Copyright © 2003-2010, The ESUP-Portail consortium & the JA-SIG Collaborative.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ESUP-Portail consortium & the JA-SIG
* Collaborative nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
require_once(dirname(__FILE__).'/../Exception.php');
/**
* An Exception for problems performing requests
*/
class CAS_Request_Exception
extends \Exception
implements CAS_Exception
{
}
| Eirbware/Core | src/Jasig/CAS/Request/Exception.php | PHP | mit | 1,880 |
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using U3d = UnityEngine;
namespace M2Image
{
/// <summary>
/// WZL(与WZX配套)文件读取工具类
/// </summary>
internal sealed class WZL : IDisposable
{
/// <summary>
/// 图片数量
/// </summary>
internal int ImageCount { get; private set; }
/// <summary>
/// 色深度
/// </summary>
internal int ColorCount { get; private set; }
/// <summary>
/// 图片数据起始位置
/// </summary>
private int[] OffsetList;
/// <summary>
/// 图片数据长度
/// </summary>
private int[] LengthList;
/// <summary>
/// 图片描述对象
/// </summary>
internal M2ImageInfo[] ImageInfos { get; private set; }
/// <summary>
/// WIL文件指针
/// </summary>
private FileStream FS_wzl;
/// <summary>
/// 是否成功初始化
/// </summary>
internal bool Loaded { get; private set; }
/// <summary>
/// 文件指针读取锁
/// </summary>
private Object wzl_locker = new Object();
internal WZL(String wzlPath)
{
Loaded = false;
ColorCount = 8;
if (!File.Exists(Path.ChangeExtension(wzlPath, "wzx"))) return;
FileStream fs_wzx = new FileStream(Path.ChangeExtension(wzlPath, "wzx"), FileMode.Open, FileAccess.Read);
fs_wzx.Position += 44; // 跳过标题
using (BinaryReader rwzx = new BinaryReader(fs_wzx))
{
ImageCount = rwzx.ReadInt32();
OffsetList = new int[ImageCount];
for (int i = 0; i < ImageCount; ++i)
{
// 读取数据偏移地址
OffsetList[i] = rwzx.ReadInt32();
}
}
//fs_wzx.Dispose();
FS_wzl = new FileStream(wzlPath, FileMode.Open, FileAccess.Read);
using (BinaryReader rwzl = new BinaryReader(FS_wzl))
{
ImageInfos = new M2ImageInfo[ImageCount];
LengthList = new int[ImageCount];
for (int i = 0; i < ImageCount; ++i)
{
// 读取图片信息和数据长度
M2ImageInfo ii = new M2ImageInfo();
FS_wzl.Position = OffsetList[i] + 4; // 跳过4字节未知数据
ii.Width = rwzl.ReadUInt16();
ii.Height = rwzl.ReadUInt16();
ii.OffsetX = rwzl.ReadInt16();
ii.OffsetY = rwzl.ReadInt16();
ImageInfos[i] = ii;
LengthList[i] = rwzl.ReadInt32();
}
}
Loaded = true;
}
/// <summary>
/// 获取某个索引的图片
/// </summary>
/// <param name="index">图片索引,从0开始</param>
/// <returns>对应图片数据</returns>
internal U3d.Texture2D this[uint index]
{
get
{
M2ImageInfo ii = ImageInfos[index];
U3d.Texture2D result = new U3d.Texture2D(ii.Width, ii.Height);
if (ii.Width == 0 && ii.Height == 0) return result;
byte[] pixels = null;
lock (wzl_locker)
{
FS_wzl.Position = OffsetList[index] + 16;
using (BinaryReader rwzl = new BinaryReader(FS_wzl))
{
pixels = unzip(rwzl.ReadBytes(LengthList[index]));
}
}
int p_index = 0;
for (int h = 0; h < ii.Height; ++h)
for (int w = 0; w < ii.Width; ++w)
{
// 跳过填充字节
if (w == 0)
p_index += Delphi.SkipBytes(8, ii.Width);
float[] pallete = Delphi.PALLETE[pixels[p_index++] & 0xff];
result.SetPixel(w, ii.Height - h, new U3d.Color(pallete[1], pallete[2], pallete[3], pallete[0]));
}
result.Apply ();
return result;
}
}
private byte[] unzip(byte[] ziped)
{
InflaterInputStream iib = new InflaterInputStream(new MemoryStream(ziped));
MemoryStream o = new MemoryStream();
int i = 1024;
byte[] buf = new byte[i];
while ((i = iib.Read(buf, 0, i)) > 0)
{
o.Write(buf, 0, i);
}
return o.ToArray();
}
public void Dispose()
{
lock (wzl_locker)
{
OffsetList = null;
ImageInfos = null;
Loaded = false;
if (FS_wzl != null)
{
FS_wzl.Dispose();
}
}
}
}
} | jootm2/m2client-u3d | Assets/Scripts/M2Image/WZL.cs | C# | mit | 5,141 |
// Copyright 2021-2022, University of Colorado Boulder
/**
* Provides a minimum and preferred width. The minimum width is set by the component, so that layout containers could
* know how "small" the component can be made. The preferred width is set by the layout container, and the component
* should adjust its size so that it takes up that width.
*
* @author Jonathan Olson <jonathan.olson@colorado.edu>
*/
import TinyProperty from '../../../axon/js/TinyProperty.js';
import memoize from '../../../phet-core/js/memoize.js';
import { scenery, Node } from '../imports.js';
import Constructor from '../../../phet-core/js/types/Constructor.js';
const WIDTH_SIZABLE_OPTION_KEYS = [
'preferredWidth',
'minimumWidth'
];
type WidthSizableSelfOptions = {
preferredWidth?: number | null,
minimumWidth?: number | null
};
const WidthSizable = memoize( <SuperType extends Constructor>( type: SuperType ) => {
const clazz = class extends type {
preferredWidthProperty: TinyProperty<number | null>;
minimumWidthProperty: TinyProperty<number | null>;
constructor( ...args: any[] ) {
super( ...args );
this.preferredWidthProperty = new TinyProperty<number | null>( null );
this.minimumWidthProperty = new TinyProperty<number | null>( null );
}
get preferredWidth(): number | null {
return this.preferredWidthProperty.value;
}
set preferredWidth( value: number | null ) {
assert && assert( value === null || ( typeof value === 'number' && isFinite( value ) && value >= 0 ),
'preferredWidth should be null or a non-negative finite number' );
this.preferredWidthProperty.value = value;
}
get minimumWidth(): number | null {
return this.minimumWidthProperty.value;
}
set minimumWidth( value: number | null ) {
assert && assert( value === null || ( typeof value === 'number' && isFinite( value ) ) );
this.minimumWidthProperty.value = value;
}
// Detection flag for this trait
get widthSizable(): boolean { return true; }
};
// If we're extending into a Node type, include option keys
// TODO: This is ugly, we'll need to mutate after construction, no?
if ( type.prototype._mutatorKeys ) {
clazz.prototype._mutatorKeys = type.prototype._mutatorKeys.concat( WIDTH_SIZABLE_OPTION_KEYS );
}
return clazz;
} );
// Some typescript gymnastics to provide a user-defined type guard that treats something as widthSizable
const wrapper = () => WidthSizable( Node );
type WidthSizableNode = InstanceType<ReturnType<typeof wrapper>>;
const isWidthSizable = ( node: Node ): node is WidthSizableNode => {
return node.widthSizable;
};
scenery.register( 'WidthSizable', WidthSizable );
export default WidthSizable;
export { isWidthSizable };
export type { WidthSizableNode, WidthSizableSelfOptions };
| phetsims/scenery | js/layout/WidthSizable.ts | TypeScript | mit | 2,836 |
//
// Created by admarkov on 09.05.17.
//
#include "mapping.h"
Node* Node::clone(Node* r, Node* p) {
if (r==nullptr) r = NodeToItsCopy[root];
Node *n = new Node (p, r, type, data, nullptr, nullptr);
NodeToItsCopy[this] = n;
CopyToClonedNode[n] = this;
if (n->root==nullptr) n->root = n;
if (left!=nullptr) n->left = left->clone(r,n);
if (right!=nullptr) n->right = right->clone(r,n);
return n;
} | admarkov/func_composer | astClone.cpp | C++ | mit | 429 |
<?php
namespace Core\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Phone
*
* @ORM\Table(name="phone", uniqueConstraints={@ORM\UniqueConstraint(name="phone", columns={"phone","ddd","people_id"})}, indexes={@ORM\Index(name="IDX_E7927C743147C936", columns={"people_id"})})
* @ORM\Entity
*/
class Phone {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var integer
*
* @ORM\Column(name="phone", type="integer", length=10, nullable=false)
*/
private $phone;
/**
* @var string
*
* @ORM\Column(name="ddd", type="integer", length=2, nullable=false)
*/
private $ddd;
/**
* @var boolean
*
* @ORM\Column(name="confirmed", type="boolean", nullable=false)
*/
private $confirmed = '0';
/**
* @var \Core\Entity\People
*
* @ORM\ManyToOne(targetEntity="Core\Entity\People")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="people_id", referencedColumnName="id")
* })
*/
private $people;
/**
* Get id
*
* @return integer
*/
public function getId() {
return $this->id;
}
/**
* Set ddd
*
* @param string $ddd
* @return Ddd
*/
public function setDdd($ddd) {
$this->ddd = $ddd;
return $this;
}
/**
* Get ddd
*
* @return string
*/
public function getDdd() {
return $this->ddd;
}
/**
* Set phone
*
* @param string $phone
* @return Phone
*/
public function setPhone($phone) {
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* @return string
*/
public function getPhone() {
return $this->phone;
}
/**
* Set confirmed
*
* @param boolean $confirmed
* @return Phone
*/
public function setConfirmed($confirmed) {
$this->confirmed = $confirmed;
return $this;
}
/**
* Get confirmed
*
* @return boolean
*/
public function getConfirmed() {
return $this->confirmed;
}
/**
* Set people
*
* @param \Core\Entity\People $people
* @return Phone
*/
public function setPeople(\Core\Entity\People $people = null) {
$this->people = $people;
return $this;
}
/**
* Get people
*
* @return \Core\Entity\People
*/
public function getPeople() {
return $this->people;
}
}
| ControleOnline/core | src/Core/Entity/Phone.php | PHP | mit | 2,644 |
/**
*
*/
package com.zimbra.qa.selenium.framework.util;
import java.net.*;
import java.util.regex.*;
import org.apache.log4j.*;
import com.zimbra.common.soap.Element;
/**
* Represents an 'external' account
*
* @author Matt Rhoades
*
*/
public class ZimbraExternalAccount extends ZimbraAccount {
private static Logger logger = LogManager.getLogger(ZimbraExternalAccount.class);
protected URI UrlRegistration = null;
protected URI UrlLogin = null;
public ZimbraExternalAccount() {
logger.info("new "+ ZimbraExternalAccount.class.getCanonicalName());
}
public void setEmailAddress(String address) {
this.EmailAddress = address;
}
public void setPassword(String password) {
this.Password = password;
}
/**
* Based on the external invitation message,
* set both the login and registration URLs for this account
* @param GetMsgResponse
* @throws HarnessException
*/
public void setURL(Element GetMsgResponse) throws HarnessException {
this.setRegistrationURL(GetMsgResponse);
this.setLoginURL(GetMsgResponse);
}
/**
* Based on the external invitation message, extract the login URL
* example, https://zqa-062.eng.vmware.com/service/extuserprov/?p=0_46059ce585e90f5d2d5...12e636f6d3b
* @param GetMsgResponse
*/
public void setRegistrationURL(Element GetMsgResponse) throws HarnessException {
String content = this.soapClient.selectValue(GetMsgResponse, "//mail:mp[@ct='text/html']//mail:content", null, 1);
try {
setRegistrationURL(determineRegistrationURL(content));
} catch (URISyntaxException e) {
throw new HarnessException("Unable to parse registration URL from ["+ content +"]", e);
}
}
/**
* Set the external user's registration URL to the specified URL
* @param url
*/
public void setRegistrationURL(URI url) {
this.UrlRegistration = url;
}
public URI getRegistrationURL() {
return (this.UrlRegistration);
}
/**
* Based on the external invitation message, extract the login URL
* example, https://zqa-062.eng.vmware.com/?virtualacctdomain=zqa-062.eng.vmware.com
* @param GetMsgResponse
* @throws HarnessException
*/
public void setLoginURL(Element GetMsgResponse) throws HarnessException {
String content = this.soapClient.selectValue(GetMsgResponse, "//mail:mp[@ct='text/html']//mail:content", null, 1);
try {
setLoginURL(determineLoginURL(content));
} catch (URISyntaxException e) {
throw new HarnessException("Unable to parse registration URL from ["+ content +"]", e);
}
}
/**
* Set the external user's login URL to the specified URL
* @param url
*/
public void setLoginURL(URI url) {
this.UrlLogin = url;
}
public URI getLoginURL() {
return (this.UrlLogin);
}
public static final Pattern patternTag = Pattern.compile("(?i)<a([^>]+)>(.+?)</a>");
public static final Pattern patternLink = Pattern.compile("\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))");
/**
* Parse the invitation message to grab the registration URL
* for the external user
* @param content
* @return
* @throws HarnessException
* @throws MalformedURLException
* @throws URISyntaxException
*/
protected URI determineRegistrationURL(String content) throws HarnessException, URISyntaxException {
String registrationURL = null;
Matcher matcherTag = patternTag.matcher(content);
while (matcherTag.find()) {
String href = matcherTag.group(1);
String text = matcherTag.group(2);
logger.info("href: "+ href);
logger.info("text: "+ text);
Matcher matcherLink = patternLink.matcher(href);
while(matcherLink.find()){
registrationURL = matcherLink.group(1); //link
if ( registrationURL.startsWith("\"") ) {
registrationURL = registrationURL.substring(1); // Strip the beginning "
}
if ( registrationURL.endsWith("\"") ) {
registrationURL = registrationURL.substring(0, registrationURL.length()-1); // Strip the ending "
}
logger.info("link: "+ registrationURL);
return (new URI(registrationURL));
}
}
throw new HarnessException("Unable to determine the regisration URL from "+ content);
}
/**
* Parse the invitation message to grab the login URL
* for the external user
* @param content
* @return
* @throws HarnessException
* @throws URISyntaxException
*/
protected URI determineLoginURL(String content) throws HarnessException, URISyntaxException {
// TODO: implement me!
return (determineRegistrationURL(content));
}
/**
* Get the external account for config.properties -> external.yahoo.account
* @return the ZimbraExternalAccount
*/
public static synchronized ZimbraExternalAccount ExternalA() {
if ( _ExternalA == null ) {
_ExternalA = new ZimbraExternalAccount();
}
return (_ExternalA);
}
private static ZimbraExternalAccount _ExternalA = null;
}
| nico01f/z-pec | ZimbraSelenium/src/java/com/zimbra/qa/selenium/framework/util/ZimbraExternalAccount.java | Java | mit | 4,848 |
<?php
namespace Cviebrock\EloquentTaggable\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ModelUntagged
{
use Dispatchable, InteractsWithSockets, SerializesModels;
private $model;
private $tags;
/**
* @return mixed
*/
public function getModel()
{
return $this->model;
}
/**
* @return mixed
*/
public function getTags()
{
return $this->tags;
}
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($model, $tags)
{
$this->model = $model;
$this->tags = $tags;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
}
}
| cviebrock/eloquent-taggable | src/Events/ModelUntagged.php | PHP | mit | 1,094 |
using System;
using System.Linq;
namespace Task_5
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
int count= 0;
Console.WriteLine("Ohjelma kertoo kuinka monta vokaalia lauseessa on!");
Console.Write("Anna lause:");
string UserInput = Console.ReadLine().ToUpper();
foreach (char letter in UserInput)
{
if (IsVowel(letter))
count++;
}
Console.WriteLine($"Vokaaleita on: {count}");
Console.ReadLine();
}
static bool IsVowel(char letter)
{
if (letter == 'A' || letter == 'E' || letter == 'I' || letter == 'O' || letter == 'U' || letter == 'Y' || letter == 'Ä' || letter == 'Ö')
return true;
else
return false;
}
}
}
| SannaNaTu/programming-basics | string-handling/Tasks/Vowel/Program.cs | C# | mit | 968 |
//{
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // brian
//}
const ll MAXn=1e5+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e15);
int main()
{
IOS();
char c;
while(cin>>c)
{
if(c<'a')c+=('a'-'A');
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='y')continue;
cout<<"."<<c;
}
cout<<endl;
}
| brianbbsu/program | code archive/CF/118A.cpp | C++ | mit | 1,757 |
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.gfx.silverlight_attach"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.gfx.silverlight_attach"] = true;
dojo.provide("dojox.gfx.silverlight_attach");
dojo.require("dojox.gfx.silverlight");
dojo.experimental("dojox.gfx.silverlight_attach");
(function(){
var g = dojox.gfx, sl = g.silverlight;
sl.attachNode = function(node){
// summary: creates a shape from a Node
// node: Node: an Silverlight node
return null; // not implemented
};
sl.attachSurface = function(node){
// summary: creates a surface from a Node
// node: Node: an Silverlight node
return null; // dojox.gfx.Surface
};
})();
}
| henry-gobiernoabierto/geomoose | htdocs/libs/dojo/release/geomoose2.6/dojox/gfx/silverlight_attach.js | JavaScript | mit | 907 |
<?php
$myArr = array("Keeyana", "Mary", "Peter", "Sally");
$myJSON = json_encode($myArr);
echo $myJSON;
?>
| keeyanajones/Samples | javascriptProject/jsonProject/public_html/php/demo_file_array.php | PHP | mit | 110 |
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import Greetings from './components/Greetings';
import SignupPage from './components/signup/SignupPage'
export default (
<Route path="/" component={App}>
<IndexRoute component={Greetings}/> //make all main routes components as class components
<Route path="signup" component={SignupPage}/>
</Route>
) | ilijabradas/react_app | client/routes.js | JavaScript | mit | 419 |
<?php
/*
Unsafe sample
input : get the field userData from the variable $_GET via an object, which store it in a array
sanitize : none
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.*/
class Input{
private $input;
public function getInput(){
return $this->input[1];
}
public function __construct(){
$this->input = array();
$this->input[0]= 'safe' ;
$this->input[1]= $_GET['UserData'] ;
$this->input[2]= 'safe' ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
//no_sanitizing
$query = "//User[username/text()='". $tainted . "']";
//flaw
$xml = simplexml_load_file("users.xml");//file load
echo "query : ". $query ."<br /><br />" ;
$res=$xml->xpath($query);//execution
print_r($res);
echo "<br />" ;
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_91/unsafe/CWE_91__object-Array__no_sanitizing__username_text-concatenation_simple_quote.php | PHP | mit | 1,659 |
#include "MoQiang.h"
enum CAUSE{
AN_ZHI_JIE_FANG=2901,
HUAN_YING_XING_CHEN=2902,
HEI_AN_SHU_FU=2903,
AN_ZHI_ZHANG_BI=2904,
CHONG_YING=2905,
CHONG_YING_DISCARD = 29051,
QI_HEI_ZHI_QIANG=2906
};
MoQiang::MoQiang()
{
makeConnection();
setMyRole(this);
Button *chongying;
chongying=new Button(3,QStringLiteral("充盈"));
buttonArea->addButton(chongying);
connect(chongying,SIGNAL(buttonSelected(int)),this,SLOT(ChongYing()));
}
void MoQiang::normal()
{
Role::normal();
handArea->disableMagic();
if(!jieFangFirst)
{
if(handArea->checkElement("thunder") || handArea->checkType("magic"))
buttonArea->enable(3);
}
unactionalCheck();
}
void MoQiang::AnZhiJieFang()
{
state=AN_ZHI_JIE_FANG;
gui->reset();
SafeList<Card*> handcards=dataInterface->getHandCards();
bool flag=true;
int magicCount = 0;
int cardCount = handcards.size();
decisionArea->enable(1);
for(int i = 0;i < cardCount;i++)
{
if(handcards[i]->getType() == "magic")
{
magicCount++;
}
}
if(magicCount == cardCount)
{
flag = false;
}
tipArea->setMsg(QStringLiteral("是否发动暗之解放?"));
if(flag)
{
decisionArea->enable(0);
}
else
{
decisionArea->disable(0);
}
}
void MoQiang::HuanYingXingChen()
{
state=HUAN_YING_XING_CHEN;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动幻影星辰?"));
playerArea->enableAll();
playerArea->setQuota(1);
decisionArea->enable(1);
}
void MoQiang::AnZhiBiZhang()
{
state=AN_ZHI_ZHANG_BI;
tipArea->setMsg(QStringLiteral("是否发动暗之障壁?"));
handArea->setQuota(1,7);
decisionArea->enable(1);
decisionArea->disable(0);
handArea->enableElement("thunder");
handArea->enableMagic();
}
void MoQiang::QiHeiZhiQiang()
{
state= QI_HEI_ZHI_QIANG;
tipArea->reset();
tipArea->setMsg(QStringLiteral("是否发动漆黑之枪?如是请选择发动能量数:"));
decisionArea->enable(0);
decisionArea->enable(1);
Player* myself=dataInterface->getMyself();
int min=myself->getEnergy();
for(;min>0;min--)
tipArea->addBoxItem(QString::number(min));
tipArea->showBox();
}
void MoQiang::ChongYing()
{
state=CHONG_YING;
playerArea->reset();
handArea->reset();
tipArea->reset();
handArea->enableElement("thunder");
handArea->enableMagic();
handArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoQiang::cardAnalyse()
{
SafeList<Card*> selectedCards;
Role::cardAnalyse();
selectedCards=handArea->getSelectedCards();
try{
switch(state)
{
case AN_ZHI_ZHANG_BI:
{
bool thunder = true;
bool magic = true;
for(int i=0;i<selectedCards.size();i++)
{
if(selectedCards[i]->getElement()!= "thunder")
{
thunder = false;
}
if(selectedCards[i]->getType() != "magic")
{
magic = false;
}
}
if(thunder || magic){
decisionArea->enable(0);
}
else{
playerArea->reset();
decisionArea->disable(0);
}
break;
}
case CHONG_YING:
decisionArea->enable(0);
break;
}
}catch(int error){
logic->onError(error);
}
}
void MoQiang::playerAnalyse()
{
Role::playerAnalyse();
switch(state)
{
case HUAN_YING_XING_CHEN:
decisionArea->enable(0);
break;
}
}
void MoQiang::turnBegin()
{
Role::turnBegin();
jieFangFirst=false;
usingChongYing = false;
}
void MoQiang::askForSkill(Command* cmd)
{
switch(cmd->respond_id())
{
case AN_ZHI_JIE_FANG:
AnZhiJieFang();
break;
case HUAN_YING_XING_CHEN:
HuanYingXingChen();
break;
case QI_HEI_ZHI_QIANG:
QiHeiZhiQiang();
break;
case AN_ZHI_ZHANG_BI:
AnZhiBiZhang();
break;
default:
Role::askForSkill(cmd);
}
}
void MoQiang::onOkClicked()
{
Role::onOkClicked();
SafeList<Card*> selectedCards;
SafeList<Player*>selectedPlayers;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
try{
switch(state)
{
case AN_ZHI_JIE_FANG:
respond = new Respond();
respond->set_src_id(myID);
respond->set_respond_id(AN_ZHI_JIE_FANG);
respond->add_args(1);
jieFangFirst=true;
start = true;
gui->reset();
emit sendCommand(network::MSG_RESPOND, respond);
break;
case HUAN_YING_XING_CHEN:
respond = newRespond(HUAN_YING_XING_CHEN);
respond->add_args(2);
respond->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_RESPOND, respond);
start = true;
gui->reset();
break;
case AN_ZHI_ZHANG_BI:
respond = newRespond(AN_ZHI_ZHANG_BI);
respond->add_args(1);
for(int i=0;i<selectedCards.size();i++)
{
respond->add_card_ids(selectedCards[i]->getID());
}
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case QI_HEI_ZHI_QIANG:
respond = newRespond(QI_HEI_ZHI_QIANG);
respond->add_args(1);
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CHONG_YING:
action = newAction(ACTION_MAGIC_SKILL,CHONG_YING);
action->add_card_ids(selectedCards[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
usingChongYing = true;
gui->reset();
break;
}
}catch(int error){
logic->onError(error);
}
}
void MoQiang::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case AN_ZHI_JIE_FANG:
respond = new Respond();
respond->set_src_id(myID);
respond->set_respond_id(AN_ZHI_JIE_FANG);
respond->add_args(0);
gui->reset();
emit sendCommand(network::MSG_RESPOND, respond);
break;
case HUAN_YING_XING_CHEN:
respond = newRespond(HUAN_YING_XING_CHEN);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case AN_ZHI_ZHANG_BI:
respond = newRespond(AN_ZHI_ZHANG_BI);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case QI_HEI_ZHI_QIANG:
respond = newRespond(QI_HEI_ZHI_QIANG);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CHONG_YING:
normal();
break;
}
}
void MoQiang::attacked(QString element, int hitRate)
{
Role::attacked(element,hitRate);
handArea->disableMagic();
}
void MoQiang::moDaned(int nextID,int sourceID, int howMany)
{
Role::moDaned(nextID,sourceID,howMany);
handArea->disableMagic();
}
| chntujia/CodfiyAsteriatedGrailClient | logic/MoQiang.cpp | C++ | mit | 7,615 |
class Item < ActiveRecord::Base
# The SecureRandom library is used to generate uid:s
require 'securerandom'
# Generate uid on creation
before_save :generate_uid, on: :new
def generate_uid
self.uid = SecureRandom.uuid
end
validates :uid,
presence: true,
format: { with: /\h{8}-\h{4}-\h{4}-\h{4}-\h{12}/ },
length: { is: 36 },
on: :update
validates :uid,
uniqueness: true,
on: :create
validates :type, presence: true
validates :title,
presence: true,
length: { in: 2..80 }
serialize :features
def features_human
if self.features
self.features.join(', ')
else
""
end
end
def features_human=(input)
self.features = input.split(',').grep(String).collect(&:strip)
end
## List of subclasses and their aliases
# When adding a new subclass, please maintain TYPES
# class => name,
TYPES = {
'Cable' => I18n.t(:cable, scope: [:activerecord, :models]),
'Device' => I18n.t(:device, scope: [:activerecord, :models]),
'Misc' => I18n.t(:misc, scope: [:activerecord, :models]),
}
def get_type_name
TYPES[self.type]
end
##
# Use uid as an URL parameter instead of id
def to_param
self.uid
end
# Returns a short version of the uid.
# Dramatically increases chances of duplicates. Not guaranteed to be unique!
def short_uid
self.uid.split(/\-/).first
end
def self.find_by_uid (uid)
Item.where("uid LIKE ?", "#{uid}%").first
end
protected
def after_create
# Expire main trivia (includes Item.count)
expire_fragment 'main_trivia'
end
def after_destroy; after_create; end
end
| ollpu/inventory | app/models/items/item.rb | Ruby | mit | 1,689 |
<?php
namespace App\AdminBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Validator\Constraints as Asset ;
/**
* @Route("/admin")
*/
class SecuredController extends Controller
{
/**
* @Route("/login", name="app_admin_login")
* @Template()
*/
public function loginAction(Request $request)
{
$form = $this->crateForm($request) ;
// $form = $this->container->get('app.admin.loader')->getAdminByName('app_user')->getLoginForm( $request ) ;
$dispatcher = $this->container->get('event_dispatcher');
$event = new \App\AdminBundle\Event\FormEvent($form, $request);
$dispatcher->dispatch('app.event.form', $event) ;
if (null !== $event->getResponse()) {
return $event->getResponse() ;
}
return array(
'form' => $form->createView() ,
);
}
/**
* @Route("/login_check", name="app_admin_check")
*/
public function securityCheckAction()
{
throw new \RuntimeException('You must configure the check path to be handled by the firewall using form_login in your security firewall configuration.');
}
/**
* @Route("/logout", name="app_admin_logout")
*/
public function logoutAction()
{
throw new \RuntimeException('You must activate the logout in your security firewall configuration.');
}
protected function crateForm(\Symfony\Component\HttpFoundation\Request $request) {
if ( $request->attributes->has(SecurityContext::AUTHENTICATION_ERROR) ) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $request->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
$request->getSession()->set( SecurityContext::AUTHENTICATION_ERROR , null ) ;
}
$tr = $this->container->get('translator') ;
$app_domain = $this->container->getParameter('app.admin.domain') ;
$builder = $this->container->get('form.factory')->createNamedBuilder('login', 'form', array(
'label' => 'app.login.label' ,
'translation_domain' => $app_domain ,
)) ;
$builder
->add('username', 'text', array(
'label' => 'app.login.username.label' ,
'translation_domain' => $app_domain ,
'data' => $request->getSession()->get(SecurityContext::LAST_USERNAME) ,
'horizontal_input_wrapper_class' => 'col-xs-6',
'attr' => array(
'placeholder' => 'app.login.username.placeholder' ,
)
) )
->add('password', 'password', array(
'label' => 'app.login.password.label' ,
'translation_domain' => $app_domain ,
'horizontal_input_wrapper_class' => 'col-xs-6',
'attr' => array(
)
) )
->add('captcha', 'appcaptcha', array(
'label' => 'app.form.captcha.label' ,
'translation_domain' => $app_domain ,
))
;
$form = $builder->getForm() ;
if( $error ) {
if( $error instanceof \Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException ) {
$_error = new \Symfony\Component\Form\FormError( $tr->trans('app.login.error.crsf', array(), $app_domain ) ) ;
$form->addError( $_error ) ;
} else if ( $error instanceof \App\UserBundle\Exception\CaptchaException ) {
$_error = $tr->trans('app.login.error.captcha' , array(), $app_domain ) ;
if( $this->container->getParameter('kernel.debug') ) {
$_error .= sprintf(" code(%s)", $error->getCode() ) ;
}
$_error = new \Symfony\Component\Form\FormError( $_error );
$form->get('captcha')->addError( $_error ) ;
} else if( $error instanceof \Symfony\Component\Security\Core\Exception\BadCredentialsException ) {
$_error = new \Symfony\Component\Form\FormError( $tr->trans('app.login.error.credentials' , array(), $app_domain ) ) ;
$form->get('username')->addError( $_error ) ;
} else if( $error instanceof \Symfony\Component\Security\Core\Exception\DisabledException ) {
$_error = new \Symfony\Component\Form\FormError( $tr->trans('app.login.error.disabled' , array(), $app_domain ) ) ;
$form->get('username')->addError( $_error ) ;
} else {
$_error = new \Symfony\Component\Form\FormError( $error->getMessage() ) ;
if( $this->container->getParameter('kernel.debug') ) {
\Dev::dump( $error ) ;
}
$form->get('username')->addError( $_error ) ;
}
}
return $form ;
}
}
| symforce/symforce-standard | src/App/AdminBundle/Controller/SecuredController.php | PHP | mit | 5,511 |
package hr.fer.bio.project.booleanarray;
import hr.fer.bio.project.rankable.Rankable;
import hr.fer.bio.project.wavelet.TreeNode;
import java.util.Arrays;
/**
* Simple class for boolean[] encapsulation
*
* @author bpervan
* @since 1.0
*/
public class BooleanArray implements Rankable {
public boolean[] data;
public BooleanArray(int size){
data = new boolean[size];
}
public BooleanArray(boolean[] data){
this.data = Arrays.copyOf(data, data.length);
}
@Override
public int rank(char c, int endPos, TreeNode rootNode){
TreeNode<BooleanArray> workingNode = rootNode;
if(workingNode.data.data.length <= endPos){
throw new IllegalArgumentException("End position larger than input data");
}
int counter = 0;
int rightBound = endPos;
while(workingNode != null){
if(workingNode.charMap.get(c) == true){
//char c is encoded as 1, count 1es, proceed to right child
for(int i = 0; i < rightBound; ++i){
if(workingNode.data.data[i]){
counter++;
}
}
workingNode = workingNode.rightChild;
} else {
//char c is encoded as 0, count 0es, proceed to left child
for(int i = 0; i < rightBound; ++i){
if(!workingNode.data.data[i]){
counter++;
}
}
workingNode = workingNode.leftChild;
}
rightBound = counter;
counter = 0;
}
return rightBound;
}
@Override
public int select(char c, int boundary, TreeNode rootNode) {
TreeNode<BooleanArray> workingNode = rootNode;
while(true){
if(!workingNode.charMap.get(c)){
//left
if(workingNode.leftChild != null){
workingNode = workingNode.leftChild;
} else {
break;
}
} else {
//right
if(workingNode.rightChild != null){
workingNode = workingNode.rightChild;
} else {
break;
}
}
}
//workingNode now contains leaf with char c
//count 0/1
//parent with same operation count -> previously calculated boundary
int counter = 0;
int newBound = boundary;
int Select = 0;
while(workingNode != null){
if(workingNode.charMap.get(c)){
for(int i = 0; i < workingNode.data.data.length; ++i){
Select++;
if(workingNode.data.data[i]){
counter++;
if(counter == newBound){
break;
}
}
}
} else {
for(int i = 0; i < workingNode.data.data.length; ++i){
Select++;
if(!workingNode.data.data[i]){
counter++;
if(counter == newBound){
break;
}
}
}
}
workingNode = workingNode.parent;
newBound = Select;
counter = 0;
Select = 0;
}
return newBound;
}
@Override
public String toString(){
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < data.length; ++i){
if(data[i]){
stringBuilder.append(1);
} else {
stringBuilder.append(0);
}
}
return stringBuilder.toString();
}
@Override
public boolean equals(Object that){
if(that == null){
return false;
}
if(!(that instanceof BooleanArray)){
return false;
}
BooleanArray thatBooleanArray = (BooleanArray) that;
if(data.length != thatBooleanArray.data.length){
return false;
}
for(int i = 0; i < data.length; ++i){
if(data[i] != thatBooleanArray.data[i]){
return false;
}
}
return true;
}
}
| bpervan/wavelet-rrr | Java1/src/hr/fer/bio/project/booleanarray/BooleanArray.java | Java | mit | 4,405 |
class Solution {
public:
string multiply(string num1, string num2) {
string a, b;
a = num1;
b = num2;
string A, B;
// cout << a;
// cout << b;
int fa = 1;
int fb = 1;
int f = 1;
int lena = 0;
int lenb = 0;
if (a[0] == '-') {
A = a.substr(1, a.size() - 1);
fa = -1;
lena = a.size() - 1;
} else {
A = a;
lena = a.size();
}
if (b[0] == '-') {
B = b.substr(1, b.size() - 1);
fb = -1;
lenb = b.size() - 1;
} else {
B = b;
lenb = b.size();
}
// cout << A << endl;
// cout << B;
f = fa * fb;
int lenmax = max(lena, lenb);
int na[lenmax];
int nb[lenmax];
int i;
int j;
// cout << lenmax<< endl;
for (i = lenmax - 1, j = lena - 1; j >= 0; --i, --j) {
na[i] = A[j] - '0';
// cout << na[i] << endl;
}
while (i >= 0) {
na[i] = 0;
--i;
}
for (i = lenmax - 1, j = lenb - 1; j >= 0; --i, --j) {
nb[i] = B[j] - '0';
// cout << nb[i] << endl;
}
while (i >= 0) {
nb[i] = 0;
--i;
}
int nc[2 * lenmax];
for (i = 0; i < 2 * lenmax; ++i) {
nc[i] = 0;
}
for (i = 0; i < lenmax; ++i) {
for (j = 0; j < lenmax; ++j) {
nc[i + j] += na[lenmax - 1 - i] * nb[lenmax - 1 - j];
}
}
for (i = 0; i < 2 * lenmax - 1; ++i) {
nc[i + 1] += nc[i] / 10;
nc[i] = nc[i] % 10;
}
j = 2 * lenmax - 1;
// cout << j << endl;
while (nc[j] == 0 && j >= 0) {
--j;
if (j == -1) {
break;
}
}
string res;
if (f == -1) {
// printf("-");
res += "-";
}
if (j == -1) {
res += "0";
return res;
} else {
for (i = j; i >= 0; --i) {
// printf("%d",nc[i]);
res += to_string(nc[i]);
}
return res;
}
}
}; | haohaibo/tutorial | leetcode/43.cpp | C++ | mit | 1,994 |
using System;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Threading;
using PropertyChanged;
using WpfTestApp.Tasks;
namespace WpfTestApp.Model
{
public interface IUIModel
{
bool Busy { get; }
void CancelOperations();
CancellationTokenSource CancellationSource { get; }
}
[ImplementPropertyChanged]
public class UIModel : IUIModel
{
[AlsoNotifyFor("SearchEnabled")]
public bool Busy { get; set; }
public ConcurrentBag<string> Logs { get; set; }
[AlsoNotifyFor("SearchEnabled")]
public string Keyword { get; set; }
[AlsoNotifyFor("SearchEnabled")]
public string DirectoryToSearch { get; set; }
public ObservableCollection<Job> CompletedJobs { get; set; }
public JobRunner JobRunner { get; set; }
public CancellationTokenSource CancellationSource { get; private set; }
public int JobCount { get; set; }
public bool HasJobs { get { return JobCount > 0; } }
public bool SearchEnabled
{
get { return !Busy && !String.IsNullOrEmpty(Keyword) && !String.IsNullOrEmpty(DirectoryToSearch); }
}
public UIModel()
{
Logs = new ConcurrentBag<string>();
DirectoryToSearch = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments,
Environment.SpecialFolderOption.DoNotVerify);
CompletedJobs = new ObservableCollection<Job>();
JobRunner = new JobRunner(CompletedJobs, OnProgressCallback, TimeSpan.FromMilliseconds(500));
CancellationSource = new CancellationTokenSource();
JobRunner.CancellationSource = CancellationSource;
}
private void OnProgressCallback(string progress)
{
AddLog(progress);
JobCount = JobRunner.JobCount;
}
[AlsoNotifyFor("Logs")]
private int LogsChanged { get; set; }
public void AddLog(string log)
{
Logs.Add(String.Format("[{0}] {1}", DateTime.Now, log));
LogsChanged++;
}
public void AddLog(string formatString, params object[] args)
{
Logs.Add(String.Format("[{0}]", DateTime.Now));
Logs.Add(String.Format(formatString, args));
LogsChanged++;
}
public void CancelOperations()
{
CancellationSource.Cancel();
JobRunner.Stop();
CancellationSource = new CancellationTokenSource();
}
public void BeginOperations()
{
CancellationSource = new CancellationTokenSource();
JobRunner.CancellationSource = CancellationSource;
JobRunner.Start();
}
}
}
| heiny/wpf-test-app | WpfTestApp/Model/UIModel.cs | C# | mit | 2,914 |
(function() {
'use strict';
angular
.module('tiny-leaflet-directive')
.factory('tldMapService', tldMapService);
tldMapService.$inject = ['tldHelpers'];
function tldMapService(tldHelpers) {
var maps = {};
return {
setMap: setMap,
getMap: getMap,
unresolveMap: unresolveMap
};
function setMap(leafletMap, mapId) {
var defer = tldHelpers.getUnresolvedDefer(maps, mapId);
defer.resolve(leafletMap);
tldHelpers.setResolvedDefer(maps, mapId);
}
function getMap (mapId) {
var defer = tldHelpers.getDefer(maps, mapId);
return defer.promise;
}
function unresolveMap(mapId) {
maps[mapId] = undefined;
}
}
})();
| CleverMaps/tiny-leaflet-directive | src/tldMap.service.js | JavaScript | mit | 824 |
<?php
App::uses('Invoices.InvoicesAppModel', 'Model');
/**
* InvoiceLine model
*
*/
class InvoiceSetting extends InvoicesAppModel {
/**
* Validation rules - initialized in constructor
*
* @var array
*/
public $validate = array();
/**
* Constructor
*
* @param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
* @param string $table Name of database table to use.
* @param string $ds DataSource connection name.
* @return void
*/
public function __construct($id = false, $table = null, $ds = null) {
$this->validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => __d('invoices', 'Please, write a name.'),
'allowEmpty' => false,
'required' => true,
),
),
'value' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => __d('invoices', 'Please, write a value.'),
'allowEmpty' => false,
'required' => true,
),
),
'tag' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => __d('invoices', 'Please, write a tag.'),
'allowEmpty' => false,
'required' => true,
'last' => false
),
'isUnique' => array(
'rule' => array('isUnique'),
'message' => __d('invoices', 'The tag must be unique.'),
)
),
);
parent::__construct($id, $table, $ds);
}
} | occitech/invoices | Model/InvoiceSetting.php | PHP | mit | 1,399 |
using UnityEditor;
using UnityEditor.Callbacks;
namespace Agens.StickersEditor
{
public class StickersBuildPostprocessor
{
[PostProcessBuild(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
if (target != BuildTarget.iOS)
{
return;
}
StickersExport.WriteToProject(pathToBuiltProject);
}
}
}
| agens-no/iMessageStickerUnity | Assets/Stickers/Editor/StickersBuildPostProcess.cs | C# | mit | 445 |
<?php
//
// Copyright (c) 2020-2022 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
defined("XYO_CLOUD") or die("Access is denied");
$this->processModel("set-primary-key-value-one");
$this->processModel("set-ds");
if (!$this->isError()) {
$this->processModel("table-toggle");
};
$this->doRedirect("table-view");
| g-stefan/xyo-cloud | source/site/module/xyo/xyo-app-table/action/table-toggle.php | PHP | mit | 419 |
module Nyaa
module Commands
module Admin
extend Discordrb::Commands::CommandContainer
command(:'bot.kill', help_available: false,
permission_level: 4, permission_message: false) do |event|
event.user.pm "Desligando..."
Nyaa::Database::ModLog.create(
event: :shutdown,
moderator: event.user.distinct,
moderator_id: event.user.id,
server_id: event.server.id
)
exit
end
command(:'bot.reiniciar', help_available: false,
permission_level: 4, permission_message: false) do |event|
event.user.pm "Reiniciando..."
Nyaa::Database::ModLog.create(
event: :restart,
moderator: event.user.distinct,
moderator_id: event.user.id,
server_id: event.server.id
)
exec "#{DIR}/start"
end
command(:'bot.avatar', help_available: false,
permission_level: 4, permission_message: false) do |event, img|
next "\\⚠ :: !bot.avatar [url]" unless img
event.bot.profile.avatar = open(img)
Nyaa::Database::ModLog.create(
event: :avatar,
moderator: event.user.distinct,
moderator_id: event.user.id,
server_id: event.server.id
)
"Avatar alterado!"
end
command(:kick, help_available: false,
permission_level: 2, permission_message: false) do |event, user, *reason|
next "\\⚠ :: !kick [usuário] [razão]" if event.message.mentions.empty? || reason.empty?
# event.server.kick( event.message.mentions.first.on( event.server ) )
user = event.message.mentions.first.on(event.server)
log = Nyaa::Database::Ban.create(
event: :kick,
user: user.distinct,
user_id: user.id,
moderator: event.user.distinct,
moderator_id: event.user.id,
server_id: event.server.id,
reason: reason.join(" ")
)
log.transparency if CONFIG["transparency"]
end
command(:ban, help_available: false,
permission_level: 3, permission_message: false) do |event, user, *reason|
next "\\⚠ :: !ban [usuário] [razão]" if event.message.mentions.empty? || reason.empty?
# event.server.kick( event.message.mentions.first.on( event.server ) )
user = event.message.mentions.first.on(event.server)
log = Nyaa::Database::Ban.create(
event: :ban,
user: user.distinct,
user_id: user.id,
moderator: event.user.distinct,
moderator_id: event.user.id,
server_id: event.server.id,
reason: reason.join(" ")
)
log.transparency if CONFIG["transparency"]
end
end
end
end
| EcchiNyaa/discord-bot | modules/commands/admin/admin.rb | Ruby | mit | 2,816 |
using System;
using System.Collections.Generic;
using System.Linq;
using hw.DebugFormatter;
using hw.Scanner;
using hw.UnitTest;
using Reni;
namespace ReniUI.Test
{
[UnitTest]
[AutoCompleteFunctionInCompound]
public sealed class AutoComplete : DependenceProvider
{
const string text = @"systemdata:
{
Memory: ((0 type *(125)) mutable) instance();
!mutable FreePointer: Memory array_reference mutable;
};
repeat: @ ^ while () then(^ body(), repeat(^));
system:
{
MaxNumber8: @! '7f' to_number_of_base 16.
MaxNumber16: @! '7fff' to_number_of_base 16.
MaxNumber32: @! '7fffffff' to_number_of_base 16.
MaxNumber64: @! '7fffffffffffffff' to_number_of_base 16.
TextItemType: @! MaxNumber8 text_item type.
NewMemory: @
{
result: (((^ elementType) * 1) array_reference mutable)
instance(systemdata FreePointer enable_reinterpretation).
initializer: ^ initializer.
count: ^ count.
!mutable position: count type instance(0).
repeat
(
while: @ position < count,
body: @
(
result(position) := initializer(position),
position :=(position + 1) enable_cut
)
).
systemdata FreePointer :=(systemdata FreePointer type)
instance((result + count) mutable enable_reinterpretation)
}
result
};
system MaxNumber8 + ;
";
[UnitTest]
public void GetDeclarationOptions()
{
var compiler = CompilerBrowser.FromText(text);
for(var offset = 1; offset < text.Length; offset++)
{
var position = compiler.Source + offset;
if((position + -1).Span(2).Id != "\r\n")
{
var t = compiler.DeclarationOptions(offset);
Tracer.Assert(t != null, () => (new Source(text) + offset).Dump());
}
}
}
}
} | hahoyer/reni.cs | src/ReniUIWithForms/Test/AutoComplete.cs | C# | mit | 1,992 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-23 08:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0003_auto_20171221_0336'),
]
operations = [
migrations.AlterField(
model_name='dailyproductivitylog',
name='source',
field=models.CharField(choices=[('api', 'Api'), ('ios', 'Ios'), ('android', 'Android'), ('mobile', 'Mobile'), ('web', 'Web'), ('user_excel', 'User_Excel'), ('text_message', 'Text_Message')], max_length=50),
),
migrations.AlterField(
model_name='sleeplog',
name='source',
field=models.CharField(choices=[('api', 'Api'), ('ios', 'Ios'), ('android', 'Android'), ('mobile', 'Mobile'), ('web', 'Web'), ('user_excel', 'User_Excel'), ('text_message', 'Text_Message')], max_length=50),
),
migrations.AlterField(
model_name='supplementlog',
name='source',
field=models.CharField(choices=[('api', 'Api'), ('ios', 'Ios'), ('android', 'Android'), ('mobile', 'Mobile'), ('web', 'Web'), ('user_excel', 'User_Excel'), ('text_message', 'Text_Message')], default='web', max_length=50),
),
migrations.AlterField(
model_name='useractivitylog',
name='source',
field=models.CharField(choices=[('api', 'Api'), ('ios', 'Ios'), ('android', 'Android'), ('mobile', 'Mobile'), ('web', 'Web'), ('user_excel', 'User_Excel'), ('text_message', 'Text_Message')], default='web', max_length=50),
),
migrations.AlterField(
model_name='usermoodlog',
name='source',
field=models.CharField(choices=[('api', 'Api'), ('ios', 'Ios'), ('android', 'Android'), ('mobile', 'Mobile'), ('web', 'Web'), ('user_excel', 'User_Excel'), ('text_message', 'Text_Message')], default='web', max_length=50),
),
]
| jeffshek/betterself | events/migrations/0004_auto_20171223_0859.py | Python | mit | 1,984 |
using System;
using System.Collections.Generic;
using System.Text;
namespace Vino.Core.TimedTask.Attribute
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class InvokeAttribute : System.Attribute
{
public string Name { set; get; }
public bool IsEnabled { get; set; } = true;
/// <summary>
/// //设置是执行一次(false)还是一直执行(true),默认为true
/// </summary>
public bool AutoReset { set; get; } = true;
public int Interval { get; set; } = 1000 * 60; // 1分钟
public DateTime BeginTime { set; get; }
public DateTime ExpireTime { set; get; }
}
}
| kulend/Vino.Core.TimedTask | source/Vino.Core.TimedTask/Attribute/InvokeAttribute.cs | C# | mit | 710 |
<?php
/**
* Part of Windwalker project Test files.
*
* @copyright Copyright (C) 2019 LYRASOFT Taiwan, Inc.
* @license LGPL-2.0-or-later
*/
declare(strict_types=1);
namespace Windwalker\Filesystem\Test;
use Windwalker\Filesystem\File;
use Windwalker\Filesystem\Path;
/**
* Test class of Path
*
* @since 2.0
*/
class PathTest extends AbstractVfsTestCase
{
/**
* Data provider for testClean() method.
*
* @return array
*
* @since 2.0
*/
public function cleanProvider(): array
{
return [
// Input Path, Directory Separator, Expected Output
'Nothing to do.' => ['/var/www/foo/bar/baz', '/', '/var/www/foo/bar/baz'],
'One backslash.' => ['/var/www/foo\\bar/baz', '/', '/var/www/foo/bar/baz'],
'Two and one backslashes.' => ['/var/www\\\\foo\\bar/baz', '/', '/var/www/foo/bar/baz'],
'Mixed backslashes and double forward slashes.' => [
'/var\\/www//foo\\bar/baz',
'/',
'/var/www/foo/bar/baz',
],
'UNC path.' => ['\\\\www\\docroot', '\\', '\\\\www\\docroot'],
'UNC path with forward slash.' => ['\\\\www/docroot', '\\', '\\\\www\\docroot'],
'UNC path with UNIX directory separator.' => ['\\\\www/docroot', '/', '/www/docroot'],
'Stream URL.' => ['vfs://files//foo\\bar', '/', 'vfs://files/foo/bar'],
'Stream URL empty.' => ['vfs://', '/', 'vfs://'],
'Windows path.' => ['C:\\files\\\\foo//bar', '\\', 'C:\\files\\foo\\bar'],
'Windows path empty.' => ['C:\\', '\\', 'C:\\'],
];
}
/**
* Method to test setPermissions().
*
* @return void
*
* @covers \Windwalker\Filesystem\Path::setPermissions
* @TODO Implement testSetPermissions().
*/
public function testSetPermissions()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* Method to test getPermissions().
*
* @return void
*
* @covers \Windwalker\Filesystem\Path::getPermissions
* @TODO Implement testGetPermissions().
*/
public function testGetPermissions()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* Method to test clean().
*
* @param string $input
* @param string $ds
* @param string $expected
*
* @return void
*
* @covers \Windwalker\Filesystem\Path::clean
*
* @dataProvider cleanProvider
*/
public function testClean(string $input, string $ds, string $expected): void
{
$this->assertEquals(
$expected,
Path::clean($input, $ds)
);
}
/**
* testExistsInsensitive
*
* @param string $path
* @param bool $sExists
* @param bool $iExists
*
* @return void
* @dataProvider existsProvider
*/
public function testExists(string $path, bool $sExists, bool $iExists): void
{
self::assertSame($sExists, Path::exists($path, Path::CASE_SENSITIVE));
self::assertSame($iExists, Path::exists($path, Path::CASE_INSENSITIVE));
}
/**
* existsProvider
*
* @return array
*/
public function existsProvider(): array
{
return [
[
__DIR__ . '/case/Flower/saKura/test.txt',
false,
true,
],
[
__DIR__ . '/case/Flower/saKura/TEST.txt',
true,
true,
],
[
__DIR__ . '/case/Flower/sakura',
false,
true,
],
[
__DIR__ . '/case/Flower/Olive',
false,
false,
],
[
'vfs://root/files',
true,
true,
],
];
}
/**
* testFixCase
*
* @return void
*/
public function testFixCase()
{
$path = __DIR__ . '/case/Flower/saKura/test.txt';
self::assertEquals(Path::clean(__DIR__ . '/case/Flower/saKura/TEST.txt'), Path::fixCase($path));
}
/**
* Method to test stripExtension().
*
* @return void
*/
public function testStripExtension()
{
$name = Path::stripExtension('Wu-la.la');
$this->assertEquals('Wu-la', $name);
$name = Path::stripExtension(__DIR__ . '/Wu-la.la');
$this->assertEquals(__DIR__ . '/Wu-la', $name);
}
/**
* Method to test getExtension().
*
* @return void
*/
public function testGetExtension()
{
$ext = Path::getExtension('Wu-la.la');
$this->assertEquals('la', $ext);
}
/**
* Method to test getFilename().
*
* @return void
*/
public function testGetFilename()
{
$name = Path::getFilename(__DIR__ . '/Wu-la.la');
$this->assertEquals('Wu-la.la', $name);
}
/**
* Provides the data to test the makeSafe method.
*
* @return array
*
* @since 2.0
*/
public function dataTestMakeSafe()
{
return [
[
'windwalker.',
['#^\.#'],
'windwalker',
'There should be no fullstop on the end of a filename',
],
[
'Test w1ndwa1ker_5-1.html',
['#^\.#'],
'Test w1ndwa1ker_5-1.html',
'Alphanumeric symbols, dots, dashes, spaces and underscores should not be filtered',
],
[
'Test w1ndwa1ker_5-1.html',
['#^\.#', '/\s+/'],
'Testw1ndwa1ker_5-1.html',
'Using strip chars parameter here to strip all spaces',
],
[
'windwalker.php!.',
['#^\.#'],
'windwalker.php',
'Non-alphanumeric symbols should be filtered to avoid disguising file extensions',
],
[
'windwalker.php.!',
['#^\.#'],
'windwalker.php',
'Non-alphanumeric symbols should be filtered to avoid disguising file extensions',
],
[
'.gitignore',
[],
'.gitignore',
'Files starting with a fullstop should be allowed when strip chars parameter is empty',
],
];
}
/**
* Method to test makeSafe().
*
* @param string $name The name of the file to test filtering of
* @param array $stripChars Whether to filter spaces out the name or not
* @param string $expected The expected safe file name
* @param string $message The message to show on failure of test
*
* @return void
*
* @dataProvider dataTestMakeSafe
*/
public function testMakeSafe($name, $stripChars, $expected, $message)
{
$this->assertEquals(Path::makeSafe($name, $stripChars), $expected, $message);
}
}
| ventoviro/ww4 | packages/filesystem/test/PathTest.php | PHP | mit | 7,414 |
package org.newdawn.slick.util.pathfinding.navmesh;
import java.util.ArrayList;
/**
* A nav-mesh is a set of shapes that describe the navigation of a map. These
* shapes are linked together allow path finding but without the high
* resolution that tile maps require. This leads to fast path finding and
* potentially much more accurate map definition.
*
* @author kevin
*
*/
public class NavMesh {
/** The list of spaces that build up this navigation mesh */
private ArrayList spaces = new ArrayList();
/**
* Create a new empty mesh
*/
public NavMesh() {
}
/**
* Create a new mesh with a set of spaces
*
* @param spaces The spaces included in the mesh
*/
public NavMesh(ArrayList spaces) {
this.spaces.addAll(spaces);
}
/**
* Get the number of spaces that are in the mesh
*
* @return The spaces in the mesh
*/
public int getSpaceCount() {
return spaces.size();
}
/**
* Get the space at a given index
*
* @param index The index of the space to retrieve
* @return The space at the given index
*/
public Space getSpace(int index) {
return (Space) spaces.get(index);
}
/**
* Add a single space to the mesh
*
* @param space The space to be added
*/
public void addSpace(Space space) {
spaces.add(space);
}
/**
* Find the space at a given location
*
* @param x The x coordinate at which to find the space
* @param y The y coordinate at which to find the space
* @return The space at the given location
*/
public Space findSpace(float x, float y) {
for (int i=0;i<spaces.size();i++) {
Space space = getSpace(i);
if (space.contains(x,y)) {
return space;
}
}
return null;
}
/**
* Find a path from the source to the target coordinates
*
* @param sx The x coordinate of the source location
* @param sy The y coordinate of the source location
* @param tx The x coordinate of the target location
* @param ty The y coordinate of the target location
* @param optimize True if paths should be optimized
* @return The path between the two spaces
*/
public NavPath findPath(float sx, float sy, float tx, float ty, boolean optimize) {
Space source = findSpace(sx,sy);
Space target = findSpace(tx,ty);
if ((source == null) || (target == null)) {
return null;
}
for (int i=0;i<spaces.size();i++) {
((Space) spaces.get(i)).clearCost();
}
target.fill(source,tx, ty, 0);
if (target.getCost() == Float.MAX_VALUE) {
return null;
}
if (source.getCost() == Float.MAX_VALUE) {
return null;
}
NavPath path = new NavPath();
path.push(new Link(sx, sy, null));
if (source.pickLowestCost(target, path)) {
path.push(new Link(tx, ty, null));
if (optimize) {
optimize(path);
}
return path;
}
return null;
}
/**
* Check if a particular path is clear
*
* @param x1 The x coordinate of the starting point
* @param y1 The y coordinate of the starting point
* @param x2 The x coordinate of the ending point
* @param y2 The y coordinate of the ending point
* @param step The size of the step between points
* @return True if there are no blockages along the path
*/
private boolean isClear(float x1, float y1, float x2, float y2, float step) {
float dx = (x2 - x1);
float dy = (y2 - y1);
float len = (float) Math.sqrt((dx*dx)+(dy*dy));
dx *= step;
dx /= len;
dy *= step;
dy /= len;
int steps = (int) (len / step);
for (int i=0;i<steps;i++) {
float x = x1 + (dx*i);
float y = y1 + (dy*i);
if (findSpace(x,y) == null) {
return false;
}
}
return true;
}
/**
* Optimize a path by removing segments that arn't required
* to reach the end point
*
* @param path The path to optimize. Redundant segments will be removed
*/
private void optimize(NavPath path) {
int pt = 0;
while (pt < path.length()-2) {
float sx = path.getX(pt);
float sy = path.getY(pt);
float nx = path.getX(pt+2);
float ny = path.getY(pt+2);
if (isClear(sx,sy,nx,ny,0.1f)) {
path.remove(pt+1);
} else {
pt++;
}
}
}
}
| dxiao/PPBunnies | slick/trunk/Slick/src/org/newdawn/slick/util/pathfinding/navmesh/NavMesh.java | Java | mit | 4,275 |
import aaf
import os
from optparse import OptionParser
parser = OptionParser()
(options, args) = parser.parse_args()
if not args:
parser.error("not enough argements")
path = args[0]
name, ext = os.path.splitext(path)
f = aaf.open(path, 'r')
f.save(name + ".xml")
f.close()
| markreidvfx/pyaaf | example/aaf2xml.py | Python | mit | 281 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../build/styles';
export default class Subtitle extends Component {
static propTypes = {
children: PropTypes.any,
className: PropTypes.string,
size: PropTypes.oneOf([
'is1',
'is2',
'is3',
'is4',
'is5',
'is6',
]),
};
static defaultProps = {
className: '',
};
createClassName() {
return [
styles.subtitle,
styles[this.props.size],
this.props.className,
].join(' ').trim();
}
render() {
return (
<p {...this.props} className={this.createClassName()}>
{this.props.children}
</p>
);
}
}
| bokuweb/re-bulma | src/elements/subtitle.js | JavaScript | mit | 713 |
define(function(require, exports, module) {
var Notify = require('common/bootstrap-notify');
exports.run = function() {
var $form = $("#user-roles-form"),
isTeacher = $form.find('input[value=ROLE_TEACHER]').prop('checked'),
currentUser = $form.data('currentuser'),
editUser = $form.data('edituser');
if (currentUser == editUser) {
$form.find('input[value=ROLE_SUPER_ADMIN]').attr('disabled', 'disabled');
};
$form.find('input[value=ROLE_USER]').on('change', function(){
if ($(this).prop('checked') === false) {
$(this).prop('checked', true);
var user_name = $('#change-user-roles-btn').data('user') ;
Notify.info('用户必须拥有'+user_name+'角色');
}
});
$form.on('submit', function() {
var roles = [];
var $modal = $('#modal');
$form.find('input[name="roles[]"]:checked').each(function(){
roles.push($(this).val());
});
if ($.inArray('ROLE_USER', roles) < 0) {
var user_name = $('#change-user-roles-btn').data('user') ;
Notify.danger('用户必须拥有'+user_name+'角色');
return false;
}
if (isTeacher && $.inArray('ROLE_TEACHER', roles) < 0) {
if (!confirm('取消该用户的教师角色,同时将收回该用户所有教授的课程的教师权限。您真的要这么做吗?')) {
return false;
}
}
$form.find('input[value=ROLE_SUPER_ADMIN]').removeAttr('disabled');
$('#change-user-roles-btn').button('submiting').addClass('disabled');
$.post($form.attr('action'), $form.serialize(), function(html) {
$modal.modal('hide');
Notify.success('用户组保存成功');
var $tr = $(html);
$('#' + $tr.attr('id')).replaceWith($tr);
}).error(function(){
Notify.danger('操作失败');
});
return false;
});
};
}); | smeagonline-developers/OnlineEducationPlatform---SMEAGonline | src/Topxia/AdminBundle/Resources/public/js/controller/user/roles-modal.js | JavaScript | mit | 2,184 |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.SignalR.Hubs
{
/// <summary>
/// The response returned from an incoming hub request.
/// </summary>
public class HubResponse
{
/// <summary>
/// The changes made the the round tripped state.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Type is used for serialization")]
[JsonProperty("S", NullValueHandling = NullValueHandling.Ignore)]
public IDictionary<string, object> State { get; set; }
/// <summary>
/// The result of the invocation.
/// </summary>
[JsonProperty("R", NullValueHandling = NullValueHandling.Ignore)]
public object Result { get; set; }
/// <summary>
/// The id of the operation.
/// </summary>
[JsonProperty("I")]
public string Id { get; set; }
/// <summary>
/// The progress update of the invocation.
/// </summary>
[JsonProperty("P", NullValueHandling = NullValueHandling.Ignore)]
public object Progress { get; set; }
/// <summary>
/// Indicates whether the Error is a see <see cref="HubException"/>.
/// </summary>
[JsonProperty("H", NullValueHandling = NullValueHandling.Ignore)]
public bool? IsHubException { get; set; }
/// <summary>
/// The exception that occurs as a result of invoking the hub method.
/// </summary>
[JsonProperty("E", NullValueHandling = NullValueHandling.Ignore)]
public string Error { get; set; }
/// <summary>
/// The stack logger of the exception that occurs as a result of invoking the hub method.
/// </summary>
[JsonProperty("T", NullValueHandling = NullValueHandling.Ignore)]
public string StackTrace { get; set; }
/// <summary>
/// Extra error data contained in the <see cref="HubException"/>
/// </summary>
[JsonProperty("D", NullValueHandling = NullValueHandling.Ignore)]
public object ErrorData { get; set; }
}
}
| proemmer/webpac | webpac/src/Microsoft.AspNetCore.SignalR.Server/Hubs/HubResponse.cs | C# | mit | 2,396 |
import * as Cookies from 'js-cookie'
import AppSettings from '../appSettings'
import { IFetchResult } from '../interfaces'
import History from './history'
export class HttpUtils {
parseJSON<T> (response: Response): Promise<IFetchResult<T>> {
return new Promise((resolve, reject) => {
if (response.status === 401) {
const location = window.location
History.push(`/account/logout?returnUrl=${encodeURIComponent(location.pathname + location.search)}&logout=true`)
return
} else if (response.status === 403) {
History.push('/account/login?returnUrl=/')
throw { message: 'Access Denied', status: response.status, response }
}
response.text()
.then((text) => {
if (text.length > 0) {
if (!response.ok && response.status === 500) {
try {
const data = JSON.parse(text) as T
resolve({
status: response.status,
ok: response.ok,
data: data
})
} catch {
reject({
ok: false,
status: response.status,
data: {
errorMessage: 'Something has gone wrong on the server!',
configurationData: undefined,
contentData: undefined,
errorMessages: ['Something has gone wrong on the server!'],
errors: {},
rulesExceptionListContainers: []
}
})
}
} else {
resolve({
status: response.status,
ok: response.ok,
data: JSON.parse(text) as T
})
}
} else {
resolve({
status: response.status,
ok: response.ok,
data: {} as T
})
}
})
.catch(err => {
reject(err)
})
})
}
get<T> (url: string): Promise<IFetchResult<T>> {
return this.futchGet(url)
}
post<T, R> (url: string, postData: T): Promise<IFetchResult<R>> {
return this.futch<T, R>(url, 'POST', postData)
}
put<T, R> (url: string, postData: T): Promise<IFetchResult<R>> {
return this.futch<T, R>(url, 'PUT', postData)
}
delete<T, R> (url: string, postData: T): Promise<IFetchResult<R>> {
return this.futch<T, R>(url, 'DELETE', postData)
}
postXhr = (url: string, opts: any, onProgress: any, onComplete: any) => {
return new Promise((res, rej) => {
let xhr = new XMLHttpRequest()
xhr.open(opts.method || 'get', url)
for (let k in opts.headers || {}) {
xhr.setRequestHeader(k, opts.headers[k])
}
xhr.onload = res
xhr.onerror = rej
xhr.onreadystatechange = onComplete
xhr.setRequestHeader('X-CSRF-TOKEN-ARRAGROCMS', this.getCSRFCookie())
if (xhr.upload && onProgress) {
xhr.upload.onprogress = onProgress // event.loaded / event.total * 100 //event.lengthComputable
}
xhr.send(opts.body)
})
}
private getCSRFCookie (): string {
const csrf = Cookies.get('ARRAGROCMSCSRF')
return csrf === undefined ? '' : csrf
}
private futchGet<T> (url: string): Promise<IFetchResult<T>> {
return fetch(url, {
credentials: 'same-origin'
})
.then((response: Response) => this.parseJSON<T>(response))
.catch((error) => {
if (url !== '/api/user/current') {
if (error.data && error.data.errorMessage) {
AppSettings.error(`${error.data.errorMessage} - ${url}`, AppSettings.AlertSettings)
} else if (error.message) {
AppSettings.error(`${error.message} - ${url}`, AppSettings.AlertSettings)
}
}
throw error
})
}
private futch<T, R> (url: string, verb: string, postData: T): Promise<IFetchResult<R>> {
return fetch(url, {
credentials: 'same-origin',
method: verb,
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN-ARRAGROCMS': this.getCSRFCookie()
},
body: JSON.stringify(postData)
})
.then((response: Response) => this.parseJSON<R>(response))
.catch((error) => {
if (error.data && error.data.errorMessage) {
AppSettings.error(`${error.data.errorMessage} - ${url}`, AppSettings.AlertSettings)
} else if (error.message) {
AppSettings.error(`${error.message} - ${url}`, AppSettings.AlertSettings)
}
throw error
})
}
}
const httpUtils = new HttpUtils()
export default httpUtils
| Arragro/ArragroCMS | src/ArragroCMS.Management/ReactAppLibrary/utils/httpUtils.ts | TypeScript | mit | 5,657 |
using System;
namespace System.Windows.Automation
{
///
public static class AutomationProperties
{
#region AutomationId
/// <summary>
/// AutomationId Property
/// </summary>
public static readonly DependencyProperty AutomationIdProperty =
DependencyProperty.RegisterAttached(
"AutomationId",
typeof(string),
typeof(AutomationProperties),
new UIPropertyMetadata(string.Empty),
new ValidateValueCallback(IsNotNull));
/// <summary>
/// Helper for setting AutomationId property on a DependencyObject.
/// </summary>
public static void SetAutomationId(DependencyObject element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(AutomationIdProperty, value);
}
/// <summary>
/// Helper for reading AutomationId property from a DependencyObject.
/// </summary>
public static string GetAutomationId(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((string)element.GetValue(AutomationIdProperty));
}
#endregion AutomationId
#region Name
/// <summary>
/// Name Property
/// </summary>
public static readonly DependencyProperty NameProperty =
DependencyProperty.RegisterAttached(
"Name",
typeof(string),
typeof(AutomationProperties),
new UIPropertyMetadata(string.Empty),
new ValidateValueCallback(IsNotNull));
/// <summary>
/// Helper for setting Name property on a DependencyObject.
/// </summary>
public static void SetName(DependencyObject element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(NameProperty, value);
}
/// <summary>
/// Helper for reading Name property from a DependencyObject.
/// </summary>
public static string GetName(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((string)element.GetValue(NameProperty));
}
#endregion Name
#region HelpText
/// <summary>
/// HelpText Property
/// </summary>
public static readonly DependencyProperty HelpTextProperty =
DependencyProperty.RegisterAttached(
"HelpText",
typeof(string),
typeof(AutomationProperties),
new UIPropertyMetadata(string.Empty),
new ValidateValueCallback(IsNotNull));
/// <summary>
/// Helper for setting HelpText property on a DependencyObject.
/// </summary>
public static void SetHelpText(DependencyObject element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(HelpTextProperty, value);
}
/// <summary>
/// Helper for reading HelpText property from a DependencyObject.
/// </summary>
public static string GetHelpText(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((string)element.GetValue(HelpTextProperty));
}
#endregion HelpText
#region AcceleratorKey
/// <summary>
/// AcceleratorKey Property
/// </summary>
public static readonly DependencyProperty AcceleratorKeyProperty =
DependencyProperty.RegisterAttached(
"AcceleratorKey",
typeof(string),
typeof(AutomationProperties),
new UIPropertyMetadata(string.Empty),
new ValidateValueCallback(IsNotNull));
/// <summary>
/// Helper for setting AcceleratorKey property on a DependencyObject.
/// </summary>
public static void SetAcceleratorKey(DependencyObject element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(AcceleratorKeyProperty, value);
}
/// <summary>
/// Helper for reading AcceleratorKey property from a DependencyObject.
/// </summary>
public static string GetAcceleratorKey(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((string)element.GetValue(AcceleratorKeyProperty));
}
#endregion AcceleratorKey
#region AccessKey
/// <summary>
/// AccessKey Property
/// </summary>
public static readonly DependencyProperty AccessKeyProperty =
DependencyProperty.RegisterAttached(
"AccessKey",
typeof(string),
typeof(AutomationProperties),
new UIPropertyMetadata(string.Empty),
new ValidateValueCallback(IsNotNull));
/// <summary>
/// Helper for setting AccessKey property on a DependencyObject.
/// </summary>
public static void SetAccessKey(DependencyObject element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(AccessKeyProperty, value);
}
/// <summary>
/// Helper for reading AccessKey property from a DependencyObject.
/// </summary>
public static string GetAccessKey(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((string)element.GetValue(AccessKeyProperty));
}
#endregion AccessKey
#region ItemStatus
/// <summary>
/// ItemStatus Property
/// </summary>
public static readonly DependencyProperty ItemStatusProperty =
DependencyProperty.RegisterAttached(
"ItemStatus",
typeof(string),
typeof(AutomationProperties),
new UIPropertyMetadata(string.Empty),
new ValidateValueCallback(IsNotNull));
/// <summary>
/// Helper for setting ItemStatus property on a DependencyObject.
/// </summary>
public static void SetItemStatus(DependencyObject element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ItemStatusProperty, value);
}
/// <summary>
/// Helper for reading ItemStatus property from a DependencyObject.
/// </summary>
public static string GetItemStatus(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((string)element.GetValue(ItemStatusProperty));
}
#endregion ItemStatus
#region ItemType
/// <summary>
/// ItemType Property
/// </summary>
public static readonly DependencyProperty ItemTypeProperty =
DependencyProperty.RegisterAttached(
"ItemType",
typeof(string),
typeof(AutomationProperties),
new UIPropertyMetadata(string.Empty),
new ValidateValueCallback(IsNotNull));
/// <summary>
/// Helper for setting ItemType property on a DependencyObject.
/// </summary>
public static void SetItemType(DependencyObject element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ItemTypeProperty, value);
}
/// <summary>
/// Helper for reading ItemType property from a DependencyObject.
/// </summary>
public static string GetItemType(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((string)element.GetValue(ItemTypeProperty));
}
#endregion ItemType
#region IsColumnHeader
/// <summary>
/// IsColumnHeader Property
/// </summary>
public static readonly DependencyProperty IsColumnHeaderProperty =
DependencyProperty.RegisterAttached(
"IsColumnHeader",
typeof(bool),
typeof(AutomationProperties),
new UIPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox));
/// <summary>
/// Helper for setting IsColumnHeader property on a DependencyObject.
/// </summary>
public static void SetIsColumnHeader(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsColumnHeaderProperty, value);
}
/// <summary>
/// Helper for reading IsColumnHeader property from a DependencyObject.
/// </summary>
public static bool GetIsColumnHeader(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((bool)element.GetValue(IsColumnHeaderProperty));
}
#endregion IsColumnHeader
#region IsRowHeader
/// <summary>
/// IsRowHeader Property
/// </summary>
public static readonly DependencyProperty IsRowHeaderProperty =
DependencyProperty.RegisterAttached(
"IsRowHeader",
typeof(bool),
typeof(AutomationProperties),
new UIPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox));
/// <summary>
/// Helper for setting IsRowHeader property on a DependencyObject.
/// </summary>
public static void SetIsRowHeader(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsRowHeaderProperty, value);
}
/// <summary>
/// Helper for reading IsRowHeader property from a DependencyObject.
/// </summary>
public static bool GetIsRowHeader(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((bool)element.GetValue(IsRowHeaderProperty));
}
#endregion IsRowHeader
#region IsRequiredForForm
/// <summary>
/// IsRequiredForForm Property
/// </summary>
public static readonly DependencyProperty IsRequiredForFormProperty =
DependencyProperty.RegisterAttached(
"IsRequiredForForm",
typeof(bool),
typeof(AutomationProperties),
new UIPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox));
/// <summary>
/// Helper for setting IsRequiredForForm property on a DependencyObject.
/// </summary>
public static void SetIsRequiredForForm(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsRequiredForFormProperty, value);
}
/// <summary>
/// Helper for reading IsRequiredForForm property from a DependencyObject.
/// </summary>
public static bool GetIsRequiredForForm(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((bool)element.GetValue(IsRequiredForFormProperty));
}
#endregion IsRequiredForForm
#region LabeledBy
/// <summary>
/// LabeledBy Property
/// </summary>
public static readonly DependencyProperty LabeledByProperty =
DependencyProperty.RegisterAttached(
"LabeledBy",
typeof(UIElement),
typeof(AutomationProperties),
new UIPropertyMetadata((UIElement)null));
/// <summary>
/// Helper for setting LabeledBy property on a DependencyObject.
/// </summary>
public static void SetLabeledBy(DependencyObject element, UIElement value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(LabeledByProperty, value);
}
/// <summary>
/// Helper for reading LabeledBy property from a DependencyObject.
/// </summary>
public static UIElement GetLabeledBy(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((UIElement)element.GetValue(LabeledByProperty));
}
#endregion LabeledBy
#region IsOffscreenBehavior
/// <summary>
/// IsOffscreenBehavior Property
/// </summary>
public static readonly DependencyProperty IsOffscreenBehaviorProperty =
DependencyProperty.RegisterAttached(
"IsOffscreenBehavior",
typeof(IsOffscreenBehavior),
typeof(AutomationProperties),
new UIPropertyMetadata(IsOffscreenBehavior.Default));
/// <summary>
/// Helper for setting IsOffscreenBehavior property on a DependencyObject.
/// </summary>
public static void SetIsOffscreenBehavior(DependencyObject element, IsOffscreenBehavior value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsOffscreenBehaviorProperty, value);
}
/// <summary>
/// Helper for reading IsOffscreenBehavior property from a DependencyObject.
/// </summary>
public static IsOffscreenBehavior GetIsOffscreenBehavior(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((IsOffscreenBehavior)element.GetValue(IsOffscreenBehaviorProperty));
}
#endregion IsOffscreenBehavior
#region private implementation
// Validation callback for string properties
private static bool IsNotNull(object value)
{
return (value != null);
}
#endregion
}
}
| mind0n/hive | Cache/Libs/net46/wpf/src/Core/CSharp/System/Windows/Automation/AutomationProperties.cs | C# | mit | 16,641 |
package org.sm.jdsa.graph.algorithm.coloring;
import java.util.stream.IntStream;
import org.sm.jdsa.graph.GraphAdjacencyListImpl;
import org.sm.jdsa.list.LinkedList;
import org.sm.jdsa.list.Iterator;
/**
*
* Counts number of colors upper bound for graph (vertex)
* coloring problem using greedy algorithm.
*
* @author Stanislav Markov
*
*/
public class ColoringAdjacentListStrategyImpl implements ColoringStrategy {
private final GraphAdjacencyListImpl graph;
private final int graphSize;
private int colorsUsed;
private final int[] vertexColors;
private final boolean[] adjecentsColors;
int numberOfColors = -1;
public ColoringAdjacentListStrategyImpl(GraphAdjacencyListImpl graph) {
this.graph = graph;
this.graphSize = graph.getGraphSize();
this.colorsUsed = 0;
this.vertexColors = new int[graphSize];
this.adjecentsColors = new boolean[graphSize];
initVertexColors();
}
/**
* Main Method, in charge of counting number of different colors.
* In case it is already calculated it just passes the value
*
* @return
*/
@Override
public int getNumberOfColors() {
if (numberOfColors < 0 && graphSize > 0) {
vertexColors[0] = colorsUsed;
IntStream.range(0, graphSize).forEach(vertex -> {
int leastAvailableColor = getLeastAvailableColor(vertex);
vertexColors[vertex] = leastAvailableColor;
colorsUsed = Math.max(colorsUsed, leastAvailableColor);
});
numberOfColors = colorsUsed + 1;
}
return numberOfColors;
}
/**
* Finds the least available color from vertex's adjacents
*
* @param vertex
* @return
*/
private int getLeastAvailableColor(int vertex) {
loadAdjecentsColors(vertex);
int leastAvailableColor = -1;
int i = 0;
while (leastAvailableColor < 0 && i < adjecentsColors.length) {
if (!adjecentsColors[i]) leastAvailableColor = i;
i++;
}
return leastAvailableColor;
}
/**
* Loads helper array with already taken color by vertex's adjacents
*
* @param vertex
*/
private void loadAdjecentsColors(int vertex) {
resetAdjecentsColors();
LinkedList<Integer> vertexAdjecents = graph.getDataStructure()[vertex];
for (int i = 0; i < adjecentsColors.length; i++) {
}
for(Iterator<Integer> iterator = vertexAdjecents.iterator(); iterator.hasNext();) {
int adjacent = iterator.next();
if (adjacent > -1) {
adjecentsColors[vertexColors[adjacent]] = true;
}
}
}
/*
* Resets helper array used for recording colors
* assigned to the vertex's adjecents for next vertex
*/
private void resetAdjecentsColors() {
IntStream.range(0, graphSize).forEach(color -> adjecentsColors[color] = false);
}
/*
* Initialization of the array which holds colors assigned to verticies
*/
private void initVertexColors() {
IntStream.range(0, graphSize).forEach(vertex -> vertexColors[vertex] = -1);
}
}
| mstane/algorithms-in-java | src/main/java/org/sm/jdsa/graph/algorithm/coloring/ColoringAdjacentListStrategyImpl.java | Java | mit | 2,912 |
import { ModuleWithProviders } from '@angular/core'
import { Routes, RouterModule } from '@angular/router'
//anything not maching a registered URL will go to the login page
const routes: Routes = [
{ path: '**', redirectTo: '/login', pathMatch: 'full' }
]
export const routing: ModuleWithProviders = RouterModule.forRoot(routes)
| Krisa/sftools | src/client/app/app.routing.ts | TypeScript | mit | 334 |
/**
* Test async injectors
*/
import { memoryHistory } from 'react-router';
import { put } from 'redux-saga/effects';
import { fromJS } from 'immutable';
import configureStore from 'store';
import {
injectAsyncReducer,
injectAsyncSagas,
getAsyncInjectors,
} from '../asyncInjectors';
// Fixtures
const initialState = fromJS({ reduced: 'soon' });
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'TEST':
return state.set('reduced', action.payload);
default:
return state;
}
};
function* testSaga() {
yield put({ type: 'TEST', payload: 'yup' });
}
const sagas = [
testSaga,
];
describe('asyncInjectors', () => {
let store;
describe('getAsyncInjectors', () => {
beforeAll(() => {
store = configureStore({}, memoryHistory);
});
it('given a store, should return all async injectors', () => {
const { injectReducer, injectSagas } = getAsyncInjectors(store);
injectReducer('test', reducer);
injectSagas(sagas);
const actual = store.getState().get('test');
const expected = initialState.merge({ reduced: 'yup' });
expect(actual.toJS()).toEqual(expected.toJS());
});
it('should throw if passed invalid store shape', () => {
let result = false;
Reflect.deleteProperty(store, 'dispatch');
try {
getAsyncInjectors(store);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
});
describe('helpers', () => {
beforeAll(() => {
store = configureStore({}, memoryHistory);
});
describe('injectAsyncReducer', () => {
it('given a store, it should provide a function to inject a reducer', () => {
const injectReducer = injectAsyncReducer(store);
injectReducer('test', reducer);
const actual = store.getState().get('test');
const expected = initialState;
expect(actual.toJS()).toEqual(expected.toJS());
});
it('should not assign reducer if already existing', () => {
const injectReducer = injectAsyncReducer(store);
injectReducer('test', reducer);
injectReducer('test', () => {});
expect(store.asyncReducers.test.toString()).toEqual(reducer.toString());
});
it('should throw if passed invalid name', () => {
let result = false;
const injectReducer = injectAsyncReducer(store);
try {
injectReducer('', reducer);
} catch (err) {
result = err.name === 'Invariant Violation';
}
try {
injectReducer(999, reducer);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
it('should throw if passed invalid reducer', () => {
let result = false;
const injectReducer = injectAsyncReducer(store);
try {
injectReducer('bad', 'nope');
} catch (err) {
result = err.name === 'Invariant Violation';
}
try {
injectReducer('coolio', 12345);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
});
describe('injectAsyncSagas', () => {
it('given a store, it should provide a function to inject a saga', () => {
const injectSagas = injectAsyncSagas(store);
injectSagas(sagas);
const actual = store.getState().get('test');
const expected = initialState.merge({ reduced: 'yup' });
expect(actual.toJS()).toEqual(expected.toJS());
});
it('should throw if passed invalid saga', () => {
let result = false;
const injectSagas = injectAsyncSagas(store);
try {
injectSagas({ testSaga });
} catch (err) {
result = err.name === 'Invariant Violation';
}
try {
injectSagas(testSaga);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
});
});
});
| HachiJiang/FamilyFinanceSite | app/utils/tests/asyncInjectors.test.js | JavaScript | mit | 4,871 |
module.exports = function (grunt) {
"use strict";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
// grunt-contrib-clean
clean: {
instrument: "<%= instrument.options.basePath %>"
},
// grunt-contrib-jshint
jshint: {
files: [
"<%= instrument.files %>",
"<%= mochaTest.test.src %>",
"bin/**.js",
"gruntfile.js",
"node_tests/**/*.js"
],
options: grunt.file.readJSON(".jshintrc")
},
// grunt-mocha-test
mochaTest: {
test: {
options: {
reporter: "spec"
},
src: "node_tests/**/*.test.js"
}
},
// grunt-contrib-watch
watch: {
files: ["<%= jshint.files %>"],
tasks: ["beautify", "test"]
},
// grunt-istanbul
instrument: {
files: "node_libs/**/*.js",
options: {
basePath: "coverage/instrument/"
}
},
storeCoverage: {
options: {
dir: "coverage/reports/<%= pkg.version %>"
}
},
makeReport: {
src: "<%= storeCoverage.options.dir %>/*.json",
options: {
type: "lcov",
dir: "<%= storeCoverage.options.dir %>",
print: "detail"
}
},
// grunt-jsbeautifier
jsbeautifier: {
files: ["<%= jshint.files %>"],
options: {
js: grunt.file.readJSON(".jsbeautifyrc")
}
}
});
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-istanbul");
grunt.loadNpmTasks("grunt-jsbeautifier");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.registerTask("register_globals", function (task) {
var moduleRoot;
if ("coverage" === task) {
moduleRoot = __dirname + "/" + grunt.template.process("<%= instrument.options.basePath %>");
} else if ("test" === task) {
moduleRoot = __dirname;
}
global.MODULE_ROOT = moduleRoot;
global.MODULE_ROOT_TESTS = __dirname + "/node_tests";
});
grunt.registerTask("beautify", ["jsbeautifier"]);
grunt.registerTask("cover", ["register_globals:coverage", "clean:instrument", "instrument", "lint", "mochaTest", "storeCoverage", "makeReport"]);
grunt.registerTask("lint", ["jshint"]);
grunt.registerTask("test", ["register_globals:test", "clean:instrument", "lint", "mochaTest"]);
grunt.registerTask("default", ["jsbeautifier", "test"]);
};
| kl3ryk/pouclaige-web-crawler | gruntfile.js | JavaScript | mit | 2,846 |
class ConcernBox
include BlackBox::Concern
subject Hash
accept :a, :b, :c, :d
expose :[], :size
end
| gmcgibbon/black_box | spec/support/integration/concern_box.rb | Ruby | mit | 113 |
const EventEmitter = require('events');
/**
* Ends the session. Uses session protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.end();
* };
*
* @method end
* @syntax .end([callback])
* @param {function} [callback] Optional callback function to be called when the command finishes.
* @see session
* @api protocol.sessions
*/
class End extends EventEmitter {
command(callback) {
const client = this.client;
if (this.api.sessionId) {
this.api.session('delete', result => {
client.session.clearSession();
client.setApiProperty('sessionId', null);
this.complete(callback, result);
});
} else {
setImmediate(() => {
this.complete(callback, null);
});
}
return this.client.api;
}
complete(callback, result) {
if (typeof callback === 'function') {
callback.call(this.api, result);
}
this.emit('complete');
}
}
module.exports = End;
| beatfactor/nightwatch | lib/api/client-commands/end.js | JavaScript | mit | 977 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
//go:generate go run gen.go
// This program generates internet protocol constants and tables by
// reading IANA protocol registries.
package main
import (
"bytes"
"encoding/xml"
"fmt"
"go/format"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
)
var registries = []struct {
url string
parse func(io.Writer, io.Reader) error
}{
{
"http://www.iana.org/assignments/dscp-registry/dscp-registry.xml",
parseDSCPRegistry,
},
{
"http://www.iana.org/assignments/ipv4-tos-byte/ipv4-tos-byte.xml",
parseTOSTCByte,
},
{
"http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml",
parseProtocolNumbers,
},
}
func main() {
var bb bytes.Buffer
fmt.Fprintf(&bb, "// go generate gen.go\n")
fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n")
fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n")
fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"` + "\n\n")
for _, r := range registries {
resp, err := http.Get(r.url)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url)
os.Exit(1)
}
if err := r.parse(&bb, resp.Body); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Fprintf(&bb, "\n")
}
b, err := format.Source(bb.Bytes())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := ioutil.WriteFile("const.go", b, 0644); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func parseDSCPRegistry(w io.Writer, r io.Reader) error {
dec := xml.NewDecoder(r)
var dr dscpRegistry
if err := dec.Decode(&dr); err != nil {
return err
}
drs := dr.escape()
fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated)
fmt.Fprintf(w, "const (\n")
for _, dr := range drs {
fmt.Fprintf(w, "DiffServ%s = %#x", dr.Name, dr.Value)
fmt.Fprintf(w, "// %s\n", dr.OrigName)
}
fmt.Fprintf(w, ")\n")
return nil
}
type dscpRegistry struct {
XMLName xml.Name `xml:"registry"`
Title string `xml:"title"`
Updated string `xml:"updated"`
Note string `xml:"note"`
RegTitle string `xml:"registry>title"`
PoolRecords []struct {
Name string `xml:"name"`
Space string `xml:"space"`
} `xml:"registry>record"`
Records []struct {
Name string `xml:"name"`
Space string `xml:"space"`
} `xml:"registry>registry>record"`
}
type canonDSCPRecord struct {
OrigName string
Name string
Value int
}
func (drr *dscpRegistry) escape() []canonDSCPRecord {
drs := make([]canonDSCPRecord, len(drr.Records))
sr := strings.NewReplacer(
"+", "",
"-", "",
"/", "",
".", "",
" ", "",
)
for i, dr := range drr.Records {
s := strings.TrimSpace(dr.Name)
drs[i].OrigName = s
drs[i].Name = sr.Replace(s)
n, err := strconv.ParseUint(dr.Space, 2, 8)
if err != nil {
continue
}
drs[i].Value = int(n) << 2
}
return drs
}
func parseTOSTCByte(w io.Writer, r io.Reader) error {
dec := xml.NewDecoder(r)
var ttb tosTCByte
if err := dec.Decode(&ttb); err != nil {
return err
}
trs := ttb.escape()
fmt.Fprintf(w, "// %s, Updated: %s\n", ttb.Title, ttb.Updated)
fmt.Fprintf(w, "const (\n")
for _, tr := range trs {
fmt.Fprintf(w, "%s = %#x", tr.Keyword, tr.Value)
fmt.Fprintf(w, "// %s\n", tr.OrigKeyword)
}
fmt.Fprintf(w, ")\n")
return nil
}
type tosTCByte struct {
XMLName xml.Name `xml:"registry"`
Title string `xml:"title"`
Updated string `xml:"updated"`
Note string `xml:"note"`
RegTitle string `xml:"registry>title"`
Records []struct {
Binary string `xml:"binary"`
Keyword string `xml:"keyword"`
} `xml:"registry>record"`
}
type canonTOSTCByteRecord struct {
OrigKeyword string
Keyword string
Value int
}
func (ttb *tosTCByte) escape() []canonTOSTCByteRecord {
trs := make([]canonTOSTCByteRecord, len(ttb.Records))
sr := strings.NewReplacer(
"Capable", "",
"(", "",
")", "",
"+", "",
"-", "",
"/", "",
".", "",
" ", "",
)
for i, tr := range ttb.Records {
s := strings.TrimSpace(tr.Keyword)
trs[i].OrigKeyword = s
ss := strings.Split(s, " ")
if len(ss) > 1 {
trs[i].Keyword = strings.Join(ss[1:], " ")
} else {
trs[i].Keyword = ss[0]
}
trs[i].Keyword = sr.Replace(trs[i].Keyword)
n, err := strconv.ParseUint(tr.Binary, 2, 8)
if err != nil {
continue
}
trs[i].Value = int(n)
}
return trs
}
func parseProtocolNumbers(w io.Writer, r io.Reader) error {
dec := xml.NewDecoder(r)
var pn protocolNumbers
if err := dec.Decode(&pn); err != nil {
return err
}
prs := pn.escape()
prs = append([]canonProtocolRecord{{
Name: "IP",
Descr: "IPv4 encapsulation, pseudo protocol number",
Value: 0,
}}, prs...)
fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated)
fmt.Fprintf(w, "const (\n")
for _, pr := range prs {
if pr.Name == "" {
continue
}
fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value)
s := pr.Descr
if s == "" {
s = pr.OrigName
}
fmt.Fprintf(w, "// %s\n", s)
}
fmt.Fprintf(w, ")\n")
return nil
}
type protocolNumbers struct {
XMLName xml.Name `xml:"registry"`
Title string `xml:"title"`
Updated string `xml:"updated"`
RegTitle string `xml:"registry>title"`
Note string `xml:"registry>note"`
Records []struct {
Value string `xml:"value"`
Name string `xml:"name"`
Descr string `xml:"description"`
} `xml:"registry>record"`
}
type canonProtocolRecord struct {
OrigName string
Name string
Descr string
Value int
}
func (pn *protocolNumbers) escape() []canonProtocolRecord {
prs := make([]canonProtocolRecord, len(pn.Records))
sr := strings.NewReplacer(
"-in-", "in",
"-within-", "within",
"-over-", "over",
"+", "P",
"-", "",
"/", "",
".", "",
" ", "",
)
for i, pr := range pn.Records {
if strings.Contains(pr.Name, "Deprecated") ||
strings.Contains(pr.Name, "deprecated") {
continue
}
prs[i].OrigName = pr.Name
s := strings.TrimSpace(pr.Name)
switch pr.Name {
case "ISIS over IPv4":
prs[i].Name = "ISIS"
case "manet":
prs[i].Name = "MANET"
default:
prs[i].Name = sr.Replace(s)
}
ss := strings.Split(pr.Descr, "\n")
for i := range ss {
ss[i] = strings.TrimSpace(ss[i])
}
if len(ss) > 1 {
prs[i].Descr = strings.Join(ss, " ")
} else {
prs[i].Descr = ss[0]
}
prs[i].Value, _ = strconv.Atoi(pr.Value)
}
return prs
}
| spacexnice/ctlplane | Godeps/_workspace/src/golang.org/x/net/internal/iana/gen.go | GO | mit | 7,845 |
[System.Serializable]
public class Objectives
{
public bool isDone;
public string Requirement;
Objectives()
{
isDone = false;
Requirement = "Objective Display";
}
}
//Possibly split into
//TimedObjective
//ResourceObjective
//BonusObjective | TheFartingFerrets/Prototype_Physics | assets/Scripts/Objectives.cs | C# | mit | 283 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from SimPEG import Mesh, Utils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from scipy.sparse import spdiags,csr_matrix, eye,kron,hstack,vstack,eye,diags
import copy
from scipy.constants import mu_0
from SimPEG import SolverLU
from scipy.sparse.linalg import spsolve,splu
from SimPEG.EM import TDEM
from SimPEG.EM.Analytics.TDEM import hzAnalyticDipoleT,hzAnalyticCentLoopT
from scipy.interpolate import interp2d,LinearNDInterpolator
from scipy.special import ellipk,ellipe
def rectangular_plane_layout(mesh,corner, closed = False,I=1.):
"""
corner: sorted list of four corners (x,y,z)
2--3
| |
1--4
y
|
|--> x
Output:
Js
"""
Jx = np.zeros(mesh.nEx)
Jy = np.zeros(mesh.nEy)
Jz = np.zeros(mesh.nEz)
indy1 = np.logical_and( \
np.logical_and( \
np.logical_and(mesh.gridEy[:,0]>=corner[0,0],mesh.gridEy[:,0]<=corner[1,0]), \
np.logical_and(mesh.gridEy[:,1] >=corner[0,1] , mesh.gridEy[:,1]<=corner[1,1] )),
(mesh.gridEy[:,2] == corner[0,2]
)
)
indx1 = np.logical_and( \
np.logical_and( \
np.logical_and(mesh.gridEx[:,0]>=corner[1,0],mesh.gridEx[:,0]<=corner[2,0]), \
np.logical_and(mesh.gridEx[:,1] >=corner[1,1] , mesh.gridEx[:,1]<=corner[2,1] )),
(mesh.gridEx[:,2] == corner[1,2]
)
)
indy2 = np.logical_and( \
np.logical_and( \
np.logical_and(mesh.gridEy[:,0]>=corner[2,0],mesh.gridEy[:,0]<=corner[3,0]), \
np.logical_and(mesh.gridEy[:,1] <=corner[2,1] , mesh.gridEy[:,1]>=corner[3,1] )),
(mesh.gridEy[:,2] == corner[2,2]
)
)
if closed:
indx2 = np.logical_and( \
np.logical_and( \
np.logical_and(mesh.gridEx[:,0]>=corner[0,0],mesh.gridEx[:,0]<=corner[3,0]), \
np.logical_and(mesh.gridEx[:,1] >=corner[0,1] , mesh.gridEx[:,1]<=corner[3,1] )),
(mesh.gridEx[:,2] == corner[0,2]
)
)
else:
indx2 = []
Jy[indy1] = -I
Jx[indx1] = -I
Jy[indy2] = I
Jx[indx2] = I
J = np.hstack((Jx,Jy,Jz))
J = J*mesh.edge
return J
def BiotSavart(locs,mesh,Js):
"""
Compute the magnetic field generated by current discretized on a mesh using Biot-Savart law
Input:
locs: observation locations
mesh: mesh on which the current J is discretized
Js: discretized source current in A-m (Finite Volume formulation)
Output:
B: magnetic field [Bx,By,Bz]
"""
c = mu_0/(4*np.pi)
nwire = np.sum(Js!=0.)
ind= np.where(Js!=0.)
ind = ind[0]
B = np.zeros([locs.shape[0],3])
gridE = np.vstack([mesh.gridEx,mesh.gridEy,mesh.gridEz])
for i in range(nwire):
# x wire
if ind[i]<mesh.nEx:
r = locs-gridE[ind[i]]
I = Js[ind[i]]*np.hstack([np.ones([locs.shape[0],1]),np.zeros([locs.shape[0],1]),np.zeros([locs.shape[0],1])])
cr = np.cross(I,r)
rsq = np.linalg.norm(r,axis=1)**3.
B = B + c*cr/rsq[:,None]
# y wire
elif ind[i]<mesh.nEx+mesh.nEy:
r = locs-gridE[ind[i]]
I = Js[ind[i]]*np.hstack([np.zeros([locs.shape[0],1]),np.ones([locs.shape[0],1]),np.zeros([locs.shape[0],1])])
cr = np.cross(I,r)
rsq = np.linalg.norm(r,axis=1)**3.
B = B + c*cr/rsq[:,None]
# z wire
elif ind[i]<mesh.nEx+mesh.nEy+mesh.nEz:
r = locs-gridE[ind[i]]
I = Js[ind[i]]*np.hstack([np.zeros([locs.shape[0],1]),np.zeros([locs.shape[0],1]),np.ones([locs.shape[0],1])])
cr = np.cross(I,r)
rsq = np.linalg.norm(r,axis=1)**3.
B = B + c*cr/rsq[:,None]
else:
print('error: index of J out of bounds (number of edges in the mesh)')
return B
def analytic_infinite_wire(obsloc,wireloc,orientation,I=1.):
"""
Compute the response of an infinite wire with orientation 'orientation'
and current I at the obsvervation locations obsloc
Output:
B: magnetic field [Bx,By,Bz]
"""
n,d = obsloc.shape
t,d = wireloc.shape
d = np.sqrt(np.dot(obsloc**2.,np.ones([d,t]))+np.dot(np.ones([n,d]),(wireloc.T)**2.)
- 2.*np.dot(obsloc,wireloc.T))
distr = np.amin(d, axis=1, keepdims = True)
idxmind = d.argmin(axis=1)
r = obsloc - wireloc[idxmind]
orient = np.c_[[orientation for i in range(obsloc.shape[0])]]
B = (mu_0*I)/(2*np.pi*(distr**2.))*np.cross(orientation,r)
return B
def mag_dipole(m,obsloc):
"""
Compute the response of an infinitesimal mag dipole at location (0,0,0)
with orientation X and magnetic moment 'm'
at the obsvervation locations obsloc
Output:
B: magnetic field [Bx,By,Bz]
"""
loc = np.r_[[[0.,0.,0.]]]
n,d = obsloc.shape
t,d = loc.shape
d = np.sqrt(np.dot(obsloc**2.,np.ones([d,t]))+np.dot(np.ones([n,d]),(loc.T)**2.)
- 2.*np.dot(obsloc,loc.T))
d = d.flatten()
ind = np.where(d==0.)
d[ind] = 1e6
x = obsloc[:,0]
y = obsloc[:,1]
z = obsloc[:,2]
#orient = np.c_[[orientation for i in range(obsloc.shape[0])]]
Bz = (mu_0*m)/(4*np.pi*(d**3.))*(3.*((z**2.)/(d**2.))-1.)
By = (mu_0*m)/(4*np.pi*(d**3.))*(3.*(z*y)/(d**2.))
Bx = (mu_0*m)/(4*np.pi*(d**3.))*(3.*(x*z)/(d**2.))
B = np.vstack([Bx,By,Bz]).T
return B
def circularloop(a,obsloc,I=1.):
"""
From Simpson, Lane, Immer, Youngquist 2001
Compute the magnetic field B response of a current loop
of radius 'a' with intensity 'I'.
input:
a: radius in m
obsloc: obsvervation locations
Output:
B: magnetic field [Bx,By,Bz]
"""
x = np.atleast_2d(obsloc[:,0]).T
y = np.atleast_2d(obsloc[:,1]).T
z = np.atleast_2d(obsloc[:,2]).T
r = np.linalg.norm(obsloc,axis=1)
loc = np.r_[[[0.,0.,0.]]]
n,d = obsloc.shape
r2 = x**2.+y**2.+z**2.
rho2 = x**2.+y**2.
alpha2 = a**2.+r2-2*a*np.sqrt(rho2)
beta2 = a**2.+r2+2*a*np.sqrt(rho2)
k2 = 1-(alpha2/beta2)
lbda = x**2.-y**2.
C = mu_0*I/np.pi
Bx = ((C*x*z)/(2*alpha2*np.sqrt(beta2)*rho2))*\
((a**2.+r2)*ellipe(k2)-alpha2*ellipk(k2))
Bx[np.isnan(Bx)] = 0.
By = ((C*y*z)/(2*alpha2*np.sqrt(beta2)*rho2))*\
((a**2.+r2)*ellipe(k2)-alpha2*ellipk(k2))
By[np.isnan(By)] = 0.
Bz = (C/(2.*alpha2*np.sqrt(beta2)))*\
((a**2.-r2)*ellipe(k2)+alpha2*ellipk(k2))
Bz[np.isnan(Bz)] = 0.
#print(Bx.shape)
#print(By.shape)
#print(Bz.shape)
B = np.hstack([Bx,By,Bz])
return B
| geoscixyz/em_examples | em_examples/Loop.py | Python | mit | 6,800 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {concatMap, filter, map} from 'rxjs/operators';
import {HttpHandler} from './backend';
import {HttpContext} from './context';
import {HttpHeaders} from './headers';
import {HttpParams, HttpParamsOptions} from './params';
import {HttpRequest} from './request';
import {HttpEvent, HttpResponse} from './response';
/**
* Constructs an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and
* the given `body`. This function clones the object and adds the body.
*
* Note that the `responseType` *options* value is a String that identifies the
* single data type of the response.
* A single overload version of the method handles each response type.
* The value of `responseType` cannot be a union, as the combined signature could imply.
*
*/
function addBody<T>(
options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
},
body: T|null): any {
return {
body,
headers: options.headers,
context: options.context,
observe: options.observe,
params: options.params,
reportProgress: options.reportProgress,
responseType: options.responseType,
withCredentials: options.withCredentials,
};
}
/**
* Performs HTTP requests.
* This service is available as an injectable class, with methods to perform HTTP requests.
* Each request method has multiple signatures, and the return type varies based on
* the signature that is called (mainly the values of `observe` and `responseType`).
*
* Note that the `responseType` *options* value is a String that identifies the
* single data type of the response.
* A single overload version of the method handles each response type.
* The value of `responseType` cannot be a union, as the combined signature could imply.
*
* @usageNotes
* Sample HTTP requests for the [Tour of Heroes](/tutorial/toh-pt0) application.
*
* ### HTTP Request Example
*
* ```
* // GET heroes whose name contains search term
* searchHeroes(term: string): observable<Hero[]>{
*
* const params = new HttpParams({fromString: 'name=term'});
* return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params});
* }
* ```
*
* Alternatively, the parameter string can be used without invoking HttpParams
* by directly joining to the URL.
* ```
* this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'});
* ```
*
*
* ### JSONP Example
* ```
* requestJsonp(url, callback = 'callback') {
* return this.httpClient.jsonp(this.heroesURL, callback);
* }
* ```
*
* ### PATCH Example
* ```
* // PATCH one of the heroes' name
* patchHero (id: number, heroName: string): Observable<{}> {
* const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42
* return this.httpClient.patch(url, {name: heroName}, httpOptions)
* .pipe(catchError(this.handleError('patchHero')));
* }
* ```
*
* @see [HTTP Guide](guide/http)
* @see [HTTP Request](api/common/http/HttpRequest)
*
* @publicApi
*/
@Injectable()
export class HttpClient {
constructor(private handler: HttpHandler) {}
/**
* Sends an `HttpRequest` and returns a stream of `HttpEvent`s.
*
* @return An `Observable` of the response, with the response body as a stream of `HttpEvent`s.
*/
request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>;
/**
* Constructs a request that interprets the body as an `ArrayBuffer` and returns the response in
* an `ArrayBuffer`.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
*
* @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<ArrayBuffer>;
/**
* Constructs a request that interprets the body as a blob and returns
* the response as a blob.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type `Blob`.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<Blob>;
/**
* Constructs a request that interprets the body as a text string and
* returns a string value.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type string.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<string>;
/**
* Constructs a request that interprets the body as an `ArrayBuffer` and returns the
* the full event stream.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body as an array of `HttpEvent`s for
* the request.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
observe: 'events',
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs a request that interprets the body as a `Blob` and returns
* the full event stream.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body of type `Blob`.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs a request which interprets the body as a text string and returns the full event
* stream.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body of type string.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
/**
* Constructs a request which interprets the body as a JSON object and returns the full event
* stream.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body of type `Object`.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
reportProgress?: boolean, observe: 'events',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<any>>;
/**
* Constructs a request which interprets the body as a JSON object and returns the full event
* stream.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body of type `R`.
*/
request<R>(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
reportProgress?: boolean, observe: 'events',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<R>>;
/**
* Constructs a request which interprets the body as an `ArrayBuffer`
* and returns the full `HttpResponse`.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with the response body as an `ArrayBuffer`.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs a request which interprets the body as a `Blob` and returns the full `HttpResponse`.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with the response body of type `Blob`.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs a request which interprets the body as a text stream and returns the full
* `HttpResponse`.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the HTTP response, with the response body of type string.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
/**
* Constructs a request which interprets the body as a JSON object and returns the full
* `HttpResponse`.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the full `HttpResponse`,
* with the response body of type `Object`.
*/
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
reportProgress?: boolean, observe: 'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
/**
* Constructs a request which interprets the body as a JSON object and returns
* the full `HttpResponse` with the response body in the requested type.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the full `HttpResponse`, with the response body of type `R`.
*/
request<R>(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
reportProgress?: boolean, observe: 'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<R>>;
/**
* Constructs a request which interprets the body as a JSON object and returns the full
* `HttpResponse` as a JSON object.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with the response body of type `Object`.
*/
request(method: string, url: string, options?: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
responseType?: 'json',
reportProgress?: boolean,
withCredentials?: boolean,
}): Observable<Object>;
/**
* Constructs a request which interprets the body as a JSON object
* with the response body of the requested type.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with the response body of type `R`.
*/
request<R>(method: string, url: string, options?: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
responseType?: 'json',
reportProgress?: boolean,
withCredentials?: boolean,
}): Observable<R>;
/**
* Constructs a request where response type and requested observable are not known statically.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the reuested response, wuth body of type `any`.
*/
request(method: string, url: string, options?: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
observe?: 'body'|'events'|'response',
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
}): Observable<any>;
/**
* Constructs an observable for a generic HTTP request that, when subscribed,
* fires the request through the chain of registered interceptors and on to the
* server.
*
* You can pass an `HttpRequest` directly as the only parameter. In this case,
* the call returns an observable of the raw `HttpEvent` stream.
*
* Alternatively you can pass an HTTP method as the first parameter,
* a URL string as the second, and an options hash containing the request body as the third.
* See `addBody()`. In this case, the specified `responseType` and `observe` options determine the
* type of returned observable.
* * The `responseType` value determines how a successful response body is parsed.
* * If `responseType` is the default `json`, you can pass a type interface for the resulting
* object as a type parameter to the call.
*
* The `observe` value determines the return type, according to what you are interested in
* observing.
* * An `observe` value of events returns an observable of the raw `HttpEvent` stream, including
* progress events by default.
* * An `observe` value of response returns an observable of `HttpResponse<T>`,
* where the `T` parameter depends on the `responseType` and any optionally provided type
* parameter.
* * An `observe` value of body returns an observable of `<T>` with the same `T` body type.
*
*/
request(first: string|HttpRequest<any>, url?: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
let req: HttpRequest<any>;
// First, check whether the primary argument is an instance of `HttpRequest`.
if (first instanceof HttpRequest) {
// It is. The other arguments must be undefined (per the signatures) and can be
// ignored.
req = first;
} else {
// It's a string, so it represents a URL. Construct a request based on it,
// and incorporate the remaining arguments (assuming `GET` unless a method is
// provided.
// Figure out the headers.
let headers: HttpHeaders|undefined = undefined;
if (options.headers instanceof HttpHeaders) {
headers = options.headers;
} else {
headers = new HttpHeaders(options.headers);
}
// Sort out parameters.
let params: HttpParams|undefined = undefined;
if (!!options.params) {
if (options.params instanceof HttpParams) {
params = options.params;
} else {
params = new HttpParams({fromObject: options.params} as HttpParamsOptions);
}
}
// Construct the request.
req = new HttpRequest(first, url!, (options.body !== undefined ? options.body : null), {
headers,
context: options.context,
params,
reportProgress: options.reportProgress,
// By default, JSON is assumed to be returned for all calls.
responseType: options.responseType || 'json',
withCredentials: options.withCredentials,
});
}
// Start with an Observable.of() the initial request, and run the handler (which
// includes all interceptors) inside a concatMap(). This way, the handler runs
// inside an Observable chain, which causes interceptors to be re-run on every
// subscription (this also makes retries re-run the handler, including interceptors).
const events$: Observable<HttpEvent<any>> =
of(req).pipe(concatMap((req: HttpRequest<any>) => this.handler.handle(req)));
// If coming via the API signature which accepts a previously constructed HttpRequest,
// the only option is to get the event stream. Otherwise, return the event stream if
// that is what was requested.
if (first instanceof HttpRequest || options.observe === 'events') {
return events$;
}
// The requested stream contains either the full response or the body. In either
// case, the first step is to filter the event stream to extract a stream of
// responses(s).
const res$: Observable<HttpResponse<any>> = <Observable<HttpResponse<any>>>events$.pipe(
filter((event: HttpEvent<any>) => event instanceof HttpResponse));
// Decide which stream to return.
switch (options.observe || 'body') {
case 'body':
// The requested stream is the body. Map the response stream to the response
// body. This could be done more simply, but a misbehaving interceptor might
// transform the response body into a different format and ignore the requested
// responseType. Guard against this by validating that the response is of the
// requested type.
switch (req.responseType) {
case 'arraybuffer':
return res$.pipe(map((res: HttpResponse<any>) => {
// Validate that the body is an ArrayBuffer.
if (res.body !== null && !(res.body instanceof ArrayBuffer)) {
throw new Error('Response is not an ArrayBuffer.');
}
return res.body;
}));
case 'blob':
return res$.pipe(map((res: HttpResponse<any>) => {
// Validate that the body is a Blob.
if (res.body !== null && !(res.body instanceof Blob)) {
throw new Error('Response is not a Blob.');
}
return res.body;
}));
case 'text':
return res$.pipe(map((res: HttpResponse<any>) => {
// Validate that the body is a string.
if (res.body !== null && typeof res.body !== 'string') {
throw new Error('Response is not a string.');
}
return res.body;
}));
case 'json':
default:
// No validation needed for JSON responses, as they can be of any type.
return res$.pipe(map((res: HttpResponse<any>) => res.body));
}
case 'response':
// The response stream was requested directly, so return it.
return res$;
default:
// Guard against new future observe types being added.
throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);
}
}
/**
* Constructs a `DELETE` request that interprets the body as an `ArrayBuffer`
* and returns the response as an `ArrayBuffer`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response body as an `ArrayBuffer`.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
body?: any|null,
}): Observable<ArrayBuffer>;
/**
* Constructs a `DELETE` request that interprets the body as a `Blob` and returns
* the response as a `Blob`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response body as a `Blob`.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
body?: any|null,
}): Observable<Blob>;
/**
* Constructs a `DELETE` request that interprets the body as a text string and returns
* a string.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type string.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
body?: any|null,
}): Observable<string>;
/**
* Constructs a `DELETE` request that interprets the body as an `ArrayBuffer`
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with response body as an `ArrayBuffer`.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
body?: any|null
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs a `DELETE` request that interprets the body as a `Blob`
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all the `HttpEvent`s for the request, with the response body as a
* `Blob`.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs a `DELETE` request that interprets the body as a text string
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request, with the response
* body of type string.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpEvent<string>>;
/**
* Constructs a `DELETE` request that interprets the body as a JSON object
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request, with response body of
* type `Object`.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpEvent<Object>>;
/**
* Constructs a `DELETE`request that interprets the body as a JSON object
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all the `HttpEvent`s for the request, with a response
* body in the requested type.
*/
delete<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | (string | number | boolean)[]},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpEvent<T>>;
/**
* Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` and returns
* the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the full `HttpResponse`, with the response body as an `ArrayBuffer`.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs a `DELETE` request that interprets the body as a `Blob` and returns the full
* `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with the response body of type `Blob`.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs a `DELETE` request that interprets the body as a text stream and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the full `HttpResponse`, with the response body of type string.
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpResponse<string>>;
/**
* Constructs a `DELETE` request the interprets the body as a JSON object and returns
* the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with the response body of type `Object`.
*
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpResponse<Object>>;
/**
* Constructs a `DELETE` request that interprets the body as a JSON object
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with the response body of the requested type.
*/
delete<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
body?: any|null,
}): Observable<HttpResponse<T>>;
/**
* Constructs a `DELETE` request that interprets the body as a JSON object and
* returns the response body as a JSON object.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type `Object`.
*/
delete(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
body?: any|null,
}): Observable<Object>;
/**
* Constructs a DELETE request that interprets the body as a JSON object and returns
* the response in a given type.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with response body in the requested type.
*/
delete<T>(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
body?: any|null,
}): Observable<T>;
/**
* Constructs an observable that, when subscribed, causes the configured
* `DELETE` request to execute on the server. See the individual overloads for
* details on the return type.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
*/
delete(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
body?: any|null,
} = {}): Observable<any> {
return this.request<any>('DELETE', url, options as any);
}
/**
* Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the
* response in an `ArrayBuffer`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<ArrayBuffer>;
/**
* Constructs a `GET` request that interprets the body as a `Blob`
* and returns the response as a `Blob`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body as a `Blob`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<Blob>;
/**
* Constructs a `GET` request that interprets the body as a text string
* and returns the response as a string value.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type string.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<string>;
/**
* Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns
* the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request, with the response
* body as an `ArrayBuffer`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs a `GET` request that interprets the body as a `Blob` and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body as a `Blob`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs a `GET` request that interprets the body as a text string and returns
* the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type string.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
/**
* Constructs a `GET` request that interprets the body as a JSON object
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type `Object`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
/**
* Constructs a `GET` request that interprets the body as a JSON object and returns the full event
* stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with a response body in the requested type.
*/
get<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
/**
* Constructs a `GET` request that interprets the body as an `ArrayBuffer` and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as an `ArrayBuffer`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs a `GET` request that interprets the body as a `Blob` and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as a `Blob`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs a `GET` request that interprets the body as a text stream and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body of type string.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
/**
* Constructs a `GET` request that interprets the body as a JSON object and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the full `HttpResponse`,
* with the response body of type `Object`.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
/**
* Constructs a `GET` request that interprets the body as a JSON object and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the full `HttpResponse` for the request,
* with a response body in the requested type.
*/
get<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
/**
* Constructs a `GET` request that interprets the body as a JSON object and
* returns the response body as a JSON object.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
*
* @return An `Observable` of the response body as a JSON object.
*/
get(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
/**
* Constructs a `GET` request that interprets the body as a JSON object and returns
* the response body in a given type.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse`, with a response body in the requested type.
*/
get<T>(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an observable that, when subscribed, causes the configured
* `GET` request to execute on the server. See the individual overloads for
* details on the return type.
*/
get(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('GET', url, options as any);
}
/**
* Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` and
* returns the response as an `ArrayBuffer`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<ArrayBuffer>;
/**
* Constructs a `HEAD` request that interprets the body as a `Blob` and returns
* the response as a `Blob`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body as a `Blob`.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<Blob>;
/**
* Constructs a `HEAD` request that interprets the body as a text string and returns the response
* as a string value.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body of type string.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<string>;
/**
* Constructs a `HEAD` request that interprets the body as an `ArrayBuffer`
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body as an `ArrayBuffer`.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs a `HEAD` request that interprets the body as a `Blob` and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body as a `Blob`.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs a `HEAD` request that interprets the body as a text string
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request, with the response body of type
* string.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
/**
* Constructs a `HEAD` request that interprets the body as a JSON object
* and returns the full HTTP event stream.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request, with a response body of
* type `Object`.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
/**
* Constructs a `HEAD` request that interprets the body as a JSON object and
* returns the full event stream.
*
* @return An `Observable` of all the `HttpEvent`s for the request,
* with a response body in the requested type.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*/
head<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
/**
* Constructs a `HEAD` request that interprets the body as an `ArrayBuffer`
* and returns the full HTTP response.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as an `ArrayBuffer`.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs a `HEAD` request that interprets the body as a `Blob` and returns
* the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as a blob.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs a `HEAD` request that interprets the body as text stream
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body of type string.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
/**
* Constructs a `HEAD` request that interprets the body as a JSON object and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body of type `Object`.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
/**
* Constructs a `HEAD` request that interprets the body as a JSON object
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a responmse body of the requested type.
*/
head<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
/**
* Constructs a `HEAD` request that interprets the body as a JSON object and
* returns the response body as a JSON object.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the response, with the response body as a JSON object.
*/
head(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
/**
* Constructs a `HEAD` request that interprets the body as a JSON object and returns
* the response in a given type.
*
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body of the given type.
*/
head<T>(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an observable that, when subscribed, causes the configured
* `HEAD` request to execute on the server. The `HEAD` method returns
* meta information about the resource without transferring the
* resource itself. See the individual overloads for
* details on the return type.
*/
head(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('HEAD', url, options as any);
}
/**
* Constructs a `JSONP` request for the given URL and name of the callback parameter.
*
* @param url The resource URL.
* @param callbackParam The callback function name.
*
* @return An `Observable` of the response object, with response body as an object.
*/
jsonp(url: string, callbackParam: string): Observable<Object>;
/**
* Constructs a `JSONP` request for the given URL and name of the callback parameter.
*
* @param url The resource URL.
* @param callbackParam The callback function name.
*
* You must install a suitable interceptor, such as one provided by `HttpClientJsonpModule`.
* If no such interceptor is reached,
* then the `JSONP` request can be rejected by the configured backend.
*
* @return An `Observable` of the response object, with response body in the requested type.
*/
jsonp<T>(url: string, callbackParam: string): Observable<T>;
/**
* Constructs an `Observable` that, when subscribed, causes a request with the special method
* `JSONP` to be dispatched via the interceptor pipeline.
* The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain
* API endpoints that don't support newer,
* and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol.
* JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the
* requests even if the API endpoint is not located on the same domain (origin) as the client-side
* application making the request.
* The endpoint API must support JSONP callback for JSONP requests to work.
* The resource API returns the JSON response wrapped in a callback function.
* You can pass the callback function name as one of the query parameters.
* Note that JSONP requests can only be used with `GET` requests.
*
* @param url The resource URL.
* @param callbackParam The callback function name.
*
*/
jsonp<T>(url: string, callbackParam: string): Observable<T> {
return this.request<any>('JSONP', url, {
params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'),
observe: 'body',
responseType: 'json',
});
}
/**
* Constructs an `OPTIONS` request that interprets the body as an
* `ArrayBuffer` and returns the response as an `ArrayBuffer`.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<ArrayBuffer>;
/**
* Constructs an `OPTIONS` request that interprets the body as a `Blob` and returns
* the response as a `Blob`.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body as a `Blob`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<Blob>;
/**
* Constructs an `OPTIONS` request that interprets the body as a text string and
* returns a string value.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body of type string.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<string>;
/**
* Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer`
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body as an `ArrayBuffer`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a `Blob` and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body as a `Blob`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a text string
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request,
* with the response body of type string.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a JSON object
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request with the response
* body of type `Object`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a JSON object and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request,
* with a response body in the requested type.
*/
options<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
/**
* Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer`
* and returns the full HTTP response.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as an `ArrayBuffer`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a `Blob`
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as a `Blob`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs an `OPTIONS` request that interprets the body as text stream
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body of type string.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a JSON object
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body of type `Object`.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a JSON object and
* returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body in the requested type.
*/
options<T>(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
/**
* Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the
* response body as a JSON object.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body as a JSON object.
*/
options(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
/**
* Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the
* response in a given type.
*
* @param url The endpoint URL.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse`, with a response body of the given type.
*/
options<T>(url: string, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` that, when subscribed, causes the configured
* `OPTIONS` request to execute on the server. This method allows the client
* to determine the supported HTTP methods and other capabilites of an endpoint,
* without implying a resource action. See the individual overloads for
* details on the return type.
*/
options(url: string, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('OPTIONS', url, options as any);
}
/**
* Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and returns
* the response as an `ArrayBuffer`.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<ArrayBuffer>;
/**
* Constructs a `PATCH` request that interprets the body as a `Blob` and returns the response
* as a `Blob`.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body as a `Blob`.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<Blob>;
/**
* Constructs a `PATCH` request that interprets the body as a text string and
* returns the response as a string value.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the response, with a response body of type string.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<string>;
/**
* Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request,
* with the response body as an `ArrayBuffer`.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs a `PATCH` request that interprets the body as a `Blob`
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request, with the
* response body as `Blob`.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs a `PATCH` request that interprets the body as a text string and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request, with a
* response body of type string.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
/**
* Constructs a `PATCH` request that interprets the body as a JSON object
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request,
* with a response body of type `Object`.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
/**
* Constructs a `PATCH` request that interprets the body as a JSON object
* and returns the full event stream.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of all the `HttpEvent`s for the request,
* with a response body in the requested type.
*/
patch<T>(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
/**
* Constructs a `PATCH` request that interprets the body as an `ArrayBuffer`
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as an `ArrayBuffer`.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs a `PATCH` request that interprets the body as a `Blob` and returns the full
* `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as a `Blob`.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs a `PATCH` request that interprets the body as a text stream and returns the
* full `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body of type string.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
/**
* Constructs a `PATCH` request that interprets the body as a JSON object
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body in the requested type.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
/**
* Constructs a `PATCH` request that interprets the body as a JSON object
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body in the given type.
*/
patch<T>(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
/**
* Constructs a `PATCH` request that interprets the body as a JSON object and
* returns the response body as a JSON object.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body as a JSON object.
*/
patch(url: string, body: any|null, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
/**
* Constructs a `PATCH` request that interprets the body as a JSON object
* and returns the response in a given type.
*
* @param url The endpoint URL.
* @param body The resources to edit.
* @param options HTTP options.
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body in the given type.
*/
patch<T>(url: string, body: any|null, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an observable that, when subscribed, causes the configured
* `PATCH` request to execute on the server. See the individual overloads for
* details on the return type.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('PATCH', url, addBody(options, body));
}
/**
* Constructs a `POST` request that interprets the body as an `ArrayBuffer` and returns
* an `ArrayBuffer`.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options.
*
* @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<ArrayBuffer>;
/**
* Constructs a `POST` request that interprets the body as a `Blob` and returns the
* response as a `Blob`.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the response, with the response body as a `Blob`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<Blob>;
/**
* Constructs a `POST` request that interprets the body as a text string and
* returns the response as a string value.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the response, with a response body of type string.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<string>;
/**
* Constructs a `POST` request that interprets the body as an `ArrayBuffer` and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body as an `ArrayBuffer`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs a `POST` request that interprets the body as a `Blob`
* and returns the response in an observable of the full event stream.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request, with the response body as `Blob`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs a `POST` request that interprets the body as a text string and returns the full
* event stream.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with a response body of type string.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
/**
* Constructs a POST request that interprets the body as a JSON object and returns the full event
* stream.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with a response body of type `Object`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
/**
* Constructs a POST request that interprets the body as a JSON object and returns the full event
* stream.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with a response body in the requested type.
*/
post<T>(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
/**
* Constructs a POST request that interprets the body as an `ArrayBuffer`
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request, with the response body as an
* `ArrayBuffer`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs a `POST` request that interprets the body as a `Blob` and returns the full
* `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as a `Blob`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs a `POST` request that interprets the body as a text stream and returns
* the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body of type string.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
/**
* Constructs a `POST` request that interprets the body as a JSON object
* and returns the full `HttpResponse`.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request, with a response body of type
* `Object`.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
/**
* Constructs a `POST` request that interprets the body as a JSON object and returns the full
* `HttpResponse`.
*
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request, with a response body in the
* requested type.
*/
post<T>(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
/**
* Constructs a `POST` request that interprets the body as a
* JSON object and returns the response body as a JSON object.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the response, with the response body as a JSON object.
*/
post(url: string, body: any|null, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
/**
* Constructs a `POST` request that interprets the body as a JSON object
* and returns an observable of the response.
*
* @param url The endpoint URL.
* @param body The content to replace with.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request, with a response body in the
* requested type.
*/
post<T>(url: string, body: any|null, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an observable that, when subscribed, causes the configured
* `POST` request to execute on the server. The server responds with the location of
* the replaced resource. See the individual overloads for
* details on the return type.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('POST', url, addBody(options, body));
}
/**
* Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and returns the
* response as an `ArrayBuffer`.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<ArrayBuffer>;
/**
* Constructs a `PUT` request that interprets the body as a `Blob` and returns
* the response as a `Blob`.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the response, with the response body as a `Blob`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<Blob>;
/**
* Constructs a `PUT` request that interprets the body as a text string and
* returns the response as a string value.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the response, with a response body of type string.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<string>;
/**
* Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and
* returns the full event stream.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body as an `ArrayBuffer`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
/**
* Constructs a `PUT` request that interprets the body as a `Blob` and returns the full event
* stream.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body as a `Blob`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
/**
* Constructs a `PUT` request that interprets the body as a text string and returns the full event
* stream.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request, with a response body
* of type string.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
/**
* Constructs a `PUT` request that interprets the body as a JSON object and returns the full event
* stream.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request, with a response body of
* type `Object`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
/**
* Constructs a `PUT` request that interprets the body as a JSON object and returns the
* full event stream.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with a response body in the requested type.
*/
put<T>(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
/**
* Constructs a `PUT` request that interprets the body as an
* `ArrayBuffer` and returns an observable of the full HTTP response.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request, with the response body as an
* `ArrayBuffer`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'arraybuffer',
withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
/**
* Constructs a `PUT` request that interprets the body as a `Blob` and returns the
* full HTTP response.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request,
* with the response body as a `Blob`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'blob',
withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
/**
* Constructs a `PUT` request that interprets the body as a text stream and returns the
* full HTTP response.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request, with a response body of type
* string.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean, responseType: 'text',
withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
/**
* Constructs a `PUT` request that interprets the body as a JSON object and returns the full HTTP
* response.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request, with a response body
* of type 'Object`.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
/**
* Constructs a `PUT` request that interprets the body as an instance of the requested type and
* returns the full HTTP response.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the `HttpResponse` for the request,
* with a response body in the requested type.
*/
put<T>(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response',
context?: HttpContext,
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
/**
* Constructs a `PUT` request that interprets the body as a JSON object
* and returns an observable of JSON object.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the response as a JSON object.
*/
put(url: string, body: any|null, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
/**
* Constructs a `PUT` request that interprets the body as an instance of the requested type
* and returns an observable of the requested type.
*
* @param url The endpoint URL.
* @param body The resources to add/update.
* @param options HTTP options
*
* @return An `Observable` of the requested type.
*/
put<T>(url: string, body: any|null, options?: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an observable that, when subscribed, causes the configured
* `PUT` request to execute on the server. The `PUT` method replaces an existing resource
* with a new set of values.
* See the individual overloads for details on the return type.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders|{[header: string]: string | string[]},
context?: HttpContext,
observe?: 'body'|'events'|'response',
params?: HttpParams|
{[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('PUT', url, addBody(options, body));
}
}
| mgechev/angular | packages/common/http/src/client.ts | TypeScript | mit | 108,596 |
<?php
include("../core/init.php");
require_once("../class/Mail.php");
$flag=true;
$id_user = addslashes($_POST['id_user']);
$res = $mysqli->query("SELECT nom, prenom, identifiant, id_classe FROM fc_user WHERE id_user = '$id_user'");
if(mysqli_num_rows($res) > 0){
$tab=$res->fetch_assoc();
$nom = stripslashes($tab['nom']);
$prenom = stripslashes($tab['prenom']);
$identifiant = stripslashes($tab['identifiant']);
$id_classe = stripslashes($tab['id_classe']);
mysqli_free_result($res);
$res_classe= $mysqli->query("SELECT referent, identifiant, niveau, barette, classe FROM fc_classe, fc_user WHERE fc_classe.id_classe = '$id_classe' AND id_user = referent");
if(mysqli_num_rows($res_classe) > 0){
$tab_classe=$res_classe->fetch_assoc();
mysqli_free_result($res_classe);
$identifiant_ref = $tab_classe['identifiant'];
$id_user_ref = $tab_classe['referent'];
$niveau=$tab_classe['niveau'];
$barette=$tab_classe['barette'];
$classe=$tab_classe['classe'];
$classe = $niveau." ".$barette." ".$classe;
$date_message=time();
$message = "L'utilisateur n°".$id_user." souhaite supprimer son compte.<br>Veuillez vous rendre dans l'espace d'administration de FreeCademy afin de procéder à l'opération.";
$message= addslashes(str_replace("<br>", "\n\r", utf8_decode($message)));
$insert = $mysqli->query("INSERT INTO fc_user_message VALUES ('', 2, '$id_user_ref', 1, '$message', '$date_message')");
$bcc='';
$cc='';
$to="Freecademy Contact utilisateurs <$identifiant_ref>";
$tab_banished_IP=array("222.77.83.226","222.77.83.231");
if(!preg_match("#http#",$email) && !in_array($_SERVER['REMOTE_ADDR'],$tab_banished_IP)){
$message="Identité du contact :
Nom : ".utf8_decode($nom)."
Prénom : ".utf8_decode($prenom)."
Classe : ".utf8_decode($classe)."
Email : ".utf8_decode($identifiant)."
Message :
".utf8_decode($message);
$file_name=array();
$object="=?iso-8859-1?B?".base64_encode((stripslashes("[Freecademy] ".$objet)))."?=";
$sendMe=send_mail($email,$to,$cc,$bcc,$message,$objet,$file_name,$path_dep="");
if($insert && $sendMe){
$flag=true;
}
}else{
$flag=false;
}
}else {
$flag=false;
}
}
if($flag){
echo "1";
}else{
echo "0";
}
$mysqli->close();
?> | guillaumfloki/freecademy | ajax/demande_suppr_compte.php | PHP | mit | 2,246 |
namespace MealsToday.MVC.Providers.DBModels
{
public class UserInserted
{
public int UserId { get; set; }
public string Email { get; set; }
}
} | spsei-programming/Homeworks | Data loading and saving/Projects/MealsToday.MVC/MealsToday.MVC.Providers/DBModels/UserInserted.cs | C# | mit | 153 |
<?php
/*
* This file is part of Sulu.
*
* (c) MASSIVE ART WebServices GmbH
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Sulu\Bundle\SecurityBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Sulu\Bundle\SecurityBundle\Entity\SecurityType;
use Symfony\Component\DependencyInjection\ContainerAware;
class LoadSecurityTypes extends ContainerAware implements FixtureInterface, OrderedFixtureInterface
{
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
// force id = 1
$metadata = $manager->getClassMetaData(get_class(new SecurityType()));
$metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
$file = $this->container->getParameter('sulu_security.security_types.fixture');
$doc = new \DOMDocument();
$doc->load($file);
$xpath = new \DOMXpath($doc);
$elements = $xpath->query('/security-types/security-type');
if (!is_null($elements)) {
/** @var $element \DOMNode */
foreach ($elements as $element) {
$securityType = new SecurityType();
$children = $element->childNodes;
/** @var $child \DOMNode */
foreach ($children as $child) {
if (isset($child->nodeName)) {
if ($child->nodeName == 'id') {
$securityType->setId($child->nodeValue);
}
if ($child->nodeName == 'name') {
$securityType->setName($child->nodeValue);
}
}
}
$manager->persist($securityType);
}
}
$manager->flush();
}
/**
* {@inheritdoc}
*/
public function getOrder()
{
return 5;
}
}
| fahadonline/sulu | vendor/sulu/sulu/src/Sulu/Bundle/SecurityBundle/DataFixtures/ORM/LoadSecurityTypes.php | PHP | mit | 2,098 |
package com.voxelgameslib.voxelgameslib.api.feature.features;
import com.google.gson.annotations.Expose;
import java.util.Arrays;
import javax.annotation.Nonnull;
import com.voxelgameslib.voxelgameslib.api.event.GameEvent;
import com.voxelgameslib.voxelgameslib.api.feature.AbstractFeature;
import com.voxelgameslib.voxelgameslib.api.feature.FeatureInfo;
import org.bukkit.Material;
import org.bukkit.event.block.BlockBreakEvent;
@FeatureInfo(name = "NoBlockBreakFeature", author = "MiniDigger", version = "1.0",
description = "Small feature that blocks block breaking if active")
public class NoBlockBreakFeature extends AbstractFeature {
@Expose
private Material[] whitelist = new Material[0];
@Expose
private Material[] blacklist = new Material[0];
/**
* Sets the list with whitelisted materials. Enabling the whitelist means that ppl are allowed to break only
* materials which are on the whitelist. to disabled the whitelist, pass an empty array.
*
* @param whitelist the new whitelist
*/
public void setWhitelist(@Nonnull Material[] whitelist) {
this.whitelist = whitelist;
}
/**
* Sets the list with blacklisted materials. Enabling the blacklist means that ppl are allowed to break every
* material other than those on the blacklist. to disabled the blacklist, pass an empty array
*
* @param blacklist the new blacklist
*/
public void setBlacklist(@Nonnull Material[] blacklist) {
this.blacklist = blacklist;
}
@SuppressWarnings({"JavaDoc", "Duplicates"})
@GameEvent
public void onBlockBreak(@Nonnull BlockBreakEvent event) {
if (blacklist.length != 0) {
if (Arrays.stream(blacklist).anyMatch(m -> m.equals(event.getBlock().getType()))) {
event.setCancelled(true);
}
} else if (whitelist.length != 0) {
if (Arrays.stream(whitelist).noneMatch(m -> m.equals(event.getBlock().getType()))) {
event.setCancelled(true);
}
} else {
event.setCancelled(true);
}
}
}
| VoxelGamesLib/VoxelGamesLibv2 | VoxelGamesLib/src/main/java/com/voxelgameslib/voxelgameslib/api/feature/features/NoBlockBreakFeature.java | Java | mit | 2,127 |
<?php
class Gestor_Tiendas_Model extends CI_Model
{
private $fileName;
private $xmlProductos;
public function __construct() {
parent::__construct();
}
/**
* Carga los datos de la tienda seleccionada
* @param type $nombreTienda
*/
public function Load($nombreTienda)
{
// Guardaremos la información en un fichero en formato JSON
$this->fileName=__DIR__.'/'.$nombreTienda.'.xml';
$this->xmlProductos=
new SimpleXMLElement(file_get_contents($this->fileName));
}
public function Total()
{
return count($this->xmlProductos);
}
/**
* Devuelve la lista de productos, desde la posición indicada
* @param type $offset Desplazamiento desde el inicio
* @param type $limit Nº de productos a devolver
* @return type
*/
public function Lista($offset, $limit)
{
$offset=(int)$offset;
$limit=(int) $limit;
$listaProductosDevolver=array();
for($idx=$offset;
$idx<count($this->xmlProductos) && $idx-$offset<$limit; $idx++)
{
$producto=$this->xmlProductos->producto[$idx];
$listaProductosDevolver[]=array(
'nombre'=>(string) $producto->nombre,
'descripcion'=>(string) $producto->descripcion,
'precio'=>(string) $producto->precio,
'img'=>(string) $producto->img,
'url'=>site_url('service/tienda01/producto/'. (string) $producto->id)
);
}
// foreach($this->xmlProductos->producto as $p)
// {
// $listaProductosDevolver[]=array(
// 'nombre'=>(string) $p->nombre,
// 'descripcion'=>(string) $p->descripcion,
// 'precio'=>(string) $p->precio,
// 'img'=>(string) $p->img,
// 'url'=>site_url('service/tienda01/'. (string) $p->id)
// );
// }
return $listaProductosDevolver; //$listaProductosDevolver;
}
}
| isacm94/Practica2_Servidor | Otros/Agregador_Tiendas/application/models/server/gestor_tiendas_model.php | PHP | mit | 2,132 |
/**
Create by Huy: codocmm@gmail.com ~ nqhuy2k6@gmail.com
07/31/2015
*/
define(["durandal/app", "knockout", "bootstrap", "viewmodels/component-4"], function (app, ko, bootstrap, Component4) {
return function () {
var me = this;
var dashboardViewModel = this;
dashboardViewModel.compoment4 = ko.observable();
dashboardViewModel.activate = function () {
me.compoment4(new Component4(0))
}
}
});
| cmasv2/client | app/page/pages/alarm-summary.js | JavaScript | mit | 457 |
/*
************************************************************************
Copyright (c) 2013 UBINITY SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************
*/
var ChromeapiPlugupCardTerminalFactory = Class.extend(CardTerminalFactory, {
/** @lends ChromeapiPlugupCardTerminalFactory.prototype */
/**
* @class Implementation of the {@link CardTerminalFactory} using the Chrome API for Plug-up Dongle
* @constructs
* @augments CardTerminalFactory
*/
initialize: function(pid, usagePage, ledgerTransport, vid) {
this.pid = pid;
this.vid = vid;
this.usagePage = usagePage;
this.ledgerTransport = ledgerTransport;
},
list_async: function(pid, usagePage) {
if (typeof chromeDevice == "undefined") {
throw "Content script is not available";
}
return chromeDevice.enumerateDongles_async(this.pid, this.usagePage, this.vid)
.then(function(result) {
return result.deviceList;
});
},
waitInserted: function() {
throw "Not implemented"
},
getCardTerminal: function(device) {
return new ChromeapiPlugupCardTerminal(device, undefined, this.ledgerTransport);
}
}); | LedgerHQ/ledger-wallet-chrome | app/libs/btchip/btchip-js-api/chromeApp/ChromeapiPlugupCardTerminalFactory.js | JavaScript | mit | 1,664 |