code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.cg.service.impl; import java.util.ArrayList; import java.util.List; import org.kuali.kfs.module.cg.CGPropertyConstants; import org.kuali.kfs.module.cg.service.ContractsAndGrantsBillingService; /** * Service with methods related to the Contracts & Grants Billing (CGB) enhancement. */ public class ContractsAndGrantsBillingServiceImpl implements ContractsAndGrantsBillingService { @Override public List<String> getAgencyContractsGrantsBillingSectionIds() { List<String> contractsGrantsSectionIds = new ArrayList<String>(); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESSES_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_COLLECTIONS_MAINTENANCE_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CONTRACTS_AND_GRANTS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CUSTOMER_SECTION_ID); return contractsGrantsSectionIds; } @Override public List<String> getAwardContractsGrantsBillingSectionIds() { List<String> contractsGrantsSectionIds = new ArrayList<String>(); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_FUND_MANAGERS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_INVOICING_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_MILESTONE_SCHEDULE_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_PREDETERMINED_BILLING_SCHEDULE_SECTION_ID); return contractsGrantsSectionIds; } }
bhutchinson/kfs
kfs-cg/src/main/java/org/kuali/kfs/module/cg/service/impl/ContractsAndGrantsBillingServiceImpl.java
Java
agpl-3.0
2,589
namespace N2.Configuration { public enum ErrorAction { None, Email } }
DejanMilicic/n2cms
src/Framework/N2/Configuration/ErrorAction.cs
C#
lgpl-2.1
99
// --------------------------------------------------------------------- // // Copyright (C) 2004 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test the PETSc CG solver #include "../tests.h" #include "../testmatrix.h" #include <cmath> #include <fstream> #include <iostream> #include <iomanip> #include <deal.II/base/logstream.h> #include <deal.II/lac/petsc_sparse_matrix.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_solver.h> #include <deal.II/lac/petsc_precondition.h> #include <deal.II/lac/vector_memory.h> #include <typeinfo> template<typename SolverType, typename MatrixType, typename VectorType, class PRECONDITION> void check_solve(SolverType &solver, const SolverControl &solver_control, const MatrixType &A, VectorType &u, VectorType &f, const PRECONDITION &P) { deallog << "Solver type: " << typeid(solver).name() << std::endl; u = 0.; f = 1.; try { solver.solve(A,u,f,P); } catch (std::exception &e) { deallog << e.what() << std::endl; abort (); } deallog << "Solver stopped after " << solver_control.last_step() << " iterations" << std::endl; } int main(int argc, char **argv) { std::ofstream logfile("output"); deallog.attach(logfile); deallog << std::setprecision(4); deallog.threshold_double(1.e-10); Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1); { SolverControl control(100, 1.e-3); const unsigned int size = 32; unsigned int dim = (size-1)*(size-1); deallog << "Size " << size << " Unknowns " << dim << std::endl; // Make matrix FDMatrix testproblem(size, size); PETScWrappers::SparseMatrix A(dim, dim, 5); testproblem.five_point(A); PETScWrappers::Vector f(dim); PETScWrappers::Vector u(dim); f = 1.; A.compress (VectorOperation::insert); PETScWrappers::SolverCG solver(control); PETScWrappers::PreconditionSOR preconditioner(A); check_solve (solver, control, A,u,f, preconditioner); } }
pesser/dealii
tests/petsc/solver_03_precondition_sor.cc
C++
lgpl-2.1
2,597
package org.herac.tuxguitar.gui.util; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.player.base.MidiRepeatController; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGMeasureHeader; public class MidiTickUtil { public static long getStart(long tick){ long startPoint = getStartPoint(); long start = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ start += length; length = header.getLength(); //verifico si es el compas correcto if(tick >= start && tick < (start + length )){ return header.getStart() + (tick - start); } } } return ( tick < startPoint ? startPoint : start ); } public static long getTick(long start){ long startPoint = getStartPoint(); long tick = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ tick += length; length = header.getLength(); //verifico si es el compas correcto if(start >= header.getStart() && start < (header.getStart() + length )){ return tick; } } } return ( start < startPoint ? startPoint : tick ); } private static long getStartPoint(){ TuxGuitar.instance().getPlayer().updateLoop( false ); return TuxGuitar.instance().getPlayer().getLoopSPosition(); } public static int getSHeader() { return TuxGuitar.instance().getPlayer().getLoopSHeader(); } public static int getEHeader() { return TuxGuitar.instance().getPlayer().getLoopEHeader(); } }
elkafoury/tux
src/org/herac/tuxguitar/gui/util/MidiTickUtil.java
Java
lgpl-2.1
2,150
/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: J.Wielemaker@vu.nl WWW: http://www.swi-prolog.org Copyright (c) 1999-2011, University of Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. */ #include <windows.h> #include <tchar.h> #define _MAKE_DLL 1 #undef _export #include "console.h" #include "console_i.h" #include "common.h" #include <memory.h> #include <string.h> #include <ctype.h> #ifndef EOF #define EOF -1 #endif typedef void (*function)(Line ln, int chr); /* edit-function */ static function dispatch_table[256]; /* general dispatch-table */ static function dispatch_meta[256]; /* ESC-char dispatch */ static RlcCompleteFunc _rlc_complete_function = rlc_complete_file_function; static void init_line_package(RlcData b); static void bind_actions(void); #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b)) #endif #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif #ifndef EOS #define EOS 0 #endif #ifndef ESC #define ESC 27 #endif #define COMPLETE_NEWLINE 1 #define COMPLETE_EOF 2 #define ctrl(c) ((c) - '@') #define META_OFFSET 128 #define meta(c) ((c) + META_OFFSET) /******************************* * BUFFER * *******************************/ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - make_room(Line, int room) Make n-characters space after the point. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ static void make_room(Line ln, size_t room) { while ( ln->size + room + 1 > ln->allocated ) { if ( !ln->data ) { ln->data = rlc_malloc(256 * sizeof(TCHAR)); ln->allocated = 256; } else { ln->allocated *= 2; ln->data = rlc_realloc(ln->data, ln->allocated * sizeof(TCHAR)); } } memmove(&ln->data[ln->point + room], &ln->data[ln->point], (ln->size - ln->point)*sizeof(TCHAR)); ln->size += room; if ( room > 0 ) ln->change_start = min(ln->change_start, ln->point); } static void set_line(Line ln, const TCHAR *s) { size_t len = _tcslen(s); ln->size = ln->point = 0; make_room(ln, len); _tcsncpy(ln->data, s, len); } static void terminate(Line ln) { if ( !ln->data ) { ln->data = rlc_malloc(sizeof(TCHAR)); ln->allocated = 1; } ln->data[ln->size] = EOS; } static void delete(Line ln, size_t from, size_t len) { if ( from < 0 || from > ln->size || len < 0 || from + len > ln->size ) return; _tcsncpy(&ln->data[from], &ln->data[from+len], ln->size - (from+len)); ln->size -= len; } /******************************* * POSITIONING * *******************************/ static size_t back_word(Line ln, size_t from) { from = min(from, ln->size); from = max(0, from); if ( ln->data ) { while(!rlc_is_word_char(ln->data[from-1]) && from > 0 ) from--; while(rlc_is_word_char(ln->data[from-1]) && from > 0 ) from--; } return from; } static size_t forw_word(Line ln, size_t from) { from = min(from, ln->size); from = max(0, from); if ( ln->data ) { while(!rlc_is_word_char(ln->data[from]) && from < ln->size ) from++; while(rlc_is_word_char(ln->data[from]) && from < ln->size ) from++; } return from; } /******************************* * EDITING FUNCTIONS * *******************************/ static __inline void changed(Line ln, size_t from) { ln->change_start = min(ln->change_start, from); } static void insert_self(Line ln, int chr) { make_room(ln, 1); ln->data[ln->point++] = chr; } static void backward_delete_character(Line ln, int chr) { if ( ln->point > 0 ) { memmove(&ln->data[ln->point-1], &ln->data[ln->point], (ln->size - ln->point)*sizeof(TCHAR)); ln->size--; ln->point--; } changed(ln, ln->point); } static void delete_character(Line ln, int chr) { if ( ln->point < ln->size ) { ln->point++; backward_delete_character(ln, chr); } } static void backward_character(Line ln, int chr) { if ( ln->point > 0 ) ln->point--; } static void forward_character(Line ln, int chr) { if ( ln->point < ln->size ) ln->point++; } static void backward_word(Line ln, int chr) { ln->point = back_word(ln, ln->point); } static void forward_word(Line ln, int chr) { ln->point = forw_word(ln, ln->point); } static void backward_delete_word(Line ln, int chr) { size_t from = back_word(ln, ln->point); memmove(&ln->data[from], &ln->data[ln->point], (ln->size - ln->point)*sizeof(TCHAR)); ln->size -= ln->point - from; ln->point = from; changed(ln, from); } static void forward_delete_word(Line ln, int chr) { size_t to = forw_word(ln, ln->point); memmove(&ln->data[ln->point], &ln->data[to], (ln->size - to)*sizeof(TCHAR)); ln->size -= to - ln->point; changed(ln, ln->point); } static void transpose_chars(Line ln, int chr) { if ( ln->point > 0 && ln->point < ln->size ) { int c0 = ln->data[ln->point-1]; ln->data[ln->point-1] = ln->data[ln->point]; ln->data[ln->point] = c0; changed(ln, ln->point-1); } } static void start_of_line(Line ln, int chr) { ln->point = 0; } static void end_of_line(Line ln, int chr) { ln->point = ln->size; } static void kill_line(Line ln, int chr) { ln->size = ln->point; changed(ln, ln->size); } static void empty_line(Line ln, int chr) { ln->size = ln->point = 0; changed(ln, 0); } static void enter(Line ln, int chr) { ln->point = ln->size; #ifdef DOS_CRNL make_room(ln, 2); ln->data[ln->point++] = '\r'; ln->data[ln->point++] = '\n'; #else make_room(ln, 1); ln->data[ln->point++] = '\n'; #endif terminate(ln); ln->complete = COMPLETE_NEWLINE; } static void eof(Line ln, int chr) { ln->point = ln->size; terminate(ln); ln->complete = COMPLETE_EOF; } static void delete_character_or_eof(Line ln, int chr) { if ( ln->size == 0 ) { ln->point = ln->size; terminate(ln); ln->complete = COMPLETE_EOF; } else delete_character(ln, chr); } static void undefined(Line ln, int chr) { } static void interrupt(Line ln, int chr) { raise(SIGINT); } /******************************* * HISTORY * *******************************/ static void add_history(rlc_console c, const TCHAR *data) { const TCHAR *s = data; while(*s && *s <= ' ') s++; if ( *s ) rlc_add_history(c, s); } static void backward_history(Line ln, int chr) { const TCHAR *h; if ( rlc_at_head_history(ln->console) && ln->size > 0 ) { terminate(ln); add_history(ln->console, ln->data); } if ( (h = rlc_bwd_history(ln->console)) ) { set_line(ln, h); ln->point = ln->size; } } static void forward_history(Line ln, int chr) { if ( !rlc_at_head_history(ln->console) ) { const TCHAR *h = rlc_fwd_history(ln->console); if ( h ) { set_line(ln, h); ln->point = ln->size; } } else empty_line(ln, chr); } /******************************* * COMPLETE * *******************************/ RlcCompleteFunc rlc_complete_hook(RlcCompleteFunc new) { RlcCompleteFunc old = _rlc_complete_function; _rlc_complete_function = new; return old; } static int common(const TCHAR *s1, const TCHAR *s2, int insensitive) { int n = 0; if ( !insensitive ) { while(*s1 && *s1 == *s2) { s1++, s2++; n++; } return n; } else { while(*s1) { if ( _totlower(*s1) == _totlower(*s2) ) { s1++, s2++; n++; } else break; } return n; } } static void complete(Line ln, int chr) { if ( _rlc_complete_function ) { rlc_complete_data dbuf; RlcCompleteData data = &dbuf; memset(data, 0, sizeof(dbuf)); data->line = ln; data->call_type = COMPLETE_INIT; if ( (*_rlc_complete_function)(data) ) { TCHAR match[COMPLETE_MAX_WORD_LEN]; int nmatches = 1; size_t ncommon = _tcslen(data->candidate); size_t patlen = ln->point - data->replace_from; _tcscpy(match, data->candidate); data->call_type = COMPLETE_ENUMERATE; while( (*data->function)(data) ) { ncommon = common(match, data->candidate, data->case_insensitive); match[ncommon] = EOS; nmatches++; } data->call_type = COMPLETE_CLOSE; (*data->function)(data); delete(ln, data->replace_from, patlen); ln->point = data->replace_from; make_room(ln, ncommon); _tcsncpy(&ln->data[data->replace_from], match, ncommon); ln->point += ncommon; if ( nmatches == 1 && data->quote ) insert_self(ln, data->quote); } } } #define MAX_LIST_COMPLETIONS 256 static void list_completions(Line ln, int chr) { if ( _rlc_complete_function ) { rlc_complete_data dbuf; RlcCompleteData data = &dbuf; memset(data, 0, sizeof(dbuf)); data->line = ln; data->call_type = COMPLETE_INIT; if ( (*_rlc_complete_function)(data) ) { TCHAR *buf[COMPLETE_MAX_MATCHES]; int n, nmatches = 0; size_t len = _tcslen(data->candidate) + 1; size_t longest = len; size_t cols; buf[nmatches] = rlc_malloc(len*sizeof(TCHAR)); _tcsncpy(buf[nmatches], data->candidate, len); nmatches++; data->call_type = COMPLETE_ENUMERATE; while( (*data->function)(data) ) { len = _tcslen(data->candidate) + 1; buf[nmatches] = rlc_malloc(len*sizeof(TCHAR)); _tcsncpy(buf[nmatches], data->candidate, len); nmatches++; longest = max(longest, len); if ( nmatches > COMPLETE_MAX_MATCHES ) { TCHAR *msg = _T("\r\n! Too many matches\r\n"); while(*msg) rlc_putchar(ln->console, *msg++); ln->reprompt = TRUE; data->call_type = COMPLETE_CLOSE; (*data->function)(data); return; } } data->call_type = COMPLETE_CLOSE; (*data->function)(data); cols = ScreenCols(ln->console) / longest; rlc_putchar(ln->console, '\r'); rlc_putchar(ln->console, '\n'); for(n=0; n<nmatches; ) { TCHAR *s = buf[n]; len = 0; while(*s) { len++; rlc_putchar(ln->console, *s++); } rlc_free(buf[n++]); if ( n % cols == 0 ) { rlc_putchar(ln->console, '\r'); rlc_putchar(ln->console, '\n'); } else { while( len++ < longest ) rlc_putchar(ln->console, ' '); } } if ( nmatches % cols != 0 ) { rlc_putchar(ln->console, '\r'); rlc_putchar(ln->console, '\n'); } ln->reprompt = TRUE; } } } /******************************* * REPAINT * *******************************/ static void output(rlc_console b, TCHAR *s, size_t len) { while(len-- > 0) { if ( *s == '\n' ) rlc_putchar(b, '\r'); rlc_putchar(b, *s++); } } static void update_display(Line ln) { if ( ln->reprompt ) { const TCHAR *prompt = rlc_prompt(ln->console, NULL); const TCHAR *s = prompt; rlc_putchar(ln->console, '\r'); while(*s) rlc_putchar(ln->console, *s++); rlc_get_mark(ln->console, &ln->origin); ln->change_start = 0; ln->reprompt = FALSE; } rlc_goto_mark(ln->console, &ln->origin, ln->data, ln->change_start); output(ln->console, &ln->data[ln->change_start], ln->size - ln->change_start); rlc_erase_from_caret(ln->console); rlc_goto_mark(ln->console, &ln->origin, ln->data, ln->point); rlc_update(ln->console); ln->change_start = ln->size; } /******************************* * TOPLEVEL * *******************************/ TCHAR * read_line(rlc_console b) { line ln; init_line_package(b); memset(&ln, 0, sizeof(line)); ln.console = b; rlc_get_mark(b, &ln.origin); while(!ln.complete) { int c; rlc_mark m0, m1; function func; rlc_get_mark(b, &m0); if ( (c = getch(b)) == IMODE_SWITCH_CHAR ) return RL_CANCELED_CHARP; if ( c == EOF ) { eof(&ln, c); update_display(&ln); break; } else if ( c == ESC ) { if ( (c = getch(b)) == IMODE_SWITCH_CHAR ) return RL_CANCELED_CHARP; if ( c > 256 ) func = undefined; else func = dispatch_meta[c&0xff]; } else { if ( c >= 256 ) func = insert_self; else func = dispatch_table[c&0xff]; } rlc_get_mark(b, &m1); (*func)(&ln, c); if ( m0.mark_x != m1.mark_x || m0.mark_y != m1.mark_y ) ln.reprompt = TRUE; update_display(&ln); } rlc_clearprompt(b); add_history(b, ln.data); return ln.data; } /******************************* * DISPATCH * *******************************/ static void init_dispatch_table() { static int done; if ( !done ) { int n; for(n=0; n<32; n++) dispatch_table[n] = undefined; for(n=32; n<256; n++) dispatch_table[n] = insert_self; for(n=0; n<256; n++) dispatch_meta[n] = undefined; bind_actions(); done = TRUE; } } static void init_line_package(RlcData b) { init_dispatch_table(); rlc_init_history(b, 50); } /******************************* * BIND * *******************************/ typedef struct _action { char *name; function function; unsigned char keys[4]; } action, *Action; #define ACTION(n, f, k) { n, f, k } static action actions[] = { ACTION("insert_self", insert_self, ""), ACTION("backward_delete_character", backward_delete_character, "\b"), ACTION("complete", complete, "\t"), ACTION("enter", enter, "\r\n"), ACTION("start_of_line", start_of_line, {ctrl('A')}), ACTION("backward_character", backward_character, {ctrl('B')}), ACTION("interrupt", interrupt, {ctrl('C')}), ACTION("end_of_line", end_of_line, {ctrl('E')}), ACTION("forward_character", forward_character, {ctrl('F')}), ACTION("transpose_chars", transpose_chars, {ctrl('T')}), ACTION("kill_line", kill_line, {ctrl('K')}), ACTION("backward_history", backward_history, {ctrl('P')}), ACTION("forward_history", forward_history, {ctrl('N')}), ACTION("empty_line", empty_line, {ctrl('U')}), ACTION("eof", eof, {ctrl('Z')}), ACTION("delete_character_or_eof", delete_character_or_eof, {ctrl('D')}), ACTION("delete_character", delete_character, {127}), { "forward_word", forward_word, {meta(ctrl('F')), meta('f')}}, { "backward_word", backward_word, {meta(ctrl('B')), meta('b')}}, { "forward_delete_word", forward_delete_word, {meta(127), meta('d')}}, ACTION("list_completions", list_completions, {meta('?')}), ACTION("backward_delete_word", backward_delete_word, {meta('\b')}), ACTION(NULL, NULL, "") }; int rlc_bind(int chr, const char *fname) { if ( chr >= 0 && chr <= 256 ) { Action a = actions; for( ; a->name; a++ ) { if ( strcmp(a->name, fname) == 0 ) { if ( chr > META_OFFSET ) dispatch_meta[chr-META_OFFSET] = a->function; else dispatch_table[chr] = a->function; return TRUE; } } } return FALSE; } static void bind_actions() { Action a = actions; for( ; a->name; a++ ) { unsigned char *k = a->keys; for( ; *k; k++ ) { int chr = *k & 0xff; if ( chr > META_OFFSET ) dispatch_meta[chr-META_OFFSET] = a->function; else dispatch_table[chr] = a->function; } } }
edechter/swipl-devel
src/win32/console/edit.c
C
lgpl-2.1
16,384
/**************************************************************************/ /* */ /* OCaml */ /* */ /* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ /* */ /* Copyright 2001 Institut National de Recherche en Informatique et */ /* en Automatique. */ /* */ /* All rights reserved. This file is distributed under the terms of */ /* the GNU Lesser General Public License version 2.1, with the */ /* special exception on linking described in the file LICENSE. */ /* */ /**************************************************************************/ #define CAML_INTERNALS /* Registration of global memory roots */ #include "caml/mlvalues.h" #include "caml/roots.h" #include "caml/globroots.h" #include "caml/skiplist.h" /* The three global root lists. Each is represented by a skip list with the key being the address of the root. (The associated data field is unused.) */ struct skiplist caml_global_roots = SKIPLIST_STATIC_INITIALIZER; /* mutable roots, don't know whether old or young */ struct skiplist caml_global_roots_young = SKIPLIST_STATIC_INITIALIZER; /* generational roots pointing to minor or major heap */ struct skiplist caml_global_roots_old = SKIPLIST_STATIC_INITIALIZER; /* generational roots pointing to major heap */ /* The invariant of the generational roots is the following: - If the global root contains a pointer to the minor heap, then the root is in [caml_global_roots_young]; - If the global root contains a pointer to the major heap, then the root is in [caml_global_roots_old] or in [caml_global_roots_young]; - Otherwise (the root contains a pointer outside of the heap or an integer), then neither [caml_global_roots_young] nor [caml_global_roots_old] contain it. */ /* Insertion and deletion */ Caml_inline void caml_insert_global_root(struct skiplist * list, value * r) { caml_skiplist_insert(list, (uintnat) r, 0); } Caml_inline void caml_delete_global_root(struct skiplist * list, value * r) { caml_skiplist_remove(list, (uintnat) r); } /* Iterate a GC scanning action over a global root list */ static void caml_iterate_global_roots(scanning_action f, struct skiplist * rootlist) { FOREACH_SKIPLIST_ELEMENT(e, rootlist, { value * r = (value *) (e->key); f(*r, r); }) } /* Register a global C root of the mutable kind */ CAMLexport void caml_register_global_root(value *r) { CAMLassert (((intnat) r & 3) == 0); /* compact.c demands this (for now) */ caml_insert_global_root(&caml_global_roots, r); } /* Un-register a global C root of the mutable kind */ CAMLexport void caml_remove_global_root(value *r) { caml_delete_global_root(&caml_global_roots, r); } enum gc_root_class { YOUNG, OLD, UNTRACKED }; static enum gc_root_class classify_gc_root(value v) { if(!Is_block(v)) return UNTRACKED; if(Is_young(v)) return YOUNG; #ifndef NO_NAKED_POINTERS if(!Is_in_heap(v)) return UNTRACKED; #endif return OLD; } /* Register a global C root of the generational kind */ CAMLexport void caml_register_generational_global_root(value *r) { CAMLassert (((intnat) r & 3) == 0); /* compact.c demands this (for now) */ switch(classify_gc_root(*r)) { case YOUNG: caml_insert_global_root(&caml_global_roots_young, r); break; case OLD: caml_insert_global_root(&caml_global_roots_old, r); break; case UNTRACKED: break; } } /* Un-register a global C root of the generational kind */ CAMLexport void caml_remove_generational_global_root(value *r) { switch(classify_gc_root(*r)) { case OLD: caml_delete_global_root(&caml_global_roots_old, r); /* Fallthrough: the root can be in the young list while actually being in the major heap. */ case YOUNG: caml_delete_global_root(&caml_global_roots_young, r); break; case UNTRACKED: break; } } /* Modify the value of a global C root of the generational kind */ CAMLexport void caml_modify_generational_global_root(value *r, value newval) { enum gc_root_class c; /* See PRs #4704, #607 and #8656 */ switch(classify_gc_root(newval)) { case YOUNG: c = classify_gc_root(*r); if(c == OLD) caml_delete_global_root(&caml_global_roots_old, r); if(c != YOUNG) caml_insert_global_root(&caml_global_roots_young, r); break; case OLD: /* If the old class is YOUNG, then we do not need to do anything: It is OK to have a root in roots_young that suddenly points to the old generation -- the next minor GC will take care of that. */ if(classify_gc_root(*r) == UNTRACKED) caml_insert_global_root(&caml_global_roots_old, r); break; case UNTRACKED: caml_remove_generational_global_root(r); break; } *r = newval; } /* Scan all global roots */ void caml_scan_global_roots(scanning_action f) { caml_iterate_global_roots(f, &caml_global_roots); caml_iterate_global_roots(f, &caml_global_roots_young); caml_iterate_global_roots(f, &caml_global_roots_old); } /* Scan global roots for a minor collection */ void caml_scan_global_young_roots(scanning_action f) { caml_iterate_global_roots(f, &caml_global_roots); caml_iterate_global_roots(f, &caml_global_roots_young); /* Move young roots to old roots */ FOREACH_SKIPLIST_ELEMENT(e, &caml_global_roots_young, { value * r = (value *) (e->key); caml_insert_global_root(&caml_global_roots_old, r); }); caml_skiplist_empty(&caml_global_roots_young); }
gerdstolpmann/ocaml
runtime/globroots.c
C
lgpl-2.1
6,109
<?php /** * @package tikiwiki */ // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: categorize.php 44444 2013-01-05 21:24:24Z changi67 $ require_once('tiki-setup.php'); $access = TikiLib::lib('access'); $access->check_script($_SERVER["SCRIPT_NAME"], basename(__FILE__)); $smarty = TikiLib::lib('smarty'); global $prefs; $catobjperms = Perms::get(array( 'type' => $cat_type, 'object' => $cat_objid )); if ($prefs['feature_categories'] == 'y' && $catobjperms->modify_object_categories ) { $categlib = TikiLib::lib('categ'); if (isset($_REQUEST['import']) and isset($_REQUEST['categories'])) { $_REQUEST["cat_categories"] = explode(',', $_REQUEST['categories']); $_REQUEST["cat_categorize"] = 'on'; } if ( !isset($_REQUEST["cat_categorize"]) || $_REQUEST["cat_categorize"] != 'on' ) { $_REQUEST['cat_categories'] = NULL; } $categlib->update_object_categories(isset($_REQUEST['cat_categories'])?$_REQUEST['cat_categories']:'', $cat_objid, $cat_type, $cat_desc, $cat_name, $cat_href, $_REQUEST['cat_managed']); }
reneejustrenee/tikiwikitest
categorize.php
PHP
lgpl-2.1
1,238
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.narayana.txframework.api.exception; /** * @deprecated The TXFramework API will be removed. The org.jboss.narayana.compensations API should be used instead. * The new API is superior for these reasons: * <p/> * i) offers a higher level API; * ii) The API very closely matches that of JTA, making it easier for developers to learn, * iii) It works for non-distributed transactions as well as distributed transactions. * iv) It is CDI based so only needs a CDI container to run, rather than a full Java EE server. * <p/> */ @Deprecated public class TXFrameworkException extends Exception { public TXFrameworkException(String message) { super(message); } public TXFrameworkException(String message, Throwable cause) { super(message, cause); } }
gytis/narayana
txframework/src/main/java/org/jboss/narayana/txframework/api/exception/TXFrameworkException.java
Java
lgpl-2.1
1,829
var classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser = [ [ "Deserialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a5e8aa7ae1372033da215d02b79947b20.html#a5e8aa7ae1372033da215d02b79947b20", null ], [ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a4aec60f5df74f482b576f4e0dad0d5f6.html#a4aec60f5df74f482b576f4e0dad0d5f6", null ], [ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a2362ae784859054bf5b9281dafeb37cd.html#a2362ae784859054bf5b9281dafeb37cd", null ], [ "ValueType", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_af5d06e2fe995f816c840a8ceefd22991.html#af5d06e2fe995f816c840a8ceefd22991", null ] ];
Chinchilla-Software-Com/CQRS
wiki/docs/2.4/html/classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser.js
JavaScript
lgpl-2.1
693
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // // Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, // UK. // package org.jboss.jbossts.qa.RawResources02Clients2; /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ import org.jboss.jbossts.qa.RawResources02.*; import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.OTS; import org.jboss.jbossts.qa.Utils.ServerIORStore; import org.omg.CORBA.TRANSACTION_ROLLEDBACK; public class Client085 { public static void main(String[] args) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]); Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1)); String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]); Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2)); ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1]; resourceBehaviors1[0] = new ResourceBehavior(); resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteRollback; resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1]; resourceBehaviors2[0] = new ResourceBehavior(); resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteReadOnly; resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; boolean correct = true; OTS.current().begin(); service1.oper(resourceBehaviors1, OTS.current().get_control()); service2.oper(resourceBehaviors2, OTS.current().get_control()); try { OTS.current().commit(true); System.err.println("Commit succeeded when it shouldn't"); correct = false; } catch (TRANSACTION_ROLLEDBACK transactionRolledback) { } correct = correct && service1.is_correct() && service2.is_correct(); if (!correct) { System.err.println("service1.is_correct() or service2.is_correct() returned false"); } ResourceTrace resourceTrace1 = service1.get_resource_trace(0); ResourceTrace resourceTrace2 = service2.get_resource_trace(0); correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareRollback); correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepare) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback)); if (correct) { System.out.println("Passed"); } else { System.out.println("Failed"); } } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); System.out.println("Failed"); } try { OAInterface.shutdownOA(); ORBInterface.shutdownORB(); } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); } } }
gytis/narayana
qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client085.java
Java
lgpl-2.1
4,881
package com.pi4j.io.gpio; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Library (Core) * FILENAME : GpioPinPwm.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2015 Pi4J * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * Gpio input pin interface. This interface is extension of {@link GpioPin} interface * with reading pwm values. * * @author Robert Savage (<a * href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) */ @SuppressWarnings("unused") public interface GpioPinPwm extends GpioPin { int getPwm(); }
curvejumper/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/GpioPinPwm.java
Java
lgpl-3.0
1,511
# This is a fix for InnoDB in MySQL >= 4.1.x # It "suspends judgement" for fkey relationships until are tables are set. SET FOREIGN_KEY_CHECKS = 0; UPDATE `config` SET `value`='2.0.1' WHERE `name`='thelia_version'; UPDATE `config` SET `value`='1' WHERE `name`='thelia_release_version'; UPDATE `config` SET `value`='' WHERE `name`='thelia_extra_version'; INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('front_cart_country_cookie_name','fcccn', 1, 1, NOW(), NOW()); INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('front_cart_country_cookie_expires','2592000', 1, 1, NOW(), NOW()); INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('sitemap_ttl','7200', 1, 1, NOW(), NOW()); INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('feed_ttl','7200', 1, 1, NOW(), NOW()); ALTER TABLE `module` ADD INDEX `idx_module_activate` (`activate`); SELECT @max := MAX(`id`) FROM `resource`; SET @max := @max+1; INSERT INTO resource (`id`, `code`, `created_at`, `updated_at`) VALUES (@max, 'admin.configuration.store', NOW(), NOW()), (@max+1, 'admin.configuration.variable', NOW(), NOW()), (@max+2, 'admin.configuration.admin-logs', NOW(), NOW()), (@max+3, 'admin.configuration.system-logs', NOW(), NOW()), (@max+4, 'admin.configuration.advanced', NOW(), NOW()), (@max+5, 'admin.configuration.translations', NOW(), NOW()), (@max+6, 'admin.tools', NOW(), NOW()), (@max+7, 'admin.export', NOW(), NOW()), (@max+8, 'admin.export.customer.newsletter', NOW(), NOW()) ; INSERT INTO resource_i18n (`id`, `locale`, `title`) VALUES (@max, 'en_US', 'Store information configuration'), (@max+1, 'en_US', 'Configuration variables'), (@max+2, 'en_US', 'View administration logs'), (@max+3, 'en_US', 'Logging system configuration'), (@max+4, 'en_US', 'Advanced configuration'), (@max+5, 'en_US', 'Translations'), (@max+6, 'en_US', 'Tools panel'), (@max+7, 'en_US', 'Back-office export management'), (@max+8, 'en_US', 'export of newsletter subscribers'), (@max, 'es_ES', NULL), (@max+1, 'es_ES', NULL), (@max+2, 'es_ES', NULL), (@max+3, 'es_ES', NULL), (@max+4, 'es_ES', NULL), (@max+5, 'es_ES', NULL), (@max+6, 'es_ES', NULL), (@max+7, 'es_ES', NULL), (@max+8, 'es_ES', NULL), (@max, 'fr_FR', 'Configuration des informations sur la boutique'), (@max+1, 'fr_FR', 'Variables de configuration'), (@max+2, 'fr_FR', 'Consulter les logs d\'administration'), (@max+3, 'fr_FR', 'Configuration du système de log'), (@max+4, 'fr_FR', 'Configuration avancée'), (@max+5, 'fr_FR', 'Traductions'), (@max+6, 'fr_FR', 'Outils'), (@max+7, 'fr_FR', 'gestion des exports'), (@max+8, 'fr_FR', 'Export des inscrits à la newsletter') ; SELECT @max := MAX(`id`) FROM `lang`; SET @max := @max+1; INSERT INTO `lang`(`id`,`title`,`code`,`locale`,`url`,`date_format`,`time_format`,`datetime_format`,`decimal_separator`,`thousands_separator`,`decimals`,`by_default`,`created_at`,`updated_at`)VALUES (@max, 'Russian', 'ru', 'ru_RU', '', 'j.n.Y', 'H:i:s', 'j.n.Y H:i:s', ',', ' ', '2', 0, NOW(), NOW()); SET @max := @max+1; INSERT INTO `lang`(`id`,`title`,`code`,`locale`,`url`,`date_format`,`time_format`,`datetime_format`,`decimal_separator`,`thousands_separator`,`decimals`,`by_default`,`created_at`,`updated_at`)VALUES (@max, 'Czech', 'cs', 'cs_CZ', '', 'j.n.Y', 'H:i:s', 'j.n.Y H:i:s', ',', ' ', '2', 0, NOW(), NOW()); SET FOREIGN_KEY_CHECKS = 1;
Vyndi/thelia
setup/update/sql/2.0.1.sql
SQL
lgpl-3.0
3,493
package ca import ( "bytes" cryptorand "crypto/rand" "crypto/tls" "crypto/x509" "encoding/hex" "encoding/json" "encoding/pem" "io" "io/ioutil" "net/http" "sync" "time" "github.com/cloudflare/cfssl/api" "github.com/cloudflare/cfssl/config" "github.com/cloudflare/cfssl/csr" "github.com/cloudflare/cfssl/signer" "github.com/docker/swarmkit/log" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/net/context" "golang.org/x/net/context/ctxhttp" ) const ( // ExternalCrossSignProfile is the profile that we will be sending cross-signing CSR sign requests with ExternalCrossSignProfile = "CA" // CertificateMaxSize is the maximum expected size of a certificate. // While there is no specced upper limit to the size of an x509 certificate in PEM format, // one with a ridiculous RSA key size (16384) and 26 256-character DNS SAN fields is about 14k. // While there is no upper limit on the length of certificate chains, long chains are impractical. // To be conservative, and to also account for external CA certificate responses in JSON format // from CFSSL, we'll set the max to be 256KiB. CertificateMaxSize int64 = 256 << 10 ) // ErrNoExternalCAURLs is an error used it indicate that an ExternalCA is // configured with no URLs to which it can proxy certificate signing requests. var ErrNoExternalCAURLs = errors.New("no external CA URLs") // ExternalCA is able to make certificate signing requests to one of a list // remote CFSSL API endpoints. type ExternalCA struct { ExternalRequestTimeout time.Duration mu sync.Mutex rootCA *RootCA urls []string client *http.Client } // NewExternalCA creates a new ExternalCA which uses the given tlsConfig to // authenticate to any of the given URLS of CFSSL API endpoints. func NewExternalCA(rootCA *RootCA, tlsConfig *tls.Config, urls ...string) *ExternalCA { return &ExternalCA{ ExternalRequestTimeout: 5 * time.Second, rootCA: rootCA, urls: urls, client: &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, }, } } // Copy returns a copy of the external CA that can be updated independently func (eca *ExternalCA) Copy() *ExternalCA { eca.mu.Lock() defer eca.mu.Unlock() return &ExternalCA{ ExternalRequestTimeout: eca.ExternalRequestTimeout, rootCA: eca.rootCA, urls: eca.urls, client: eca.client, } } // UpdateTLSConfig updates the HTTP Client for this ExternalCA by creating // a new client which uses the given tlsConfig. func (eca *ExternalCA) UpdateTLSConfig(tlsConfig *tls.Config) { eca.mu.Lock() defer eca.mu.Unlock() eca.client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, } } // UpdateURLs updates the list of CSR API endpoints by setting it to the given urls. func (eca *ExternalCA) UpdateURLs(urls ...string) { eca.mu.Lock() defer eca.mu.Unlock() eca.urls = urls } // UpdateRootCA changes the root CA used to append intermediates func (eca *ExternalCA) UpdateRootCA(rca *RootCA) { eca.mu.Lock() eca.rootCA = rca eca.mu.Unlock() } // Sign signs a new certificate by proxying the given certificate signing // request to an external CFSSL API server. func (eca *ExternalCA) Sign(ctx context.Context, req signer.SignRequest) (cert []byte, err error) { // Get the current HTTP client and list of URLs in a small critical // section. We will use these to make certificate signing requests. eca.mu.Lock() urls := eca.urls client := eca.client intermediates := eca.rootCA.Intermediates eca.mu.Unlock() if len(urls) == 0 { return nil, ErrNoExternalCAURLs } csrJSON, err := json.Marshal(req) if err != nil { return nil, errors.Wrap(err, "unable to JSON-encode CFSSL signing request") } // Try each configured proxy URL. Return after the first success. If // all fail then the last error will be returned. for _, url := range urls { requestCtx, cancel := context.WithTimeout(ctx, eca.ExternalRequestTimeout) cert, err = makeExternalSignRequest(requestCtx, client, url, csrJSON) cancel() if err == nil { return append(cert, intermediates...), err } log.G(ctx).Debugf("unable to proxy certificate signing request to %s: %s", url, err) } return nil, err } // CrossSignRootCA takes a RootCA object, generates a CA CSR, sends a signing request with the CA CSR to the external // CFSSL API server in order to obtain a cross-signed root func (eca *ExternalCA) CrossSignRootCA(ctx context.Context, rca RootCA) ([]byte, error) { // ExtractCertificateRequest generates a new key request, and we want to continue to use the old // key. However, ExtractCertificateRequest will also convert the pkix.Name to csr.Name, which we // need in order to generate a signing request rcaSigner, err := rca.Signer() if err != nil { return nil, err } rootCert := rcaSigner.parsedCert cfCSRObj := csr.ExtractCertificateRequest(rootCert) der, err := x509.CreateCertificateRequest(cryptorand.Reader, &x509.CertificateRequest{ RawSubjectPublicKeyInfo: rootCert.RawSubjectPublicKeyInfo, RawSubject: rootCert.RawSubject, PublicKeyAlgorithm: rootCert.PublicKeyAlgorithm, Subject: rootCert.Subject, Extensions: rootCert.Extensions, DNSNames: rootCert.DNSNames, EmailAddresses: rootCert.EmailAddresses, IPAddresses: rootCert.IPAddresses, }, rcaSigner.cryptoSigner) if err != nil { return nil, err } req := signer.SignRequest{ Request: string(pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: der, })), Subject: &signer.Subject{ CN: rootCert.Subject.CommonName, Names: cfCSRObj.Names, }, Profile: ExternalCrossSignProfile, } // cfssl actually ignores non subject alt name extensions in the CSR, so we have to add the CA extension in the signing // request as well for _, ext := range rootCert.Extensions { if ext.Id.Equal(BasicConstraintsOID) { req.Extensions = append(req.Extensions, signer.Extension{ ID: config.OID(ext.Id), Critical: ext.Critical, Value: hex.EncodeToString(ext.Value), }) } } return eca.Sign(ctx, req) } func makeExternalSignRequest(ctx context.Context, client *http.Client, url string, csrJSON []byte) (cert []byte, err error) { resp, err := ctxhttp.Post(ctx, client, url, "application/json", bytes.NewReader(csrJSON)) if err != nil { return nil, recoverableErr{err: errors.Wrap(err, "unable to perform certificate signing request")} } defer resp.Body.Close() b := io.LimitReader(resp.Body, CertificateMaxSize) body, err := ioutil.ReadAll(b) if err != nil { return nil, recoverableErr{err: errors.Wrap(err, "unable to read CSR response body")} } if resp.StatusCode != http.StatusOK { return nil, recoverableErr{err: errors.Errorf("unexpected status code in CSR response: %d - %s", resp.StatusCode, string(body))} } var apiResponse api.Response if err := json.Unmarshal(body, &apiResponse); err != nil { logrus.Debugf("unable to JSON-parse CFSSL API response body: %s", string(body)) return nil, recoverableErr{err: errors.Wrap(err, "unable to parse JSON response")} } if !apiResponse.Success || apiResponse.Result == nil { if len(apiResponse.Errors) > 0 { return nil, errors.Errorf("response errors: %v", apiResponse.Errors) } return nil, errors.New("certificate signing request failed") } result, ok := apiResponse.Result.(map[string]interface{}) if !ok { return nil, errors.Errorf("invalid result type: %T", apiResponse.Result) } certPEM, ok := result["certificate"].(string) if !ok { return nil, errors.Errorf("invalid result certificate field type: %T", result["certificate"]) } return []byte(certPEM), nil }
hqhq/moby
vendor/github.com/docker/swarmkit/ca/external.go
GO
apache-2.0
7,794
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.extensions.ml; import static org.junit.Assert.assertThrows; import java.util.List; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.PCollectionView; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DLPInspectTextTest { @Rule public TestPipeline testPipeline = TestPipeline.create(); private static final Integer BATCH_SIZE_SMALL = 200; private static final String DELIMITER = ";"; private static final String TEMPLATE_NAME = "test_template"; private static final String PROJECT_ID = "test_id"; @Test public void throwsExceptionWhenDeidentifyConfigAndTemplatesAreEmpty() { assertThrows( "Either inspectTemplateName or inspectConfig must be supplied!", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsNullAndHeadersAreSet() { PCollectionView<List<String>> header = testPipeline.apply(Create.of("header")).apply(View.asList()); assertThrows( "Column delimiter should be set if headers are present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setHeaderColumns(header) .build()); testPipeline.run().waitUntilFinish(); } @Test public void throwsExceptionWhenBatchSizeIsTooLarge() { assertThrows( String.format( "Batch size is too large! It should be smaller or equal than %d.", DLPInspectText.DLP_PAYLOAD_LIMIT_BYTES), IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(Integer.MAX_VALUE) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsSetAndHeadersAreNot() { assertThrows( "Column headers should be supplied when delimiter is present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } }
lukecwik/incubator-beam
sdks/java/extensions/ml/src/test/java/org/apache/beam/sdk/extensions/ml/DLPInspectTextTest.java
Java
apache-2.0
3,694
/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a full listing * of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ /* * Copyright (C) 2002, * * Arjuna Technologies Limited, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ */ package com.arjuna.wsas.tests; import com.arjuna.mw.wsas.context.Context; import com.arjuna.mw.wsas.UserActivityFactory; import com.arjuna.mw.wsas.common.GlobalId; import com.arjuna.mw.wsas.activity.Outcome; import com.arjuna.mw.wsas.activity.HLS; import com.arjuna.mw.wsas.completionstatus.CompletionStatus; import com.arjuna.mw.wsas.exceptions.*; import java.util.*; /** * @author Mark Little (mark.little@arjuna.com) * @version $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ * @since 1.0. */ public class DemoHLS implements HLS { private Stack<GlobalId> _id; public DemoHLS() { _id = new Stack<GlobalId>(); } /** * An activity has begun and is active on the current thread. */ public void begun () throws SystemException { try { GlobalId activityId = UserActivityFactory.userActivity().activityId(); _id.push(activityId); System.out.println("DemoHLS.begun "+activityId); } catch (Exception ex) { ex.printStackTrace(); } } /** * The current activity is completing with the specified completion status. * * @return The result of terminating the relationship of this HLS and * the current activity. */ public Outcome complete (CompletionStatus cs) throws SystemException { try { System.out.println("DemoHLS.complete ( "+cs+" ) " + UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * The activity has been suspended. How does the HLS know which activity * has been suspended? It must remember what its notion of current is. */ public void suspended () throws SystemException { System.out.println("DemoHLS.suspended"); } /** * The activity has been resumed on the current thread. */ public void resumed () throws SystemException { System.out.println("DemoHLS.resumed"); } /** * The activity has completed and is no longer active on the current * thread. */ public void completed () throws SystemException { try { System.out.println("DemoHLS.completed "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } if (!_id.isEmpty()) { _id.pop(); } } /** * The HLS name. */ public String identity () throws SystemException { return "DemoHLS"; } /** * The activity service maintains a priority ordered list of HLS * implementations. If an HLS wishes to be ordered based on priority * then it can return a non-negative value: the higher the value, * the higher the priority and hence the earlier in the list of HLSes * it will appear (and be used in). * * @return a positive value for the priority for this HLS, or zero/negative * if the order is not important. */ public int priority () throws SystemException { return 0; } /** * Return the context augmentation for this HLS, if any on the current * activity. * * @return a context object or null if no augmentation is necessary. */ public Context context () throws SystemException { if (_id.isEmpty()) { throw new SystemException("request for context when inactive"); } try { System.out.println("DemoHLS.context "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return new DemoSOAPContextImple(identity() + "_" + _id.size()); } }
nmcl/scratch
graalvm/transactions/fork/narayana/XTS/localjunit/unit/src/test/java/com/arjuna/wsas/tests/DemoHLS.java
Java
apache-2.0
4,846
// // ColdAddressListCell.h // bither-ios // // Copyright 2014 http://Bither.net // // 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. #import <UIKit/UIKit.h> #import <Bitheri/BTAddress.h> @interface ColdAddressListCell : UITableViewCell - (void)showAddress:(BTAddress *)address; @end
rickw/bither-ios
bither-ios/Cells/ColdAddressListCell.h
C
apache-2.0
801
//// [privateIdentifierChain.1.ts] class A { a?: A #b?: A; getA(): A { return new A(); } constructor() { this?.#b; // Error this?.a.#b; // Error this?.getA().#b; // Error } } //// [privateIdentifierChain.1.js] "use strict"; class A { constructor() { this?.#b; // Error this?.a.#b; // Error this?.getA().#b; // Error } #b; getA() { return new A(); } }
Microsoft/TypeScript
tests/baselines/reference/privateIdentifierChain.1.js
JavaScript
apache-2.0
498
/*! * \~chinese * @header EMOptions+PrivateDeploy.h * @abstract SDK私有部署属性 * @author Hyphenate * @version 3.0 * * \~english * @header EMOptions+PrivateDeploy.h * @abstract SDK setting options of private deployment * @author Hyphenate * @version 3.0 */ #import "EMOptions.h" @interface EMOptions (PrivateDeploy) /*! * \~chinese * 是否允许使用DNS, 默认为YES * * 只能在[EMClient initializeSDKWithOptions:]中设置,不能在程序运行过程中动态修改。 * * \~english * Whether allow to use DNS, default is YES * * Can only set when initialize SDK [EMClient initializeSDKWithOptions:], can't change it in runtime */ @property (nonatomic, assign) BOOL enableDnsConfig; /*! * \~chinese * IM服务器端口 * * enableDnsConfig为NO时有效。只能在[EMClient initializeSDKWithOptions:]中设置,不能在程序运行过程中动态修改 * * \~english * IM server port * * It's effective only when enableDnsConfig is NO. Can only set when initialize SDK [EMClient initializeSDKWithOptions:], can't change it in runtime */ @property (nonatomic, assign) int chatPort; /*! * \~chinese * IM服务器地址 * * enableDnsConfig为NO时生效。只能在[EMClient initializeSDKWithOptions:]中设置,不能在程序运行过程中动态修改 * * \~english * IM server * * It's effective only when enableDnsConfig is NO. Can only set when initialize SDK [EMClient initializeSDKWithOptions:], can't change it in runtime */ @property (nonatomic, strong) NSString *chatServer; /*! * \~chinese * REST服务器地址 * * enableDnsConfig为NO时生效。只能在[EMClient initializeSDKWithOptions:]中设置,不能在程序运行过程中动态修改 * * \~english * REST server * * It's effective only when enableDnsConfig is NO. Can only set when initialize SDK [EMClient initializeSDKWithOptions:], can't change it in runtime */ @property (nonatomic, strong) NSString *restServer; @end
gaoyuhang/HuanXinTest
testhuanxin/HyphenateSDK/include/EMOptions+PrivateDeploy.h
C
apache-2.0
2,021
// @allowjs: true // @checkjs: true // @noemit: true // @strict: true // @filename: thisPropertyAssignmentComputed.js this["a" + "b"] = 0
Microsoft/TypeScript
tests/cases/conformance/salsa/thisPropertyAssignmentComputed.ts
TypeScript
apache-2.0
138
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.metadata.tool; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.common.util.HiveClient; import org.apache.kylin.metadata.MetadataConstants; import org.apache.kylin.metadata.MetadataManager; import org.apache.kylin.metadata.model.ColumnDesc; import org.apache.kylin.metadata.model.TableDesc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; /** * Management class to sync hive table metadata with command See main method for * how to use the class * * @author jianliu */ public class HiveSourceTableLoader { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HiveSourceTableLoader.class); public static final String OUTPUT_SURFIX = "json"; public static final String TABLE_FOLDER_NAME = "table"; public static final String TABLE_EXD_FOLDER_NAME = "table_exd"; public static Set<String> reloadHiveTables(String[] hiveTables, KylinConfig config) throws IOException { Map<String, Set<String>> db2tables = Maps.newHashMap(); for (String table : hiveTables) { String[] parts = HadoopUtil.parseHiveTableName(table); Set<String> set = db2tables.get(parts[0]); if (set == null) { set = Sets.newHashSet(); db2tables.put(parts[0], set); } set.add(parts[1]); } // extract from hive Set<String> loadedTables = Sets.newHashSet(); for (String database : db2tables.keySet()) { List<String> loaded = extractHiveTables(database, db2tables.get(database), config); loadedTables.addAll(loaded); } return loadedTables; } private static List<String> extractHiveTables(String database, Set<String> tables, KylinConfig config) throws IOException { List<String> loadedTables = Lists.newArrayList(); MetadataManager metaMgr = MetadataManager.getInstance(KylinConfig.getInstanceFromEnv()); for (String tableName : tables) { Table table = null; HiveClient hiveClient = new HiveClient(); List<FieldSchema> partitionFields = null; List<FieldSchema> fields = null; try { table = hiveClient.getHiveTable(database, tableName); partitionFields = table.getPartitionKeys(); fields = hiveClient.getHiveTableFields(database, tableName); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } if (fields != null && partitionFields != null && partitionFields.size() > 0) { fields.addAll(partitionFields); } long tableSize = hiveClient.getFileSizeForTable(table); long tableFileNum = hiveClient.getFileNumberForTable(table); TableDesc tableDesc = metaMgr.getTableDesc(database + "." + tableName); if (tableDesc == null) { tableDesc = new TableDesc(); tableDesc.setDatabase(database.toUpperCase()); tableDesc.setName(tableName.toUpperCase()); tableDesc.setUuid(UUID.randomUUID().toString()); tableDesc.setLastModified(0); } int columnNumber = fields.size(); List<ColumnDesc> columns = new ArrayList<ColumnDesc>(columnNumber); for (int i = 0; i < columnNumber; i++) { FieldSchema field = fields.get(i); ColumnDesc cdesc = new ColumnDesc(); cdesc.setName(field.getName().toUpperCase()); cdesc.setDatatype(field.getType()); cdesc.setId(String.valueOf(i + 1)); columns.add(cdesc); } tableDesc.setColumns(columns.toArray(new ColumnDesc[columnNumber])); StringBuffer partitionColumnString = new StringBuffer(); for (int i = 0, n = partitionFields.size(); i < n; i++) { if (i > 0) partitionColumnString.append(", "); partitionColumnString.append(partitionFields.get(i).getName().toUpperCase()); } Map<String, String> map = metaMgr.getTableDescExd(tableDesc.getIdentity()); if (map == null) { map = Maps.newHashMap(); } map.put(MetadataConstants.TABLE_EXD_TABLENAME, table.getTableName()); map.put(MetadataConstants.TABLE_EXD_LOCATION, table.getSd().getLocation()); map.put(MetadataConstants.TABLE_EXD_IF, table.getSd().getInputFormat()); map.put(MetadataConstants.TABLE_EXD_OF, table.getSd().getOutputFormat()); map.put(MetadataConstants.TABLE_EXD_OWNER, table.getOwner()); map.put(MetadataConstants.TABLE_EXD_LAT, String.valueOf(table.getLastAccessTime())); map.put(MetadataConstants.TABLE_EXD_PC, partitionColumnString.toString()); map.put(MetadataConstants.TABLE_EXD_TFS, String.valueOf(tableSize)); map.put(MetadataConstants.TABLE_EXD_TNF, String.valueOf(tableFileNum)); map.put(MetadataConstants.TABLE_EXD_PARTITIONED, Boolean.valueOf(partitionFields != null && partitionFields.size() > 0).toString()); metaMgr.saveSourceTable(tableDesc); metaMgr.saveTableExd(tableDesc.getIdentity(), map); loadedTables.add(tableDesc.getIdentity()); } return loadedTables; } }
nvoron23/Kylin
metadata/src/main/java/org/apache/kylin/metadata/tool/HiveSourceTableLoader.java
Java
apache-2.0
6,633
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.io; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.Platform; import com.google.common.base.Splitter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class ConfiguredBuckOutIntegrationTest { private ProjectWorkspace workspace; @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Before public void setUp() throws IOException { workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "configured_buck_out", tmp); workspace.setUp(); } @Test public void outputPathsUseConfiguredBuckOut() throws IOException { String buckOut = "new-buck-out"; Path output = workspace.buildAndReturnOutput("-c", "project.buck_out=" + buckOut, "//:dummy"); assertTrue(Files.exists(output)); assertThat(workspace.getDestPath().relativize(output).toString(), Matchers.startsWith(buckOut)); } @Test public void configuredBuckOutAffectsRuleKey() throws IOException { String out = workspace .runBuckCommand("targets", "--show-rulekey", "//:dummy") .assertSuccess() .getStdout(); String ruleKey = Splitter.on(' ').splitToList(out).get(1); String configuredOut = workspace .runBuckCommand( "targets", "--show-rulekey", "-c", "project.buck_out=something", "//:dummy") .assertSuccess() .getStdout(); String configuredRuleKey = Splitter.on(' ').splitToList(configuredOut).get(1); assertThat(ruleKey, Matchers.not(Matchers.equalTo(configuredRuleKey))); } @Test public void buckOutCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); ProcessResult result = workspace.runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy"); result.assertSuccess(); assertThat( Files.readSymbolicLink(workspace.resolve("buck-out/gen")), Matchers.equalTo(workspace.getDestPath().getFileSystem().getPath("../something/gen"))); } @Test public void verifyTogglingConfiguredBuckOut() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.runBuckBuild("//:dummy").assertSuccess(); workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); } @Test public void verifyNoopBuildWithCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); // Do an initial build. workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.getBuildLog().assertTargetBuiltLocally("//:dummy"); // Run another build immediately after and verify everything was up to date. workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.getBuildLog().assertTargetHadMatchingRuleKey("//:dummy"); } @Test public void targetsShowOutput() throws IOException { String output = workspace .runBuckCommand( "targets", "--show-output", "-c", "project.buck_out=something", "//:dummy") .assertSuccess() .getStdout() .trim(); output = Splitter.on(' ').splitToList(output).get(1); assertThat(MorePaths.pathWithUnixSeparators(output), Matchers.startsWith("something/")); } @Test public void targetsShowOutputCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); String output = workspace .runBuckCommand( "targets", "--show-output", "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess() .getStdout() .trim(); output = Splitter.on(' ').splitToList(output).get(1); assertThat(MorePaths.pathWithUnixSeparators(output), Matchers.startsWith("buck-out/gen/")); } @Test public void buildShowOutput() throws IOException { Path output = workspace.buildAndReturnOutput("-c", "project.buck_out=something", "//:dummy"); assertThat( MorePaths.pathWithUnixSeparators(workspace.getDestPath().relativize(output)), Matchers.startsWith("something/")); } @Test public void buildShowOutputCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); Path output = workspace.buildAndReturnOutput( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy"); assertThat( MorePaths.pathWithUnixSeparators(workspace.getDestPath().relativize(output)), Matchers.startsWith("buck-out/gen/")); } }
LegNeato/buck
test/com/facebook/buck/io/ConfiguredBuckOutIntegrationTest.java
Java
apache-2.0
6,709
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.thrift.model; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.collect.Maps; import com.netflix.astyanax.Serializer; import com.netflix.astyanax.model.AbstractColumnList; import com.netflix.astyanax.model.Column; public class ThriftCounterColumnListImpl<C> extends AbstractColumnList<C> { private final List<org.apache.cassandra.thrift.CounterColumn> columns; private Map<C, org.apache.cassandra.thrift.CounterColumn> lookup; private final Serializer<C> colSer; public ThriftCounterColumnListImpl(List<org.apache.cassandra.thrift.CounterColumn> columns, Serializer<C> colSer) { this.columns = columns; this.colSer = colSer; } @Override public Iterator<Column<C>> iterator() { class IteratorImpl implements Iterator<Column<C>> { Iterator<org.apache.cassandra.thrift.CounterColumn> base; public IteratorImpl(Iterator<org.apache.cassandra.thrift.CounterColumn> base) { this.base = base; } @Override public boolean hasNext() { return base.hasNext(); } @Override public Column<C> next() { org.apache.cassandra.thrift.CounterColumn c = base.next(); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public void remove() { throw new UnsupportedOperationException("Iterator is immutable"); } } return new IteratorImpl(columns.iterator()); } @Override public Column<C> getColumnByName(C columnName) { constructMap(); org.apache.cassandra.thrift.CounterColumn c = lookup.get(columnName); if (c == null) { return null; } return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public Column<C> getColumnByIndex(int idx) { org.apache.cassandra.thrift.CounterColumn c = columns.get(idx); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public <C2> Column<C2> getSuperColumn(C columnName, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public <C2> Column<C2> getSuperColumn(int idx, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public boolean isEmpty() { return columns.isEmpty(); } @Override public int size() { return columns.size(); } @Override public boolean isSuperColumn() { return false; } @Override public Collection<C> getColumnNames() { constructMap(); return lookup.keySet(); } private void constructMap() { if (lookup == null) { lookup = Maps.newHashMap(); for (org.apache.cassandra.thrift.CounterColumn column : columns) { lookup.put(colSer.fromBytes(column.getName()), column); } } } }
0x6e6562/astyanax
src/main/java/com/netflix/astyanax/thrift/model/ThriftCounterColumnListImpl.java
Java
apache-2.0
3,953
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.unnest; import com.facebook.presto.Session; import com.facebook.presto.block.BlockAssertions.Encoding; import com.facebook.presto.common.Page; import com.facebook.presto.common.type.ArrayType; import com.facebook.presto.common.type.RowType; import com.facebook.presto.common.type.Type; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.operator.DriverContext; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OperatorFactory; import com.facebook.presto.operator.PageAssertions; import com.facebook.presto.spi.plan.PlanNodeId; import com.facebook.presto.testing.MaterializedResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.facebook.airlift.concurrent.Threads.daemonThreadsNamed; import static com.facebook.presto.RowPagesBuilder.rowPagesBuilder; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.block.BlockAssertions.Encoding.DICTIONARY; import static com.facebook.presto.block.BlockAssertions.Encoding.RUN_LENGTH; import static com.facebook.presto.block.BlockAssertions.createMapType; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.BooleanType.BOOLEAN; import static com.facebook.presto.common.type.DecimalType.createDecimalType; import static com.facebook.presto.common.type.Decimals.MAX_SHORT_PRECISION; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.common.type.IntegerType.INTEGER; import static com.facebook.presto.common.type.RowType.withDefaultFieldNames; import static com.facebook.presto.common.type.SmallintType.SMALLINT; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.facebook.presto.metadata.MetadataManager.createTestMetadataManager; import static com.facebook.presto.operator.OperatorAssertion.assertOperatorEquals; import static com.facebook.presto.operator.PageAssertions.assertPageEquals; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildExpectedPage; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildOutputTypes; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.calculateMaxCardinalities; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.mergePages; import static com.facebook.presto.testing.MaterializedResult.resultBuilder; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static com.facebook.presto.testing.TestingTaskContext.createTaskContext; import static com.facebook.presto.tpch.TpchMetadata.TINY_SCHEMA_NAME; import static com.facebook.presto.util.StructuralTestUtil.arrayBlockOf; import static com.facebook.presto.util.StructuralTestUtil.mapBlockOf; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.NaN; import static java.lang.Double.POSITIVE_INFINITY; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestUnnestOperator { private static final int PAGE_COUNT = 10; private static final int POSITION_COUNT = 500; private static final ExecutorService EXECUTOR = newCachedThreadPool(daemonThreadsNamed("test-EXECUTOR-%s")); private static final ScheduledExecutorService SCHEDULER = newScheduledThreadPool(1, daemonThreadsNamed("test-%s")); private ExecutorService executor; private ScheduledExecutorService scheduledExecutor; private DriverContext driverContext; @BeforeMethod public void setUp() { executor = newCachedThreadPool(daemonThreadsNamed("test-executor-%s")); scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s")); driverContext = createTaskContext(executor, scheduledExecutor, TEST_SESSION) .addPipelineContext(0, true, true, false) .addDriverContext(); } @AfterMethod public void tearDown() { executor.shutdownNow(); scheduledExecutor.shutdownNow(); } @Test public void testUnnest() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L) .row(1L, 3L, null, null) .row(2L, 99L, null, null) .row(6L, 7L, 9L, 10L) .row(6L, 8L, 11L, 12L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArray() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(array(bigint))")); Type mapType = metadata.getType(parseTypeSignature("map(array(bigint),array(bigint))")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row( 1L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(2, 4), ImmutableList.of(3, 6)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(4, 8), ImmutableList.of(5, 10)))) .row(2L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(99, 198)), null) .row(3L, null, null) .pageBreak() .row( 6, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(7, 14), ImmutableList.of(8, 16)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(9, 18), ImmutableList.of(10, 20), ImmutableList.of(11, 22), ImmutableList.of(12, 24)))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, new ArrayType(BIGINT), new ArrayType(BIGINT), new ArrayType(BIGINT)) .row(1L, ImmutableList.of(2L, 4L), ImmutableList.of(4L, 8L), ImmutableList.of(5L, 10L)) .row(1L, ImmutableList.of(3L, 6L), null, null) .row(2L, ImmutableList.of(99L, 198L), null, null) .row(6L, ImmutableList.of(7L, 14L), ImmutableList.of(9L, 18L), ImmutableList.of(10L, 20L)) .row(6L, ImmutableList.of(8L, 16L), ImmutableList.of(11L, 22L), ImmutableList.of(12L, 24L)) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithOrdinality() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), true); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L, 1L) .row(1L, 3L, null, null, 2L) .row(2L, 99L, null, null, 1L) .row(6L, 7L, 9L, 10L, 1L) .row(6L, 8L, 11L, 12L, 2L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestNonNumericDoubles() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(double)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,double)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(DOUBLE, NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN), mapBlockOf(BIGINT, DOUBLE, ImmutableMap.of(1, NEGATIVE_INFINITY, 2, POSITIVE_INFINITY, 3, NaN))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, DOUBLE, BIGINT, DOUBLE) .row(1L, NEGATIVE_INFINITY, 1L, NEGATIVE_INFINITY) .row(1L, POSITIVE_INFINITY, 2L, POSITIVE_INFINITY) .row(1L, NaN, 3L, NaN) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArrayOfRows() { MetadataManager metadata = createTestMetadataManager(); Type arrayOfRowType = metadata.getType(parseTypeSignature("array(row(bigint, double, varchar))")); Type elementType = RowType.anonymous(ImmutableList.of(BIGINT, DOUBLE, VARCHAR)); List<Page> input = rowPagesBuilder(BIGINT, arrayOfRowType) .row(1, arrayBlockOf(elementType, ImmutableList.of(2, 4.2, "abc"), ImmutableList.of(3, 6.6, "def"))) .row(2, arrayBlockOf(elementType, ImmutableList.of(99, 3.14, "pi"), null)) .row(3, null) .pageBreak() .row(6, arrayBlockOf(elementType, null, ImmutableList.of(8, 1.111, "tt"))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1), ImmutableList.of(arrayOfRowType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, DOUBLE, VARCHAR) .row(1L, 2L, 4.2, "abc") .row(1L, 3L, 6.6, "def") .row(2L, 99L, 3.14, "pi") .row(2L, null, null, null) .row(6L, null, null, null) .row(6L, 8L, 1.111, "tt") .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestSingleArrayUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleMapUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleArrayOfRowUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR))))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BOOLEAN); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BOOLEAN), new ArrayType(BOOLEAN)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(SMALLINT); unnestTypes = ImmutableList.of(new ArrayType(SMALLINT), new ArrayType(SMALLINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(INTEGER); unnestTypes = ImmutableList.of(new ArrayType(INTEGER), new ArrayType(INTEGER)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(BIGINT), new ArrayType(BIGINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(createDecimalType(MAX_SHORT_PRECISION + 1)); unnestTypes = ImmutableList.of( new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1)), new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR), new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT)), new ArrayType(new ArrayType(VARCHAR))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(createMapType(BIGINT, BIGINT)), new ArrayType(createMapType(BIGINT, BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoMapUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT), createMapType(VARCHAR, VARCHAR)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayOfRowUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER))), new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestMultipleUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR), new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT))), new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } protected void testUnnest(List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types) { testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); } protected void testUnnest( List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types, float primitiveNullRate, float nestedNullRate, boolean useBlockView, List<Encoding> wrappings) { List<Page> inputPages = new ArrayList<>(); for (int i = 0; i < PAGE_COUNT; i++) { Page inputPage = PageAssertions.createPageWithRandomData(types, POSITION_COUNT, false, false, primitiveNullRate, nestedNullRate, useBlockView, wrappings); inputPages.add(inputPage); } testUnnest(inputPages, replicatedTypes, unnestTypes, false, false); testUnnest(inputPages, replicatedTypes, unnestTypes, true, false); testUnnest(inputPages, replicatedTypes, unnestTypes, false, true); testUnnest(inputPages, replicatedTypes, unnestTypes, true, true); } private void testUnnest(List<Page> inputPages, List<Type> replicatedTypes, List<Type> unnestTypes, boolean withOrdinality, boolean legacyUnnest) { List<Integer> replicatedChannels = IntStream.range(0, replicatedTypes.size()).boxed().collect(Collectors.toList()); List<Integer> unnestChannels = IntStream.range(replicatedTypes.size(), replicatedTypes.size() + unnestTypes.size()).boxed().collect(Collectors.toList()); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), replicatedChannels, replicatedTypes, unnestChannels, unnestTypes, withOrdinality); Operator unnestOperator = ((UnnestOperator.UnnestOperatorFactory) operatorFactory).createOperator(createDriverContext(), legacyUnnest); for (Page inputPage : inputPages) { int[] maxCardinalities = calculateMaxCardinalities(inputPage, replicatedTypes, unnestTypes); List<Type> outputTypes = buildOutputTypes(replicatedTypes, unnestTypes, withOrdinality, legacyUnnest); Page expectedPage = buildExpectedPage(inputPage, replicatedTypes, unnestTypes, outputTypes, maxCardinalities, withOrdinality, legacyUnnest); unnestOperator.addInput(inputPage); List<Page> outputPages = new ArrayList<>(); while (true) { Page outputPage = unnestOperator.getOutput(); if (outputPage == null) { break; } assertTrue(outputPage.getPositionCount() <= 1000); outputPages.add(outputPage); } Page mergedOutputPage = mergePages(outputTypes, outputPages); assertPageEquals(outputTypes, mergedOutputPage, expectedPage); } } private DriverContext createDriverContext() { Session testSession = testSessionBuilder() .setCatalog("tpch") .setSchema(TINY_SCHEMA_NAME) .build(); return createTaskContext(EXECUTOR, SCHEDULER, testSession) .addPipelineContext(0, true, true, false) .addDriverContext(); } }
facebook/presto
presto-main/src/test/java/com/facebook/presto/operator/unnest/TestUnnestOperator.java
Java
apache-2.0
26,599
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../includes/main.css" type="text/css"> <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"> <title>Apache CloudStack | The Power Behind Your Cloud</title> </head> <body> <div id="insidetopbg"> <div id="inside_wrapper"> <div class="uppermenu_panel"> <div class="uppermenu_box"></div> </div> <div id="main_master"> <div id="inside_header"> <div class="header_top"> <a class="cloud_logo" href="http://cloudstack.org"></a> <div class="mainemenu_panel"></div> </div> </div> <div id="main_content"> <div class="inside_apileftpanel"> <div class="inside_contentpanel" style="width:930px;"> <div class="api_titlebox"> <div class="api_titlebox_left"> <span> Apache CloudStack v4.8.0 Root Admin API Reference </span> <p></p> <h1>deleteProject</h1> <p>Deletes a project</p> </div> <div class="api_titlebox_right"> <a class="api_backbutton" href="../TOC_Root_Admin.html"></a> </div> </div> <div class="api_tablepanel"> <h2>Request parameters</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td> </tr> <tr> <td style="width:200px;"><strong>id</strong></td><td style="width:500px;"><strong>id of the project to be deleted</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> </table> </div> <div class="api_tablepanel"> <h2>Response Tags</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td> </tr> <tr> <td style="width:200px;"><strong>displaytext</strong></td><td style="width:500px;">any text associated with the success or failure</td> </tr> <tr> <td style="width:200px;"><strong>success</strong></td><td style="width:500px;">true if operation is executed successfully</td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> <div id="comments_thread"> <script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script> <noscript> <iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&amp;page=4.2.0/rootadmin"></iframe> </noscript> </div> <div id="footer_mainmaster"> <p>Copyright &copy; 2016 The Apache Software Foundation, Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a> <br> Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p> </div> </div> </div> </div> </body> </html>
apache/cloudstack-www
source/api/apidocs-4.8/root_admin/deleteProject.html
HTML
apache-2.0
2,932
// RUN: %clang_cc1 -fsyntax-only -fshow-overloads=best -std=c++11 -verify %s template <class T> struct X { operator T() const {return T();} }; void test_char16t(X<char16_t> x) { bool b = x == char16_t(); }
jeltz/rust-debian-package
src/llvm/tools/clang/test/SemaCXX/overloaded-builtin-operators-0x.cpp
C++
apache-2.0
215
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure.Commands.CloudService.Development; using Microsoft.WindowsAzure.Commands.Common.Test.Mocks; using Microsoft.WindowsAzure.Commands.Test.Utilities.CloudService; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Microsoft.WindowsAzure.Commands.Utilities.CloudService; using Xunit; namespace Microsoft.WindowsAzure.Commands.Test.CloudService.Development.Tests.Cmdlet { public class GetAzureServiceProjectRuntimesTests : TestBase { private const string serviceName = "AzureService"; MockCommandRuntime mockCommandRuntime; private GetAzureServiceProjectRoleRuntimeCommand cmdlet; public GetAzureServiceProjectRuntimesTests() { cmdlet = new GetAzureServiceProjectRoleRuntimeCommand(); mockCommandRuntime = new MockCommandRuntime(); cmdlet.CommandRuntime = mockCommandRuntime; } /// <summary> /// Verify that the correct runtimes are returned in the correct format from a given runtime manifest /// </summary> [Fact] public void TestGetRuntimes() { using (FileSystemHelper files = new FileSystemHelper(this)) { string manifest = RuntimePackageHelper.GetTestManifest(files); CloudRuntimeCollection runtimes; CloudRuntimeCollection.CreateCloudRuntimeCollection(out runtimes, manifest); cmdlet.GetAzureRuntimesProcess(string.Empty, manifest); List<CloudRuntimePackage> actual = mockCommandRuntime.OutputPipeline[0] as List<CloudRuntimePackage>; Assert.Equal<int>(runtimes.Count, actual.Count); Assert.True(runtimes.All<CloudRuntimePackage>(p => actual.Any<CloudRuntimePackage>(p2 => p2.PackageUri.Equals(p.PackageUri)))); } } } }
amarzavery/azure-powershell
src/ServiceManagement/Services/Commands.Test/CloudService/Development/GetAzureServiceProjectRuntimesTest.cs
C#
apache-2.0
2,685
// // Copyright (C) 2012-2014 DataStax Inc. // // 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. // namespace Cassandra.IntegrationTests.TestBase { public class Options : TestGlobals { public static Options Default = new Options(); /// <summary> /// Cassandra version. For example: 1.2.16 or 2.0.7 /// </summary> public readonly string CASSANDRA_VERSION; public readonly string IP_PREFIX; public string SSH_HOST; public string SSH_PASSWORD; public int SSH_PORT; public string SSH_USERNAME; public bool USE_COMPRESSION; public bool USE_LOGGER; public bool USE_NOBUFFERING; private Options() { CASSANDRA_VERSION = CassandraVersionStr; IP_PREFIX = DefaultIpPrefix; SSH_HOST = SSHHost; SSH_PORT = SSHPort; SSH_USERNAME = SSHUser; SSH_PASSWORD = SSHPassword; USE_COMPRESSION = UseCompression; USE_NOBUFFERING = NoUseBuffering; USE_LOGGER = UseLogger; } } }
bridgewell/csharp-driver
src/Cassandra.IntegrationTests/TestBase/Options.cs
C#
apache-2.0
1,638
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: $ */ package org.apache.xml.serializer.dom3; import org.w3c.dom.DOMError; import org.w3c.dom.DOMLocator; /** * Implementation of the DOM Level 3 DOMError interface. * * <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ERROR-Interfaces-DOMError'>DOMError Interface definition from Document Object Model (DOM) Level 3 Core Specification</a>. * * @xsl.usage internal */ public final class DOMErrorImpl implements DOMError { /** private data members */ // The DOMError Severity private short fSeverity = DOMError.SEVERITY_WARNING; // The Error message private String fMessage = null; // A String indicating which related data is expected in relatedData. private String fType; // The platform related exception private Exception fException = null; // private Object fRelatedData; // The location of the exception private DOMLocatorImpl fLocation = new DOMLocatorImpl(); // // Constructors // /** * Default constructor. */ DOMErrorImpl () { } /** * @param severity * @param message * @param type */ public DOMErrorImpl(short severity, String message, String type) { fSeverity = severity; fMessage = message; fType = type; } /** * @param severity * @param message * @param type * @param exception */ public DOMErrorImpl(short severity, String message, String type, Exception exception) { fSeverity = severity; fMessage = message; fType = type; fException = exception; } /** * @param severity * @param message * @param type * @param exception * @param relatedData * @param location */ public DOMErrorImpl(short severity, String message, String type, Exception exception, Object relatedData, DOMLocatorImpl location) { fSeverity = severity; fMessage = message; fType = type; fException = exception; fRelatedData = relatedData; fLocation = location; } /** * The severity of the error, either <code>SEVERITY_WARNING</code>, * <code>SEVERITY_ERROR</code>, or <code>SEVERITY_FATAL_ERROR</code>. * * @return A short containing the DOMError severity */ public short getSeverity() { return fSeverity; } /** * The DOMError message string. * * @return String */ public String getMessage() { return fMessage; } /** * The location of the DOMError. * * @return A DOMLocator object containing the DOMError location. */ public DOMLocator getLocation() { return fLocation; } /** * The related platform dependent exception if any. * * @return A java.lang.Exception */ public Object getRelatedException(){ return fException; } /** * Returns a String indicating which related data is expected in relatedData. * * @return A String */ public String getType(){ return fType; } /** * The related DOMError.type dependent data if any. * * @return java.lang.Object */ public Object getRelatedData(){ return fRelatedData; } public void reset(){ fSeverity = DOMError.SEVERITY_WARNING; fException = null; fMessage = null; fType = null; fRelatedData = null; fLocation = null; } }// class DOMErrorImpl
mirego/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/dom3/DOMErrorImpl.java
Java
apache-2.0
4,503
package org.axonframework.test.saga; public class NonTransientResource { }
bojanv55/AxonFramework
test/src/test/java/org/axonframework/test/saga/NonTransientResource.java
Java
apache-2.0
76
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dfareporting.model; /** * Click-through URL * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the DCM/DFA Reporting And Trafficking API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class CreativeClickThroughUrl extends com.google.api.client.json.GenericJson { /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String computedClickThroughUrl; /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String customClickThroughUrl; /** * ID of the landing page for the click-through URL. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long landingPageId; /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @return value or {@code null} for none */ public java.lang.String getComputedClickThroughUrl() { return computedClickThroughUrl; } /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @param computedClickThroughUrl computedClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setComputedClickThroughUrl(java.lang.String computedClickThroughUrl) { this.computedClickThroughUrl = computedClickThroughUrl; return this; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @return value or {@code null} for none */ public java.lang.String getCustomClickThroughUrl() { return customClickThroughUrl; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @param customClickThroughUrl customClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setCustomClickThroughUrl(java.lang.String customClickThroughUrl) { this.customClickThroughUrl = customClickThroughUrl; return this; } /** * ID of the landing page for the click-through URL. * @return value or {@code null} for none */ public java.lang.Long getLandingPageId() { return landingPageId; } /** * ID of the landing page for the click-through URL. * @param landingPageId landingPageId or {@code null} for none */ public CreativeClickThroughUrl setLandingPageId(java.lang.Long landingPageId) { this.landingPageId = landingPageId; return this; } @Override public CreativeClickThroughUrl set(String fieldName, Object value) { return (CreativeClickThroughUrl) super.set(fieldName, value); } @Override public CreativeClickThroughUrl clone() { return (CreativeClickThroughUrl) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-dfareporting/v3.4/1.29.2/com/google/api/services/dfareporting/model/CreativeClickThroughUrl.java
Java
apache-2.0
4,569
// @declaration: true // @noImplicitThis: true // https://github.com/microsoft/TypeScript/issues/29902 function createObj() { return { func1() { return this; }, func2() { return this; }, func3() { return this; } }; } function createObjNoCrash() { return { func1() { return this; }, func2() { return this; }, func3() { return this; }, func4() { return this; }, func5() { return this; }, func6() { return this; }, func7() { return this; }, func8() { return this; }, func9() { return this; } }; }
Microsoft/TypeScript
tests/cases/compiler/noImplicitThisBigThis.ts
TypeScript
apache-2.0
899
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_31) on Mon Jul 22 15:25:23 PDT 2013 --> <TITLE> Uses of Class org.apache.hadoop.mapred.join.ResetableIterator.EMPTY (Hadoop 1.2.1 API) </TITLE> <META NAME="date" CONTENT="2013-07-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.mapred.join.ResetableIterator.EMPTY (Hadoop 1.2.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/mapred/join/ResetableIterator.EMPTY.html" title="class in org.apache.hadoop.mapred.join"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/mapred/join//class-useResetableIterator.EMPTY.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ResetableIterator.EMPTY.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.mapred.join.ResetableIterator.EMPTY</B></H2> </CENTER> No usage of org.apache.hadoop.mapred.join.ResetableIterator.EMPTY <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/mapred/join/ResetableIterator.EMPTY.html" title="class in org.apache.hadoop.mapred.join"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/mapred/join//class-useResetableIterator.EMPTY.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ResetableIterator.EMPTY.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
determinedcheetahs/cheetah_juniper
hadoop/docs/api/org/apache/hadoop/mapred/join/class-use/ResetableIterator.EMPTY.html
HTML
apache-2.0
6,195
package strategy import ( "reflect" "strings" "testing" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation" kapi "k8s.io/kubernetes/pkg/api" buildapi "github.com/openshift/origin/pkg/build/api" _ "github.com/openshift/origin/pkg/build/api/install" ) func TestDockerCreateBuildPod(t *testing.T) { strategy := DockerBuildStrategy{ Image: "docker-test-image", Codec: kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion), } build := mockDockerBuild() actual, err := strategy.CreateBuildPod(build) if err != nil { t.Errorf("Unexpected error: %v", err) } if expected, actual := buildapi.GetBuildPodName(build), actual.ObjectMeta.Name; expected != actual { t.Errorf("Expected %s, but got %s!", expected, actual) } if !reflect.DeepEqual(map[string]string{buildapi.BuildLabel: buildapi.LabelValue(build.Name)}, actual.Labels) { t.Errorf("Pod Labels does not match Build Labels!") } if !reflect.DeepEqual(nodeSelector, actual.Spec.NodeSelector) { t.Errorf("Pod NodeSelector does not match Build NodeSelector. Expected: %v, got: %v", nodeSelector, actual.Spec.NodeSelector) } container := actual.Spec.Containers[0] if container.Name != "docker-build" { t.Errorf("Expected docker-build, but got %s!", container.Name) } if container.Image != strategy.Image { t.Errorf("Expected %s image, got %s!", container.Image, strategy.Image) } if container.ImagePullPolicy != kapi.PullIfNotPresent { t.Errorf("Expected %v, got %v", kapi.PullIfNotPresent, container.ImagePullPolicy) } if actual.Spec.RestartPolicy != kapi.RestartPolicyNever { t.Errorf("Expected never, got %#v", actual.Spec.RestartPolicy) } if len(container.Env) != 10 { var keys []string for _, env := range container.Env { keys = append(keys, env.Name) } t.Fatalf("Expected 10 elements in Env table, got %d:\n%s", len(container.Env), strings.Join(keys, ", ")) } if len(container.VolumeMounts) != 4 { t.Fatalf("Expected 4 volumes in container, got %d", len(container.VolumeMounts)) } if *actual.Spec.ActiveDeadlineSeconds != 60 { t.Errorf("Expected ActiveDeadlineSeconds 60, got %d", *actual.Spec.ActiveDeadlineSeconds) } for i, expected := range []string{dockerSocketPath, DockerPushSecretMountPath, DockerPullSecretMountPath, sourceSecretMountPath} { if container.VolumeMounts[i].MountPath != expected { t.Fatalf("Expected %s in VolumeMount[%d], got %s", expected, i, container.VolumeMounts[i].MountPath) } } if len(actual.Spec.Volumes) != 4 { t.Fatalf("Expected 4 volumes in Build pod, got %d", len(actual.Spec.Volumes)) } if !kapi.Semantic.DeepEqual(container.Resources, build.Spec.Resources) { t.Fatalf("Expected actual=expected, %v != %v", container.Resources, build.Spec.Resources) } found := false foundIllegal := false for _, v := range container.Env { if v.Name == "BUILD_LOGLEVEL" && v.Value == "bar" { found = true } if v.Name == "ILLEGAL" { foundIllegal = true } } if !found { t.Fatalf("Expected variable BUILD_LOGLEVEL be defined for the container") } if foundIllegal { t.Fatalf("Found illegal environment variable 'ILLEGAL' defined on container") } buildJSON, _ := runtime.Encode(kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion), build) errorCases := map[int][]string{ 0: {"BUILD", string(buildJSON)}, } for index, exp := range errorCases { if e := container.Env[index]; e.Name != exp[0] || e.Value != exp[1] { t.Errorf("Expected %s:%s, got %s:%s!\n", exp[0], exp[1], e.Name, e.Value) } } } func TestDockerBuildLongName(t *testing.T) { strategy := DockerBuildStrategy{ Image: "docker-test-image", Codec: kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion), } build := mockDockerBuild() build.Name = strings.Repeat("a", validation.DNS1123LabelMaxLength*2) pod, err := strategy.CreateBuildPod(build) if err != nil { t.Fatalf("unexpected: %v", err) } if pod.Labels[buildapi.BuildLabel] != build.Name[:validation.DNS1123LabelMaxLength] { t.Errorf("Unexpected build label value: %s", pod.Labels[buildapi.BuildLabel]) } } func mockDockerBuild() *buildapi.Build { timeout := int64(60) return &buildapi.Build{ ObjectMeta: metav1.ObjectMeta{ Name: "dockerBuild", Labels: map[string]string{ "name": "dockerBuild", }, }, Spec: buildapi.BuildSpec{ CommonSpec: buildapi.CommonSpec{ Revision: &buildapi.SourceRevision{ Git: &buildapi.GitSourceRevision{}, }, Source: buildapi.BuildSource{ Git: &buildapi.GitBuildSource{ URI: "http://my.build.com/the/dockerbuild/Dockerfile", Ref: "master", }, ContextDir: "my/test/dir", SourceSecret: &kapi.LocalObjectReference{Name: "secretFoo"}, }, Strategy: buildapi.BuildStrategy{ DockerStrategy: &buildapi.DockerBuildStrategy{ PullSecret: &kapi.LocalObjectReference{Name: "bar"}, Env: []kapi.EnvVar{ {Name: "ILLEGAL", Value: "foo"}, {Name: "BUILD_LOGLEVEL", Value: "bar"}, }, }, }, Output: buildapi.BuildOutput{ To: &kapi.ObjectReference{ Kind: "DockerImage", Name: "docker-registry/repository/dockerBuild", }, PushSecret: &kapi.LocalObjectReference{Name: "foo"}, }, Resources: kapi.ResourceRequirements{ Limits: kapi.ResourceList{ kapi.ResourceName(kapi.ResourceCPU): resource.MustParse("10"), kapi.ResourceName(kapi.ResourceMemory): resource.MustParse("10G"), }, }, CompletionDeadlineSeconds: &timeout, NodeSelector: nodeSelector, }, }, Status: buildapi.BuildStatus{ Phase: buildapi.BuildPhaseNew, }, } }
stevekuznetsov/origin
pkg/build/controller/strategy/docker_test.go
GO
apache-2.0
5,708
#!/bin/bash ######################################################################## # # Linux on Hyper-V and Azure Test Code, ver. 1.0.0 # Copyright (c) Microsoft Corporation # # All rights reserved. # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION # ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR # PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. # # See the Apache Version 2.0 License for specific language governing # permissions and limitations under the License. # ######################################################################## ####################################################################### # # performance_zk.sh # # Description: # This tool uses the ZooKeeper (zk) python binding to test various operation latencies # # # In general the script does the following: # # 1.create a root znode for the test, i.e. /zk-latencies # 2.attach a zk session to each server in the ensemble (the --servers list) # 3.run various (create/get/set/delete) operations against each server, note the latencies of operations # 4.client then cleans up, removing /zk-latencies znode # # # Parameters: # ZK_VERSION zookeeper-server version # ZK_SERVERS: comma separated list of host:port (default localhost:2181) # ZK_TIMEOUT; session timeout in milliseconds (default 5000) # ZK_ZNODE_SIZE; data size when creating/setting znodes (default 25) # ZK_ZNODE_COUNT; the number of znodes to operate on in each performance section (default 10000) # ZK_FORCE; (optional) force the test to run, even if root_znode exists -WARNING! don't run this on a real znode or you'll lose it !!! # ZK_SYNCHRONOUS; by default asynchronous ZK api is used, this forces synchronous calls # ZK_VERBOSE; verbose output, include more detail # ####################################################################### ICA_TESTRUNNING="TestRunning" ICA_TESTCOMPLETED="TestCompleted" ICA_TESTABORTED="TestAborted" ICA_TESTFAILED="TestFailed" # # Function definitions # LogMsg() { echo `date "+%a %b %d %T %Y"` ": ${1}" } UpdateTestState() { echo $1 > ~/state.txt } ####################################################################### # # LinuxRelease() # ####################################################################### LinuxRelease() { DISTRO=`grep -ihs "buntu\|Suse\|Fedora\|Debian\|CentOS\|Red Hat Enterprise Linux" /etc/{issue,*release,*version}` case $DISTRO in *buntu*) echo "UBUNTU";; Fedora*) echo "FEDORA";; CentOS*) echo "CENTOS";; *SUSE*) echo "SLES";; Red*Hat*) echo "RHEL";; Debian*) echo "DEBIAN";; esac } ###################################################################### # # DoSlesAB() # # Description: # Perform distro specific Apache and tool installation steps for SLES # and then run the benchmark tool # ####################################################################### ConfigSlesZK() { # # Note: A number of steps will use SSH to issue commands to the # APACHE_SERVER. This requires that the SSH keys be provisioned # in advanced, and strict mode be disabled for both the SSH # server and client. # LogMsg "Info: Running SLES" arr=$(echo $ZK_SERVERS | tr "," "\n") for ZK_SERVER in $arr do #echo "${ZK_SERVER}" SERVER=(`echo "${ZK_SERVER}" | awk -F':' '{print $1}'`) #echo "${SERVER}" #ssh root@${SERVER} "mkdir /root/kk" #exit 1 LogMsg "Info: -----------------------------------------" LogMsg "Info: Zookeeper-Server installation on server ${SERVER}" LogMsg "Info: Installing required packages first" ssh root@${SERVER} "zypper --non-interactive install wget" if [ $? -ne 0 ]; then msg="Error: Unable to install package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi # # Install Java # LogMsg "Check if Java is installed" javaInstalled=`which java` if [ ! $javaInstalled ]; then LogMsg "Installing Java" ssh root@${SERVER} "zypper --non-interactive install jre-1.7.0" if [ $? -ne 0 ]; then LogMsg "Error: Unable to install java" UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Download ZK package" pkg=(`ssh root@${SERVER} "ls /root/ | grep ${ZK_ARCHIVE}"`) echo $pkg if [ -z "$pkg" ]; then LogMsg "Downloading ZK package ${ZK_ARCHIVE}" #exit 1 ssh root@${SERVER} "wget ${ZK_URL}" if [ $? -ne 0 ]; then msg="Error: Unable to download ZK package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Untar and Config ZK server" ssh root@${SERVER} "tar -xzf ./${ZK_ARCHIVE}" ssh root@${SERVER} "cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg" LogMsg "Info: Starting Zookeeper-Server ${SERVER}" ssh root@${SERVER} "zookeeper-${ZK_VERSION}/bin/zkServer.sh start" if [ $? -ne 0 ]; then msg="Error: Unable to start Zookeeper-Server on ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi LogMsg "Info: Server started successfully" done } ConfigUbuntuZK() { # # Note: A number of steps will use SSH to issue commands to the # ZK_SERVER. This requires that the SSH keys be provisioned # in advanced, and strict mode be disabled for both the SSH # server and client. # LogMsg "Info: Running Ubuntu" arr=$(echo $ZK_SERVERS | tr "," "\n") for ZK_SERVER in $arr do SERVER=(`echo "${ZK_SERVER}" | awk -F':' '{print $1}'`) LogMsg "Info: -----------------------------------------" LogMsg "Info: Zookeeper-Server installation on server ${SERVER}" LogMsg "Info: Installing required packages first" ssh root@${SERVER} "apt-get install -y wget" if [ $? -ne 0 ]; then msg="Error: Unable to install package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi # # Install Java # LogMsg "Check if Java is installed" javaInstalled=`which java` if [ ! $javaInstalled ]; then LogMsg "Installing Java" ssh root@${SERVER} "apt-get -y install default-jdk" if [ $? -ne 0 ]; then LogMsg "Error: Unable to install java" UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Download ZK package" pkg=(`ssh root@${SERVER} "ls /root/ | grep ${ZK_ARCHIVE}"`) echo $pkg if [ -z "$pkg" ]; then LogMsg "Downloading ZK package ${ZK_ARCHIVE}" #exit 1 ssh root@${SERVER} "wget ${ZK_URL}" if [ $? -ne 0 ]; then msg="Error: Unable to download ZK package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Untar and Config ZK server" ssh root@${SERVER} "tar -xzf ./${ZK_ARCHIVE}" ssh root@${SERVER} "cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg" LogMsg "Info: Starting Zookeeper-Server ${SERVER}" ssh root@${SERVER} "zookeeper-${ZK_VERSION}/bin/zkServer.sh start" if [ $? -ne 0 ]; then msg="Error: Unable to start Zookeeper-Server on ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi LogMsg "Info: Server started successfully" done } ConfigRHELZK() { # # Note: A number of steps will use SSH to issue commands to the # ZK_SERVER. This requires that the SSH keys be provisioned # in advanced, and strict mode be disabled for both the SSH # server and client. # LogMsg "Info: Running RHEL" arr=$(echo $ZK_SERVERS | tr "," "\n") for ZK_SERVER in $arr do SERVER=(`echo "${ZK_SERVER}" | awk -F':' '{print $1}'`) LogMsg "Info: -----------------------------------------" LogMsg "Info: Zookeeper-Server installation on server ${SERVER}" LogMsg "Info: Installing required packages first" ssh root@${SERVER} "yum install -y wget" if [ $? -ne 0 ]; then msg="Error: Unable to install package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi # # Install Java # LogMsg "Check if Java is installed" javaInstalled=`which java` if [ ! $javaInstalled ]; then LogMsg "Installing Java" ssh root@${SERVER} "yum -y install java-1.7.0-openjdk" if [ $? -ne 0 ]; then LogMsg "Error: Unable to install Java" UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Download ZK package" pkg=(`ssh root@${SERVER} "ls /root/ | grep ${ZK_ARCHIVE}"`) echo $pkg if [ -z "$pkg" ]; then LogMsg "Downloading ZK package ${ZK_ARCHIVE}" #exit 1 ssh root@${SERVER} "wget ${ZK_URL}" if [ $? -ne 0 ]; then msg="Error: Unable to download ZK package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Untar and Config ZK server" ssh root@${SERVER} "tar -xzf ./${ZK_ARCHIVE}" ssh root@${SERVER} "cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg" LogMsg "Info: Starting Zookeeper-Server ${SERVER}" ssh root@${SERVER} "zookeeper-${ZK_VERSION}/bin/zkServer.sh start" if [ $? -ne 0 ]; then msg="Error: Unable to start Zookeeper-Server on ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi LogMsg "Info: Server started successfully" done } ####################################################################### # # Main script body # ####################################################################### cd ~ UpdateTestState $ICA_TESTRUNNING LogMsg "Starting test" # # Delete any old summary.log file # LogMsg "Cleaning up old summary.log" if [ -e ~/summary.log ]; then rm -f ~/summary.log fi touch ~/summary.log # # Source the constants.sh file # LogMsg "Sourcing constants.sh" if [ -e ~/constants.sh ]; then . ~/constants.sh else msg="Error: ~/constants.sh does not exist" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState $ICA_TESTABORTED exit 10 fi # # Make sure the required test parameters are defined # if [ "${ZK_VERSION:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_VERSION test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState $ICA_TESTFAILED exit 20 fi if [ "${ZK_SERVERS:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_SERVER test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState $ICA_TESTFAILED exit 20 fi if [ "${ZK_TIMEOUT:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_TIMEOUT test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log ZK_TIMEOUT=100000 fi if [ "${ZK_ZNODE_SIZE:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_ZNODE_SIZE test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log ZK_ZNODE_SIZE=100 fi if [ "${ZK_ZNODE_COUNT:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_ZNODE_COUNT test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log ZK_ZNODE_SIZE=100 fi if [ "${ZK_FORCE:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_FORCE test parameter is missing" LogMsg "${msg}" ZK_FORCE=$false fi if [ "${ZK_VERBOSE:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_VERBOSE test parameter is missing" LogMsg "${msg}" ZK_VERBOSE=$false fi LogMsg "Info: Test run parameters" echo "ZK_VERSION = ${ZK_VERSION}" echo "ZK_SERVERS = ${ZK_SERVERS}" echo "ZK_TIMEOUT = ${ZK_TIMEOUT}" echo "ZK_ZNODE_SIZE = ${ZK_ZNODE_SIZE}" echo "ZK_ZNODE_COUNT = ${ZK_ZNODE_COUNT}" echo "ZK_FORCE = ${ZK_FORCE}" echo "ZK_SYNCHRONOUS = ${ZK_SYNCHRONOUS}" echo "ZK_VERBOSE = ${ZK_VERBOSE}" LogMsg "Info : ZK_VERSION = ${ZK_VERSION}" ZK_ARCHIVE="zookeeper-${ZK_VERSION}.tar.gz" ZK_URL=http://apache.spinellicreations.com/zookeeper/zookeeper-${ZK_VERSION}/${ZK_ARCHIVE} # # Configure ZK server - this has distro specific behaviour # distro=`LinuxRelease` case $distro in "CENTOS" | "RHEL") ConfigRHELZK ;; "UBUNTU") ConfigUbuntuZK ;; "DEBIAN") ConfigDebianZK ;; "SLES") ConfigSlesZK ;; *) msg="Error: Distro '${distro}' not supported" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState "TestAborted" exit 1 ;; esac IFS=',' read -ra ADDR <<< "$ZK_SERVERS" for zk_server in "${ADDR[@]}"; do LogMsg "Prepare ZK test cmd for ${zk_server}" testBaseString='PYTHONPATH="lib.linux-x86_64-2.6" LD_LIBRARY_PATH="lib.linux-x86_64-2.6" python ./zk-latencies.py ' #testBaseString='./zk-latencies.py PYTHONPATH=lib.linux-x86_64-2.6 LD_LIBRARY_PATH=lib.linux-x86_64-2.6 ' testString="${testBaseString}""--servers=${zk_server} --timeout=${ZK_TIMEOUT} --znode_count=${ZK_ZNODE_COUNT} --znode_size=${ZK_ZNODE_SIZE}" if [ "${ZK_FORCE}" = true ]; then testString="${testString}"" --force" fi if [ "${ZK_SYNCHRONOUS}" = true ]; then testString="${testString}"" --synchronous" fi if [ "${ZK_VERBOSE}" = true ]; then testString="${testString}"" --verbose" fi LogMsg "Running zookeeper tests with cmd: ${testString}" eval $testString if [ $? -ne 0 ]; then msg="Error: Unable to run test" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi done # # If we made it here, everything worked. # Indicate success # LogMsg "Test completed successfully" UpdateTestState $ICA_TESTCOMPLETED exit 0
hglkrijger/azure-linux-automation
remote-scripts/performance_zk.sh
Shell
apache-2.0
14,855
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. --------------------------------------------------------------------------- */ /** @file Implementation of the post processing step to calculate * tangents and bitangents for all imported meshes */ #include "AssimpPCH.h" // internal headers #include "CalcTangentsProcess.h" #include "ProcessHelper.h" #include "TinyFormatter.h" using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer CalcTangentsProcess::CalcTangentsProcess() : configMaxAngle( AI_DEG_TO_RAD(45.f) ) , configSourceUV( 0 ) { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Destructor, private as well CalcTangentsProcess::~CalcTangentsProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Returns whether the processing step is present in the given flag field. bool CalcTangentsProcess::IsActive( unsigned int pFlags) const { return (pFlags & aiProcess_CalcTangentSpace) != 0; } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. void CalcTangentsProcess::SetupProperties(const Importer* pImp) { ai_assert( NULL != pImp ); // get the current value of the property configMaxAngle = pImp->GetPropertyFloat(AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE,45.f); configMaxAngle = std::max(std::min(configMaxAngle,45.0f),0.0f); configMaxAngle = AI_DEG_TO_RAD(configMaxAngle); configSourceUV = pImp->GetPropertyInteger(AI_CONFIG_PP_CT_TEXTURE_CHANNEL_INDEX,0); } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. void CalcTangentsProcess::Execute( aiScene* pScene) { ai_assert( NULL != pScene ); DefaultLogger::get()->debug("CalcTangentsProcess begin"); bool bHas = false; for ( unsigned int a = 0; a < pScene->mNumMeshes; a++ ) { if(ProcessMesh( pScene->mMeshes[a],a))bHas = true; } if ( bHas ) { DefaultLogger::get()->info("CalcTangentsProcess finished. Tangents have been calculated"); } else { DefaultLogger::get()->debug("CalcTangentsProcess finished"); } } // ------------------------------------------------------------------------------------------------ // Calculates tangents and bitangents for the given mesh bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) { // we assume that the mesh is still in the verbose vertex format where each face has its own set // of vertices and no vertices are shared between faces. Sadly I don't know any quick test to // assert() it here. //assert( must be verbose, dammit); if (pMesh->mTangents) // thisimplies that mBitangents is also there return false; // If the mesh consists of lines and/or points but not of // triangles or higher-order polygons the normal vectors // are undefined. if (!(pMesh->mPrimitiveTypes & (aiPrimitiveType_TRIANGLE | aiPrimitiveType_POLYGON))) { DefaultLogger::get()->info("Tangents are undefined for line and point meshes"); return false; } // what we can check, though, is if the mesh has normals and texture coordinates. That's a requirement if( pMesh->mNormals == NULL) { DefaultLogger::get()->error("Failed to compute tangents; need normals"); return false; } if( configSourceUV >= AI_MAX_NUMBER_OF_TEXTURECOORDS || !pMesh->mTextureCoords[configSourceUV] ) { DefaultLogger::get()->error((Formatter::format("Failed to compute tangents; need UV data in channel"),configSourceUV)); return false; } const float angleEpsilon = 0.9999f; std::vector<bool> vertexDone( pMesh->mNumVertices, false); const float qnan = get_qnan(); // create space for the tangents and bitangents pMesh->mTangents = new aiVector3D[pMesh->mNumVertices]; pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices]; const aiVector3D* meshPos = pMesh->mVertices; const aiVector3D* meshNorm = pMesh->mNormals; const aiVector3D* meshTex = pMesh->mTextureCoords[configSourceUV]; aiVector3D* meshTang = pMesh->mTangents; aiVector3D* meshBitang = pMesh->mBitangents; // calculate the tangent and bitangent for every face for( unsigned int a = 0; a < pMesh->mNumFaces; a++) { const aiFace& face = pMesh->mFaces[a]; if (face.mNumIndices < 3) { // There are less than three indices, thus the tangent vector // is not defined. We are finished with these vertices now, // their tangent vectors are set to qnan. for (unsigned int i = 0; i < face.mNumIndices;++i) { register unsigned int idx = face.mIndices[i]; vertexDone [idx] = true; meshTang [idx] = aiVector3D(qnan); meshBitang [idx] = aiVector3D(qnan); } continue; } // triangle or polygon... we always use only the first three indices. A polygon // is supposed to be planar anyways.... // FIXME: (thom) create correct calculation for multi-vertex polygons maybe? const unsigned int p0 = face.mIndices[0], p1 = face.mIndices[1], p2 = face.mIndices[2]; // position differences p1->p2 and p1->p3 aiVector3D v = meshPos[p1] - meshPos[p0], w = meshPos[p2] - meshPos[p0]; // texture offset p1->p2 and p1->p3 float sx = meshTex[p1].x - meshTex[p0].x, sy = meshTex[p1].y - meshTex[p0].y; float tx = meshTex[p2].x - meshTex[p0].x, ty = meshTex[p2].y - meshTex[p0].y; float dirCorrection = (tx * sy - ty * sx) < 0.0f ? -1.0f : 1.0f; // when t1, t2, t3 in same position in UV space, just use default UV direction. if ( 0 == sx && 0 ==sy && 0 == tx && 0 == ty ) { sx = 0.0; sy = 1.0; tx = 1.0; ty = 0.0; } // tangent points in the direction where to positive X axis of the texture coord's would point in model space // bitangent's points along the positive Y axis of the texture coord's, respectively aiVector3D tangent, bitangent; tangent.x = (w.x * sy - v.x * ty) * dirCorrection; tangent.y = (w.y * sy - v.y * ty) * dirCorrection; tangent.z = (w.z * sy - v.z * ty) * dirCorrection; bitangent.x = (w.x * sx - v.x * tx) * dirCorrection; bitangent.y = (w.y * sx - v.y * tx) * dirCorrection; bitangent.z = (w.z * sx - v.z * tx) * dirCorrection; // store for every vertex of that face for( unsigned int b = 0; b < face.mNumIndices; ++b ) { unsigned int p = face.mIndices[b]; // project tangent and bitangent into the plane formed by the vertex' normal aiVector3D localTangent = tangent - meshNorm[p] * (tangent * meshNorm[p]); aiVector3D localBitangent = bitangent - meshNorm[p] * (bitangent * meshNorm[p]); localTangent.Normalize(); localBitangent.Normalize(); // reconstruct tangent/bitangent according to normal and bitangent/tangent when it's infinite or NaN. bool invalid_tangent = is_special_float(localTangent.x) || is_special_float(localTangent.y) || is_special_float(localTangent.z); bool invalid_bitangent = is_special_float(localBitangent.x) || is_special_float(localBitangent.y) || is_special_float(localBitangent.z); if (invalid_tangent != invalid_bitangent) { if (invalid_tangent) { localTangent = meshNorm[p] ^ localBitangent; localTangent.Normalize(); } else { localBitangent = localTangent ^ meshNorm[p]; localBitangent.Normalize(); } } // and write it into the mesh. meshTang[ p ] = localTangent; meshBitang[ p ] = localBitangent; } } // create a helper to quickly find locally close vertices among the vertex array // FIX: check whether we can reuse the SpatialSort of a previous step SpatialSort* vertexFinder = NULL; SpatialSort _vertexFinder; float posEpsilon; if (shared) { std::vector<std::pair<SpatialSort,float> >* avf; shared->GetProperty(AI_SPP_SPATIAL_SORT,avf); if (avf) { std::pair<SpatialSort,float>& blubb = avf->operator [] (meshIndex); vertexFinder = &blubb.first; posEpsilon = blubb.second;; } } if (!vertexFinder) { _vertexFinder.Fill(pMesh->mVertices, pMesh->mNumVertices, sizeof( aiVector3D)); vertexFinder = &_vertexFinder; posEpsilon = ComputePositionEpsilon(pMesh); } std::vector<unsigned int> verticesFound; const float fLimit = cosf(configMaxAngle); std::vector<unsigned int> closeVertices; // in the second pass we now smooth out all tangents and bitangents at the same local position // if they are not too far off. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) { if( vertexDone[a]) continue; const aiVector3D& origPos = pMesh->mVertices[a]; const aiVector3D& origNorm = pMesh->mNormals[a]; const aiVector3D& origTang = pMesh->mTangents[a]; const aiVector3D& origBitang = pMesh->mBitangents[a]; closeVertices.clear(); // find all vertices close to that position vertexFinder->FindPositions( origPos, posEpsilon, verticesFound); closeVertices.reserve (verticesFound.size()+5); closeVertices.push_back( a); // look among them for other vertices sharing the same normal and a close-enough tangent/bitangent for( unsigned int b = 0; b < verticesFound.size(); b++) { unsigned int idx = verticesFound[b]; if( vertexDone[idx]) continue; if( meshNorm[idx] * origNorm < angleEpsilon) continue; if( meshTang[idx] * origTang < fLimit) continue; if( meshBitang[idx] * origBitang < fLimit) continue; // it's similar enough -> add it to the smoothing group closeVertices.push_back( idx); vertexDone[idx] = true; } // smooth the tangents and bitangents of all vertices that were found to be close enough aiVector3D smoothTangent( 0, 0, 0), smoothBitangent( 0, 0, 0); for( unsigned int b = 0; b < closeVertices.size(); ++b) { smoothTangent += meshTang[ closeVertices[b] ]; smoothBitangent += meshBitang[ closeVertices[b] ]; } smoothTangent.Normalize(); smoothBitangent.Normalize(); // and write it back into all affected tangents for( unsigned int b = 0; b < closeVertices.size(); ++b) { meshTang[ closeVertices[b] ] = smoothTangent; meshBitang[ closeVertices[b] ] = smoothBitangent; } } return true; }
gsi-upm/SmartSim
smartbody/src/assimp-3.1.1/code/CalcTangentsProcess.cpp
C++
apache-2.0
12,469
.picture-background{ background-image:linear-gradient(rgba(0, 0, 0, 0.6),rgba(0, 0, 0, 0.6)),url("../Fz-imgs/fact-img/technology3.jpeg"); background-position:center center; background-size:cover; } .main-home-nav{ background-color:#2c3e50; } .main-home-nav:after, .main-home-nav:before{ background-color:#2c3e50; }
deangelo200/deangeloalmeus-app-1
www/Fz-css/technology.css
CSS
apache-2.0
329
<?php /** * @xmlNamespace http://schema.intuit.com/finance/v3 * @xmlType string * @xmlName IPPIdType * @var IPPIdType * @xmlDefinition Product: ALL Description: Allows for strong-typing of Ids and qualifying the domain origin of the Id. The valid values for the domain are defined in the idDomainEnum. */ class IPPIdType { /** * Initializes this object, optionally with pre-defined property values * * Initializes this object and it's property members, using the dictionary * of key/value pairs passed as an optional argument. * * @param dictionary $keyValInitializers key/value pairs to be populated into object's properties * @param boolean $verbose specifies whether object should echo warnings */ public function __construct($keyValInitializers=array(), $verbose=FALSE) { foreach($keyValInitializers as $initPropName => $initPropVal) { if (property_exists('IPPIdType',$initPropName)) { $this->{$initPropName} = $initPropVal; } else { if ($verbose) echo "Property does not exist ($initPropName) in class (".get_class($this).")"; } } } /** * @xmlType value * @var string */ public $value; } // end class IPPIdType
hlu2/QuickBooks_Demo
src/Data/IPPIdType.php
PHP
apache-2.0
1,546
/// <reference path='fourslash.ts' /> //@Filename: file.tsx //// declare module JSX { //// interface Element { } //// interface IntrinsicElements { //// } //// interface ElementAttributesProperty { props } //// } //// class MyClass { //// props: { //// [|[|{| "contextRangeIndex": 0 |}name|]?: string;|] //// size?: number; //// } //// //// //// var x = <MyClass [|[|{| "contextRangeIndex": 2 |}name|]='hello'|]/>; verify.rangesWithSameTextAreRenameLocations("name");
Microsoft/TypeScript
tests/cases/fourslash/tsxRename3.ts
TypeScript
apache-2.0
515
/* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.neural.pattern; import java.util.ArrayList; import java.util.List; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ml.MLMethod; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.BasicLayer; import org.encog.neural.networks.layers.Layer; /** * Used to create feedforward neural networks. A feedforward network has an * input and output layers separated by zero or more hidden layers. The * feedforward neural network is one of the most common neural network patterns. * * @author jheaton * */ public class FeedForwardPattern implements NeuralNetworkPattern { /** * The number of input neurons. */ private int inputNeurons; /** * The number of output neurons. */ private int outputNeurons; /** * The activation function. */ private ActivationFunction activationHidden; /** * The activation function. */ private ActivationFunction activationOutput; /** * The number of hidden neurons. */ private final List<Integer> hidden = new ArrayList<Integer>(); /** * Add a hidden layer, with the specified number of neurons. * * @param count * The number of neurons to add. */ public void addHiddenLayer(final int count) { this.hidden.add(count); } /** * Clear out any hidden neurons. */ public void clear() { this.hidden.clear(); } /** * Generate the feedforward neural network. * * @return The feedforward neural network. */ public MLMethod generate() { if( this.activationOutput==null ) this.activationOutput = this.activationHidden; final Layer input = new BasicLayer(null, true, this.inputNeurons); final BasicNetwork result = new BasicNetwork(); result.addLayer(input); for (final Integer count : this.hidden) { final Layer hidden = new BasicLayer(this.activationHidden, true, count); result.addLayer(hidden); } final Layer output = new BasicLayer(this.activationOutput, false, this.outputNeurons); result.addLayer(output); result.getStructure().finalizeStructure(); result.reset(); return result; } /** * Set the activation function to use on each of the layers. * * @param activation * The activation function. */ public void setActivationFunction(final ActivationFunction activation) { this.activationHidden = activation; } /** * Set the number of input neurons. * * @param count * Neuron count. */ public void setInputNeurons(final int count) { this.inputNeurons = count; } /** * Set the number of output neurons. * * @param count * Neuron count. */ public void setOutputNeurons(final int count) { this.outputNeurons = count; } /** * @return the activationOutput */ public ActivationFunction getActivationOutput() { return activationOutput; } /** * @param activationOutput the activationOutput to set */ public void setActivationOutput(ActivationFunction activationOutput) { this.activationOutput = activationOutput; } }
Crespo911/encog-java-core
src/main/java/org/encog/neural/pattern/FeedForwardPattern.java
Java
apache-2.0
3,936
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net.starlark.java.syntax; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; /** Syntax node for a for loop statement, {@code for vars in iterable: ...}. */ public final class ForStatement extends Statement { private final int forOffset; private final Expression vars; private final Expression iterable; private final ImmutableList<Statement> body; // non-empty if well formed /** Constructs a for loop statement. */ ForStatement( FileLocations locs, int forOffset, Expression vars, Expression iterable, ImmutableList<Statement> body) { super(locs); this.forOffset = forOffset; this.vars = Preconditions.checkNotNull(vars); this.iterable = Preconditions.checkNotNull(iterable); this.body = body; } /** * Returns variables assigned by each iteration. May be a compound target such as {@code (a[b], * c.d)}. */ public Expression getVars() { return vars; } /** Returns the iterable value. */ // TODO(adonovan): rename to getIterable. public Expression getCollection() { return iterable; } /** Returns the statements of the loop body. Non-empty if parsing succeeded. */ public ImmutableList<Statement> getBody() { return body; } @Override public int getStartOffset() { return forOffset; } @Override public int getEndOffset() { return body.isEmpty() ? iterable.getEndOffset() // wrong, but tree is ill formed : body.get(body.size() - 1).getEndOffset(); } @Override public String toString() { return "for " + vars + " in " + iterable + ": ...\n"; } @Override public void accept(NodeVisitor visitor) { visitor.visit(this); } @Override public Kind kind() { return Kind.FOR; } }
twitter-forks/bazel
src/main/java/net/starlark/java/syntax/ForStatement.java
Java
apache-2.0
2,418
package de.j4velin.pedometer.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class ColorPreview extends View { private Paint paint = new Paint(); private int color; public ColorPreview(Context context) { super(context); } public ColorPreview(Context context, AttributeSet attrs) { super(context, attrs); } public ColorPreview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setColor(final int c) { color = c; invalidate(); } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); paint.setColor(color); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, paint); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2 - 1, paint); } }
hgl888/Pedometer
src/main/java/de/j4velin/pedometer/util/ColorPreview.java
Java
apache-2.0
1,251
/* * Copyright (C) 2009-2017 Lightbend Inc. <https://www.lightbend.com> */ package javaguide.xml; import org.w3c.dom.Document; import play.libs.XPath; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; public class JavaXmlRequests extends Controller { //#xml-hello public Result sayHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello //#xml-hello-bodyparser @BodyParser.Of(BodyParser.Xml.class) public Result sayHelloBP() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello-bodyparser //#xml-reply @BodyParser.Of(BodyParser.Xml.class) public Result replyHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("<message \"status\"=\"KO\">Missing parameter [name]</message>").as("application/xml"); } else { return ok("<message \"status\"=\"OK\">Hello " + name + "</message>").as("application/xml"); } } } //#xml-reply }
wsargent/playframework
documentation/manual/working/javaGuide/main/xml/code/javaguide/xml/JavaXmlRequests.java
Java
apache-2.0
1,900
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.indexer; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.io.IOUtils; import org.apache.druid.common.utils.UUIDUtils; import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.IOE; import org.apache.druid.java.util.common.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.MRJobConfig; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class HdfsClasspathSetupTest { private static MiniDFSCluster miniCluster; private static File hdfsTmpDir; private static Configuration conf; private static String dummyJarString = "This is a test jar file."; private File dummyJarFile; private Path finalClasspath; private Path intermediatePath; @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @BeforeClass public static void setupStatic() throws IOException { hdfsTmpDir = File.createTempFile("hdfsClasspathSetupTest", "dir"); if (!hdfsTmpDir.delete()) { throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath()); } conf = new Configuration(true); conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath()); miniCluster = new MiniDFSCluster.Builder(conf).build(); } @Before public void setUp() throws IOException { // intermedatePath and finalClasspath are relative to hdfsTmpDir directory. intermediatePath = new Path(StringUtils.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(StringUtils.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = tempFolder.newFile("dummy-test.jar"); Files.copy( new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); } @AfterClass public static void tearDownStatic() throws IOException { if (miniCluster != null) { miniCluster.shutdown(true); } FileUtils.deleteDirectory(hdfsTmpDir); } @After public void tearDown() throws IOException { dummyJarFile.delete(); Assert.assertFalse(dummyJarFile.exists()); miniCluster.getFileSystem().delete(finalClasspath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(finalClasspath)); miniCluster.getFileSystem().delete(intermediatePath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(intermediatePath)); } @Test public void testAddSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); Path intermediatePath = new Path("/tmp/classpath"); JobHelper.addSnapshotJarToClassPath(dummyJarFile, intermediatePath, fs, job); Path expectedJarPath = new Path(intermediatePath, dummyJarFile.getName()); // check file gets uploaded to HDFS Assert.assertTrue(fs.exists(expectedJarPath)); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testAddNonSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePath, fs, job); Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file gets deleted Assert.assertFalse(fs.exists(new Path(intermediatePath, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testIsSnapshot() { Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT.jar"))); Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT-selfcontained.jar"))); } @Test public void testConcurrentUpload() throws IOException, InterruptedException, ExecutionException, TimeoutException { final int concurrency = 10; ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(concurrency)); // barrier ensures that all jobs try to add files to classpath at same time. final CyclicBarrier barrier = new CyclicBarrier(concurrency); final DistributedFileSystem fs = miniCluster.getFileSystem(); final Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); List<ListenableFuture<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < concurrency; i++) { futures.add( pool.submit( new Callable() { @Override public Boolean call() throws Exception { int id = barrier.await(); Job job = Job.getInstance(conf, "test-job-" + id); Path intermediatePathForJob = new Path(intermediatePath, "job-" + id); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePathForJob, fs, job); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file is not present Assert.assertFalse(fs.exists(new Path(intermediatePathForJob, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals( expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES) ); return true; } } ) ); } Futures.allAsList(futures).get(30, TimeUnit.SECONDS); pool.shutdownNow(); } }
pjain1/druid
indexing-hadoop/src/test/java/org/apache/druid/indexer/HdfsClasspathSetupTest.java
Java
apache-2.0
8,361
// Copyright 2019 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CRASHPAD_UTIL_PROCESS_PROCESS_ID_H_ #define CRASHPAD_UTIL_PROCESS_PROCESS_ID_H_ #include <type_traits> #include "base/format_macros.h" #include "build/build_config.h" #if BUILDFLAG(IS_POSIX) #include <sys/types.h> #elif BUILDFLAG(IS_WIN) #include <windows.h> #elif BUILDFLAG(IS_FUCHSIA) #include <zircon/types.h> #endif namespace crashpad { #if BUILDFLAG(IS_POSIX) || DOXYGEN //! \brief Alias for platform-specific type to represent a process. using ProcessID = pid_t; constexpr ProcessID kInvalidProcessID = -1; static_assert(std::is_same<ProcessID, int>::value, "Port."); #define PRI_PROCESS_ID "d" #elif BUILDFLAG(IS_WIN) using ProcessID = DWORD; constexpr ProcessID kInvalidProcessID = 0; #define PRI_PROCESS_ID "lu" #elif BUILDFLAG(IS_FUCHSIA) using ProcessID = zx_koid_t; constexpr ProcessID kInvalidProcessID = ZX_KOID_INVALID; static_assert(std::is_same<ProcessID, int64_t>::value, "Port."); #define PRI_PROCESS_ID PRId64 #else #error Port. #endif } // namespace crashpad #endif // CRASHPAD_UTIL_PROCESS_PROCESS_ID_H_
chromium/crashpad
util/process/process_id.h
C
apache-2.0
1,663
<div style="width: 600px"> <div class="delayed-image-load" data-src="base/test/fixtures/interpolated/B-{width}.jpg"></div> </div> <div style="width: 600px"> <div class="delayed-image-load" data-src="base/test/fixtures/{width}/{width}.jpg" data-width="1024"></div> </div>
kendrick-k/Imager.js
test/fixtures/data-src-interpolate.html
HTML
apache-2.0
276
[#]: subject: (Keep track of your IRC chats with ZNC) [#]: via: (https://opensource.com/article/21/6/irc-matrix-bridge-znc) [#]: author: (John 'Warthog9' Hawley https://opensource.com/users/warthog9) [#]: collector: (lujun9972) [#]: translator: ( ) [#]: reviewer: ( ) [#]: publisher: ( ) [#]: url: ( ) Keep track of your IRC chats with ZNC ====== Create a bridge between IRC and Matrix. ![Chat bubbles][1] For a bit more than a year, I've been wondering if it is possible to bolt the open source [Matrix][2] communications network to Internet Relay Chat (IRC) in such a way that I can still use my [ZNC][3] IRC bouncer without an extra proliferation of nicknames. The answer, is amusingly, yes. But first, some background. ### What's IRC? IRC has been around since August 1988, and it's been a staple of real-time communications ever since. It's also one of the early open source projects, as the code for the original IRC server was eventually shared. Over the years, it's been quite useful for meeting many developers' real-time communication needs, although not without its own share of drama. However, it has been resilient and is still widely used despite newer options. ### Enter the bouncer ZNC solves a specific problem on IRC: IRC is intentionally a very ephemeral system, so no state is saved. When you log into an IRC server, you get nothing except what is happening right then—nothing before, and once you leave, nothing after. This contrasts with more modern systems that give historical context, scrollback, searchability, etc. Some of this can be handled by clients that are left on continuously, but that's not ideal. Enter the IRC bouncer. A bouncer acts as a middleman to the IRC connection. It connects to IRC and can log in on the user's behalf. It can then relay chats back out to the client (or, in many cases, clients). This can make it seem like a user is always on, which gives some context. Many folks who use IRC use either a bouncer or a client that runs long-term to keep that context going. ZNC is a relatively popular and well-understood bouncer for IRC. Other services like [IRCCloud][4] can provide this and other features bolted around IRC to make the experience more pleasant and usable. ### Building bridges Matrix is a newer standard that isn't really a program or a codebase. It's actually a protocol definition that lends itself particularly well to bridging other protocols and provides a framework for real-time encrypted chat. One of its reference implementations is called Synapse, and it happens to be a pretty solid base from which to build. It has a rich set of prebuilt [bridges][5], including Slack, Gitter, XMPP, and email. While not all features translate everywhere, the fact that so many good bridges exist speaks to a great community and a robust protocol. ### The crux of the matter I've been on IRC for 26 or 27 years; my clients are set up the way I like, and I'm used to interacting with it in certain ways on certain systems. This is great until I want to start interfacing with IRC when I have Matrix, [Mattermost][6], [Rocket.Chat][7], or other systems running. Traditionally, this meant I ended up with an extra nickname every time I logged into IRC. After a while, username[m], username[m]1, username[m]2, and so forth start looking old. Imagine everyone trying to do this, and you understand that this eventually gets untenable. I've been running a Matrix server with bridges. So why can't I bridge ZNC into Matrix and get the best of all worlds? It's doable with some prerequisites and prep work (which I won't cover in detail, but there's documentation out there should you wish to set this up for yourself). * You need a Matrix server, I'm using [Synapse][8], and it's what I'm going to assume going forward. You will also need admin privileges and access to the low-level system. * You need a [ZNC server][3] up and running or a bouncer that acts like ZNC (although your mileage will vary if you aren't using ZNC). You just need a ZNC account; you don't need admin privileges. * You need a copy of Heisenbridge, an IRC bridge for Matrix that works differently from a normal IRC bridge. It's possible to run both simultaneously; I am, and the [Heisenbridge README][9] will help you do the same. You'll likely want to run Heisenbridge on the same system you're running Synapse, although it's not required. I'll assume you have Synapse and a working IRC bouncer set up and working. Now comes the fun part: bolting Heisenbridge into place. Follow the Heisenbridge install guide, except before you restart Synapse and start Heisenbridge, you'll want to make a couple of small changes to the configuration file generated during setup. That config file will look something like this: ``` id: heisenbridge url: <http://127.0.0.1:9898> as_token: alongstringtoken hs_token: anotherlongstringtoken rate_limited: false sender_localpart: heisenbridge namespaces:  users:  - regex: '@irc_.*'    exclusive: true  aliases: []  rooms: [] ``` * Change the port it will use because `9898` is also preferred by other bridges. I chose `9897`. As long as it is the same in Synapse and the bridge, it doesn't matter what you use. * In the `namespaces` section, take note of the regex for the users. The `matrix-appservice-irc` system uses the same regex, and having both of them run in the same namespace causes issues. I changed mine from `@irc_` to `@hirc`. * You need to add `@heisenbridge:your.homeserver.tld` to the admin list on your server. The easiest way to do this is to start up Heisenbridge once, turn it off, and then edit the database to give the user admin privileges (i.e., set `admin=1` on that user). Then restart Heisenbridge. My updated config file looks like this: ``` id: heisenbridge url: <http://127.0.0.1:9897> as_token: alongstringtoken hs_token: anotherlongstringtoken rate_limited: false sender_localpart: heisenbridge namespaces:  users:  - regex: '@hirc_.*'    exclusive: true  aliases: []  rooms: [] ``` Then, restart Synapse, start Heisenbridge, and go from there. I started mine using: ``` `python3 -m heisenbridge -c /path/to/heisenbridge.yaml -p 9897` ``` Next, talk to the Heisenbridge user on your home server and set up a network and a server for your bouncer. If you want to add a server, there are some options that aren't documented. If you want to add a server name and host, issue: ``` `addserver networkname hostname portnumber --tls` ``` Open the network as your user. You'll be invited to a room where you can set the password for the network login (this is likely needed for ZNC), and then you can connect. > **Security warning:** The password will be stored in clear text, so don't use passwords you don't mind being stored this way, and don't do this on machines you don't trust. After you hit **Connect**, you should get a flurry of activity as your IRC bouncer pushes its state into Matrix. That should do it! -------------------------------------------------------------------------------- via: https://opensource.com/article/21/6/irc-matrix-bridge-znc 作者:[John 'Warthog9' Hawley][a] 选题:[lujun9972][b] 译者:[译者ID](https://github.com/译者ID) 校对:[校对者ID](https://github.com/校对者ID) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 [a]: https://opensource.com/users/warthog9 [b]: https://github.com/lujun9972 [1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/talk_chat_communication_team.png?itok=CYfZ_gE7 (Chat bubbles) [2]: https://matrix.org/ [3]: https://wiki.znc.in/ZNC [4]: https://www.irccloud.com/ [5]: https://matrix.org/bridges/ [6]: https://mattermost.com/ [7]: http://rocket.chat/ [8]: https://matrix.org/docs/projects/server/synapse [9]: https://github.com/hifi/heisenbridge
runningwater/TranslateProject
sources/tech/20210615 Keep track of your IRC chats with ZNC.md
Markdown
apache-2.0
7,898
from click_plugins import with_plugins from pkg_resources import iter_entry_points import click @with_plugins(iter_entry_points('girder.cli_plugins')) @click.group(help='Girder: data management platform for the web.', context_settings=dict(help_option_names=['-h', '--help'])) @click.version_option(message='%(version)s') def main(): pass
manthey/girder
girder/cli/__init__.py
Python
apache-2.0
358
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Test")] [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("c605d998-9772-4948-8fdf-41d7afc94c31")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
fengshao0907/Gaea
client/net/client/Test/Properties/AssemblyInfo.cs
C#
apache-2.0
1,358
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.twill.internal; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.apache.twill.internal.state.Message; import org.apache.twill.internal.state.MessageCodec; import org.apache.twill.zookeeper.ZKClient; import org.apache.twill.zookeeper.ZKOperations; import org.apache.zookeeper.CreateMode; /** * Helper class to send messages to remote instances using Apache Zookeeper watch mechanism. */ public final class ZKMessages { /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. * @return A {@link ListenableFuture} that will be completed when the message is consumed, which indicated * by deletion of the node. If there is exception during the process, it will be reflected * to the future returned. */ public static <V> ListenableFuture<V> sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final V completionResult) { SettableFuture<V> result = SettableFuture.create(); sendMessage(zkClient, messagePathPrefix, message, result, completionResult); return result; } /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completion A {@link SettableFuture} to reflect the result of message process completion. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. */ public static <V> void sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final SettableFuture<V> completion, final V completionResult) { // Creates a message and watch for its deletion for completion. Futures.addCallback(zkClient.create(messagePathPrefix, MessageCodec.encode(message), CreateMode.PERSISTENT_SEQUENTIAL), new FutureCallback<String>() { @Override public void onSuccess(String path) { Futures.addCallback(ZKOperations.watchDeleted(zkClient, path), new FutureCallback<String>() { @Override public void onSuccess(String result) { completion.set(completionResult); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } private ZKMessages() { } }
cdapio/twill
twill-core/src/main/java/org/apache/twill/internal/ZKMessages.java
Java
apache-2.0
4,170
## Pinpoint JBoss plugin configuration ### Known Issue There is a bug in our ASM engine in 1.6.0. In order to trace jboss in 1.6.0, **you must set `profiler.instrument.engine=JAVASSIST` in pinpoint.config**. (The issue has been fixed in 1.6.1) **You must set jboss log manager starting from pinpoint 1.6.1+** - issue : #2612 ### Standalone mode <br/> Add following configuration in __standalone.conf__ :- <br/> ```bash JAVA_OPTS="$JAVA_OPTS -Djboss.modules.system.pkgs=org.jboss.byteman,org.jboss.logmanager,com.navercorp.pinpoint.bootstrap, com.navercorp.pinpoint.common,com.navercorp.pinpoint.exception" JAVA_OPTS="$JAVA_OPTS -Djava.util.logging.manager=org.jboss.logmanager.LogManager" JAVA_OPTS="$JAVA_OPTS -Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-$JBOSS_LOGMANAGER_VERSION.jar" JAVA_OPTS="$JAVA_OPTS -javaagent:$PINPOINT_AGENT_HOME/pinpoint-bootstrap-$PINPOINT_VERSION.jar" JAVA_OPTS="$JAVA_OPTS -Dpinpoint.applicationName=APP-APPLICATION-NAME" JAVA_OPTS="$JAVA_OPTS -Dpinpoint.agentId=APP-AGENTID" ``` ### Domain mode <br/> * Add below configuration in __domain.xml__ :- <br/> ```xml <system-properties> ... <property name="jboss.modules.system.pkgs" value="org.jboss.logmanager,com.navercorp.pinpoint.bootstrap, com.navercorp.pinpoint.common,com.navercorp.pinpoint.exception" boot-time="true"/> <property name="java.util.logging.manager" value="org.jboss.logmanager.LogManager"/> ... </system-properties> ``` * Add below configuration in __host.xml__ :- <br/> ```xml <servers> ... <server name="server-one" group="main-server-group"> ... <jvm name="default"> ... <jvm-options> ... <option value="-Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-$JBOSS_LOGMANAGER_VERSION.jar"/> <option value="-javaagent:$PINPOINT_AGENT_HOME/pinpoint-bootstrap-$PINPOINT_VERSION.jar"/> <option value="-Dpinpoint.applicationName=APP-APPLICATION-NAME"/> <option value="-Dpinpoint.agentId=APP-AGENT-1"/> </jvm-options> </jvm> ... </server> <server name="server-two" group="main-server-group" auto-start="true"> ... <jvm name="default"> ... <jvm-options> ... <option value="-Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-$JBOSS_LOGMANAGER_VERSION.jar"/> <option value="-javaagent:$PINPOINT_AGENT_HOME/pinpoint-bootstrap-$PINPOINT_VERSION.jar"/> <option value="-Dpinpoint.applicationName=APP-APPLICATION-NAME"/> <option value="-Dpinpoint.agentId=APP-AGENT-2"/> </jvm-options> </jvm> ... </server> </servers> ``` #### Set ```profiler.jboss.traceEjb=true``` for remote ejb based application in *pinpoint.config* file #### Set ```profiler.jboss.traceEjb=false``` for non-ejb based application in *pinpoint.config* file ### If your application shows up as *STAND_ALONE* Pinpoint agent throws an exception if multiple class file transformers are registered for a class. Since multiple plugins register class file transformers for `org.apache.catalina.core.StandardHostValve`, the agent will throw an exception on start up if they all blindly add class file transformers. To cirvumvent this issue, JBoss plugin will only register it's class file transformers if the application is detected or configured to be a *JBOSS* application. As a result, if your application is not identified as a *JBOSS* application, JBoss class file transformers will not be registered and your application will not be traced. When this happens, please manually set `profiler.applicationservertype=JBOSS` in *pinpoint.config*.
jaehong-kim/pinpoint
plugins/jboss/README.md
Markdown
apache-2.0
3,971
/************************************************************************** * * Copyright 2009 Younes Manton. * Copyright 2011 Christian König. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #ifndef vl_decoder_h #define vl_decoder_h #include "pipe/p_video_codec.h" /** * check if a given profile is supported with shader based decoding */ bool vl_profile_supported(struct pipe_screen *screen, enum pipe_video_profile profile, enum pipe_video_entrypoint entrypoint); /** * get the maximum supported level for the given profile with shader based decoding */ int vl_level_supported(struct pipe_screen *screen, enum pipe_video_profile profile); /** * standard implementation of pipe->create_video_codec */ struct pipe_video_codec * vl_create_decoder(struct pipe_context *pipe, const struct pipe_video_codec *templat); #endif /* vl_decoder_h */
execunix/vinos
xsrc/external/mit/MesaLib/dist/src/gallium/auxiliary/vl/vl_decoder.h
C
apache-2.0
2,061
param($installPath, $toolsPath, $package, $project) # Need to load MSBuild assembly if it's not loaded yet. Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' # Grab the loaded MSBuild project for the project $msbuild = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1 $importToRemove = $msbuild.Xml.Imports | Where-Object { $_.Project.Endswith($package.Id + '.targets') } if ($importToRemove) { # Remove the import and save the project $msbuild.Xml.RemoveChild($importToRemove) | out-null $project.Save() }
wadewegner/BeerStation
ref/BeerStation/packages/Microsoft.Bcl.Build.1.0.8/tools/Uninstall.ps1
PowerShell
apache-2.0
700
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; /** * Sets the level for a particular DiagnosticGroup. * @author nicksantos@google.com (Nick Santos) */ public class DiagnosticGroupWarningsGuard extends WarningsGuard { private final DiagnosticGroup group; private final CheckLevel level; public DiagnosticGroupWarningsGuard( DiagnosticGroup group, CheckLevel level) { this.group = group; this.level = level; } @Override public CheckLevel level(JSError error) { return group.matches(error) ? level : null; } @Override public boolean disables(DiagnosticGroup otherGroup) { return !level.isOn() && group.isSubGroup(otherGroup); } @Override public boolean enables(DiagnosticGroup otherGroup) { if (level.isOn()) { for (DiagnosticType type : otherGroup.getTypes()) { if (group.matches(type)) { return true; } } } return false; } }
johan/closure-compiler
src/com/google/javascript/jscomp/DiagnosticGroupWarningsGuard.java
Java
apache-2.0
1,568
//===-- CoreFoundation/URL/CFURLSessionInterface.h - Very brief description -----------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// \file /// This file contains wrappes / helpers to import libcurl into Swift. /// It is used to implement the NSURLSession API. /// /// In most cases each `curl_…` API is mapped 1-to-1 to a corresponding /// `CFURLSession_…` API. /// /// This approach lets us keep most of the logic inside Swift code as opposed /// to more C code. /// /// - SeeAlso: https://curl.haxx.se/libcurl/c/ /// //===----------------------------------------------------------------------===// #if !defined(__COREFOUNDATION_URLSESSIONINTERFACE__) #define __COREFOUNDATION_URLSESSIONINTERFACE__ 1 #include <stdio.h> CF_IMPLICIT_BRIDGING_ENABLED CF_EXTERN_C_BEGIN /// CURL typedef void * CFURLSessionEasyHandle; /// CURLM typedef void * CFURLSessionMultiHandle; // This must match libcurl's curl_socket_t typedef int CFURLSession_socket_t; typedef struct CFURLSessionEasyCode { int value; } CFURLSessionEasyCode; CF_EXPORT CFStringRef _Nonnull CFURLSessionCreateErrorDescription(int value); CF_EXPORT int const CFURLSessionEasyErrorSize; /// CURLcode CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOK; // CURLE_OK CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeUNSUPPORTED_PROTOCOL; // CURLE_UNSUPPORTED_PROTOCOL CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFAILED_INIT; // CURLE_FAILED_INIT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeURL_MALFORMAT; // CURLE_URL_MALFORMAT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeNOT_BUILT_IN; // CURLE_NOT_BUILT_IN CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeCOULDNT_RESOLVE_PROXY; // CURLE_COULDNT_RESOLVE_PROXY CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeCOULDNT_RESOLVE_HOST; // CURLE_COULDNT_RESOLVE_HOST CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeCOULDNT_CONNECT; // CURLE_COULDNT_CONNECT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_WEIRD_SERVER_REPLY; // CURLE_FTP_WEIRD_SERVER_REPLY CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeREMOTE_ACCESS_DENIED; // CURLE_REMOTE_ACCESS_DENIED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_ACCEPT_FAILED; // CURLE_FTP_ACCEPT_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_WEIRD_PASS_REPLY; // CURLE_FTP_WEIRD_PASS_REPLY CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_ACCEPT_TIMEOUT; // CURLE_FTP_ACCEPT_TIMEOUT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_WEIRD_PASV_REPLY; // CURLE_FTP_WEIRD_PASV_REPLY CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_WEIRD_227_FORMAT; // CURLE_FTP_WEIRD_227_FORMAT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_CANT_GET_HOST; // CURLE_FTP_CANT_GET_HOST //CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeHTTP2; // CURLE_HTTP2 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_COULDNT_SET_TYPE; // CURLE_FTP_COULDNT_SET_TYPE CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodePARTIAL_FILE; // CURLE_PARTIAL_FILE CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_COULDNT_RETR_FILE; // CURLE_FTP_COULDNT_RETR_FILE CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE20; // CURLE_OBSOLETE20 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeQUOTE_ERROR; // CURLE_QUOTE_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeHTTP_RETURNED_ERROR; // CURLE_HTTP_RETURNED_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeWRITE_ERROR; // CURLE_WRITE_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE24; // CURLE_OBSOLETE24 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeUPLOAD_FAILED; // CURLE_UPLOAD_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeREAD_ERROR; // CURLE_READ_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOUT_OF_MEMORY; // CURLE_OUT_OF_MEMORY CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOPERATION_TIMEDOUT; // CURLE_OPERATION_TIMEDOUT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE29; // CURLE_OBSOLETE29 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_PORT_FAILED; // CURLE_FTP_PORT_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_COULDNT_USE_REST; // CURLE_FTP_COULDNT_USE_REST CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE32; // CURLE_OBSOLETE32 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeRANGE_ERROR; // CURLE_RANGE_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeHTTP_POST_ERROR; // CURLE_HTTP_POST_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_CONNECT_ERROR; // CURLE_SSL_CONNECT_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeBAD_DOWNLOAD_RESUME; // CURLE_BAD_DOWNLOAD_RESUME CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFILE_COULDNT_READ_FILE; // CURLE_FILE_COULDNT_READ_FILE CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeLDAP_CANNOT_BIND; // CURLE_LDAP_CANNOT_BIND CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeLDAP_SEARCH_FAILED; // CURLE_LDAP_SEARCH_FAILED //CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE40; // CURLE_OBSOLETE40 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFUNCTION_NOT_FOUND; // CURLE_FUNCTION_NOT_FOUND CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeABORTED_BY_CALLBACK; // CURLE_ABORTED_BY_CALLBACK CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeBAD_FUNCTION_ARGUMENT; // CURLE_BAD_FUNCTION_ARGUMENT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE44; // CURLE_OBSOLETE44 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeINTERFACE_FAILED; // CURLE_INTERFACE_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE46; // CURLE_OBSOLETE46 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeTOO_MANY_REDIRECTS; // CURLE_TOO_MANY_REDIRECTS CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeUNKNOWN_OPTION; // CURLE_UNKNOWN_OPTION CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeTELNET_OPTION_SYNTAX; // CURLE_TELNET_OPTION_SYNTAX CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE50; // CURLE_OBSOLETE50 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodePEER_FAILED_VERIFICATION; // CURLE_PEER_FAILED_VERIFICATION CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeGOT_NOTHING; // CURLE_GOT_NOTHING CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_ENGINE_NOTFOUND; // CURLE_SSL_ENGINE_NOTFOUND CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_ENGINE_SETFAILED; // CURLE_SSL_ENGINE_SETFAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSEND_ERROR; // CURLE_SEND_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeRECV_ERROR; // CURLE_RECV_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeOBSOLETE57; // CURLE_OBSOLETE57 CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_CERTPROBLEM; // CURLE_SSL_CERTPROBLEM CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_CIPHER; // CURLE_SSL_CIPHER CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_CACERT; // CURLE_SSL_CACERT CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeBAD_CONTENT_ENCODING; // CURLE_BAD_CONTENT_ENCODING CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeLDAP_INVALID_URL; // CURLE_LDAP_INVALID_URL CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFILESIZE_EXCEEDED; // CURLE_FILESIZE_EXCEEDED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeUSE_SSL_FAILED; // CURLE_USE_SSL_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSEND_FAIL_REWIND; // CURLE_SEND_FAIL_REWIND CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_ENGINE_INITFAILED; // CURLE_SSL_ENGINE_INITFAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeLOGIN_DENIED; // CURLE_LOGIN_DENIED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeTFTP_NOTFOUND; // CURLE_TFTP_NOTFOUND CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeTFTP_PERM; // CURLE_TFTP_PERM CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeREMOTE_DISK_FULL; // CURLE_REMOTE_DISK_FULL CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeTFTP_ILLEGAL; // CURLE_TFTP_ILLEGAL CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeTFTP_UNKNOWNID; // CURLE_TFTP_UNKNOWNID CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeREMOTE_FILE_EXISTS; // CURLE_REMOTE_FILE_EXISTS CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeTFTP_NOSUCHUSER; // CURLE_TFTP_NOSUCHUSER CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeCONV_FAILED; // CURLE_CONV_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeCONV_REQD; // CURLE_CONV_REQD CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_CACERT_BADFILE; // CURLE_SSL_CACERT_BADFILE CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeREMOTE_FILE_NOT_FOUND; // CURLE_REMOTE_FILE_NOT_FOUND CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSH; // CURLE_SSH CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_SHUTDOWN_FAILED; // CURLE_SSL_SHUTDOWN_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeAGAIN; // CURLE_AGAIN CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_CRL_BADFILE; // CURLE_SSL_CRL_BADFILE CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_ISSUER_ERROR; // CURLE_SSL_ISSUER_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_PRET_FAILED; // CURLE_FTP_PRET_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeRTSP_CSEQ_ERROR; // CURLE_RTSP_CSEQ_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeRTSP_SESSION_ERROR; // CURLE_RTSP_SESSION_ERROR CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeFTP_BAD_FILE_LIST; // CURLE_FTP_BAD_FILE_LIST CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeCHUNK_FAILED; // CURLE_CHUNK_FAILED CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeNO_CONNECTION_AVAILABLE; // CURLE_NO_CONNECTION_AVAILABLE //CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_PINNEDPUBKEYNOTMATCH; // CURLE_SSL_PINNEDPUBKEYNOTMATCH //CF_EXPORT CFURLSessionEasyCode const CFURLSessionEasyCodeSSL_INVALIDCERTSTATUS; // CURLE_SSL_INVALIDCERTSTATUS /// CURLOPTTYPE typedef enum { CFURLSessionOptTypeLONG = 0, // CURLOPTTYPE_LONG CFURLSessionOptTypeOBJECTPOINT = 10000, // CURLOPTTYPE_OBJECTPOINT CFURLSessionOptTypeFUNCTIONPOINT = 20000, // CURLOPTTYPE_FUNCTIONPOINT CFURLSessionOptTypeOFF_T = 30000, // CURLOPTTYPE_OFF_T } CFURLSessionOptType; typedef struct CFURLSessionOption { int value; } CFURLSessionOption; /// CURLoption CF_EXPORT CFURLSessionOption const CFURLSessionOptionWRITEDATA; // CURLOPT_WRITEDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionURL; // CURLOPT_URL CF_EXPORT CFURLSessionOption const CFURLSessionOptionPORT; // CURLOPT_PORT CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXY; // CURLOPT_PROXY CF_EXPORT CFURLSessionOption const CFURLSessionOptionUSERPWD; // CURLOPT_USERPWD CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXYUSERPWD; // CURLOPT_PROXYUSERPWD CF_EXPORT CFURLSessionOption const CFURLSessionOptionRANGE; // CURLOPT_RANGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionREADDATA; // CURLOPT_READDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionERRORBUFFER; // CURLOPT_ERRORBUFFER CF_EXPORT CFURLSessionOption const CFURLSessionOptionWRITEFUNCTION; // CURLOPT_WRITEFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionREADFUNCTION; // CURLOPT_READFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionTIMEOUT; // CURLOPT_TIMEOUT CF_EXPORT CFURLSessionOption const CFURLSessionOptionINFILESIZE; // CURLOPT_INFILESIZE CF_EXPORT CFURLSessionOption const CFURLSessionOptionPOSTFIELDS; // CURLOPT_POSTFIELDS CF_EXPORT CFURLSessionOption const CFURLSessionOptionREFERER; // CURLOPT_REFERER CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTPPORT; // CURLOPT_FTPPORT CF_EXPORT CFURLSessionOption const CFURLSessionOptionUSERAGENT; // CURLOPT_USERAGENT CF_EXPORT CFURLSessionOption const CFURLSessionOptionLOW_SPEED_LIMIT; // CURLOPT_LOW_SPEED_LIMIT CF_EXPORT CFURLSessionOption const CFURLSessionOptionLOW_SPEED_TIME; // CURLOPT_LOW_SPEED_TIME CF_EXPORT CFURLSessionOption const CFURLSessionOptionRESUME_FROM; // CURLOPT_RESUME_FROM CF_EXPORT CFURLSessionOption const CFURLSessionOptionCOOKIE; // CURLOPT_COOKIE CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTPHEADER; // CURLOPT_HTTPHEADER CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTPPOST; // CURLOPT_HTTPPOST CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSLCERT; // CURLOPT_SSLCERT CF_EXPORT CFURLSessionOption const CFURLSessionOptionKEYPASSWD; // CURLOPT_KEYPASSWD CF_EXPORT CFURLSessionOption const CFURLSessionOptionCRLF; // CURLOPT_CRLF CF_EXPORT CFURLSessionOption const CFURLSessionOptionQUOTE; // CURLOPT_QUOTE CF_EXPORT CFURLSessionOption const CFURLSessionOptionHEADERDATA; // CURLOPT_HEADERDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionCOOKIEFILE; // CURLOPT_COOKIEFILE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSLVERSION; // CURLOPT_SSLVERSION CF_EXPORT CFURLSessionOption const CFURLSessionOptionTIMECONDITION; // CURLOPT_TIMECONDITION CF_EXPORT CFURLSessionOption const CFURLSessionOptionTIMEVALUE; // CURLOPT_TIMEVALUE CF_EXPORT CFURLSessionOption const CFURLSessionOptionCUSTOMREQUEST; // CURLOPT_CUSTOMREQUEST CF_EXPORT CFURLSessionOption const CFURLSessionOptionSTDERR; // CURLOPT_STDERR CF_EXPORT CFURLSessionOption const CFURLSessionOptionPOSTQUOTE; // CURLOPT_POSTQUOTE CF_EXPORT CFURLSessionOption const CFURLSessionOptionOBSOLETE40; // CURLOPT_OBSOLETE40 CF_EXPORT CFURLSessionOption const CFURLSessionOptionVERBOSE; // CURLOPT_VERBOSE CF_EXPORT CFURLSessionOption const CFURLSessionOptionHEADER; // CURLOPT_HEADER CF_EXPORT CFURLSessionOption const CFURLSessionOptionNOPROGRESS; // CURLOPT_NOPROGRESS CF_EXPORT CFURLSessionOption const CFURLSessionOptionNOBODY; // CURLOPT_NOBODY CF_EXPORT CFURLSessionOption const CFURLSessionOptionFAILONERROR; // CURLOPT_FAILONERROR CF_EXPORT CFURLSessionOption const CFURLSessionOptionUPLOAD; // CURLOPT_UPLOAD CF_EXPORT CFURLSessionOption const CFURLSessionOptionPOST; // CURLOPT_POST CF_EXPORT CFURLSessionOption const CFURLSessionOptionDIRLISTONLY; // CURLOPT_DIRLISTONLY CF_EXPORT CFURLSessionOption const CFURLSessionOptionAPPEND; // CURLOPT_APPEND CF_EXPORT CFURLSessionOption const CFURLSessionOptionNETRC; // CURLOPT_NETRC CF_EXPORT CFURLSessionOption const CFURLSessionOptionFOLLOWLOCATION; // CURLOPT_FOLLOWLOCATION CF_EXPORT CFURLSessionOption const CFURLSessionOptionTRANSFERTEXT; // CURLOPT_TRANSFERTEXT CF_EXPORT CFURLSessionOption const CFURLSessionOptionPUT; // CURLOPT_PUT CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROGRESSFUNCTION; // CURLOPT_PROGRESSFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROGRESSDATA; // CURLOPT_PROGRESSDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionAUTOREFERER; // CURLOPT_AUTOREFERER CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXYPORT; // CURLOPT_PROXYPORT CF_EXPORT CFURLSessionOption const CFURLSessionOptionPOSTFIELDSIZE; // CURLOPT_POSTFIELDSIZE CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTPPROXYTUNNEL; // CURLOPT_HTTPPROXYTUNNEL CF_EXPORT CFURLSessionOption const CFURLSessionOptionINTERFACE; // CURLOPT_INTERFACE CF_EXPORT CFURLSessionOption const CFURLSessionOptionKRBLEVEL; // CURLOPT_KRBLEVEL CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_VERIFYPEER; // CURLOPT_SSL_VERIFYPEER CF_EXPORT CFURLSessionOption const CFURLSessionOptionCAINFO; // CURLOPT_CAINFO CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAXREDIRS; // CURLOPT_MAXREDIRS CF_EXPORT CFURLSessionOption const CFURLSessionOptionFILETIME; // CURLOPT_FILETIME CF_EXPORT CFURLSessionOption const CFURLSessionOptionTELNETOPTIONS; // CURLOPT_TELNETOPTIONS CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAXCONNECTS; // CURLOPT_MAXCONNECTS //CF_EXPORT CFURLSessionOption const CFURLSessionOptionOBSOLETE72; // CURLOPT_OBSOLETE72 CF_EXPORT CFURLSessionOption const CFURLSessionOptionFRESH_CONNECT; // CURLOPT_FRESH_CONNECT CF_EXPORT CFURLSessionOption const CFURLSessionOptionFORBID_REUSE; // CURLOPT_FORBID_REUSE CF_EXPORT CFURLSessionOption const CFURLSessionOptionRANDOM_FILE; // CURLOPT_RANDOM_FILE CF_EXPORT CFURLSessionOption const CFURLSessionOptionEGDSOCKET; // CURLOPT_EGDSOCKET CF_EXPORT CFURLSessionOption const CFURLSessionOptionCONNECTTIMEOUT; // CURLOPT_CONNECTTIMEOUT CF_EXPORT CFURLSessionOption const CFURLSessionOptionHEADERFUNCTION; // CURLOPT_HEADERFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTPGET; // CURLOPT_HTTPGET //CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_VERIFYHOST; // CURLOPT_SSL_VERIFYHOST CF_EXPORT CFURLSessionOption const CFURLSessionOptionCOOKIEJAR; // CURLOPT_COOKIEJAR CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_CIPHER_LIST; // CURLOPT_SSL_CIPHER_LIST CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTP_VERSION; // CURLOPT_HTTP_VERSION CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_USE_EPSV; // CURLOPT_FTP_USE_EPSV CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSLCERTTYPE; // CURLOPT_SSLCERTTYPE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSLKEY; // CURLOPT_SSLKEY CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSLKEYTYPE; // CURLOPT_SSLKEYTYPE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSLENGINE; // CURLOPT_SSLENGINE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSLENGINE_DEFAULT; // CURLOPT_SSLENGINE_DEFAULT CF_EXPORT CFURLSessionOption const CFURLSessionOptionDNS_USE_GLOBAL_CACHE; // CURLOPT_DNS_USE_GLOBAL_CACHE CF_EXPORT CFURLSessionOption const CFURLSessionOptionDNS_CACHE_TIMEOUT; // CURLOPT_DNS_CACHE_TIMEOUT CF_EXPORT CFURLSessionOption const CFURLSessionOptionPREQUOTE; // CURLOPT_PREQUOTE CF_EXPORT CFURLSessionOption const CFURLSessionOptionDEBUGFUNCTION; // CURLOPT_DEBUGFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionDEBUGDATA; // CURLOPT_DEBUGDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionCOOKIESESSION; // CURLOPT_COOKIESESSION CF_EXPORT CFURLSessionOption const CFURLSessionOptionCAPATH; // CURLOPT_CAPATH CF_EXPORT CFURLSessionOption const CFURLSessionOptionBUFFERSIZE; // CURLOPT_BUFFERSIZE CF_EXPORT CFURLSessionOption const CFURLSessionOptionNOSIGNAL; // CURLOPT_NOSIGNAL CF_EXPORT CFURLSessionOption const CFURLSessionOptionSHARE; // CURLOPT_SHARE CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXYTYPE; // CURLOPT_PROXYTYPE CF_EXPORT CFURLSessionOption const CFURLSessionOptionACCEPT_ENCODING; // CURLOPT_ACCEPT_ENCODING CF_EXPORT CFURLSessionOption const CFURLSessionOptionPRIVATE; // CURLOPT_PRIVATE CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTP200ALIASES; // CURLOPT_HTTP200ALIASES CF_EXPORT CFURLSessionOption const CFURLSessionOptionUNRESTRICTED_AUTH; // CURLOPT_UNRESTRICTED_AUTH CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_USE_EPRT; // CURLOPT_FTP_USE_EPRT CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTPAUTH; // CURLOPT_HTTPAUTH CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_CTX_FUNCTION; // CURLOPT_SSL_CTX_FUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_CTX_DATA; // CURLOPT_SSL_CTX_DATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_CREATE_MISSING_DIRS; // CURLOPT_FTP_CREATE_MISSING_DIRS CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXYAUTH; // CURLOPT_PROXYAUTH CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_RESPONSE_TIMEOUT; // CURLOPT_FTP_RESPONSE_TIMEOUT CF_EXPORT CFURLSessionOption const CFURLSessionOptionIPRESOLVE; // CURLOPT_IPRESOLVE CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAXFILESIZE; // CURLOPT_MAXFILESIZE CF_EXPORT CFURLSessionOption const CFURLSessionOptionINFILESIZE_LARGE; // CURLOPT_INFILESIZE_LARGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionRESUME_FROM_LARGE; // CURLOPT_RESUME_FROM_LARGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAXFILESIZE_LARGE; // CURLOPT_MAXFILESIZE_LARGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionNETRC_FILE; // CURLOPT_NETRC_FILE CF_EXPORT CFURLSessionOption const CFURLSessionOptionUSE_SSL; // CURLOPT_USE_SSL CF_EXPORT CFURLSessionOption const CFURLSessionOptionPOSTFIELDSIZE_LARGE; // CURLOPT_POSTFIELDSIZE_LARGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionTCP_NODELAY; // CURLOPT_TCP_NODELAY CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTPSSLAUTH; // CURLOPT_FTPSSLAUTH CF_EXPORT CFURLSessionOption const CFURLSessionOptionIOCTLFUNCTION; // CURLOPT_IOCTLFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionIOCTLDATA; // CURLOPT_IOCTLDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_ACCOUNT; // CURLOPT_FTP_ACCOUNT CF_EXPORT CFURLSessionOption const CFURLSessionOptionCOOKIELIST; // CURLOPT_COOKIELIST CF_EXPORT CFURLSessionOption const CFURLSessionOptionIGNORE_CONTENT_LENGTH; // CURLOPT_IGNORE_CONTENT_LENGTH CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_SKIP_PASV_IP; // CURLOPT_FTP_SKIP_PASV_IP CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_FILEMETHOD; // CURLOPT_FTP_FILEMETHOD CF_EXPORT CFURLSessionOption const CFURLSessionOptionLOCALPORT; // CURLOPT_LOCALPORT CF_EXPORT CFURLSessionOption const CFURLSessionOptionLOCALPORTRANGE; // CURLOPT_LOCALPORTRANGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionCONNECT_ONLY; // CURLOPT_CONNECT_ONLY CF_EXPORT CFURLSessionOption const CFURLSessionOptionCONV_FROM_NETWORK_FUNCTION; // CURLOPT_CONV_FROM_NETWORK_FUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionCONV_TO_NETWORK_FUNCTION; // CURLOPT_CONV_TO_NETWORK_FUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionCONV_FROM_UTF8_FUNCTION; // CURLOPT_CONV_FROM_UTF8_FUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAX_SEND_SPEED_LARGE; // CURLOPT_MAX_SEND_SPEED_LARGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAX_RECV_SPEED_LARGE; // CURLOPT_MAX_RECV_SPEED_LARGE CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_ALTERNATIVE_TO_USER; // CURLOPT_FTP_ALTERNATIVE_TO_USER CF_EXPORT CFURLSessionOption const CFURLSessionOptionSOCKOPTFUNCTION; // CURLOPT_SOCKOPTFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionSOCKOPTDATA; // CURLOPT_SOCKOPTDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_SESSIONID_CACHE; // CURLOPT_SSL_SESSIONID_CACHE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSH_AUTH_TYPES; // CURLOPT_SSH_AUTH_TYPES CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSH_PUBLIC_KEYFILE; // CURLOPT_SSH_PUBLIC_KEYFILE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSH_PRIVATE_KEYFILE; // CURLOPT_SSH_PRIVATE_KEYFILE CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_SSL_CCC; // CURLOPT_FTP_SSL_CCC CF_EXPORT CFURLSessionOption const CFURLSessionOptionTIMEOUT_MS; // CURLOPT_TIMEOUT_MS CF_EXPORT CFURLSessionOption const CFURLSessionOptionCONNECTTIMEOUT_MS; // CURLOPT_CONNECTTIMEOUT_MS CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTP_TRANSFER_DECODING; // CURLOPT_HTTP_TRANSFER_DECODING CF_EXPORT CFURLSessionOption const CFURLSessionOptionHTTP_CONTENT_DECODING; // CURLOPT_HTTP_CONTENT_DECODING CF_EXPORT CFURLSessionOption const CFURLSessionOptionNEW_FILE_PERMS; // CURLOPT_NEW_FILE_PERMS CF_EXPORT CFURLSessionOption const CFURLSessionOptionNEW_DIRECTORY_PERMS; // CURLOPT_NEW_DIRECTORY_PERMS CF_EXPORT CFURLSessionOption const CFURLSessionOptionPOSTREDIR; // CURLOPT_POSTREDIR CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSH_HOST_PUBLIC_KEY_MD5; // CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 CF_EXPORT CFURLSessionOption const CFURLSessionOptionOPENSOCKETFUNCTION; // CURLOPT_OPENSOCKETFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionOPENSOCKETDATA; // CURLOPT_OPENSOCKETDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionCOPYPOSTFIELDS; // CURLOPT_COPYPOSTFIELDS CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXY_TRANSFER_MODE; // CURLOPT_PROXY_TRANSFER_MODE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSEEKFUNCTION; // CURLOPT_SEEKFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionSEEKDATA; // CURLOPT_SEEKDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionCRLFILE; // CURLOPT_CRLFILE CF_EXPORT CFURLSessionOption const CFURLSessionOptionISSUERCERT; // CURLOPT_ISSUERCERT CF_EXPORT CFURLSessionOption const CFURLSessionOptionADDRESS_SCOPE; // CURLOPT_ADDRESS_SCOPE CF_EXPORT CFURLSessionOption const CFURLSessionOptionCERTINFO; // CURLOPT_CERTINFO CF_EXPORT CFURLSessionOption const CFURLSessionOptionUSERNAME; // CURLOPT_USERNAME CF_EXPORT CFURLSessionOption const CFURLSessionOptionPASSWORD; // CURLOPT_PASSWORD CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXYUSERNAME; // CURLOPT_PROXYUSERNAME CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXYPASSWORD; // CURLOPT_PROXYPASSWORD CF_EXPORT CFURLSessionOption const CFURLSessionOptionNOPROXY; // CURLOPT_NOPROXY CF_EXPORT CFURLSessionOption const CFURLSessionOptionTFTP_BLKSIZE; // CURLOPT_TFTP_BLKSIZE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSOCKS5_GSSAPI_SERVICE; // CURLOPT_SOCKS5_GSSAPI_SERVICE CF_EXPORT CFURLSessionOption const CFURLSessionOptionSOCKS5_GSSAPI_NEC; // CURLOPT_SOCKS5_GSSAPI_NEC CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROTOCOLS; // CURLOPT_PROTOCOLS CF_EXPORT CFURLSessionOption const CFURLSessionOptionREDIR_PROTOCOLS; // CURLOPT_REDIR_PROTOCOLS CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSH_KNOWNHOSTS; // CURLOPT_SSH_KNOWNHOSTS CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSH_KEYFUNCTION; // CURLOPT_SSH_KEYFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSH_KEYDATA; // CURLOPT_SSH_KEYDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAIL_FROM; // CURLOPT_MAIL_FROM CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAIL_RCPT; // CURLOPT_MAIL_RCPT CF_EXPORT CFURLSessionOption const CFURLSessionOptionFTP_USE_PRET; // CURLOPT_FTP_USE_PRET CF_EXPORT CFURLSessionOption const CFURLSessionOptionRTSP_REQUEST; // CURLOPT_RTSP_REQUEST CF_EXPORT CFURLSessionOption const CFURLSessionOptionRTSP_SESSION_ID; // CURLOPT_RTSP_SESSION_ID CF_EXPORT CFURLSessionOption const CFURLSessionOptionRTSP_STREAM_URI; // CURLOPT_RTSP_STREAM_URI CF_EXPORT CFURLSessionOption const CFURLSessionOptionRTSP_TRANSPORT; // CURLOPT_RTSP_TRANSPORT CF_EXPORT CFURLSessionOption const CFURLSessionOptionRTSP_CLIENT_CSEQ; // CURLOPT_RTSP_CLIENT_CSEQ CF_EXPORT CFURLSessionOption const CFURLSessionOptionRTSP_SERVER_CSEQ; // CURLOPT_RTSP_SERVER_CSEQ CF_EXPORT CFURLSessionOption const CFURLSessionOptionINTERLEAVEDATA; // CURLOPT_INTERLEAVEDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionINTERLEAVEFUNCTION; // CURLOPT_INTERLEAVEFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionWILDCARDMATCH; // CURLOPT_WILDCARDMATCH CF_EXPORT CFURLSessionOption const CFURLSessionOptionCHUNK_BGN_FUNCTION; // CURLOPT_CHUNK_BGN_FUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionCHUNK_END_FUNCTION; // CURLOPT_CHUNK_END_FUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionFNMATCH_FUNCTION; // CURLOPT_FNMATCH_FUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionCHUNK_DATA; // CURLOPT_CHUNK_DATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionFNMATCH_DATA; // CURLOPT_FNMATCH_DATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionRESOLVE; // CURLOPT_RESOLVE CF_EXPORT CFURLSessionOption const CFURLSessionOptionTLSAUTH_USERNAME; // CURLOPT_TLSAUTH_USERNAME CF_EXPORT CFURLSessionOption const CFURLSessionOptionTLSAUTH_PASSWORD; // CURLOPT_TLSAUTH_PASSWORD CF_EXPORT CFURLSessionOption const CFURLSessionOptionTLSAUTH_TYPE; // CURLOPT_TLSAUTH_TYPE CF_EXPORT CFURLSessionOption const CFURLSessionOptionTRANSFER_ENCODING; // CURLOPT_TRANSFER_ENCODING CF_EXPORT CFURLSessionOption const CFURLSessionOptionCLOSESOCKETFUNCTION; // CURLOPT_CLOSESOCKETFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionCLOSESOCKETDATA; // CURLOPT_CLOSESOCKETDATA CF_EXPORT CFURLSessionOption const CFURLSessionOptionGSSAPI_DELEGATION; // CURLOPT_GSSAPI_DELEGATION CF_EXPORT CFURLSessionOption const CFURLSessionOptionDNS_SERVERS; // CURLOPT_DNS_SERVERS CF_EXPORT CFURLSessionOption const CFURLSessionOptionACCEPTTIMEOUT_MS; // CURLOPT_ACCEPTTIMEOUT_MS CF_EXPORT CFURLSessionOption const CFURLSessionOptionTCP_KEEPALIVE; // CURLOPT_TCP_KEEPALIVE CF_EXPORT CFURLSessionOption const CFURLSessionOptionTCP_KEEPIDLE; // CURLOPT_TCP_KEEPIDLE CF_EXPORT CFURLSessionOption const CFURLSessionOptionTCP_KEEPINTVL; // CURLOPT_TCP_KEEPINTVL CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_OPTIONS; // CURLOPT_SSL_OPTIONS CF_EXPORT CFURLSessionOption const CFURLSessionOptionMAIL_AUTH; // CURLOPT_MAIL_AUTH CF_EXPORT CFURLSessionOption const CFURLSessionOptionSASL_IR; // CURLOPT_SASL_IR CF_EXPORT CFURLSessionOption const CFURLSessionOptionXFERINFOFUNCTION; // CURLOPT_XFERINFOFUNCTION CF_EXPORT CFURLSessionOption const CFURLSessionOptionXFERINFODATA; CF_EXPORT CFURLSessionOption const CFURLSessionOptionXOAUTH2_BEARER; // CURLOPT_XOAUTH2_BEARER CF_EXPORT CFURLSessionOption const CFURLSessionOptionDNS_INTERFACE; // CURLOPT_DNS_INTERFACE CF_EXPORT CFURLSessionOption const CFURLSessionOptionDNS_LOCAL_IP4; // CURLOPT_DNS_LOCAL_IP4 CF_EXPORT CFURLSessionOption const CFURLSessionOptionDNS_LOCAL_IP6; // CURLOPT_DNS_LOCAL_IP6 CF_EXPORT CFURLSessionOption const CFURLSessionOptionLOGIN_OPTIONS; // CURLOPT_LOGIN_OPTIONS //CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_ENABLE_NPN; // CURLOPT_SSL_ENABLE_NPN //CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_ENABLE_ALPN; // CURLOPT_SSL_ENABLE_ALPN //CF_EXPORT CFURLSessionOption const CFURLSessionOptionEXPECT_100_TIMEOUT_MS; // CURLOPT_EXPECT_100_TIMEOUT_MS //CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXYHEADER; // CURLOPT_PROXYHEADER //CF_EXPORT CFURLSessionOption const CFURLSessionOptionHEADEROPT; // CURLOPT_HEADEROPT //CF_EXPORT CFURLSessionOption const CFURLSessionOptionPINNEDPUBLICKEY; // CURLOPT_PINNEDPUBLICKEY //CF_EXPORT CFURLSessionOption const CFURLSessionOptionUNIX_SOCKET_PATH; // CURLOPT_UNIX_SOCKET_PATH //CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_VERIFYSTATUS; // CURLOPT_SSL_VERIFYSTATUS //CF_EXPORT CFURLSessionOption const CFURLSessionOptionSSL_FALSESTART; // CURLOPT_SSL_FALSESTART //CF_EXPORT CFURLSessionOption const CFURLSessionOptionPATH_AS_IS; // CURLOPT_PATH_AS_IS //CF_EXPORT CFURLSessionOption const CFURLSessionOptionPROXY_SERVICE_NAME; // CURLOPT_PROXY_SERVICE_NAME //CF_EXPORT CFURLSessionOption const CFURLSessionOptionSERVICE_NAME; // CURLOPT_SERVICE_NAME //CF_EXPORT CFURLSessionOption const CFURLSessionOptionPIPEWAIT; // CURLOPT_PIPEWAIT /// This is a mash-up of these two types: /// curl_infotype & CURLoption typedef struct CFURLSessionInfo { int value; } CFURLSessionInfo; CF_EXPORT CFURLSessionInfo const CFURLSessionInfoTEXT; // CURLINFO_TEXT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoHEADER_IN; // CURLINFO_HEADER_IN CF_EXPORT CFURLSessionInfo const CFURLSessionInfoHEADER_OUT; // CURLINFO_HEADER_OUT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoDATA_IN; // CURLINFO_DATA_IN CF_EXPORT CFURLSessionInfo const CFURLSessionInfoDATA_OUT; // CURLINFO_DATA_OUT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSSL_DATA_IN; // CURLINFO_SSL_DATA_IN CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSSL_DATA_OUT; // CURLINFO_SSL_DATA_OUT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoEND; // CURLINFO_END CF_EXPORT CFURLSessionInfo const CFURLSessionInfoNONE; // CURLINFO_NONE CF_EXPORT CFURLSessionInfo const CFURLSessionInfoEFFECTIVE_URL; // CURLINFO_EFFECTIVE_URL CF_EXPORT CFURLSessionInfo const CFURLSessionInfoRESPONSE_CODE; // CURLINFO_RESPONSE_CODE CF_EXPORT CFURLSessionInfo const CFURLSessionInfoTOTAL_TIME; // CURLINFO_TOTAL_TIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoNAMELOOKUP_TIME; // CURLINFO_NAMELOOKUP_TIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoCONNECT_TIME; // CURLINFO_CONNECT_TIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoPRETRANSFER_TIME; // CURLINFO_PRETRANSFER_TIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSIZE_UPLOAD; // CURLINFO_SIZE_UPLOAD CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSIZE_DOWNLOAD; // CURLINFO_SIZE_DOWNLOAD CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSPEED_DOWNLOAD; // CURLINFO_SPEED_DOWNLOAD CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSPEED_UPLOAD; // CURLINFO_SPEED_UPLOAD CF_EXPORT CFURLSessionInfo const CFURLSessionInfoHEADER_SIZE; // CURLINFO_HEADER_SIZE CF_EXPORT CFURLSessionInfo const CFURLSessionInfoREQUEST_SIZE; // CURLINFO_REQUEST_SIZE CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSSL_VERIFYRESULT; // CURLINFO_SSL_VERIFYRESULT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoFILETIME; // CURLINFO_FILETIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoCONTENT_LENGTH_DOWNLOAD; // CURLINFO_CONTENT_LENGTH_DOWNLOAD CF_EXPORT CFURLSessionInfo const CFURLSessionInfoCONTENT_LENGTH_UPLOAD; // CURLINFO_CONTENT_LENGTH_UPLOAD CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSTARTTRANSFER_TIME; // CURLINFO_STARTTRANSFER_TIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoCONTENT_TYPE; // CURLINFO_CONTENT_TYPE CF_EXPORT CFURLSessionInfo const CFURLSessionInfoREDIRECT_TIME; // CURLINFO_REDIRECT_TIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoREDIRECT_COUNT; // CURLINFO_REDIRECT_COUNT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoPRIVATE; // CURLINFO_PRIVATE CF_EXPORT CFURLSessionInfo const CFURLSessionInfoHTTP_CONNECTCODE; // CURLINFO_HTTP_CONNECTCODE CF_EXPORT CFURLSessionInfo const CFURLSessionInfoHTTPAUTH_AVAIL; // CURLINFO_HTTPAUTH_AVAIL CF_EXPORT CFURLSessionInfo const CFURLSessionInfoPROXYAUTH_AVAIL; // CURLINFO_PROXYAUTH_AVAIL CF_EXPORT CFURLSessionInfo const CFURLSessionInfoOS_ERRNO; // CURLINFO_OS_ERRNO CF_EXPORT CFURLSessionInfo const CFURLSessionInfoNUM_CONNECTS; // CURLINFO_NUM_CONNECTS CF_EXPORT CFURLSessionInfo const CFURLSessionInfoSSL_ENGINES; // CURLINFO_SSL_ENGINES CF_EXPORT CFURLSessionInfo const CFURLSessionInfoCOOKIELIST; // CURLINFO_COOKIELIST CF_EXPORT CFURLSessionInfo const CFURLSessionInfoLASTSOCKET; // CURLINFO_LASTSOCKET CF_EXPORT CFURLSessionInfo const CFURLSessionInfoFTP_ENTRY_PATH; // CURLINFO_FTP_ENTRY_PATH CF_EXPORT CFURLSessionInfo const CFURLSessionInfoREDIRECT_URL; // CURLINFO_REDIRECT_URL CF_EXPORT CFURLSessionInfo const CFURLSessionInfoPRIMARY_IP; // CURLINFO_PRIMARY_IP CF_EXPORT CFURLSessionInfo const CFURLSessionInfoAPPCONNECT_TIME; // CURLINFO_APPCONNECT_TIME CF_EXPORT CFURLSessionInfo const CFURLSessionInfoCERTINFO; // CURLINFO_CERTINFO CF_EXPORT CFURLSessionInfo const CFURLSessionInfoCONDITION_UNMET; // CURLINFO_CONDITION_UNMET CF_EXPORT CFURLSessionInfo const CFURLSessionInfoRTSP_SESSION_ID; // CURLINFO_RTSP_SESSION_ID CF_EXPORT CFURLSessionInfo const CFURLSessionInfoRTSP_CLIENT_CSEQ; // CURLINFO_RTSP_CLIENT_CSEQ CF_EXPORT CFURLSessionInfo const CFURLSessionInfoRTSP_SERVER_CSEQ; // CURLINFO_RTSP_SERVER_CSEQ CF_EXPORT CFURLSessionInfo const CFURLSessionInfoRTSP_CSEQ_RECV; // CURLINFO_RTSP_CSEQ_RECV CF_EXPORT CFURLSessionInfo const CFURLSessionInfoPRIMARY_PORT; // CURLINFO_PRIMARY_PORT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoLOCAL_IP; // CURLINFO_LOCAL_IP CF_EXPORT CFURLSessionInfo const CFURLSessionInfoLOCAL_PORT; // CURLINFO_LOCAL_PORT CF_EXPORT CFURLSessionInfo const CFURLSessionInfoTLS_SESSION; // CURLINFO_TLS_SESSION CF_EXPORT CFURLSessionInfo const CFURLSessionInfoLASTONE; // CURLINFO_LASTONE typedef struct CFURLSessionMultiOption { int value; } CFURLSessionMultiOption; /// CURLMoption CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionSOCKETFUNCTION; // CURLMOPT_SOCKETFUNCTION CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionSOCKETDATA; // CURLMOPT_SOCKETDATA CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionPIPELINING; // CURLMOPT_PIPELINING CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionTIMERFUNCTION; // CURLMOPT_TIMERFUNCTION CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionTIMERDATA; // CURLMOPT_TIMERDATA CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionMAXCONNECTS; // CURLMOPT_MAXCONNECTS CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionMAX_HOST_CONNECTIONS; // CURLMOPT_MAX_HOST_CONNECTIONS CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionMAX_PIPELINE_LENGTH; // CURLMOPT_MAX_PIPELINE_LENGTH CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionCONTENT_LENGTH_PENALTY_SIZE; // CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionCHUNK_LENGTH_PENALTY_SIZE; // CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionPIPELINING_SITE_BL; // CURLMOPT_PIPELINING_SITE_BL CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionPIPELINING_SERVER_BL; // CURLMOPT_PIPELINING_SERVER_BL CF_EXPORT CFURLSessionMultiOption const CFURLSessionMultiOptionMAX_TOTAL_CONNECTIONS; // CURLMOPT_MAX_TOTAL_CONNECTIONS typedef struct CFURLSessionMultiCode { int value; } CFURLSessionMultiCode; /// CURLMcode CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeCALL_MULTI_PERFORM; // CURLM_CALL_MULTI_PERFORM CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeOK; // CURLM_OK CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeBAD_HANDLE; // CURLM_BAD_HANDLE CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeBAD_EASY_HANDLE; // CURLM_BAD_EASY_HANDLE CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeOUT_OF_MEMORY; // CURLM_OUT_OF_MEMORY CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeINTERNAL_ERROR; // CURLM_INTERNAL_ERROR CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeBAD_SOCKET; // CURLM_BAD_SOCKET CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeUNKNOWN_OPTION; // CURLM_UNKNOWN_OPTION CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeADDED_ALREADY; // CURLM_ADDED_ALREADY CF_EXPORT CFURLSessionMultiCode const CFURLSessionMultiCodeLAST; // CURLM_LAST typedef struct CFURLSessionPoll { int value; } CFURLSessionPoll; CF_EXPORT CFURLSessionPoll const CFURLSessionPollNone; // CURL_POLL_NONE CF_EXPORT CFURLSessionPoll const CFURLSessionPollIn; // CURL_POLL_IN CF_EXPORT CFURLSessionPoll const CFURLSessionPollOut; // CURL_POLL_OUT CF_EXPORT CFURLSessionPoll const CFURLSessionPollInOut; // CURL_POLL_INOUT CF_EXPORT CFURLSessionPoll const CFURLSessionPollRemove; // CURL_POLL_REMOVE typedef long CFURLSessionProtocol; CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolHTTP; // CURLPROTO_HTTP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolHTTPS; // CURLPROTO_HTTPS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolFTP; // CURLPROTO_FTP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolFTPS; // CURLPROTO_FTPS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolSCP; // CURLPROTO_SCP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolSFTP; // CURLPROTO_SFTP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolTELNET; // CURLPROTO_TELNET CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolLDAP; // CURLPROTO_LDAP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolLDAPS; // CURLPROTO_LDAPS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolDICT; // CURLPROTO_DICT CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolFILE; // CURLPROTO_FILE CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolTFTP; // CURLPROTO_TFTP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolIMAP; // CURLPROTO_IMAP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolIMAPS; // CURLPROTO_IMAPS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolPOP3; // CURLPROTO_POP3 CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolPOP3S; // CURLPROTO_POP3S CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolSMTP; // CURLPROTO_SMTP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolSMTPS; // CURLPROTO_SMTPS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolRTSP; // CURLPROTO_RTSP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolRTMP; // CURLPROTO_RTMP CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolRTMPT; // CURLPROTO_RTMPT CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolRTMPE; // CURLPROTO_RTMPE CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolRTMPTE; // CURLPROTO_RTMPTE CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolRTMPS; // CURLPROTO_RTMPS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolRTMPTS; // CURLPROTO_RTMPTS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolGOPHER; // CURLPROTO_GOPHER //CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolSMB; // CURLPROTO_SMB //CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolSMBS; // CURLPROTO_SMBS CF_EXPORT CFURLSessionProtocol const CFURLSessionProtocolALL; // CURLPROTO_ALL CF_EXPORT size_t const CFURLSessionMaxWriteSize; // CURL_MAX_WRITE_SIZE CF_EXPORT char * _Nonnull CFURLSessionCurlVersionString(void); typedef struct CFURLSessionCurlVersion { int major; int minor; int patch; } CFURLSessionCurlVersion; CF_EXPORT CFURLSessionCurlVersion CFURLSessionCurlVersionInfo(void); CF_EXPORT int const CFURLSessionWriteFuncPause; CF_EXPORT int const CFURLSessionReadFuncPause; CF_EXPORT int const CFURLSessionReadFuncAbort; CF_EXPORT int const CFURLSessionSocketTimeout; CF_EXPORT int const CFURLSessionSeekOk; CF_EXPORT int const CFURLSessionSeekCantSeek; CF_EXPORT int const CFURLSessionSeekFail; CF_EXPORT CFURLSessionEasyHandle _Nonnull CFURLSessionEasyHandleInit(void); CF_EXPORT void CFURLSessionEasyHandleDeinit(CFURLSessionEasyHandle _Nonnull handle); CF_EXPORT CFURLSessionEasyCode CFURLSessionEasyHandleSetPauseState(CFURLSessionEasyHandle _Nonnull handle, int send, int receive); CF_EXPORT CFURLSessionMultiHandle _Nonnull CFURLSessionMultiHandleInit(void); CF_EXPORT CFURLSessionMultiCode CFURLSessionMultiHandleDeinit(CFURLSessionMultiHandle _Nonnull handle); CF_EXPORT CFURLSessionMultiCode CFURLSessionMultiHandleAddHandle(CFURLSessionMultiHandle _Nonnull handle, CFURLSessionEasyHandle _Nonnull curl); CF_EXPORT CFURLSessionMultiCode CFURLSessionMultiHandleRemoveHandle(CFURLSessionMultiHandle _Nonnull handle, CFURLSessionEasyHandle _Nonnull curl); CF_EXPORT CFURLSessionMultiCode CFURLSessionMultiHandleAssign(CFURLSessionMultiHandle _Nonnull handle, CFURLSession_socket_t socket, void * _Nullable sockp); CF_EXPORT CFURLSessionMultiCode CFURLSessionMultiHandleAction(CFURLSessionMultiHandle _Nonnull handle, CFURLSession_socket_t socket, int bitmask, int * _Nonnull running_handles); typedef struct CFURLSessionMultiHandleInfo { CFURLSessionEasyHandle _Nullable easyHandle; CFURLSessionEasyCode resultCode; } CFURLSessionMultiHandleInfo; CF_EXPORT CFURLSessionMultiHandleInfo CFURLSessionMultiHandleInfoRead(CFURLSessionMultiHandle _Nonnull handle, int * _Nonnull msgs_in_queue); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_fptr(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, void *_Nullable a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_ptr(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, void *_Nullable a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_int(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, int a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_long(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, long a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_int64(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, int64_t a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_wc(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, size_t(*_Nonnull a)(char *_Nonnull, size_t, size_t, void *_Nullable)); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_fwc(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, size_t(*_Nonnull a)(char *_Nonnull, size_t, size_t, void *_Nullable)); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_dc(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, int(*_Nonnull a)(CFURLSessionEasyHandle _Nonnull handle, int type, char *_Nonnull data, size_t size, void *_Nullable userptr)); typedef enum { CFURLSessionSocketTypeIPCXN, // socket created for a specific IP connection CFURLSessionSocketTypeAccept, // socket created by accept() call } CFURLSessionSocketType; typedef int (CFURLSessionSocketOptionCallback)(void *_Nullable clientp, int fd, CFURLSessionSocketType purpose); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_sc(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, CFURLSessionSocketOptionCallback * _Nullable a); typedef int (CFURLSessionSeekCallback)(void *_Nullable userp, int64_t offset, int origin); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_seek(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, CFURLSessionSeekCallback * _Nullable a); typedef int (CFURLSessionTransferInfoCallback)(void *_Nullable userp, int64_t dltotal, int64_t dlnow, int64_t ultotal, int64_t ulnow); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_setopt_tc(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionOption option, CFURLSessionTransferInfoCallback * _Nullable a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_getinfo_long(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionInfo info, long *_Nonnull a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_getinfo_double(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionInfo info, double *_Nonnull a); CF_EXPORT CFURLSessionEasyCode CFURLSession_easy_getinfo_charp(CFURLSessionEasyHandle _Nonnull curl, CFURLSessionInfo info, char *_Nullable*_Nonnull a); CF_EXPORT CFURLSessionMultiCode CFURLSession_multi_setopt_ptr(CFURLSessionMultiHandle _Nonnull multi_handle, CFURLSessionMultiOption option, void *_Nullable a); CF_EXPORT CFURLSessionMultiCode CFURLSession_multi_setopt_l(CFURLSessionMultiHandle _Nonnull multi_handle, CFURLSessionMultiOption option, long a); CF_EXPORT CFURLSessionMultiCode CFURLSession_multi_setopt_sf(CFURLSessionMultiHandle _Nonnull multi_handle, CFURLSessionMultiOption option, int (*_Nonnull a)(CFURLSessionEasyHandle _Nonnull, CFURLSession_socket_t, int, void *_Nullable, void *_Nullable)); CF_EXPORT CFURLSessionMultiCode CFURLSession_multi_setopt_tf(CFURLSessionMultiHandle _Nonnull multi_handle, CFURLSessionMultiOption option, int (*_Nonnull a)(CFURLSessionMultiHandle _Nonnull, long, void *_Nullable)); CF_EXPORT CFURLSessionEasyCode CFURLSessionInit(void); typedef struct CFURLSessionSList CFURLSessionSList; CF_EXPORT CFURLSessionSList *_Nullable CFURLSessionSListAppend(CFURLSessionSList *_Nullable list, const char * _Nullable string); CF_EXPORT void CFURLSessionSListFreeAll(CFURLSessionSList *_Nullable list); CF_EXTERN_C_END CF_IMPLICIT_BRIDGING_DISABLED #endif /* __COREFOUNDATION_URLSESSIONINTERFACE__ */
johnno1962b/swift-corelibs-foundation
CoreFoundation/URL.subproj/CFURLSessionInterface.h
C
apache-2.0
47,599
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.expressions import java.util.UUID import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.codegen._ import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.UTF8String /** * Print the result of an expression to stderr (used for debugging codegen). */ case class PrintToStderr(child: Expression) extends UnaryExpression { override def dataType: DataType = child.dataType protected override def nullSafeEval(input: Any): Any = input private val outputPrefix = s"Result of ${child.simpleString} is " override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { val outputPrefixField = ctx.addReferenceObj("outputPrefix", outputPrefix) nullSafeCodeGen(ctx, ev, c => s""" | System.err.println($outputPrefixField + $c); | ${ev.value} = $c; """.stripMargin) } } /** * A function throws an exception if 'condition' is not true. */ @ExpressionDescription( usage = "_FUNC_(expr) - Throws an exception if `expr` is not true.", examples = """ Examples: > SELECT _FUNC_(0 < 1); NULL """) case class AssertTrue(child: Expression) extends UnaryExpression with ImplicitCastInputTypes { override def nullable: Boolean = true override def inputTypes: Seq[DataType] = Seq(BooleanType) override def dataType: DataType = NullType override def prettyName: String = "assert_true" private val errMsg = s"'${child.simpleString}' is not true!" override def eval(input: InternalRow) : Any = { val v = child.eval(input) if (v == null || java.lang.Boolean.FALSE.equals(v)) { throw new RuntimeException(errMsg) } else { null } } override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { val eval = child.genCode(ctx) // Use unnamed reference that doesn't create a local field here to reduce the number of fields // because errMsgField is used only when the value is null or false. val errMsgField = ctx.addReferenceMinorObj(errMsg) ExprCode(code = s"""${eval.code} |if (${eval.isNull} || !${eval.value}) { | throw new RuntimeException($errMsgField); |}""".stripMargin, isNull = "true", value = "null") } override def sql: String = s"assert_true(${child.sql})" } /** * Returns the current database of the SessionCatalog. */ @ExpressionDescription( usage = "_FUNC_() - Returns the current database.", examples = """ Examples: > SELECT _FUNC_(); default """) case class CurrentDatabase() extends LeafExpression with Unevaluable { override def dataType: DataType = StringType override def foldable: Boolean = true override def nullable: Boolean = false override def prettyName: String = "current_database" } // scalastyle:off line.size.limit @ExpressionDescription( usage = "_FUNC_() - Returns an universally unique identifier (UUID) string. The value is returned as a canonical UUID 36-character string.", examples = """ Examples: > SELECT _FUNC_(); 46707d92-02f4-4817-8116-a4c3b23e6266 """) // scalastyle:on line.size.limit case class Uuid() extends LeafExpression { override lazy val deterministic: Boolean = false override def nullable: Boolean = false override def dataType: DataType = StringType override def eval(input: InternalRow): Any = UTF8String.fromString(UUID.randomUUID().toString) override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { ev.copy(code = s"final UTF8String ${ev.value} = " + s"UTF8String.fromString(java.util.UUID.randomUUID().toString());", isNull = "false") } }
akopich/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/misc.scala
Scala
apache-2.0
4,467
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.kafka.test.base; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * The util class for kafka example. */ public class KafkaExampleUtil { public static StreamExecutionEnvironment prepareExecutionEnv(ParameterTool parameterTool) throws Exception { if (parameterTool.getNumberOfParameters() < 5) { System.out.println("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); throw new Exception("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); } StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setRestartStrategy(RestartStrategies.fixedDelayRestart(4, 10000)); env.enableCheckpointing(5000); // create a checkpoint every 5 seconds env.getConfig().setGlobalJobParameters(parameterTool); // make parameters available in the web interface env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); return env; } }
GJL/flink
flink-end-to-end-tests/flink-streaming-kafka-test-base/src/main/java/org/apache/flink/streaming/kafka/test/base/KafkaExampleUtil.java
Java
apache-2.0
2,183
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.content.model; /** * Model definition for OrdersSetLineItemMetadataResponse. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class OrdersSetLineItemMetadataResponse extends com.google.api.client.json.GenericJson { /** * The status of the execution. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String executionStatus; /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * The status of the execution. * @return value or {@code null} for none */ public java.lang.String getExecutionStatus() { return executionStatus; } /** * The status of the execution. * @param executionStatus executionStatus or {@code null} for none */ public OrdersSetLineItemMetadataResponse setExecutionStatus(java.lang.String executionStatus) { this.executionStatus = executionStatus; return this; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @param kind kind or {@code null} for none */ public OrdersSetLineItemMetadataResponse setKind(java.lang.String kind) { this.kind = kind; return this; } @Override public OrdersSetLineItemMetadataResponse set(String fieldName, Object value) { return (OrdersSetLineItemMetadataResponse) super.set(fieldName, value); } @Override public OrdersSetLineItemMetadataResponse clone() { return (OrdersSetLineItemMetadataResponse) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-content/v2/1.29.2/com/google/api/services/content/model/OrdersSetLineItemMetadataResponse.java
Java
apache-2.0
3,052
/* Uncaught exception * Output: EH_UNCAUGHT_EXCEPTION */ function throwsException() { throw new Error(); } function doSomething() { try { throwsException(); } catch (e) { } } function doSomethingElse() { throwsException(); } doSomething(); doSomethingElse();
qhanam/Pangor
js/test/input/error_handling/eh_methods_old.js
JavaScript
apache-2.0
272
/** * Copyright 2010-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.spring; import static java.lang.reflect.Proxy.newProxyInstance; import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable; import static org.mybatis.spring.SqlSessionUtils.closeSqlSession; import static org.mybatis.spring.SqlSessionUtils.getSqlSession; import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional; import static org.springframework.util.Assert.notNull; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.Connection; import java.util.List; import java.util.Map; import org.apache.ibatis.cursor.Cursor; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.executor.BatchResult; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.dao.support.PersistenceExceptionTranslator; /** * Thread safe, Spring managed, {@code SqlSession} that works with Spring * transaction management to ensure that that the actual SqlSession used is the * one associated with the current Spring transaction. In addition, it manages * the session life-cycle, including closing, committing or rolling back the * session as necessary based on the Spring transaction configuration. * <p> * The template needs a SqlSessionFactory to create SqlSessions, passed as a * constructor argument. It also can be constructed indicating the executor type * to be used, if not, the default executor type, defined in the session factory * will be used. * <p> * This template converts MyBatis PersistenceExceptions into unchecked * DataAccessExceptions, using, by default, a {@code MyBatisExceptionTranslator}. * <p> * Because SqlSessionTemplate is thread safe, a single instance can be shared * by all DAOs; there should also be a small memory savings by doing this. This * pattern can be used in Spring configuration files as follows: * * <pre class="code"> * {@code * <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg ref="sqlSessionFactory" /> * </bean> * } * </pre> * * @author Putthibong Boonbong * @author Hunter Presnall * @author Eduardo Macarron * * @see SqlSessionFactory * @see MyBatisExceptionTranslator * @version $Id$ */ public class SqlSessionTemplate implements SqlSession, DisposableBean { private final SqlSessionFactory sqlSessionFactory; private final ExecutorType executorType; private final SqlSession sqlSessionProxy; private final PersistenceExceptionTranslator exceptionTranslator; /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument. * * @param sqlSessionFactory */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); } /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument and the given {@code ExecutorType} * {@code ExecutorType} cannot be changed once the {@code SqlSessionTemplate} * is constructed. * * @param sqlSessionFactory * @param executorType */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) { this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator( sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true)); } /** * Constructs a Spring managed {@code SqlSession} with the given * {@code SqlSessionFactory} and {@code ExecutorType}. * A custom {@code SQLExceptionTranslator} can be provided as an * argument so any {@code PersistenceException} thrown by MyBatis * can be custom translated to a {@code RuntimeException} * The {@code SQLExceptionTranslator} can also be null and thus no * exception translation will be done and MyBatis exceptions will be * thrown * * @param sqlSessionFactory * @param executorType * @param exceptionTranslator */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required"); notNull(executorType, "Property 'executorType' is required"); this.sqlSessionFactory = sqlSessionFactory; this.executorType = executorType; this.exceptionTranslator = exceptionTranslator; this.sqlSessionProxy = (SqlSession) newProxyInstance( SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class }, new SqlSessionInterceptor()); } public SqlSessionFactory getSqlSessionFactory() { return this.sqlSessionFactory; } public ExecutorType getExecutorType() { return this.executorType; } public PersistenceExceptionTranslator getPersistenceExceptionTranslator() { return this.exceptionTranslator; } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement) { return this.sqlSessionProxy.<T> selectOne(statement); } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement, Object parameter) { return this.sqlSessionProxy.<T> selectOne(statement, parameter); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement) { return this.sqlSessionProxy.selectCursor(statement); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter) { return this.sqlSessionProxy.selectCursor(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.selectCursor(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement) { return this.sqlSessionProxy.<E> selectList(statement); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter) { return this.sqlSessionProxy.<E> selectList(statement, parameter); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public void select(String statement, ResultHandler handler) { this.sqlSessionProxy.select(statement, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, rowBounds, handler); } /** * {@inheritDoc} */ @Override public int insert(String statement) { return this.sqlSessionProxy.insert(statement); } /** * {@inheritDoc} */ @Override public int insert(String statement, Object parameter) { return this.sqlSessionProxy.insert(statement, parameter); } /** * {@inheritDoc} */ @Override public int update(String statement) { return this.sqlSessionProxy.update(statement); } /** * {@inheritDoc} */ @Override public int update(String statement, Object parameter) { return this.sqlSessionProxy.update(statement, parameter); } /** * {@inheritDoc} */ @Override public int delete(String statement) { return this.sqlSessionProxy.delete(statement); } /** * {@inheritDoc} */ @Override public int delete(String statement, Object parameter) { return this.sqlSessionProxy.delete(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> T getMapper(Class<T> type) { return getConfiguration().getMapper(type, this); } /** * {@inheritDoc} */ @Override public void commit() { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void commit(boolean force) { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback() { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback(boolean force) { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void close() { throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void clearCache() { this.sqlSessionProxy.clearCache(); } /** * {@inheritDoc} * */ @Override public Configuration getConfiguration() { return this.sqlSessionFactory.getConfiguration(); } /** * {@inheritDoc} */ @Override public Connection getConnection() { return this.sqlSessionProxy.getConnection(); } /** * {@inheritDoc} * * @since 1.0.2 * */ @Override public List<BatchResult> flushStatements() { return this.sqlSessionProxy.flushStatements(); } /** * Allow gently dispose bean: * <pre> * {@code * * <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg index="0" ref="sqlSessionFactory" /> * </bean> * } *</pre> * * The implementation of {@link DisposableBean} forces spring context to use {@link DisposableBean#destroy()} method instead of {@link SqlSessionTemplate#close()} to shutdown gently. * * @see SqlSessionTemplate#close() * @see org.springframework.beans.factory.support.DisposableBeanAdapter#inferDestroyMethodIfNecessary * @see org.springframework.beans.factory.support.DisposableBeanAdapter#CLOSE_METHOD_NAME */ @Override public void destroy() throws Exception { //This method forces spring disposer to avoid call of SqlSessionTemplate.close() which gives UnsupportedOperationException } /** * Proxy needed to route MyBatis method calls to the proper SqlSession got * from Spring's Transaction Manager * It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to * pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}. */ private class SqlSessionInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession sqlSession = getSqlSession( SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator); try { Object result = method.invoke(sqlSession, args); if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) { // force commit even on non-dirty sessions because some databases require // a commit/rollback before calling close() sqlSession.commit(true); } return result; } catch (Throwable t) { Throwable unwrapped = unwrapThrowable(t); if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) { // release the connection to avoid a deadlock if the translator is no loaded. See issue #22 closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); sqlSession = null; Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped); if (translated != null) { unwrapped = translated; } } throw unwrapped; } finally { if (sqlSession != null) { closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); } } } } }
jiangchaoting/spring
src/main/java/org/mybatis/spring/SqlSessionTemplate.java
Java
apache-2.0
13,876
--- layout: post title: "Beam Summit Europe 2018" date: 2018-08-21 00:00:01 -0800 excerpt_separator: <!--more--> categories: blog authors: - mbaetens --- <!-- 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. --> With a growing community of contributors and users, the Apache Beam project is organising the first European Beam Summit. We are happy to invite you to this event, which will take place in **London** on **October 1st and 2nd of 2018**. <!--more--> <img src="{{ "/images/blog/Facebook-AD.png" | prepend: site.baseurl }}" alt="Beam Summit Europe 2018 flyer" height="360" width="640" > ### What is the Beam Summit 2018? The summit is a 2 day, multi-track event. During the first day we’ll host sessions to share use cases from companies using Apache Beam, community driven talks, and a session to discuss the project's roadmap (from the main partners in the project as well as all users planning to contribute to the project and wanting to share their plans). We'll also have break-out sessions that will allow cross team collaboration in multiple sub-topics. The second day will be a "hands-on" day. We will offer an introductory session to Apache Beam. Additionally, we'll host an advanced track for more advanced users with open-table discussions about more complex and newer Apache Beam features. The agenda will grow and be communicated in the coming month, keep an eye on the page. ### Event Details - **Venue**: [Level39, One Canada Square, Canary Wharf, London E14 5AB](https://goo.gl/maps/LAC4haDzSzR2) - **Dates**: 1-2 October 2018 ### How do I register? You can register for free on the [Eventbrite registration page](https://www.eventbrite.com/e/beam-summit-london-2018-tickets-49100625292#tickets). ### I am interested in speaking, how do I propose my session? With this we are also launching a Call for Papers in case you want to secure a slot for one of the sessions. Please fill out the [CfP form](https://goo.gl/forms/nrZOCC1JwEfLtKfA2). ### I'd love to get involved as a volunteer or sponsor Furthermore, in order to keep this event free, we are looking for people to help out at and/or sponsor some parts of the conference. If you (or your company) are interested to help out, please reach out to: <baetensmatthias@gmail.com> or <alex@vanboxel.be>. You can find more info in the [sponsor booklet](https://drive.google.com/file/d/1RnZ52rGaB6BR-EKneBcabdMcg9Pl7z9M) Thanks, and we hope to see you at the event! The Events & Meetups Group
mxm/incubator-beam
website/src/_posts/2018-08-21-beam-summit-europe.md
Markdown
apache-2.0
2,959
abstract class AbstractClass { constructor(str: string, other: AbstractClass) { this.method(parseInt(str)); let val = this.prop.toLowerCase(); if (!str) { this.prop = "Hello World"; } this.cb(str); // OK, reference is inside function const innerFunction = () => { return this.prop; } // OK, references are to another instance other.cb(other.prop); } abstract prop: string; abstract cb: (s: string) => void; abstract method(num: number): void; other = this.prop; fn = () => this.prop; method2() { this.prop = this.prop + "!"; } } abstract class DerivedAbstractClass extends AbstractClass { cb = (s: string) => {}; constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { super(str, other); // there is no implementation of 'prop' in any base class this.cb(this.prop.toLowerCase()); this.method(1); // OK, references are to another instance other.cb(other.prop); yetAnother.cb(yetAnother.prop); } } class Implementation extends DerivedAbstractClass { prop = ""; cb = (s: string) => {}; constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { super(str, other, yetAnother); this.cb(this.prop); } method(n: number) { this.cb(this.prop + n); } } class User { constructor(a: AbstractClass) { a.prop; a.cb("hi"); a.method(12); a.method2(); } }
weswigham/TypeScript
tests/cases/compiler/abstractPropertyInConstructor.ts
TypeScript
apache-2.0
1,679
#!/usr/bin/env python3 class UniqueIndexViolationCheck: unique_indexes_query = """ select table_oid, index_name, table_name, array_agg(attname) as column_names from pg_attribute, ( select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index from pg_index, pg_class index_class, pg_class table_class where pg_index.indisunique='t' and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog') and index_class.relkind = 'i' and index_class.oid = pg_index.indexrelid and table_class.oid = pg_index.indrelid ) as unique_catalog_index_columns where attnum = column_index and attrelid = table_oid group by table_oid, index_name, table_name; """ def __init__(self): self.violated_segments_query = """ select distinct(gp_segment_id) from ( (select gp_segment_id, %s from gp_dist_random('%s') where (%s) is not null group by gp_segment_id, %s having count(*) > 1) union (select gp_segment_id, %s from %s where (%s) is not null group by gp_segment_id, %s having count(*) > 1) ) as violations """ def runCheck(self, db_connection): unique_indexes = db_connection.query(self.unique_indexes_query).getresult() violations = [] for (table_oid, index_name, table_name, column_names) in unique_indexes: column_names = ",".join(column_names) sql = self.get_violated_segments_query(table_name, column_names) violated_segments = db_connection.query(sql).getresult() if violated_segments: violations.append(dict(table_oid=table_oid, table_name=table_name, index_name=index_name, column_names=column_names, violated_segments=[row[0] for row in violated_segments])) return violations def get_violated_segments_query(self, table_name, column_names): return self.violated_segments_query % ( column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names )
50wu/gpdb
gpMgmt/bin/gpcheckcat_modules/unique_index_violation_check.py
Python
apache-2.0
2,547
-- @Description Tests the behavior while compacting is disabled CREATE TABLE uao_eof_truncate (a INT, b INT, c CHAR(128)) WITH (appendonly=true); CREATE INDEX uao_eof_truncate_index ON uao_eof_truncate(b); BEGIN; INSERT INTO uao_eof_truncate SELECT i as a, 1 as b, 'hello world' as c FROM generate_series(1,1000) AS i; ANALYZE uao_eof_truncate; COMMIT; BEGIN; INSERT INTO uao_eof_truncate SELECT i as a, 1 as b, 'hello world' as c FROM generate_series(1000,2000) AS i; ROLLBACK; SET gp_appendonly_compaction=false; SELECT COUNT(*) FROM uao_eof_truncate; VACUUM uao_eof_truncate; SELECT COUNT(*) FROM uao_eof_truncate; -- Insert afterwards INSERT INTO uao_eof_truncate SELECT i as a, 1 as b, 'hello world' as c FROM generate_series(1,10) AS i; SELECT COUNT(*) FROM uao_eof_truncate;
50wu/gpdb
src/test/regress/sql/uao_compaction/eof_truncate.sql
SQL
apache-2.0
784
/* * Copyright (c) 2010, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.test.jdbc4.jdbc41; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.postgresql.test.TestUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.Properties; public class SchemaTest { private Connection _conn; private boolean dropUserSchema; @Before public void setUp() throws Exception { _conn = TestUtil.openDB(); Statement stmt = _conn.createStatement(); try { stmt.execute("CREATE SCHEMA " + TestUtil.getUser()); dropUserSchema = true; } catch (SQLException e) { /* assume schema existed */ } stmt.execute("CREATE SCHEMA schema1"); stmt.execute("CREATE SCHEMA schema2"); stmt.execute("CREATE SCHEMA \"schema 3\""); stmt.execute("CREATE SCHEMA \"schema \"\"4\""); stmt.execute("CREATE SCHEMA \"schema '5\""); stmt.execute("CREATE SCHEMA \"schema ,6\""); stmt.execute("CREATE SCHEMA \"UpperCase\""); TestUtil.createTable(_conn, "schema1.table1", "id integer"); TestUtil.createTable(_conn, "schema2.table2", "id integer"); TestUtil.createTable(_conn, "\"UpperCase\".table3", "id integer"); TestUtil.createTable(_conn, "schema1.sptest", "id integer"); TestUtil.createTable(_conn, "schema2.sptest", "id varchar"); } @After public void tearDown() throws SQLException { _conn.setAutoCommit(true); _conn.setSchema(null); Statement stmt = _conn.createStatement(); if (dropUserSchema) { stmt.execute("DROP SCHEMA " + TestUtil.getUser() + " CASCADE"); } stmt.execute("DROP SCHEMA schema1 CASCADE"); stmt.execute("DROP SCHEMA schema2 CASCADE"); stmt.execute("DROP SCHEMA \"schema 3\" CASCADE"); stmt.execute("DROP SCHEMA \"schema \"\"4\" CASCADE"); stmt.execute("DROP SCHEMA \"schema '5\" CASCADE"); stmt.execute("DROP SCHEMA \"schema ,6\""); stmt.execute("DROP SCHEMA \"UpperCase\" CASCADE"); TestUtil.closeDB(_conn); } /** * Test that what you set is what you get */ @Test public void testGetSetSchema() throws SQLException { _conn.setSchema("schema1"); assertEquals("schema1", _conn.getSchema()); _conn.setSchema("schema2"); assertEquals("schema2", _conn.getSchema()); _conn.setSchema("schema 3"); assertEquals("schema 3", _conn.getSchema()); _conn.setSchema("schema \"4"); assertEquals("schema \"4", _conn.getSchema()); _conn.setSchema("schema '5"); assertEquals("schema '5", _conn.getSchema()); _conn.setSchema("UpperCase"); assertEquals("UpperCase", _conn.getSchema()); } /** * Test that setting the schema allows to access objects of this schema without prefix, hide * objects from other schemas but doesn't prevent to prefix-access to them. */ @Test public void testUsingSchema() throws SQLException { Statement stmt = _conn.createStatement(); try { try { _conn.setSchema("schema1"); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("schema2"); stmt.executeQuery(TestUtil.selectSQL("table2", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("UpperCase"); stmt.executeQuery(TestUtil.selectSQL("table3", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } } catch (SQLException e) { fail("Could not find expected schema elements: " + e.getMessage()); } } finally { try { stmt.close(); } catch (SQLException e) { } } } /** * Test that get schema returns the schema with the highest priority in the search path */ @Test public void testMultipleSearchPath() throws SQLException { execute("SET search_path TO schema1,schema2"); assertEquals("schema1", _conn.getSchema()); execute("SET search_path TO \"schema ,6\",schema2"); assertEquals("schema ,6", _conn.getSchema()); } @Test public void testSchemaInProperties() throws Exception { Properties properties = new Properties(); properties.setProperty("currentSchema", "schema1"); Connection conn = TestUtil.openDB(properties); try { assertEquals("schema1", conn.getSchema()); Statement stmt = conn.createStatement(); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } } finally { TestUtil.closeDB(conn); } } @Test public void testSchemaPath$User() throws Exception { execute("SET search_path TO \"$user\",public,schema2"); assertEquals(TestUtil.getUser(), _conn.getSchema()); } private void execute(String sql) throws SQLException { Statement stmt = _conn.createStatement(); try { stmt.execute(sql); } finally { try { stmt.close(); } catch (SQLException e) { } } } @Test public void testSearchPathPreparedStatementAutoCommitFalse() throws SQLException { _conn.setAutoCommit(false); testSearchPathPreparedStatement(); } @Test public void testSearchPathPreparedStatementAutoCommitTrue() throws SQLException { testSearchPathPreparedStatement(); } @Test public void testSearchPathPreparedStatement() throws SQLException { execute("set search_path to schema1,public"); PreparedStatement ps = _conn.prepareStatement("select * from sptest"); for (int i = 0; i < 10; i++) { ps.execute(); } assertColType(ps, "sptest should point to schema1.sptest, thus column type should be INT", Types.INTEGER); ps.close(); execute("set search_path to schema2,public"); ps = _conn.prepareStatement("select * from sptest"); assertColType(ps, "sptest should point to schema2.sptest, thus column type should be VARCHAR", Types.VARCHAR); ps.close(); } private void assertColType(PreparedStatement ps, String message, int expected) throws SQLException { ResultSet rs = ps.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int columnType = md.getColumnType(1); assertEquals(message, expected, columnType); rs.close(); } }
panchenko/pgjdbc
pgjdbc/src/test/java/org/postgresql/test/jdbc4/jdbc41/SchemaTest.java
Java
bsd-2-clause
7,435
# This shell snippet unsets all variables/functions that can be used in # a package template and can also be used in subpkgs. ## VARIABLES unset -v noarch conf_files mutable_files preserve triggers unset -v depends run_depends replaces provides conflicts tags # hooks/post-install/03-strip-and-debug-pkgs unset -v nostrip nostrip_files # hooks/pre-pkg/04-generate-runtime-deps unset -v noverifyrdeps allow_unknown_shlibs shlib_requires # hooks/pre-pkg/06-prepare-32bit unset -v lib32depends lib32disabled lib32files lib32mode lib32symlinks # hooks/pre-pkg/06-shlib-provides unset -v noshlibprovides shlib_provides # xbps-triggers: system-accounts unset -v system_accounts system_groups # xbps-triggers: font-dirs unset -v font_dirs # xbps-triggers: xml-catalog unset -v xml_entries sgml_entries xml_catalogs sgml_catalogs # xbps-triggers: pycompile unset -v pycompile_version pycompile_dirs pycompile_module # xbps-triggers: dkms unset -v dkms_modules # xbps-triggers: kernel-hooks unset -v kernel_hooks_version # xbps-triggers: mkdirs unset -v make_dirs # xbps-triggers: binfmts unset -v binfmts
ylixir/void-packages
common/environment/setup-subpkg/subpkg.sh
Shell
bsd-2-clause
1,110
/** * Copyright 2013-2014 Facebook, Inc. * * 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. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPluginRegistry = require("./EventPluginRegistry"); var ReactEventEmitterMixin = require("./ReactEventEmitterMixin"); var ViewportMetrics = require("./ViewportMetrics"); var isEventSupported = require("./isEventSupported"); var merge = require("./merge"); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topBlur: 'blur', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTextInput: 'textInput', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = merge(ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel ); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled() ); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!( isListening.hasOwnProperty(dependency) && isListening[dependency] )) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'wheel', mountAt ); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'mousewheel', mountAt ); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt ); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topScroll, 'scroll', mountAt ); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE ); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topFocus, 'focus', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topBlur, 'blur', mountAt ); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topFocus, 'focusin', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topBlur, 'focusout', mountAt ); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( dependency, topEventMapping[dependency], mountAt ); } isListening[dependency] = true; } } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelType, handlerBaseName, handle ); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelType, handlerBaseName, handle ); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function(){ if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); module.exports = ReactBrowserEventEmitter;
KnisterPeter/jreact
src/test/resources/react-0.11/node_modules/react/lib/ReactBrowserEventEmitter.js
JavaScript
bsd-2-clause
12,568
/* * Copyright 2010-2016 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause */ #ifndef BX_FLOAT4X4_H_HEADER_GUARD #define BX_FLOAT4X4_H_HEADER_GUARD #include "simd_t.h" namespace bx { BX_ALIGN_DECL_16(struct) float4x4_t { simd128_t col[4]; }; BX_SIMD_FORCE_INLINE simd128_t simd_mul_xyz1(simd128_t _a, const float4x4_t* _b) { const simd128_t xxxx = simd_swiz_xxxx(_a); const simd128_t yyyy = simd_swiz_yyyy(_a); const simd128_t zzzz = simd_swiz_zzzz(_a); const simd128_t col0 = simd_mul(_b->col[0], xxxx); const simd128_t col1 = simd_mul(_b->col[1], yyyy); const simd128_t col2 = simd_madd(_b->col[2], zzzz, col0); const simd128_t col3 = simd_add(_b->col[3], col1); const simd128_t result = simd_add(col2, col3); return result; } BX_SIMD_FORCE_INLINE simd128_t simd_mul(simd128_t _a, const float4x4_t* _b) { const simd128_t xxxx = simd_swiz_xxxx(_a); const simd128_t yyyy = simd_swiz_yyyy(_a); const simd128_t zzzz = simd_swiz_zzzz(_a); const simd128_t wwww = simd_swiz_wwww(_a); const simd128_t col0 = simd_mul(_b->col[0], xxxx); const simd128_t col1 = simd_mul(_b->col[1], yyyy); const simd128_t col2 = simd_madd(_b->col[2], zzzz, col0); const simd128_t col3 = simd_madd(_b->col[3], wwww, col1); const simd128_t result = simd_add(col2, col3); return result; } BX_SIMD_INLINE void float4x4_mul(float4x4_t* __restrict _result, const float4x4_t* __restrict _a, const float4x4_t* __restrict _b) { _result->col[0] = simd_mul(_a->col[0], _b); _result->col[1] = simd_mul(_a->col[1], _b); _result->col[2] = simd_mul(_a->col[2], _b); _result->col[3] = simd_mul(_a->col[3], _b); } BX_SIMD_FORCE_INLINE void float4x4_transpose(float4x4_t* __restrict _result, const float4x4_t* __restrict _mtx) { const simd128_t aibj = simd_shuf_xAyB(_mtx->col[0], _mtx->col[2]); // aibj const simd128_t emfn = simd_shuf_xAyB(_mtx->col[1], _mtx->col[3]); // emfn const simd128_t ckdl = simd_shuf_zCwD(_mtx->col[0], _mtx->col[2]); // ckdl const simd128_t gohp = simd_shuf_zCwD(_mtx->col[1], _mtx->col[3]); // gohp _result->col[0] = simd_shuf_xAyB(aibj, emfn); // aeim _result->col[1] = simd_shuf_zCwD(aibj, emfn); // bfjn _result->col[2] = simd_shuf_xAyB(ckdl, gohp); // cgko _result->col[3] = simd_shuf_zCwD(ckdl, gohp); // dhlp } BX_SIMD_INLINE void float4x4_inverse(float4x4_t* __restrict _result, const float4x4_t* __restrict _a) { const simd128_t tmp0 = simd_shuf_xAzC(_a->col[0], _a->col[1]); const simd128_t tmp1 = simd_shuf_xAzC(_a->col[2], _a->col[3]); const simd128_t tmp2 = simd_shuf_yBwD(_a->col[0], _a->col[1]); const simd128_t tmp3 = simd_shuf_yBwD(_a->col[2], _a->col[3]); const simd128_t t0 = simd_shuf_xyAB(tmp0, tmp1); const simd128_t t1 = simd_shuf_xyAB(tmp3, tmp2); const simd128_t t2 = simd_shuf_zwCD(tmp0, tmp1); const simd128_t t3 = simd_shuf_zwCD(tmp3, tmp2); const simd128_t t23 = simd_mul(t2, t3); const simd128_t t23_yxwz = simd_swiz_yxwz(t23); const simd128_t t23_wzyx = simd_swiz_wzyx(t23); simd128_t cof0, cof1, cof2, cof3; const simd128_t zero = simd_zero(); cof0 = simd_nmsub(t1, t23_yxwz, zero); cof0 = simd_madd(t1, t23_wzyx, cof0); cof1 = simd_nmsub(t0, t23_yxwz, zero); cof1 = simd_madd(t0, t23_wzyx, cof1); cof1 = simd_swiz_zwxy(cof1); const simd128_t t12 = simd_mul(t1, t2); const simd128_t t12_yxwz = simd_swiz_yxwz(t12); const simd128_t t12_wzyx = simd_swiz_wzyx(t12); cof0 = simd_madd(t3, t12_yxwz, cof0); cof0 = simd_nmsub(t3, t12_wzyx, cof0); cof3 = simd_mul(t0, t12_yxwz); cof3 = simd_nmsub(t0, t12_wzyx, cof3); cof3 = simd_swiz_zwxy(cof3); const simd128_t t1_zwxy = simd_swiz_zwxy(t1); const simd128_t t2_zwxy = simd_swiz_zwxy(t2); const simd128_t t13 = simd_mul(t1_zwxy, t3); const simd128_t t13_yxwz = simd_swiz_yxwz(t13); const simd128_t t13_wzyx = simd_swiz_wzyx(t13); cof0 = simd_madd(t2_zwxy, t13_yxwz, cof0); cof0 = simd_nmsub(t2_zwxy, t13_wzyx, cof0); cof2 = simd_mul(t0, t13_yxwz); cof2 = simd_nmsub(t0, t13_wzyx, cof2); cof2 = simd_swiz_zwxy(cof2); const simd128_t t01 = simd_mul(t0, t1); const simd128_t t01_yxwz = simd_swiz_yxwz(t01); const simd128_t t01_wzyx = simd_swiz_wzyx(t01); cof2 = simd_nmsub(t3, t01_yxwz, cof2); cof2 = simd_madd(t3, t01_wzyx, cof2); cof3 = simd_madd(t2_zwxy, t01_yxwz, cof3); cof3 = simd_nmsub(t2_zwxy, t01_wzyx, cof3); const simd128_t t03 = simd_mul(t0, t3); const simd128_t t03_yxwz = simd_swiz_yxwz(t03); const simd128_t t03_wzyx = simd_swiz_wzyx(t03); cof1 = simd_nmsub(t2_zwxy, t03_yxwz, cof1); cof1 = simd_madd(t2_zwxy, t03_wzyx, cof1); cof2 = simd_madd(t1, t03_yxwz, cof2); cof2 = simd_nmsub(t1, t03_wzyx, cof2); const simd128_t t02 = simd_mul(t0, t2_zwxy); const simd128_t t02_yxwz = simd_swiz_yxwz(t02); const simd128_t t02_wzyx = simd_swiz_wzyx(t02); cof1 = simd_madd(t3, t02_yxwz, cof1); cof1 = simd_nmsub(t3, t02_wzyx, cof1); cof3 = simd_nmsub(t1, t02_yxwz, cof3); cof3 = simd_madd(t1, t02_wzyx, cof3); const simd128_t det = simd_dot(t0, cof0); const simd128_t invdet = simd_rcp(det); _result->col[0] = simd_mul(cof0, invdet); _result->col[1] = simd_mul(cof1, invdet); _result->col[2] = simd_mul(cof2, invdet); _result->col[3] = simd_mul(cof3, invdet); } } // namespace bx #endif // BX_FLOAT4X4_H_HEADER_GUARD
dariomanesku/bx
include/bx/float4x4_t.h
C
bsd-2-clause
5,418
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """ Test the Worksheet _write_worksheet() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_worksheet(self): """Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">""" got = self.fh.getvalue() self.assertEqual(got, exp)
jvrsantacruz/XlsxWriter
xlsxwriter/test/worksheet/test_write_worksheet.py
Python
bsd-2-clause
887
class Jellyfish < Formula desc "Fast, memory-efficient counting of DNA k-mers" homepage "http://www.genome.umd.edu/jellyfish.html" url "https://github.com/gmarcais/Jellyfish/releases/download/v2.3.0/jellyfish-2.3.0.tar.gz" sha256 "e195b7cf7ba42a90e5e112c0ed27894cd7ac864476dc5fb45ab169f5b930ea5a" license any_of: ["BSD-3-Clause", "GPL-3.0-or-later"] bottle do sha256 cellar: :any, arm64_monterey: "3368a53a61d961a9169a4156a60d8023aee069084c108d67e8b81d12c01e5106" sha256 cellar: :any, arm64_big_sur: "15ceae21239d0a1f851e878d20889ef5539b121222153829b3b1e2dcb6cc2548" sha256 cellar: :any, monterey: "00ffb57295d4f3362c58fc69bb017c183efbb7a7533a57d49cbf2dd83ca4d5cb" sha256 cellar: :any, big_sur: "04b22121bce09df2e3cee997d3973a12e9f58e9b5e928465502eb4e83d429352" sha256 cellar: :any, catalina: "0ce228d3b386be6f7e10bed1186abfc74544658e092defaa4a7001a06c7f0eed" sha256 cellar: :any, mojave: "78083728d3d3d1cba0ec71786d1f633c4a626c1b64432ce46f84dacfb0a714d6" sha256 cellar: :any_skip_relocation, x86_64_linux: "1e1922bf36c12b1d56d19e1ead6bd461000bd7ed19a8ac5cfd4398f2bbd54e61" end depends_on "autoconf@2.69" => :build depends_on "automake" => :build depends_on "gettext" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "htslib" def install # autoreconf to fix flat namespace detection bug. system "autoreconf", "-fvi" system "./configure", *std_configure_args system "make" system "make", "install" end test do (testpath/"test.fa").write <<~EOS >Homebrew AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC EOS system "#{bin}/jellyfish", "count", "-m17", "-s100M", "-t2", "-C", "test.fa" assert_match "1 54", shell_output("#{bin}/jellyfish histo mer_counts.jf") assert_match(/Unique:\s+54/, shell_output("#{bin}/jellyfish stats mer_counts.jf")) end end
sjackman/homebrew-core
Formula/jellyfish.rb
Ruby
bsd-2-clause
2,051
package org.atmosphere.cpr import java.net.URI import org.scalatra.atmosphere.{ RedisScalatraBroadcaster, ScalatraBroadcaster } trait BroadcasterConf { def broadcasterClass: Class[_ <: ScalatraBroadcaster] def uri: URI def extraSetup: Broadcaster => Unit // To perform optional plugin-specific Broadcaster setup } /** * * Basic Configuration-holder for Scalatra Atmosphere Broadcaster configuration * @param broadcasterClass Class[_<:ScalatraBroadcaster] * @param uri [[URI]] defaults to http://127.0.0.1 * @param extraSetup Broadcaster => Unit Function that is passed an initialized [[Broadcaster]] in order to allow for * optional plugin-specific Broadcaster setup. Defaults to doing nothing. */ sealed case class ScalatraBroadcasterConfig(broadcasterClass: Class[_ <: ScalatraBroadcaster], uri: URI = URI.create("http://127.0.0.1"), extraSetup: Broadcaster => Unit = { b => }) extends BroadcasterConf /** * Convenient configuration class for RedisBroadcaster * * Using this class will automatically take care of setting Redis auth on the underlying * RedisBroadcaster if the auth parameter is given an argument * * @param uri [[URI]] for the Redis Server. Defaults to redis://127.0.0.1:6379 * @param auth An Option[String] if the Redis Server requires a password. Defaults to None */ sealed case class RedisScalatraBroadcasterConfig(uri: URI = URI.create("redis://127.0.0.1:6379"), auth: Option[String] = None) extends BroadcasterConf { final def broadcasterClass = classOf[RedisScalatraBroadcaster] final def extraSetup = { b: Broadcaster => auth.foreach(b.asInstanceOf[RedisScalatraBroadcaster].setAuth(_)) } }
dozed/scalatra
atmosphere/src/main/scala/org/atmosphere/cpr/broadcaster_configs.scala
Scala
bsd-2-clause
1,673
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2013, Knut Reinert, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Tobias Rausch <rausch@embl.de> // ========================================================================== #ifndef SEQAN_HEADER_FIND_AHOCORASICK_H #define SEQAN_HEADER_FIND_AHOCORASICK_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // AhoCorasick ////////////////////////////////////////////////////////////////////////////// /** .Spec.AhoCorasick: ..summary: Multiple exact string matching using Aho-Corasick. ..general:Class.Pattern ..cat:Searching ..signature:Pattern<TNeedle, AhoCorasick> ..param.TNeedle:The needle type, a string of keywords. ...type:Class.String ..remarks.text:The types of the keywords in the needle container and the haystack have to match. ..remarks.text:Matching positions do not come in order because we report beginning positions of matches. ..remarks.text:Likewise, if multiple keywords match at a given position no pre-specified order is guaranteed. ..include:seqan/find.h */ ///.Class.Pattern.param.TSpec.type:Spec.AhoCorasick struct AhoCorasick_; typedef Tag<AhoCorasick_> AhoCorasick; ////////////////////////////////////////////////////////////////////////////// template <typename TNeedle> class Pattern<TNeedle, AhoCorasick> { //____________________________________________________________________________ private: Pattern(Pattern const& other); Pattern const& operator=(Pattern const & other); //____________________________________________________________________________ public: typedef typename Size<TNeedle>::Type TSize; typedef typename Value<TNeedle>::Type TKeyword; typedef typename Value<TKeyword>::Type TAlphabet; typedef Graph<Automaton<TAlphabet> > TGraph; typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor; Holder<TNeedle> data_host; String<TVertexDescriptor> data_supplyMap; String<String<TSize> > data_terminalStateMap; TGraph data_graph; // To restore the automaton after a hit String<TSize> data_endPositions; // All remaining keyword indices TSize data_keywordIndex; // Current keyword that produced a hit TSize data_needleLength; // Last length of needle to reposition finder TVertexDescriptor data_lastState; // Last state in the trie //____________________________________________________________________________ Pattern() { } template <typename TNeedle2> Pattern(TNeedle2 const & ndl) { SEQAN_CHECKPOINT setHost(*this, ndl); } ~Pattern() { SEQAN_CHECKPOINT } //____________________________________________________________________________ }; ////////////////////////////////////////////////////////////////////////////// // Host Metafunctions ////////////////////////////////////////////////////////////////////////////// template <typename TNeedle> struct Host< Pattern<TNeedle, AhoCorasick> > { typedef TNeedle Type; }; template <typename TNeedle> struct Host< Pattern<TNeedle, AhoCorasick> const> { typedef TNeedle const Type; }; ////////////////////////////////////////////////////////////////////////////// // Functions ////////////////////////////////////////////////////////////////////////////// template <typename TNeedle> inline void _createAcTrie(Pattern<TNeedle, AhoCorasick> & me) { typedef typename Position<TNeedle>::Type TPosition; typedef typename Value<TNeedle>::Type TKeyword; typedef typename Value<TKeyword>::Type TAlphabet; typedef Graph<Automaton<TAlphabet> > TGraph; typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor; TVertexDescriptor nilVal = getNil<TVertexDescriptor>(); // Create regular trie createTrie(me.data_graph,me.data_terminalStateMap, host(me)); // Create parent map String<TVertexDescriptor> parentMap; String<TAlphabet> parentCharMap; resizeVertexMap(me.data_graph,parentMap); resizeVertexMap(me.data_graph,parentCharMap); for(TPosition i = 0;i<length(parentMap);++i) { assignProperty(parentMap, i, nilVal); } typedef typename Iterator<TGraph, EdgeIterator>::Type TEdgeIterator; TEdgeIterator itEd(me.data_graph); for(;!atEnd(itEd);goNext(itEd)) { assignProperty(parentMap, targetVertex(itEd), sourceVertex(itEd)); assignProperty(parentCharMap, targetVertex(itEd), label(itEd)); } // Build AC TVertexDescriptor root = getRoot(me.data_graph); resizeVertexMap(me.data_graph,me.data_supplyMap); assignProperty(me.data_supplyMap, root, nilVal); // Bfs Traversal typedef typename Iterator<TGraph, BfsIterator>::Type TBfsIterator; TBfsIterator it(me.data_graph,root); for(;!atEnd(it);goNext(it)) { if (atBegin(it)) continue; TVertexDescriptor parent = getProperty(parentMap, *it); TAlphabet sigma = getProperty(parentCharMap, *it); TVertexDescriptor down = getProperty(me.data_supplyMap, parent); while ((down != nilVal) && (getSuccessor(me.data_graph, down, sigma) == nilVal)) { down = getProperty(me.data_supplyMap, down); } if (down != nilVal) { assignProperty(me.data_supplyMap, *it, getSuccessor(me.data_graph, down, sigma)); String<TPosition> endPositions = getProperty(me.data_terminalStateMap, getProperty(me.data_supplyMap, *it)); if (!empty(endPositions)) { String<TPosition> endPositionsCurrent = getProperty(me.data_terminalStateMap, *it); typedef typename Iterator<String<TPosition>, Rooted >::Type TStringIterator; TStringIterator sit = begin(endPositions); for(;!atEnd(sit);goNext(sit)) { appendValue(endPositionsCurrent, *sit); } assignProperty(me.data_terminalStateMap, *it, endPositionsCurrent); } } else { assignProperty(me.data_supplyMap, *it, root); } } } template <typename TNeedle, typename TNeedle2> void setHost (Pattern<TNeedle, AhoCorasick> & me, TNeedle2 const & needle) { SEQAN_CHECKPOINT; SEQAN_ASSERT_NOT(empty(needle)); setValue(me.data_host, needle); clear(me.data_graph); clear(me.data_supplyMap); clear(me.data_endPositions); clear(me.data_terminalStateMap); _createAcTrie(me); me.data_needleLength = 0; //fstream strm; //strm.open(TEST_PATH "my_trie.dot", ios_base::out | ios_base::trunc); //String<String<char> > nodeMap; //_createTrieNodeAttributes(me.data_graph, me.data_terminalStateMap, nodeMap); //String<String<char> > edgeMap; //_createEdgeAttributes(me.data_graph,edgeMap); //write(strm,me.data_graph,nodeMap,edgeMap,DotDrawing()); //strm.close(); // Supply links //for(unsigned int i=0;i<length(me.data_supplyMap);++i) { // std::cout << i << "->" << getProperty(me.data_supplyMap,i) << ::std::endl; //} } template <typename TNeedle, typename TNeedle2> inline void setHost (Pattern<TNeedle, AhoCorasick> & me, TNeedle2 & needle) { setHost(me, reinterpret_cast<TNeedle2 const &>(needle)); } //____________________________________________________________________________ template <typename TNeedle> inline void _patternInit (Pattern<TNeedle, AhoCorasick> & me) { SEQAN_CHECKPOINT clear(me.data_endPositions); me.data_keywordIndex = 0; me.data_lastState = getRoot(me.data_graph); } //____________________________________________________________________________ template <typename TNeedle> inline typename Size<TNeedle>::Type position(Pattern<TNeedle, AhoCorasick> & me) { return me.data_keywordIndex; } template <typename TFinder, typename TNeedle> inline bool find(TFinder & finder, Pattern<TNeedle, AhoCorasick> & me) { typedef typename Value<TNeedle>::Type TKeyword; typedef typename Value<TKeyword>::Type TAlphabet; typedef Graph<Automaton<TAlphabet> > TGraph; typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor; if (empty(finder)) { _patternInit(me); _finderSetNonEmpty(finder); } else { finder += me.data_needleLength; ++finder; // Set forward the finder } // Process left-over hits if (!empty(me.data_endPositions)) { --finder; // Set back the finder me.data_keywordIndex = me.data_endPositions[length(me.data_endPositions)-1]; me.data_needleLength = length(value(host(me), me.data_keywordIndex))-1; if (length(me.data_endPositions) > 1) resize(me.data_endPositions, (length(me.data_endPositions)-1)); else clear(me.data_endPositions); finder -= me.data_needleLength; _setFinderLength(finder, me.data_needleLength+1); _setFinderEnd(finder, position(finder)+length(finder)); return true; } TVertexDescriptor current = me.data_lastState; TVertexDescriptor nilVal = getNil<TVertexDescriptor>(); while (!atEnd(finder)) { while ((getSuccessor(me.data_graph, current, *finder) == nilVal) && (getProperty(me.data_supplyMap, current) != nilVal)) { current = getProperty(me.data_supplyMap,current); } if (getSuccessor(me.data_graph, current, *finder) != nilVal) { current = getSuccessor(me.data_graph, current, *finder); } else { current = getRoot(me.data_graph); } me.data_endPositions = getProperty(me.data_terminalStateMap,current); if (!empty(me.data_endPositions)) { me.data_keywordIndex = me.data_endPositions[length(me.data_endPositions)-1]; me.data_needleLength = length(value(host(me), me.data_keywordIndex))-1; if (length(me.data_endPositions) > 1) resize(me.data_endPositions, length(me.data_endPositions)-1); else clear(me.data_endPositions); me.data_lastState = current; finder -= me.data_needleLength; _setFinderLength(finder, me.data_needleLength+1); _setFinderEnd(finder, position(finder)+length(finder)); return true; } ++finder; } return false; } }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_FIND_AHOCORASICK_H
charite/Q
src/seqan/core/include/seqan/find/find_ahocorasick.h
C
bsd-2-clause
11,338
<?php /** * Squiz_Sniffs_Classes_ValidClassNameSniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@squiz.net> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Squiz_Sniffs_Classes_ValidClassNameSniff. * * Ensures classes are in camel caps, and the first letter is capitalised * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@squiz.net> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ class Squiz_Sniffs_Classes_ValidClassNameSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array( T_CLASS, T_INTERFACE, ); }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The current file being processed. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if (isset($tokens[$stackPtr]['scope_opener']) === false) { $error = 'Possible parse error: %s missing opening or closing brace'; $data = array($tokens[$stackPtr]['content']); $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $data); return; } // Determine the name of the class or interface. Note that we cannot // simply look for the first T_STRING because a class name // starting with the number will be multiple tokens. $opener = $tokens[$stackPtr]['scope_opener']; $nameStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $opener, true); $nameEnd = $phpcsFile->findNext(T_WHITESPACE, $nameStart, $opener); $name = trim($phpcsFile->getTokensAsString($nameStart, ($nameEnd - $nameStart))); // Check for camel caps format. $valid = PHP_CodeSniffer::isCamelCaps($name, true, true, false); if ($valid === false) { $type = ucfirst($tokens[$stackPtr]['content']); $error = '%s name "%s" is not in camel caps format'; $data = array( $type, $name, ); $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $data); } }//end process() }//end class ?>
scaryml1000/ZendSkeleton
vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/Squiz/Sniffs/Classes/ValidClassNameSniff.php
PHP
bsd-3-clause
3,154
/**************************************************************************** * sched/pthread_condwait.c * * Copyright (C) 2007-2009, 2012 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name NuttX 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <unistd.h> #include <pthread.h> #include <sched.h> #include <errno.h> #include <debug.h> #include "pthread_internal.h" /**************************************************************************** * Definitions ****************************************************************************/ /**************************************************************************** * Private Type Declarations ****************************************************************************/ /**************************************************************************** * Global Variables ****************************************************************************/ /**************************************************************************** * Private Variables ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: int pthread_cond_wait * * Description: * A thread can wait for a condition variable to be signalled or broadcast. * * Parameters: * None * * Return Value: * None * * Assumptions: * ****************************************************************************/ int pthread_cond_wait(FAR pthread_cond_t *cond, FAR pthread_mutex_t *mutex) { int ret; sdbg("cond=0x%p mutex=0x%p\n", cond, mutex); /* Make sure that non-NULL references were provided. */ if (!cond || !mutex) { ret = EINVAL; } /* Make sure that the caller holds the mutex */ else if (mutex->pid != (int)getpid()) { ret = EPERM; } else { /* Give up the mutex */ sdbg("Give up mutex / take cond\n"); sched_lock(); mutex->pid = 0; ret = pthread_givesemaphore((sem_t*)&mutex->sem); /* Take the semaphore */ ret |= pthread_takesemaphore((sem_t*)&cond->sem); sched_unlock(); /* Reacquire the mutex */ sdbg("Reacquire mutex...\n"); ret |= pthread_takesemaphore((sem_t*)&mutex->sem); if (!ret) { mutex->pid = getpid();; } } sdbg("Returning %d\n", ret); return ret; }
gcds/project_xxx
nuttx/sched/pthread_condwait.c
C
bsd-3-clause
4,507
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\helpers; /** * Console helper provides useful methods for command line related tasks such as getting input or formatting and coloring * output. * * @author Carsten Brandt <mail@cebe.cc> * @since 2.0 */ class Console extends BaseConsole { }
nikn/it-asu.ru
vendor/yiisoft/yii2/helpers/Console.php
PHP
bsd-3-clause
432
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ 'use strict'; const {polyfillObjectProperty} = require('../Utilities/PolyfillFunctions'); let navigator = global.navigator; if (navigator === undefined) { global.navigator = navigator = {}; } // see https://github.com/facebook/react-native/issues/10881 polyfillObjectProperty(navigator, 'product', () => 'ReactNative');
pandiaraj44/react-native
Libraries/Core/setUpNavigator.js
JavaScript
bsd-3-clause
545
/* * Copyright (c) 2016-2020, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <stdint.h> #include <string.h> #include <lib/mmio.h> #include <lib/fconf/fconf.h> #include <plat/arm/common/plat_arm.h> #include <plat/arm/common/fconf_nv_cntr_getter.h> #include <plat/common/platform.h> #include <platform_def.h> #include <tools_share/tbbr_oid.h> /* * Return the ROTPK hash in the following ASN.1 structure in DER format: * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * DigestInfo ::= SEQUENCE { * digestAlgorithm AlgorithmIdentifier, * digest OCTET STRING * } */ int plat_get_rotpk_info(void *cookie, void **key_ptr, unsigned int *key_len, unsigned int *flags) { return arm_get_rotpk_info(cookie, key_ptr, key_len, flags); } /* * Store a new non-volatile counter value. * * On some FVP versions, the non-volatile counters are read-only so this * function will always fail. * * Return: 0 = success, Otherwise = error */ int plat_set_nv_ctr(void *cookie, unsigned int nv_ctr) { const char *oid; uintptr_t nv_ctr_addr; assert(cookie != NULL); oid = (const char *)cookie; if (strcmp(oid, TRUSTED_FW_NVCOUNTER_OID) == 0) { nv_ctr_addr = FCONF_GET_PROPERTY(cot, nv_cntr_addr, TRUSTED_NV_CTR_ID); } else if (strcmp(oid, NON_TRUSTED_FW_NVCOUNTER_OID) == 0) { nv_ctr_addr = FCONF_GET_PROPERTY(cot, nv_cntr_addr, NON_TRUSTED_NV_CTR_ID); } else { return 1; } mmio_write_32(nv_ctr_addr, nv_ctr); /* * If the FVP models a locked counter then its value cannot be updated * and the above write operation has been silently ignored. */ return (mmio_read_32(nv_ctr_addr) == nv_ctr) ? 0 : 1; }
jenswi-linaro/arm-trusted-firmware
plat/arm/board/fvp/fvp_trusted_boot.c
C
bsd-3-clause
1,842
-- Copyright 2004-present Facebook. All Rights Reserved. require 'nn' local TemporalConvolutionFB, parent = torch.class('nn.TemporalConvolutionFB', 'nn.Module') function TemporalConvolutionFB:__init(inputFrameSize, outputFrameSize, kW, dW) parent.__init(self) dW = dW or 1 self.inputFrameSize = inputFrameSize self.outputFrameSize = outputFrameSize self.kW = kW self.dW = dW self.weight = torch.Tensor(outputFrameSize, kW, inputFrameSize) self.bias = torch.Tensor(outputFrameSize) self.gradWeight = torch.Tensor(outputFrameSize, kW, inputFrameSize) self.gradBias = torch.Tensor(outputFrameSize) self:reset() end function TemporalConvolutionFB:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.inputFrameSize) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function TemporalConvolutionFB:updateOutput(input) input.nn.TemporalConvolutionFB_updateOutput(self, input) return self.output end function TemporalConvolutionFB:updateGradInput(input, gradOutput) if self.gradInput then return input.nn.TemporalConvolutionFB_updateGradInput( self, input, gradOutput) end end function TemporalConvolutionFB:accGradParameters(input, gradOutput, scale) scale = scale or 1 input.nn.TemporalConvolutionFB_accGradParameters( self, input, gradOutput, scale) end -- we do not need to accumulate parameters when sharing TemporalConvolutionFB.sharedAccUpdateGradParameters = TemporalConvolutionFB.accUpdateGradParameters
u20024804/fbcunn
fbcunn/TemporalConvolutionFB.lua
Lua
bsd-3-clause
1,799
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/permissions/permission_request_id.h" #include <inttypes.h> #include <stdint.h> #include "base/strings/stringprintf.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" namespace permissions { PermissionRequestID::PermissionRequestID( content::RenderFrameHost* render_frame_host, RequestLocalId request_local_id) : render_process_id_(render_frame_host->GetProcess()->GetID()), render_frame_id_(render_frame_host->GetRoutingID()), request_local_id_(request_local_id) {} PermissionRequestID::PermissionRequestID(int render_process_id, int render_frame_id, RequestLocalId request_local_id) : render_process_id_(render_process_id), render_frame_id_(render_frame_id), request_local_id_(request_local_id) {} PermissionRequestID::~PermissionRequestID() {} PermissionRequestID::PermissionRequestID(const PermissionRequestID&) = default; PermissionRequestID& PermissionRequestID::operator=( const PermissionRequestID&) = default; bool PermissionRequestID::operator==(const PermissionRequestID& other) const { return render_process_id_ == other.render_process_id_ && render_frame_id_ == other.render_frame_id_ && request_local_id_ == other.request_local_id_; } bool PermissionRequestID::operator!=(const PermissionRequestID& other) const { return !operator==(other); } std::string PermissionRequestID::ToString() const { return base::StringPrintf("%d,%d,%" PRId64, render_process_id_, render_frame_id_, request_local_id_.value()); } } // namespace permissions
scheib/chromium
components/permissions/permission_request_id.cc
C++
bsd-3-clause
1,886
#include <iostream> #include <seqan/file.h> #include <seqan/sequence.h> #include <seqan/score.h> using namespace seqan; template <typename TText, typename TPattern> int computeLocalScore(TText const & subText, TPattern const & pattern) { int localScore = 0; for (unsigned i = 0; i < length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText, typename TPattern> String<int> computeScore(TText const & text, TPattern const & pattern) { String<int> score; resize(score, length(text) - length(pattern) + 1, 0); for (unsigned i = 0; i < length(text) - length(pattern) + 1; ++i) score[i] = computeLocalScore(infix(text, i, i + length(pattern)), pattern); return score; } void print(String<int> const & text) { for (unsigned i = 0; i < length(text); ++i) std::cout << text[i] << " "; std::cout << std::endl; } int main() { String<char> text = "This is an awesome tutorial to get to know SeqAn!"; String<char> pattern = "tutorial"; String<int> score = computeScore(text, pattern); print(score); return 0; }
bestrauc/seqan
demos/tutorial/a_first_example/solution_4.cpp
C++
bsd-3-clause
1,153
module Stupidedi module Versions module FunctionalGroups module ThirtyForty module SegmentDefs s = Schema e = ElementDefs r = ElementReqs MS1 = s::SegmentDef.build(:MS1, "Equipment, Shipment, or Real Property Location", "To specify the location of a piece of equipment, a shipment, or real property in terms of city and state for the stop location that relates to the AT7 shipment status details.", e::E19 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E156 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E26 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1654.simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1655.simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1280.simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E1280.simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E116 .simple_use(r::Optional, s::RepeatCount.bounded(1)), SyntaxNotes::L.build(1, 2, 3), SyntaxNotes::E.build(1, 4), SyntaxNotes::C.build(2, 1), SyntaxNotes::C.build(3, 1), SyntaxNotes::P.build(4, 5), SyntaxNotes::C.build(6, 4), SyntaxNotes::C.build(7, 4), SyntaxNotes::C.build(8, 1)) end end end end end
justworkshr/stupidedi
lib/stupidedi/versions/functional_groups/003040/segment_defs/MS1.rb
Ruby
bsd-3-clause
1,438
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/convert_web_app.h" #include <cmath> #include <limits> #include <string> #include <vector> #include "base/base64.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/stringprintf.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_manifest_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/web_apps.h" #include "crypto/sha2.h" #include "googleurl/src/gurl.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" namespace keys = extension_manifest_keys; using base::Time; namespace { const char kIconsDirName[] = "icons"; // Create the public key for the converted web app. // // Web apps are not signed, but the public key for an extension doubles as // its unique identity, and we need one of those. A web app's unique identity // is its manifest URL, so we hash that to create a public key. There will be // no corresponding private key, which means that these extensions cannot be // auto-updated using ExtensionUpdater. But Chrome does notice updates to the // manifest and regenerates these extensions. std::string GenerateKey(const GURL& manifest_url) { char raw[crypto::kSHA256Length] = {0}; std::string key; crypto::SHA256HashString(manifest_url.spec().c_str(), raw, crypto::kSHA256Length); base::Base64Encode(std::string(raw, crypto::kSHA256Length), &key); return key; } } // Generates a version for the converted app using the current date. This isn't // really needed, but it seems like useful information. std::string ConvertTimeToExtensionVersion(const Time& create_time) { Time::Exploded create_time_exploded; create_time.UTCExplode(&create_time_exploded); double micros = static_cast<double>( (create_time_exploded.millisecond * Time::kMicrosecondsPerMillisecond) + (create_time_exploded.second * Time::kMicrosecondsPerSecond) + (create_time_exploded.minute * Time::kMicrosecondsPerMinute) + (create_time_exploded.hour * Time::kMicrosecondsPerHour)); double day_fraction = micros / Time::kMicrosecondsPerDay; double stamp = day_fraction * std::numeric_limits<uint16>::max(); // Ghetto-round, since VC++ doesn't have round(). stamp = stamp >= (floor(stamp) + 0.5) ? (stamp + 1) : stamp; return base::StringPrintf("%i.%i.%i.%i", create_time_exploded.year, create_time_exploded.month, create_time_exploded.day_of_month, static_cast<uint16>(stamp)); } scoped_refptr<Extension> ConvertWebAppToExtension( const WebApplicationInfo& web_app, const Time& create_time) { FilePath user_data_temp_dir = extension_file_util::GetUserDataTempDir(); if (user_data_temp_dir.empty()) { LOG(ERROR) << "Could not get path to profile temporary directory."; return NULL; } ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDirUnderPath(user_data_temp_dir)) { LOG(ERROR) << "Could not create temporary directory."; return NULL; } // Create the manifest scoped_ptr<DictionaryValue> root(new DictionaryValue); if (!web_app.is_bookmark_app) root->SetString(keys::kPublicKey, GenerateKey(web_app.manifest_url)); else root->SetString(keys::kPublicKey, GenerateKey(web_app.app_url)); root->SetString(keys::kName, UTF16ToUTF8(web_app.title)); root->SetString(keys::kVersion, ConvertTimeToExtensionVersion(create_time)); root->SetString(keys::kDescription, UTF16ToUTF8(web_app.description)); root->SetString(keys::kLaunchWebURL, web_app.app_url.spec()); if (!web_app.launch_container.empty()) root->SetString(keys::kLaunchContainer, web_app.launch_container); // Add the icons. DictionaryValue* icons = new DictionaryValue(); root->Set(keys::kIcons, icons); for (size_t i = 0; i < web_app.icons.size(); ++i) { std::string size = StringPrintf("%i", web_app.icons[i].width); std::string icon_path = StringPrintf("%s/%s.png", kIconsDirName, size.c_str()); icons->SetString(size, icon_path); } // Add the permissions. ListValue* permissions = new ListValue(); root->Set(keys::kPermissions, permissions); for (size_t i = 0; i < web_app.permissions.size(); ++i) { permissions->Append(Value::CreateStringValue(web_app.permissions[i])); } // Add the URLs. ListValue* urls = new ListValue(); root->Set(keys::kWebURLs, urls); for (size_t i = 0; i < web_app.urls.size(); ++i) { urls->Append(Value::CreateStringValue(web_app.urls[i].spec())); } // Write the manifest. FilePath manifest_path = temp_dir.path().Append( Extension::kManifestFilename); JSONFileValueSerializer serializer(manifest_path); if (!serializer.Serialize(*root)) { LOG(ERROR) << "Could not serialize manifest."; return NULL; } // Write the icon files. FilePath icons_dir = temp_dir.path().AppendASCII(kIconsDirName); if (!file_util::CreateDirectory(icons_dir)) { LOG(ERROR) << "Could not create icons directory."; return NULL; } for (size_t i = 0; i < web_app.icons.size(); ++i) { // Skip unfetched bitmaps. if (web_app.icons[i].data.config() == SkBitmap::kNo_Config) continue; FilePath icon_file = icons_dir.AppendASCII( StringPrintf("%i.png", web_app.icons[i].width)); std::vector<unsigned char> image_data; if (!gfx::PNGCodec::EncodeBGRASkBitmap(web_app.icons[i].data, false, &image_data)) { LOG(ERROR) << "Could not create icon file."; return NULL; } const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(icon_file, image_data_ptr, image_data.size())) { LOG(ERROR) << "Could not write icon file."; return NULL; } } // Finally, create the extension object to represent the unpacked directory. std::string error; int extension_flags = Extension::STRICT_ERROR_CHECKS; if (web_app.is_bookmark_app) extension_flags |= Extension::FROM_BOOKMARK; scoped_refptr<Extension> extension = Extension::Create( temp_dir.path(), Extension::INTERNAL, *root, extension_flags, &error); if (!extension) { LOG(ERROR) << error; return NULL; } temp_dir.Take(); // The caller takes ownership of the directory. return extension; }
robclark/chromium
chrome/browser/extensions/convert_web_app.cc
C++
bsd-3-clause
6,936
<!DOCTYPE html> <html> <body> <script src="../../resources/js-test.js"></script> <a id="id1" name="name1"></a> <a id="id2" name="name1"></a> <a id="id3"></a> <a id="id4" name="name4"></a> <a name="name5"></a> <a id="id4" name="name6"></a> <script> description("This tests verifies the enumerated properties on HTMLCollection and their order."); var testLink = document.getElementById("testLink"); var htmlCollection = document.getElementsByTagName("a"); shouldBe("htmlCollection.__proto__", "HTMLCollection.prototype"); shouldBe("htmlCollection.length", "6"); // As per http://dom.spec.whatwg.org/#htmlcollection: // - The object's supported property indices are the numbers in the range zero to one less than the // number of nodes represented by the collection. If there are no such elements, then there are no // supported property indices. // - The supported property names are the values from the list returned by these steps: // 1. Let result be an empty list. // 2. For each element represented by the collection, in tree order, run these substeps: // 1. If element has an ID which is neither the empty string nor is in result, append element's ID to result. // 2. If element is in the HTML namespace and has a name attribute whose value is neither the empty string // nor is in result, append element's name attribute value to result. // 3. Return result. var expectedEnumeratedProperties = ["0", "1" , "2", "3", "4", "5", "length", "id1", "name1", "id2", "id3", "id4", "name4", "name5", "name6", "item", "namedItem"]; var enumeratedProperties = []; for (var property in htmlCollection) { enumeratedProperties[enumeratedProperties.length] = property; } shouldBe("enumeratedProperties", "expectedEnumeratedProperties"); </script> </body> </html>
modulexcite/blink
LayoutTests/fast/dom/htmlcollection-enumerated-properties.html
HTML
bsd-3-clause
1,790
#if 0 // Disabled until updated to use current API. // Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "tools/fiddle/examples.h" // HASH=a75bbdb8bb866b125c4c1dd5e967d470 REG_FIDDLE(Paint_setTextScaleX, 256, 256, true, 0) { void draw(SkCanvas* canvas) { SkPaint paint; paint.setTextScaleX(0.f / 0.f); SkDebugf("text scale %s-a-number\n", SkScalarIsNaN(paint.getTextScaleX()) ? "not" : "is"); } } // END FIDDLE #endif // Disabled until updated to use current API.
youtube/cobalt
third_party/skia_next/third_party/skia/docs/examples/Paint_setTextScaleX.cpp
C++
bsd-3-clause
566
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/file_system_provider/operations/execute_action.h" #include <algorithm> #include <string> #include "chrome/common/extensions/api/file_system_provider.h" #include "chrome/common/extensions/api/file_system_provider_internal.h" namespace ash { namespace file_system_provider { namespace operations { ExecuteAction::ExecuteAction(extensions::EventRouter* event_router, const ProvidedFileSystemInfo& file_system_info, const std::vector<base::FilePath>& entry_paths, const std::string& action_id, storage::AsyncFileUtil::StatusCallback callback) : Operation(event_router, file_system_info), entry_paths_(entry_paths), action_id_(action_id), callback_(std::move(callback)) {} ExecuteAction::~ExecuteAction() { } bool ExecuteAction::Execute(int request_id) { using extensions::api::file_system_provider::ExecuteActionRequestedOptions; ExecuteActionRequestedOptions options; options.file_system_id = file_system_info_.file_system_id(); options.request_id = request_id; for (const auto& entry_path : entry_paths_) options.entry_paths.push_back(entry_path.AsUTF8Unsafe()); options.action_id = action_id_; return SendEvent( request_id, extensions::events::FILE_SYSTEM_PROVIDER_ON_EXECUTE_ACTION_REQUESTED, extensions::api::file_system_provider::OnExecuteActionRequested:: kEventName, extensions::api::file_system_provider::OnExecuteActionRequested::Create( options)); } void ExecuteAction::OnSuccess(int /* request_id */, std::unique_ptr<RequestValue> result, bool has_more) { DCHECK(callback_); std::move(callback_).Run(base::File::FILE_OK); } void ExecuteAction::OnError(int /* request_id */, std::unique_ptr<RequestValue> /* result */, base::File::Error error) { DCHECK(callback_); std::move(callback_).Run(error); } } // namespace operations } // namespace file_system_provider } // namespace ash
ric2b/Vivaldi-browser
chromium/chrome/browser/ash/file_system_provider/operations/execute_action.cc
C++
bsd-3-clause
2,321
//======================================================================== // GLFW 3.3 OSMesa - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2016 Google Inc. // Copyright (c) 2006-2016 Camilla Löwy <elmindreda@glfw.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // //======================================================================== #define OSMESA_RGBA 0x1908 #define OSMESA_FORMAT 0x22 #define OSMESA_DEPTH_BITS 0x30 #define OSMESA_STENCIL_BITS 0x31 #define OSMESA_ACCUM_BITS 0x32 #define OSMESA_PROFILE 0x33 #define OSMESA_CORE_PROFILE 0x34 #define OSMESA_COMPAT_PROFILE 0x35 #define OSMESA_CONTEXT_MAJOR_VERSION 0x36 #define OSMESA_CONTEXT_MINOR_VERSION 0x37 typedef void* OSMesaContext; typedef void (*OSMESAproc)(void); typedef OSMesaContext (GLAPIENTRY * PFN_OSMesaCreateContextExt)(GLenum,GLint,GLint,GLint,OSMesaContext); typedef OSMesaContext (GLAPIENTRY * PFN_OSMesaCreateContextAttribs)(const int*,OSMesaContext); typedef void (GLAPIENTRY * PFN_OSMesaDestroyContext)(OSMesaContext); typedef int (GLAPIENTRY * PFN_OSMesaMakeCurrent)(OSMesaContext,void*,int,int,int); typedef int (GLAPIENTRY * PFN_OSMesaGetColorBuffer)(OSMesaContext,int*,int*,int*,void**); typedef int (GLAPIENTRY * PFN_OSMesaGetDepthBuffer)(OSMesaContext,int*,int*,int*,void**); typedef GLFWglproc (GLAPIENTRY * PFN_OSMesaGetProcAddress)(const char*); #define OSMesaCreateContextExt _glfw.osmesa.CreateContextExt #define OSMesaCreateContextAttribs _glfw.osmesa.CreateContextAttribs #define OSMesaDestroyContext _glfw.osmesa.DestroyContext #define OSMesaMakeCurrent _glfw.osmesa.MakeCurrent #define OSMesaGetColorBuffer _glfw.osmesa.GetColorBuffer #define OSMesaGetDepthBuffer _glfw.osmesa.GetDepthBuffer #define OSMesaGetProcAddress _glfw.osmesa.GetProcAddress #define _GLFW_OSMESA_CONTEXT_STATE _GLFWcontextOSMesa osmesa #define _GLFW_OSMESA_LIBRARY_CONTEXT_STATE _GLFWlibraryOSMesa osmesa // OSMesa-specific per-context data // typedef struct _GLFWcontextOSMesa { OSMesaContext handle; int width; int height; void* buffer; } _GLFWcontextOSMesa; // OSMesa-specific global data // typedef struct _GLFWlibraryOSMesa { void* handle; PFN_OSMesaCreateContextExt CreateContextExt; PFN_OSMesaCreateContextAttribs CreateContextAttribs; PFN_OSMesaDestroyContext DestroyContext; PFN_OSMesaMakeCurrent MakeCurrent; PFN_OSMesaGetColorBuffer GetColorBuffer; PFN_OSMesaGetDepthBuffer GetDepthBuffer; PFN_OSMesaGetProcAddress GetProcAddress; } _GLFWlibraryOSMesa; GLFWbool _glfwInitOSMesa(void); void _glfwTerminateOSMesa(void); GLFWbool _glfwCreateContextOSMesa(_GLFWwindow* window, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig);
endlessm/chromium-browser
third_party/glfw/src/src/osmesa_context.h
C
bsd-3-clause
3,768
<html> <body> <select aria-label="selection_list" size="10" id="listbox"> <optgroup label="Enabled" id="listbox_optgroup_enabled"> <option value="listbox_e1" id="listbox_option_enabled_one">One</option> <option value="listbox_e2">Two</option> <option value="listbox_e3">Three</option> <option value="listbox_e4">Four</option> </optgroup> </select> </body> </html>
scheib/chromium
content/test/data/accessibility/html/selection-container.html
HTML
bsd-3-clause
382
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.browserservices.ui.splashscreen.trustedwebactivity; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static androidx.browser.trusted.TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.browser.customtabs.TrustedWebUtils; import androidx.browser.trusted.TrustedWebActivityIntentBuilder; import androidx.browser.trusted.splashscreens.SplashScreenParamKey; import org.chromium.base.IntentUtils; import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashController; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashDelegate; import org.chromium.chrome.browser.customtabs.TranslucentCustomTabActivity; import org.chromium.chrome.browser.tab.Tab; import org.chromium.ui.base.ActivityWindowAndroid; import org.chromium.ui.util.ColorUtils; import javax.inject.Inject; /** * Orchestrates the flow of showing and removing splash screens for apps based on Trusted Web * Activities. * * The flow is as follows: * - TWA client app verifies conditions for showing splash screen. If the checks pass, it shows the * splash screen immediately. * - The client passes the URI to a file with the splash image to * {@link androidx.browser.customtabs.CustomTabsService}. The image is decoded and put into * {@link SplashImageHolder}. * - The client then launches a TWA, at which point the Bitmap is already available. * - ChromeLauncherActivity calls {@link #handleIntent}, which starts * {@link TranslucentCustomTabActivity} - a CustomTabActivity with translucent style. The * translucency is necessary in order to avoid a flash that might be seen when starting the activity * before the splash screen is attached. * - {@link TranslucentCustomTabActivity} creates an instance of {@link TwaSplashController} which * immediately displays the splash screen in an ImageView on top of the rest of view hierarchy. * - It also immediately removes the translucency. See comment in {@link SplashController} for more * details. * - It waits for the page to load, and removes the splash image once first paint (or a failure) * occurs. * * Lifecycle: this class is resolved only once when CustomTabActivity is launched, and is * gc-ed when it finishes its job. * If these lifecycle assumptions change, consider whether @ActivityScope needs to be added. */ public class TwaSplashController implements SplashDelegate { // TODO(pshmakov): move this to AndroidX. private static final String KEY_SHOWN_IN_CLIENT = "androidx.browser.trusted.KEY_SPLASH_SCREEN_SHOWN_IN_CLIENT"; private final SplashController mSplashController; private final Activity mActivity; private final SplashImageHolder mSplashImageCache; private final BrowserServicesIntentDataProvider mIntentDataProvider; @Inject public TwaSplashController(SplashController splashController, Activity activity, ActivityWindowAndroid activityWindowAndroid, SplashImageHolder splashImageCache, BrowserServicesIntentDataProvider intentDataProvider) { mSplashController = splashController; mActivity = activity; mSplashImageCache = splashImageCache; mIntentDataProvider = intentDataProvider; long splashHideAnimationDurationMs = IntentUtils.safeGetInt(getSplashScreenParamsFromIntent(), SplashScreenParamKey.KEY_FADE_OUT_DURATION_MS, 0); mSplashController.setConfig(this, splashHideAnimationDurationMs); } @Override public View buildSplashView() { Bitmap bitmap = mSplashImageCache.takeImage(mIntentDataProvider.getSession()); if (bitmap == null) { return null; } ImageView splashView = new ImageView(mActivity); splashView.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); splashView.setImageBitmap(bitmap); applyCustomizationsToSplashScreenView(splashView); return splashView; } @Override public void onSplashHidden(Tab tab, long startTimestamp, long endTimestamp) {} @Override public boolean shouldWaitForSubsequentPageLoadToHideSplash() { return false; } private void applyCustomizationsToSplashScreenView(ImageView imageView) { Bundle params = getSplashScreenParamsFromIntent(); int backgroundColor = IntentUtils.safeGetInt( params, SplashScreenParamKey.KEY_BACKGROUND_COLOR, Color.WHITE); imageView.setBackgroundColor(ColorUtils.getOpaqueColor(backgroundColor)); int scaleTypeOrdinal = IntentUtils.safeGetInt(params, SplashScreenParamKey.KEY_SCALE_TYPE, -1); ImageView.ScaleType[] scaleTypes = ImageView.ScaleType.values(); ImageView.ScaleType scaleType; if (scaleTypeOrdinal < 0 || scaleTypeOrdinal >= scaleTypes.length) { scaleType = ImageView.ScaleType.CENTER; } else { scaleType = scaleTypes[scaleTypeOrdinal]; } imageView.setScaleType(scaleType); if (scaleType != ImageView.ScaleType.MATRIX) return; float[] matrixValues = IntentUtils.safeGetFloatArray( params, SplashScreenParamKey.KEY_IMAGE_TRANSFORMATION_MATRIX); if (matrixValues == null || matrixValues.length != 9) return; Matrix matrix = new Matrix(); matrix.setValues(matrixValues); imageView.setImageMatrix(matrix); } private Bundle getSplashScreenParamsFromIntent() { return mIntentDataProvider.getIntent().getBundleExtra(EXTRA_SPLASH_SCREEN_PARAMS); } /** * Returns true if the intent corresponds to a TWA with a splash screen. */ public static boolean intentIsForTwaWithSplashScreen(Intent intent) { boolean isTrustedWebActivity = IntentUtils.safeGetBooleanExtra( intent, TrustedWebUtils.EXTRA_LAUNCH_AS_TRUSTED_WEB_ACTIVITY, false); boolean requestsSplashScreen = IntentUtils.safeGetParcelableExtra(intent, EXTRA_SPLASH_SCREEN_PARAMS) != null; return isTrustedWebActivity && requestsSplashScreen; } /** * Handles the intent if it should launch a TWA with splash screen. * @param activity Activity, from which to start the next one. * @param intent Incoming intent. * @return Whether the intent was handled. */ public static boolean handleIntent(Activity activity, Intent intent) { if (!intentIsForTwaWithSplashScreen(intent)) return false; Bundle params = IntentUtils.safeGetBundleExtra( intent, TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS); boolean shownInClient = IntentUtils.safeGetBoolean(params, KEY_SHOWN_IN_CLIENT, true); // shownInClient is "true" by default for the following reasons: // - For compatibility with older clients which don't use this bundle key. // - Because getting "false" when it should be "true" leads to more severe visual glitches, // than vice versa. if (shownInClient) { // If splash screen was shown in client, we must launch a translucent activity to // ensure smooth transition. intent.setClassName(activity, TranslucentCustomTabActivity.class.getName()); } intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); activity.startActivity(intent); activity.overridePendingTransition(0, 0); return true; } }
ric2b/Vivaldi-browser
chromium/chrome/android/java/src/org/chromium/chrome/browser/browserservices/ui/splashscreen/trustedwebactivity/TwaSplashController.java
Java
bsd-3-clause
8,032
using System; using System.Collections.Generic; namespace SharpCompress { internal class LazyReadOnlyCollection<T> : ICollection<T> { private readonly List<T> backing = new List<T>(); private readonly IEnumerator<T> source; private bool fullyLoaded; public LazyReadOnlyCollection(IEnumerable<T> source) { this.source = source.GetEnumerator(); } private class LazyLoader : IEnumerator<T> { private readonly LazyReadOnlyCollection<T> lazyReadOnlyCollection; private bool disposed; private int index = -1; internal LazyLoader(LazyReadOnlyCollection<T> lazyReadOnlyCollection) { this.lazyReadOnlyCollection = lazyReadOnlyCollection; } #region IEnumerator<T> Members public T Current { get { return lazyReadOnlyCollection.backing[index]; } } #endregion #region IDisposable Members public void Dispose() { if (!disposed) { disposed = true; } } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (index + 1 < lazyReadOnlyCollection.backing.Count) { index++; return true; } if (!lazyReadOnlyCollection.fullyLoaded && lazyReadOnlyCollection.source.MoveNext()) { lazyReadOnlyCollection.backing.Add(lazyReadOnlyCollection.source.Current); index++; return true; } lazyReadOnlyCollection.fullyLoaded = true; return false; } public void Reset() { throw new NotSupportedException(); } #endregion } internal void EnsureFullyLoaded() { if (!fullyLoaded) { this.ForEach(x => { }); fullyLoaded = true; } } internal IEnumerable<T> GetLoaded() { return backing; } #region ICollection<T> Members public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { EnsureFullyLoaded(); return backing.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { EnsureFullyLoaded(); backing.CopyTo(array, arrayIndex); } public int Count { get { EnsureFullyLoaded(); return backing.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(T item) { throw new NotSupportedException(); } #endregion #region IEnumerable<T> Members //TODO check for concurrent access public IEnumerator<T> GetEnumerator() { return new LazyLoader(this); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
catester/sharpcompress
SharpCompress/LazyReadOnlyCollection.cs
C#
mit
3,931
VERSION = (1, 3, 0, 'alpha', 1) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) from django.utils.version import get_svn_revision svn_rev = get_svn_revision() if svn_rev != u'SVN-unknown': version = "%s %s" % (version, svn_rev) return version
hunch/hunch-gift-app
django/__init__.py
Python
mit
565
package com.greenlemonmobile.app.ebook.books.parser; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; public interface ZipWrapper { ZipEntry getEntry(String entryName); InputStream getInputStream(ZipEntry entry) throws IOException; Enumeration<? extends ZipEntry> entries(); void close() throws IOException; }
xiaopengs/iBooks
src/com/greenlemonmobile/app/ebook/books/parser/ZipWrapper.java
Java
mit
433
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace AutoTest.TestRunners.XUnit.Tests.TestResource { public class Class2 { [Fact] public void Anothger_passing_test() { Assert.Equal(1, 1); } } }
acken/AutoTest.Net
src/AutoTest.TestRunner/Plugins/AutoTest.TestRunners.XUnit.Tests.TestResource/Class2.cs
C#
mit
310
version https://git-lfs.github.com/spec/v1 oid sha256:ff6a5c1204e476c89870c6f14e75db666fa26de9359f9d8c372ef779b55c8875 size 2736
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.8.9/cldr/nls/cs/buddhist.js.uncompressed.js
JavaScript
mit
129
function example(name, deps) { console.log('This is where fpscounter plugin code would execute in the node process.'); } module.exports = example;
BenjaminTsai/openrov-cockpit
src/plugins/fpscounter/index.js
JavaScript
mit
148
# -*- coding: utf-8 -*- import re import django, logging, warnings from django import forms from django.conf import settings from django.core.urlresolvers import reverse from django.forms.models import formset_factory from django.middleware.csrf import _get_new_csrf_key from django.template import ( loader, TemplateSyntaxError, Context ) from django.utils.translation import ugettext_lazy as _ from .base import CrispyTestCase from .forms import TestForm from crispy_forms.bootstrap import ( FieldWithButtons, PrependedAppendedText, AppendedText, PrependedText, StrictButton ) from crispy_forms.compatibility import text_type from crispy_forms.helper import FormHelper, FormHelpersException from crispy_forms.layout import ( Layout, Submit, Reset, Hidden, Button, MultiField, Field ) from crispy_forms.utils import render_crispy_form from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode class TestFormHelper(CrispyTestCase): urls = 'crispy_forms.tests.urls' def test_inputs(self): form_helper = FormHelper() form_helper.add_input(Submit('my-submit', 'Submit', css_class="button white")) form_helper.add_input(Reset('my-reset', 'Reset')) form_helper.add_input(Hidden('my-hidden', 'Hidden')) form_helper.add_input(Button('my-button', 'Button')) template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy form form_helper %} """) c = Context({'form': TestForm(), 'form_helper': form_helper}) html = template.render(c) self.assertTrue('button white' in html) self.assertTrue('id="submit-id-my-submit"' in html) self.assertTrue('id="reset-id-my-reset"' in html) self.assertTrue('name="my-hidden"' in html) self.assertTrue('id="button-id-my-button"' in html) if self.current_template_pack == 'uni_form': self.assertTrue('submit submitButton' in html) self.assertTrue('reset resetButton' in html) self.assertTrue('class="button"' in html) else: self.assertTrue('class="btn"' in html) self.assertTrue('btn btn-primary' in html) self.assertTrue('btn btn-inverse' in html) self.assertEqual(len(re.findall(r'<input[^>]+> <', html)), 8) def test_invalid_form_method(self): form_helper = FormHelper() try: form_helper.form_method = "superPost" self.fail("Setting an invalid form_method within the helper should raise an Exception") except FormHelpersException: pass def test_form_with_helper_without_layout(self): form_helper = FormHelper() form_helper.form_id = 'this-form-rocks' form_helper.form_class = 'forms-that-rock' form_helper.form_method = 'GET' form_helper.form_action = 'simpleAction' form_helper.form_error_title = 'ERRORS' template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy testForm form_helper %} """) # now we render it, with errors form = TestForm({'password1': 'wargame','password2': 'god'}) form.is_valid() c = Context({'testForm': form, 'form_helper': form_helper}) html = template.render(c) # Lets make sure everything loads right self.assertTrue(html.count('<form'), 1) self.assertTrue('forms-that-rock' in html) self.assertTrue('method="get"' in html) self.assertTrue('id="this-form-rocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) if (self.current_template_pack == 'uni_form'): self.assertTrue('class="uniForm' in html) self.assertTrue("ERRORS" in html) self.assertTrue("<li>Passwords dont match</li>" in html) # now lets remove the form tag and render it again. All the True items above # should now be false because the form tag is removed. form_helper.form_tag = False html = template.render(c) self.assertFalse('<form' in html) self.assertFalse('forms-that-rock' in html) self.assertFalse('method="get"' in html) self.assertFalse('id="this-form-rocks"' in html) def test_form_show_errors_non_field_errors(self): form = TestForm({'password1': 'wargame', 'password2': 'god'}) form.helper = FormHelper() form.helper.form_show_errors = True form.is_valid() template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy testForm %} """) # First we render with errors c = Context({'testForm': form}) html = template.render(c) # Ensure those errors were rendered self.assertTrue('<li>Passwords dont match</li>' in html) self.assertTrue(text_type(_('This field is required.')) in html) self.assertTrue('error' in html) # Now we render without errors form.helper.form_show_errors = False c = Context({'testForm': form}) html = template.render(c) # Ensure errors were not rendered self.assertFalse('<li>Passwords dont match</li>' in html) self.assertFalse(text_type(_('This field is required.')) in html) self.assertFalse('error' in html) def test_html5_required(self): form = TestForm() form.helper = FormHelper() form.helper.html5_required = True html = render_crispy_form(form) # 6 out of 7 fields are required and an extra one for the SplitDateTimeWidget makes 7. self.assertEqual(html.count('required="required"'), 7) form = TestForm() form.helper = FormHelper() form.helper.html5_required = False html = render_crispy_form(form) def test_attrs(self): form = TestForm() form.helper = FormHelper() form.helper.attrs = {'id': 'TestIdForm', 'autocomplete': "off"} html = render_crispy_form(form) self.assertTrue('autocomplete="off"' in html) self.assertTrue('id="TestIdForm"' in html) def test_template_context(self): helper = FormHelper() helper.attrs = { 'id': 'test-form', 'class': 'test-forms', 'action': 'submit/test/form', 'autocomplete': 'off', } node = CrispyFormNode('form', 'helper') context = node.get_response_dict(helper, {}, False) self.assertEqual(context['form_id'], "test-form") self.assertEqual(context['form_attrs']['id'], "test-form") self.assertTrue("test-forms" in context['form_class']) self.assertTrue("test-forms" in context['form_attrs']['class']) self.assertEqual(context['form_action'], "submit/test/form") self.assertEqual(context['form_attrs']['action'], "submit/test/form") self.assertEqual(context['form_attrs']['autocomplete'], "off") def test_template_context_using_form_attrs(self): helper = FormHelper() helper.form_id = 'test-form' helper.form_class = 'test-forms' helper.form_action = 'submit/test/form' node = CrispyFormNode('form', 'helper') context = node.get_response_dict(helper, {}, False) self.assertEqual(context['form_id'], "test-form") self.assertEqual(context['form_attrs']['id'], "test-form") self.assertTrue("test-forms" in context['form_class']) self.assertTrue("test-forms" in context['form_attrs']['class']) self.assertEqual(context['form_action'], "submit/test/form") self.assertEqual(context['form_attrs']['action'], "submit/test/form") def test_template_helper_access(self): helper = FormHelper() helper.form_id = 'test-form' self.assertEqual(helper['form_id'], 'test-form') def test_without_helper(self): template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy form %} """) c = Context({'form': TestForm()}) html = template.render(c) # Lets make sure everything loads right self.assertTrue('<form' in html) self.assertTrue('method="post"' in html) self.assertFalse('action' in html) if (self.current_template_pack == 'uni_form'): self.assertTrue('uniForm' in html) def test_template_pack_override_compact(self): current_pack = self.current_template_pack override_pack = current_pack == 'uni_form' and 'bootstrap' or 'uni_form' # {% crispy form 'template_pack_name' %} template = loader.get_template_from_string(u""" {%% load crispy_forms_tags %%} {%% crispy form "%s" %%} """ % override_pack) c = Context({'form': TestForm()}) html = template.render(c) if (current_pack == 'uni_form'): self.assertTrue('control-group' in html) else: self.assertTrue('uniForm' in html) def test_template_pack_override_verbose(self): current_pack = self.current_template_pack override_pack = current_pack == 'uni_form' and 'bootstrap' or 'uni_form' # {% crispy form helper 'template_pack_name' %} template = loader.get_template_from_string(u""" {%% load crispy_forms_tags %%} {%% crispy form form_helper "%s" %%} """ % override_pack) c = Context({'form': TestForm(), 'form_helper': FormHelper()}) html = template.render(c) if (current_pack == 'uni_form'): self.assertTrue('control-group' in html) else: self.assertTrue('uniForm' in html) def test_template_pack_override_wrong(self): try: loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy form 'foo' %} """) except TemplateSyntaxError: pass def test_invalid_helper(self): template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy form form_helper %} """) c = Context({'form': TestForm(), 'form_helper': "invalid"}) settings.CRISPY_FAIL_SILENTLY = False # Django >= 1.4 is not wrapping exceptions in TEMPLATE_DEBUG mode if settings.TEMPLATE_DEBUG and django.VERSION < (1, 4): self.assertRaises(TemplateSyntaxError, lambda:template.render(c)) else: self.assertRaises(TypeError, lambda:template.render(c)) del settings.CRISPY_FAIL_SILENTLY def test_formset_with_helper_without_layout(self): template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy testFormSet formset_helper %} """) form_helper = FormHelper() form_helper.form_id = 'thisFormsetRocks' form_helper.form_class = 'formsets-that-rock' form_helper.form_method = 'POST' form_helper.form_action = 'simpleAction' TestFormSet = formset_factory(TestForm, extra = 3) testFormSet = TestFormSet() c = Context({'testFormSet': testFormSet, 'formset_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) self.assertEqual(html.count('<form'), 1) self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) # Check formset management form self.assertTrue('form-TOTAL_FORMS' in html) self.assertTrue('form-INITIAL_FORMS' in html) self.assertTrue('form-MAX_NUM_FORMS' in html) self.assertTrue('formsets-that-rock' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) if (self.current_template_pack == 'uni_form'): self.assertTrue('class="uniForm' in html) def test_CSRF_token_POST_form(self): form_helper = FormHelper() template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy form form_helper %} """) # The middleware only initializes the CSRF token when processing a real request # So using RequestContext or csrf(request) here does not work. # Instead I set the key `csrf_token` to a CSRF token manually, which `csrf_token` tag uses c = Context({'form': TestForm(), 'form_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) self.assertTrue("<input type='hidden' name='csrfmiddlewaretoken'" in html) def test_CSRF_token_GET_form(self): form_helper = FormHelper() form_helper.form_method = 'GET' template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy form form_helper %} """) c = Context({'form': TestForm(), 'form_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) self.assertFalse("<input type='hidden' name='csrfmiddlewaretoken'" in html) def test_disable_csrf(self): form = TestForm() helper = FormHelper() helper.disable_csrf = True html = render_crispy_form(form, helper, {'csrf_token': _get_new_csrf_key()}) self.assertFalse('csrf' in html) def test_render_hidden_fields(self): test_form = TestForm() test_form.helper = FormHelper() test_form.helper.layout = Layout( 'email' ) test_form.helper.render_hidden_fields = True html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 1) # Now hide a couple of fields for field in ('password1', 'password2'): test_form.fields[field].widget = forms.HiddenInput() html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 3) self.assertEqual(html.count('hidden'), 2) if django.VERSION < (1, 5): self.assertEqual(html.count('type="hidden" name="password1"'), 1) self.assertEqual(html.count('type="hidden" name="password2"'), 1) else: self.assertEqual(html.count('name="password1" type="hidden"'), 1) self.assertEqual(html.count('name="password2" type="hidden"'), 1) def test_render_required_fields(self): test_form = TestForm() test_form.helper = FormHelper() test_form.helper.layout = Layout( 'email' ) test_form.helper.render_required_fields = True html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 7) def test_helper_custom_template(self): form = TestForm() form.helper = FormHelper() form.helper.template = 'custom_form_template.html' html = render_crispy_form(form) self.assertTrue("<h1>Special custom form</h1>" in html) def test_helper_custom_field_template(self): form = TestForm() form.helper = FormHelper() form.helper.layout = Layout( 'password1', 'password2', ) form.helper.field_template = 'custom_field_template.html' html = render_crispy_form(form) self.assertEqual(html.count("<h1>Special custom field</h1>"), 2) class TestUniformFormHelper(TestFormHelper): def test_form_show_errors(self): if settings.CRISPY_TEMPLATE_PACK != 'uni_form': warnings.warn('skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK) return form = TestForm({ 'email': 'invalidemail', 'first_name': 'first_name_too_long', 'last_name': 'last_name_too_long', 'password1': 'yes', 'password2': 'yes', }) form.helper = FormHelper() form.helper.layout = Layout( Field('email'), Field('first_name'), Field('last_name'), Field('password1'), Field('password2'), ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) self.assertEqual(html.count('error'), 9) form.helper.form_show_errors = False html = render_crispy_form(form) self.assertEqual(html.count('error'), 0) def test_multifield_errors(self): if settings.CRISPY_TEMPLATE_PACK != 'uni_form': warnings.warn('skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK) return form = TestForm({ 'email': 'invalidemail', 'password1': 'yes', 'password2': 'yes', }) form.helper = FormHelper() form.helper.layout = Layout( MultiField('legend', 'email') ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) self.assertEqual(html.count('error'), 3) # Reset layout for avoiding side effects form.helper.layout = Layout( MultiField('legend', 'email') ) form.helper.form_show_errors = False html = render_crispy_form(form) self.assertEqual(html.count('error'), 0) class TestBootstrapFormHelper(TestFormHelper): def test_form_show_errors(self): form = TestForm({ 'email': 'invalidemail', 'first_name': 'first_name_too_long', 'last_name': 'last_name_too_long', 'password1': 'yes', 'password2': 'yes', }) form.helper = FormHelper() form.helper.layout = Layout( AppendedText('email', 'whatever'), PrependedText('first_name', 'blabla'), PrependedAppendedText('last_name', 'foo', 'bar'), AppendedText('password1', 'whatever'), PrependedText('password2', 'blabla'), ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) self.assertEqual(html.count('error'), 6) form.helper.form_show_errors = False html = render_crispy_form(form) self.assertEqual(html.count('error'), 0) def test_error_text_inline(self): form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() layout = Layout( AppendedText('first_name', 'wat'), PrependedText('email', '@'), PrependedAppendedText('last_name', '@', 'wat'), ) form.helper.layout = layout form.is_valid() html = render_crispy_form(form) help_class = 'help-inline' if self.current_template_pack == 'bootstrap3': help_class = 'help-block' matches = re.findall( '<span id="error_\d_\w*" class="%s"' % help_class, html, re.MULTILINE ) self.assertEqual(len(matches), 3) form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.layout = layout form.helper.error_text_inline = False html = render_crispy_form(form) matches = re.findall('<p id="error_\d_\w*" class="help-block"', html, re.MULTILINE) self.assertEqual(len(matches), 3) def test_error_and_help_inline(self): form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.error_text_inline = False form.helper.help_text_inline = True form.helper.layout = Layout('email') form.is_valid() html = render_crispy_form(form) # Check that help goes before error, otherwise CSS won't work help_position = html.find('<span id="hint_id_email" class="help-inline">') error_position = html.find('<p id="error_1_id_email" class="help-block">') self.assertTrue(help_position < error_position) # Viceversa form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.error_text_inline = True form.helper.help_text_inline = False form.helper.layout = Layout('email') form.is_valid() html = render_crispy_form(form) # Check that error goes before help, otherwise CSS won't work error_position = html.find('<span id="error_1_id_email" class="help-inline">') help_position = html.find('<p id="hint_id_email" class="help-block">') self.assertTrue(error_position < help_position) def test_form_show_labels(self): form = TestForm() form.helper = FormHelper() form.helper.layout = Layout( 'password1', FieldWithButtons( 'password2', StrictButton("Confirm") ), PrependedText( 'first_name', 'Mr.' ), AppendedText( 'last_name', '@' ), PrependedAppendedText( 'datetime_field', 'on', 'secs' ) ) form.helper.form_show_labels = False html = render_crispy_form(form) self.assertEqual(html.count("<label"), 0) class TestBootstrap3FormHelper(TestFormHelper): def test_label_class_and_field_class(self): if settings.CRISPY_TEMPLATE_PACK != 'bootstrap3': warnings.warn('skipping bootstrap3 tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK) return form = TestForm() form.helper = FormHelper() form.helper.label_class = 'col-lg-2' form.helper.field_class = 'col-lg-8' html = render_crispy_form(form) self.assertTrue('<div class="form-group"> <div class="controls col-lg-offset-2 col-lg-8"> <div id="div_id_is_company" class="checkbox"> <label for="id_is_company" class=""> <input class="checkboxinput checkbox" id="id_is_company" name="is_company" type="checkbox" />') self.assertEqual(html.count('col-lg-8'), 7) form.helper.label_class = 'col-sm-3' form.helper.field_class = 'col-sm-8' html = render_crispy_form(form) self.assertTrue('<div class="form-group"> <div class="controls col-sm-offset-3 col-sm-8"> <div id="div_id_is_company" class="checkbox"> <label for="id_is_company" class=""> <input class="checkboxinput checkbox" id="id_is_company" name="is_company" type="checkbox" />') self.assertEqual(html.count('col-sm-8'), 7) def test_template_pack(self): if settings.CRISPY_TEMPLATE_PACK != 'bootstrap3': warnings.warn('skipping bootstrap3 tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK) return form = TestForm() form.helper = FormHelper() form.helper.template_pack = 'uni_form' html = render_crispy_form(form) self.assertFalse('form-control' in html) self.assertTrue('ctrlHolder' in html)
zixan/django-crispy-forms
crispy_forms/tests/test_form_helper.py
Python
mit
23,197
<?php namespace Concrete\Controller\Element\Express\Search; use Concrete\Core\Controller\ElementController; use Concrete\Core\Entity\Express\Entity; use Concrete\Core\Entity\Search\Query; use Concrete\Core\File\Search\SearchProvider; use Concrete\Core\Foundation\Serializer\JsonSerializer; class Search extends ElementController { /** * This is where the header search bar in the page should point. This search bar allows keyword searching in * different contexts. * * @var string */ protected $headerSearchAction; /** * @var Entity */ protected $entity; /** * @var Query */ protected $query; public function getElement() { return 'express/search/search'; } /** * @param Query $query */ public function setQuery(Query $query = null): void { $this->query = $query; } /** * @param string $headerSearchAction */ public function setHeaderSearchAction(string $headerSearchAction): void { $this->headerSearchAction = $headerSearchAction; } /** * @param Entity $entity */ public function setEntity(Entity $entity): void { $this->entity = $entity; } public function view() { $this->set('entity', $this->entity); $this->set('form', $this->app->make('helper/form')); $this->set('token', $this->app->make('token')); if (isset($this->headerSearchAction)) { $this->set('headerSearchAction', $this->headerSearchAction); } else { $this->set( 'headerSearchAction', $this->app->make('url')->to('/dashboard/express/entries/', 'view', $this->entity->getId()) ); } if (isset($this->query)) { $this->set('query', $this->app->make(JsonSerializer::class)->serialize($this->query, 'json')); } } }
haeflimi/concrete5
concrete/controllers/element/express/search/search.php
PHP
mit
1,932
// Node if (typeof module !== 'undefined' && module.exports) { var numeral = require('../../numeral'); var expect = require('chai').expect; var language = require('../../languages/th'); } describe('Language: th', function() { before(function() { numeral.language('th', language); numeral.language('th'); }); after(function() { numeral.reset(); }); describe('Number', function() { it('should format a number', function() { var tests = [ [10000,'0,0.0000','10,000.0000'], [10000.23,'0,0','10,000'], [-10000,'0,0.0','-10,000.0'], [10000.1234,'0.000','10000.123'], [-10000,'(0,0.0000)','(10,000.0000)'], [-0.23,'.00','-.23'], [-0.23,'(.00)','(.23)'], [0.23,'0.00000','0.23000'], [1230974,'0.0a','1.2ล้าน'], [1460,'0a','1พัน'], [-104000,'0a','-104พัน'], [1,'0o','1.'], [52,'0o','52.'], [23,'0o','23.'], [100,'0o','100.'], [1,'0[.]0','1'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Currency', function() { it('should format a currency', function() { var tests = [ [1000.234,'$0,0.00','฿1,000.23'], [-1000.234,'($0,0)','(฿1,000)'], [-1000.234,'$0.00','-฿1000.23'], [1230974,'($0.00a)','฿1.23ล้าน'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Percentages', function() { it('should format a percentages', function() { var tests = [ [1,'0%','100%'], [0.974878234,'0.000%','97.488%'], [-0.43,'0%','-43%'], [0.43,'(0.000%)','43.000%'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Unformat', function() { it('should unformat', function() { var tests = [ ['10,000.123',10000.123], ['(0.12345)',-0.12345], ['(฿1.23ล้าน)',-1230000], ['10พัน',10000], ['-10พัน',-10000], ['23.',23], ['฿10,000.00',10000], ['-76%',-0.76], ['2:23:57',8637] ]; for (var i = 0; i < tests.length; i++) { expect(numeral().unformat(tests[i][0])).to.equal(tests[i][1]); } }); }); });
Nrupesh29/Web-Traffic-Visualizer
vizceral/node_modules/numeral/tests/languages/th.js
JavaScript
mit
3,021
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>The "Artistic License" - dev.perl.org</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link rel="stylesheet" type="text/css" href="http://cdn.pimg.net/css/leostyle.vffcd481.css"> <link rel="stylesheet" type="text/css" href="http://cdn.pimg.net/css/dev.v5f7fab3.css"> <link rel="shortcut icon" href="http://cdn.pimg.net/favicon.v249dfa7.ico"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="http://cdn.pimg.net/js/jquery.corner.v84b7681.js" type="text/javascript" charset="utf-8"></script> <script src="http://cdn.pimg.net/js/leo.v9872b9c.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="header_holder"> <div class="sub_holder"> <div id="page_image"></div> <h1> The "Artistic License" </h1> <div id="logo_holder"> <a href="/"><img src="http://cdn.pimg.net/images/camel_head.v25e738a.png" id="logo" alt="Perl programming" height="65" align="right" /></a> <span>dev.perl.org</span> </div> </div> </div> <div id="nav"> <div class="sub_holder"> <ul> <li> <a href="/">Home</a> </li> <li class=""> <a href="/perl5/">Perl 5</a> </li> <li class=""> <a href="/perl6/">Perl 6</a> </li> </ul> </div> </div> <div id="crum_holder"> <div id="crum" class="sub_holder"> &nbsp; </div> </div> <div id="content_holder"> <div id="content" class="sub_holder"> <div id="main"> <PRE> <A style="float:right" HREF="http://www.opensource.org/licenses/artistic-license.php" ><IMG BORDER=0 SRC="osi-certified-90x75.gif" ></A> The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End </PRE> </div> <div id="short_lists" class="short_lists"> <div id="spacer_for_google"></div> </div> </div> </div> <div style="clear:both"></div> <div id="footer"> <div class="sub_holder"> <p class="sites"> &nbsp;When you need <em>Perl</em> think <strong>Perl.org</strong>: <a href="http://www.perl.org/">www</a> | <a href="http://blogs.perl.org/">blogs</a> | <a href="http://jobs.perl.org/">jobs</a> | <a href="http://learn.perl.org/">learn</a> <!-- | <a href="http://lists.perl.org/">lists</a> --> | <a href="http://dev.perl.org/">dev</a> </p> <p class="copyright"> <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/3.0/us/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-nd/3.0/us/80x15.png"></a> © 2002-2011 Perl.org | <a href="/siteinfo.html">Site Info</a> </p> <div style="clear:both"></div> <div id="google_translate_element"></div><script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en', autoDisplay: false , gaTrack: true, gaId: 'UA-50555-6' }, 'google_translate_element'); } </script><script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"> </script> </div> </div> <!--[if lt IE 7]> <div style='border: 1px solid #F7941D; background: #FEEFDA; text-align: center; clear: both; height: 75px; position: relative; margin-top: 2em;'> <div style='position: absolute; right: 3px; top: 3px; font-family: courier new; font-weight: bold;'><a href='#' onclick='javascript:this.parentNode.parentNode.style.display="none"; return false;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-cornerx.jpg' style='border: none;' alt='Close this notice'/></a></div> <div style='width: 640px; margin: 0 auto; text-align: left; padding: 0; overflow: hidden; color: black;'> <div style='width: 75px; float: left;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-warning.jpg' alt='Warning!'/></div> <div style='width: 275px; float: left; font-family: Arial, sans-serif;'> <div style='font-size: 14px; font-weight: bold; margin-top: 12px;'>You are using an outdated browser</div> <div style='font-size: 12px; margin-top: 6px; line-height: 12px;'>For a better experience using this site, please upgrade to a modern web browser.</div> </div> <div style='width: 75px; float: left;'><a href='http://www.firefox.com' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-firefox.jpg' style='border: none;' alt='Get Firefox 3.5'/></a></div> <div style='width: 75px; float: left;'><a href='http://www.browserforthebetter.com/download.html' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-ie8.jpg' style='border: none;' alt='Get Internet Explorer 8'/></a></div> <div style='width: 73px; float: left;'><a href='http://www.apple.com/safari/download/' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-safari.jpg' style='border: none;' alt='Get Safari 4'/></a></div> <div style='float: left;'><a href='http://www.google.com/chrome' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-chrome.jpg' style='border: none;' alt='Get Google Chrome'/></a></div> </div> </div> <![endif]--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-50555-6']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; ga.setAttribute('async', 'true'); document.documentElement.firstChild.appendChild(ga); })(); </script> </body> </html>
Jarob22/sc2_app_fyp_backend
vendor/bundle/ruby/1.9.1/gems/diff-lcs-1.1.3/docs/artistic.html
HTML
mit
12,246
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_raw_socket::get_implementation (2 of 2 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../get_implementation.html" title="basic_raw_socket::get_implementation"> <link rel="prev" href="overload1.html" title="basic_raw_socket::get_implementation (1 of 2 overloads)"> <link rel="next" href="../get_io_service.html" title="basic_raw_socket::get_io_service"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../get_implementation.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../get_io_service.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.basic_raw_socket.get_implementation.overload2"></a><a class="link" href="overload2.html" title="basic_raw_socket::get_implementation (2 of 2 overloads)">basic_raw_socket::get_implementation (2 of 2 overloads)</a> </h5></div></div></div> <p> <span class="emphasis"><em>Inherited from basic_io_object.</em></span> </p> <p> Get the underlying implementation of the I/O object. </p> <pre class="programlisting"><span class="keyword">const</span> <span class="identifier">implementation_type</span> <span class="special">&amp;</span> <span class="identifier">get_implementation</span><span class="special">()</span> <span class="keyword">const</span><span class="special">;</span> </pre> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2012 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../get_implementation.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../get_io_service.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
mxrrow/zaicoin
src/deps/boost/doc/html/boost_asio/reference/basic_raw_socket/get_implementation/overload2.html
HTML
mit
3,658
// boost win32_test.cpp -----------------------------------------------------// // Copyright 2010 Vicente J. Botet Escriba // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // See http://www.boost.org/libs/chrono for documentation. #include <boost/chrono/config.hpp> #include <boost/detail/lightweight_test.hpp> #if defined(BOOST_CHRONO_WINDOWS_API) || defined(__CYGWIN__) #include <boost/chrono/detail/static_assert.hpp> #if !defined(BOOST_NO_CXX11_STATIC_ASSERT) #define NOTHING "" #endif #include <boost/type_traits.hpp> #include <boost/typeof/typeof.hpp> #undef BOOST_USE_WINDOWS_H #include <boost/detail/win/basic_types.hpp> #include <boost/detail/win/time.hpp> #include <windows.h> void test() { { boost::detail::win32::LARGE_INTEGER_ a; LARGE_INTEGER b; BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::LARGE_INTEGER_)==sizeof(LARGE_INTEGER) ), NOTHING, (boost::detail::win32::LARGE_INTEGER_, LARGE_INTEGER)); BOOST_TEST(( sizeof(a.QuadPart)==sizeof(b.QuadPart) )); BOOST_CHRONO_STATIC_ASSERT(( offsetof(boost::detail::win32::LARGE_INTEGER_, QuadPart)==offsetof(LARGE_INTEGER, QuadPart) ), NOTHING, (boost::detail::win32::LARGE_INTEGER_, LARGE_INTEGER)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same< BOOST_TYPEOF(a.QuadPart), BOOST_TYPEOF(b.QuadPart) >::value ), NOTHING, (boost::detail::win32::LARGE_INTEGER_, LARGE_INTEGER)); } BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::BOOL_)==sizeof(BOOL) ), NOTHING, (boost::detail::win32::BOOL_, BOOL)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same<boost::detail::win32::BOOL_,BOOL>::value ), NOTHING, (boost::detail::win32::BOOL_, BOOL)); BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::DWORD_)==sizeof(DWORD) ), NOTHING, (boost::detail::win32::DWORD_, DWORD)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same<boost::detail::win32::DWORD_,DWORD>::value ), NOTHING, (boost::detail::win32::DWORD_, DWORD)); BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::HANDLE_)==sizeof(HANDLE) ), NOTHING, (boost::detail::win32::HANDLE_, HANDLE)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same<boost::detail::win32::HANDLE_,HANDLE>::value ), NOTHING, (boost::detail::win32::HANDLE_, HANDLE)); BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::LONG_)==sizeof(LONG) ), NOTHING, (boost::detail::win32::LONG_, LONG)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same<boost::detail::win32::LONG_,LONG>::value ), NOTHING, (boost::detail::win32::LONG_, LONG)); BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::LONGLONG_)==sizeof(LONGLONG) ), NOTHING, (boost::detail::win32::LONGLONG_, LONGLONG)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same<boost::detail::win32::LONGLONG_,LONGLONG>::value ), NOTHING, (boost::detail::win32::LONGLONG_, LONGLONG)); BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::ULONG_PTR_)==sizeof(ULONG_PTR) ), NOTHING, (boost::detail::win32::ULONG_PTR_, ULONG_PTR)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same<boost::detail::win32::ULONG_PTR_,ULONG_PTR>::value ), NOTHING, (boost::detail::win32::ULONG_PTR_, ULONG_PTR)); BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::PLARGE_INTEGER_)==sizeof(PLARGE_INTEGER) ), NOTHING, (boost::detail::win32::PLARGE_INTEGER_, PLARGE_INTEGER)); //~ BOOST_CHRONO_STATIC_ASSERT(( //~ boost::is_same<boost::detail::win32::PLARGE_INTEGER_,PLARGE_INTEGER>::value //~ ), NOTHING, (boost::detail::win32::PLARGE_INTEGER_, PLARGE_INTEGER)); { BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::FILETIME_)==sizeof(FILETIME) ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); BOOST_CHRONO_STATIC_ASSERT(( sizeof(boost::detail::win32::PFILETIME_)==sizeof(PFILETIME) ), NOTHING, (boost::detail::win32::PFILETIME_, PFILETIME)); boost::detail::win32::FILETIME_ a; FILETIME b; BOOST_TEST(( sizeof(a.dwLowDateTime)==sizeof(b.dwLowDateTime) )); BOOST_TEST(( sizeof(a.dwHighDateTime)==sizeof(b.dwHighDateTime) )); BOOST_CHRONO_STATIC_ASSERT(( offsetof(boost::detail::win32::FILETIME_, dwLowDateTime)==offsetof(FILETIME, dwLowDateTime) ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); BOOST_CHRONO_STATIC_ASSERT(( offsetof(boost::detail::win32::FILETIME_, dwHighDateTime)==offsetof(FILETIME, dwHighDateTime) ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same< BOOST_TYPEOF(a.dwLowDateTime), BOOST_TYPEOF(b.dwLowDateTime) >::value ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); BOOST_CHRONO_STATIC_ASSERT(( boost::is_same< BOOST_TYPEOF(a.dwHighDateTime), BOOST_TYPEOF(b.dwHighDateTime) >::value ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); } // BOOST_CHRONO_STATIC_ASSERT(( // GetLastError==boost::detail::win32::::GetLastError // ), NOTHING, ()); } #else void test() { } #endif int main( ) { test(); return boost::report_errors(); }
mxrrow/zaicoin
src/deps/boost/libs/chrono/test/win32_test.cpp
C++
mit
5,830
/* Copyright (c) 2016. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ #ifndef YR_MUTEX_H #define YR_MUTEX_H #if defined(_WIN32) || defined(__CYGWIN__) #include <windows.h> typedef DWORD YR_THREAD_ID; typedef DWORD YR_THREAD_STORAGE_KEY; typedef HANDLE YR_MUTEX; #else #include <pthread.h> typedef pthread_t YR_THREAD_ID; typedef pthread_key_t YR_THREAD_STORAGE_KEY; typedef pthread_mutex_t YR_MUTEX; #endif YR_THREAD_ID yr_current_thread_id(void); int yr_mutex_create(YR_MUTEX*); int yr_mutex_destroy(YR_MUTEX*); int yr_mutex_lock(YR_MUTEX*); int yr_mutex_unlock(YR_MUTEX*); int yr_thread_storage_create(YR_THREAD_STORAGE_KEY*); int yr_thread_storage_destroy(YR_THREAD_STORAGE_KEY*); int yr_thread_storage_set_value(YR_THREAD_STORAGE_KEY*, void*); void* yr_thread_storage_get_value(YR_THREAD_STORAGE_KEY*); #endif
ThunderCls/xLCB
xLCB/pluginsdk/yara/yara/threading.h
C
mit
2,317