repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
xanderflood/math-circle
app/models/semester.rb
class Semester < ApplicationRecord default_scope { order(start: :desc) } has_many :courses, dependent: :destroy has_many :sections, through: :courses, dependent: :destroy has_many :events, through: :sections has_many :rollcalls, through: :events has_many :ballots, dependent: :destroy has_many :registrees, dependent: :destroy has_many :lotteries, dependent: :destroy has_many :special_events, dependent: :destroy has_many :special_registrees, through: :special_events validates :name, presence: { allow_blank: false, message: "must be provided." } validate :end_after_start ### state tracking ### state_machine(initial: :hidden) do # TODO: put email callbacks here before_transition hidden: :lottery_open, do: :reset_for_publish event(:publish) { transition hidden: :lottery_open } event(:close_lottery) { transition lottery_open: :lottery_closed } event(:run) { transition [:lottery_closed, :lottery_done] => :lottery_done } event(:open_registration) { transition lottery_done: :registration_open, closed: :registration_open } event(:close_registration) { transition registration_open: :closed } end LOTTERY_STATES = ["lottery_closed", "lottery_done", "lottery_open"] REGISTRATION_STATE = ["registration_open", "closed"] def self.current self.where.not(state: 'hidden').limit(1).first end def self.current_courses(level=nil) courses = Semester.current.courses courses = courses.where(level: level) if level courses end def self.current_special_events self.current.special_events.where('date >= ?', Date.today).all end def current?; Semester.current == self; end ### methods ### def lottery? LOTTERY_STATES.include? self.state end def registration? REGISTRATION_STATE.include? self.state end def applicants self.ballots.map(&:student) end def roster @roster ||= self.courses.map(&:roster).inject([], :+) end def waitlist @waitlist ||= self.courses.map(&:waitlist).inject([], :+) end def all_students @all_students ||= roster + waitlist end def state_description SemesterStateHelper::STATE_DESCRIPTIONS[self.state] end protected ### callbacks ### def reset_for_publish Student.update_all(level_id: nil, school_grade: nil) Semester.where.not(state: [:hidden, :closed]).update(state: :closed) end def end_after_start errors.add(:end, 'must be later than the start date.') if self.end <= self.start end end
yakuizhao/intel-vaapi-driver
android/android_9/frameworks/av/media/libstagefright/include/media/stagefright/MediaBuffer.h
<filename>android/android_9/frameworks/av/media/libstagefright/include/media/stagefright/MediaBuffer.h /* * Copyright (C) 2009 The Android Open Source Project * * 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 MEDIA_BUFFER_H_ #define MEDIA_BUFFER_H_ #include <atomic> #include <list> #include <pthread.h> #include <binder/MemoryDealer.h> #include <utils/Errors.h> #include <utils/RefBase.h> #include <media/stagefright/MediaBufferBase.h> namespace android { struct ABuffer; class MediaBuffer; class MediaBufferObserver; class MetaDataBase; class MediaBuffer : public MediaBufferBase { public: // allocations larger than or equal to this will use shared memory. static const size_t kSharedMemThreshold = 64 * 1024; // The underlying data remains the responsibility of the caller! MediaBuffer(void *data, size_t size); explicit MediaBuffer(size_t size); explicit MediaBuffer(const sp<ABuffer> &buffer); MediaBuffer(const sp<IMemory> &mem) : MediaBuffer((uint8_t *)mem->pointer() + sizeof(SharedControl), mem->size()) { // delegate and override mMemory mMemory = mem; } // If MediaBufferGroup is set, decrement the local reference count; // if the local reference count drops to 0, return the buffer to the // associated MediaBufferGroup. // // If no MediaBufferGroup is set, the local reference count must be zero // when called, whereupon the MediaBuffer is deleted. virtual void release(); // Increments the local reference count. // Use only when MediaBufferGroup is set. virtual void add_ref(); virtual void *data() const; virtual size_t size() const; virtual size_t range_offset() const; virtual size_t range_length() const; virtual void set_range(size_t offset, size_t length); MetaDataBase& meta_data(); // Clears meta data and resets the range to the full extent. virtual void reset(); virtual void setObserver(MediaBufferObserver *group); // Returns a clone of this MediaBuffer increasing its reference count. // The clone references the same data but has its own range and // MetaData. virtual MediaBufferBase *clone(); // sum of localRefcount() and remoteRefcount() virtual int refcount() const { return localRefcount() + remoteRefcount(); } virtual int localRefcount() const { return mRefCount; } virtual int remoteRefcount() const { if (mMemory.get() == nullptr || mMemory->pointer() == nullptr) return 0; int32_t remoteRefcount = reinterpret_cast<SharedControl *>(mMemory->pointer())->getRemoteRefcount(); // Sanity check so that remoteRefCount() is non-negative. return remoteRefcount >= 0 ? remoteRefcount : 0; // do not allow corrupted data. } // returns old value int addRemoteRefcount(int32_t value) { if (mMemory.get() == nullptr || mMemory->pointer() == nullptr) return 0; return reinterpret_cast<SharedControl *>(mMemory->pointer())->addRemoteRefcount(value); } bool isDeadObject() const { return isDeadObject(mMemory); } static bool isDeadObject(const sp<IMemory> &memory) { if (memory.get() == nullptr || memory->pointer() == nullptr) return false; return reinterpret_cast<SharedControl *>(memory->pointer())->isDeadObject(); } // Sticky on enabling of shared memory MediaBuffers. By default we don't use // shared memory for MediaBuffers, but we enable this for those processes // that export MediaBuffers. static void useSharedMemory() { std::atomic_store_explicit( &mUseSharedMemory, (int_least32_t)1, std::memory_order_seq_cst); } protected: // true if MediaBuffer is observed (part of a MediaBufferGroup). inline bool isObserved() const { return mObserver != nullptr; } virtual ~MediaBuffer(); sp<IMemory> mMemory; private: friend class MediaBufferGroup; friend class OMXDecoder; friend class BnMediaSource; friend class BpMediaSource; // For use by OMXDecoder, reference count must be 1, drop reference // count to 0 without signalling the observer. void claim(); MediaBufferObserver *mObserver; int mRefCount; void *mData; size_t mSize, mRangeOffset, mRangeLength; sp<ABuffer> mBuffer; bool mOwnsData; MetaDataBase* mMetaData; MediaBuffer *mOriginal; static std::atomic_int_least32_t mUseSharedMemory; MediaBuffer(const MediaBuffer &); MediaBuffer &operator=(const MediaBuffer &); // SharedControl block at the start of IMemory. struct SharedControl { enum { FLAG_DEAD_OBJECT = (1 << 0), }; // returns old value inline int32_t addRemoteRefcount(int32_t value) { return std::atomic_fetch_add_explicit( &mRemoteRefcount, (int_least32_t)value, std::memory_order_seq_cst); } inline int32_t getRemoteRefcount() const { return std::atomic_load_explicit(&mRemoteRefcount, std::memory_order_seq_cst); } inline void setRemoteRefcount(int32_t value) { std::atomic_store_explicit( &mRemoteRefcount, (int_least32_t)value, std::memory_order_seq_cst); } inline bool isDeadObject() const { return (std::atomic_load_explicit( &mFlags, std::memory_order_seq_cst) & FLAG_DEAD_OBJECT) != 0; } inline void setDeadObject() { (void)std::atomic_fetch_or_explicit( &mFlags, (int_least32_t)FLAG_DEAD_OBJECT, std::memory_order_seq_cst); } inline void clear() { std::atomic_store_explicit( &mFlags, (int_least32_t)0, std::memory_order_seq_cst); std::atomic_store_explicit( &mRemoteRefcount, (int_least32_t)0, std::memory_order_seq_cst); } private: // Caution: atomic_int_fast32_t is 64 bits on LP64. std::atomic_int_least32_t mFlags; std::atomic_int_least32_t mRemoteRefcount; int32_t unused[6] __attribute__((__unused__)); // additional buffer space }; inline SharedControl *getSharedControl() const { return reinterpret_cast<SharedControl *>(mMemory->pointer()); } }; } // namespace android #endif // MEDIA_BUFFER_H_
ggouaillardet/SOS
test/unit/c11_test_shmem_atomic_and.c
/* * This test program is derived from a unit test created by <NAME>. * The original unit test is a work of the U.S. Government and is not subject * to copyright protection in the United States. Foreign copyrights may * apply. * * Copyright (c) 2017 Intel Corporation. All rights reserved. * This software is available to you under the BSD license below: * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stddef.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <shmem.h> #ifdef ENABLE_SHMEMX_TESTS #include <shmemx.h> #endif #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L enum op { AND = 0, CTX_AND, FETCH_AND, CTX_FETCH_AND, FETCH_AND_NBI, CTX_FETCH_AND_NBI }; /* Initially, remote = 111...b. Each PE performs an atomic AND where the * PEth bit of the input value is set to 0 and all other bits are set to 1. * The result has the NPES least significant bits cleared, 111...000...b. */ #ifdef ENABLE_SHMEMX_TESTS #define SHMEMX_NBI_OPS_CASES(OP, TYPE) \ case FETCH_AND_NBI: \ shmemx_atomic_fetch_and_nbi(&old, &remote, \ ~(TYPE)(1LLU << mype), i); \ shmem_quiet(); \ if ((old & (TYPE)(1LLU << mype)) == 0) { \ printf("PE %i error inconsistent value of old (%s, %s)\n", \ mype, #OP, #TYPE); \ rc = EXIT_FAILURE; \ } \ break; \ case CTX_FETCH_AND_NBI: \ shmemx_atomic_fetch_and_nbi(SHMEM_CTX_DEFAULT, &old, &remote, \ ~(TYPE)(1LLU << mype), i); \ shmem_quiet(); \ if ((old & (TYPE)(1LLU << mype)) == 0) { \ printf("PE %i error inconsistent value of old (%s, %s)\n", \ mype, #OP, #TYPE); \ rc = EXIT_FAILURE; \ } \ break; #else #define SHMEMX_NBI_OPS_CASES(OP, TYPE) #endif #define TEST_SHMEM_AND(OP, TYPE) \ do { \ static TYPE remote = ~(TYPE)0; \ const int mype = shmem_my_pe(); \ const int npes = shmem_n_pes(); \ TYPE old = (TYPE)0; \ if ((size_t) npes-1 > sizeof(TYPE)) break; /* Avoid overflow */ \ for (int i = 0; i < npes; i++) \ switch (OP) { \ case AND: \ shmem_atomic_and(&remote, ~(TYPE)(1LLU << mype), i); \ break; \ case CTX_AND: \ shmem_atomic_and(SHMEM_CTX_DEFAULT, &remote, ~(TYPE)(1LLU << mype), i); \ break; \ case FETCH_AND: \ old = shmem_atomic_fetch_and(&remote, ~(TYPE)(1LLU << mype), i); \ if ((old & (TYPE)(1LLU << mype)) == 0) { \ printf("PE %i error inconsistent value of old (%s, %s)\n", \ mype, #OP, #TYPE); \ rc = EXIT_FAILURE; \ } \ break; \ case CTX_FETCH_AND: \ old = shmem_atomic_fetch_and(SHMEM_CTX_DEFAULT, &remote, ~(TYPE)(1LLU << mype), i); \ if ((old & (TYPE)(1LLU << mype)) == 0) { \ printf("PE %i error inconsistent value of old (%s, %s)\n", \ mype, #OP, #TYPE); \ rc = EXIT_FAILURE; \ } \ break; \ SHMEMX_NBI_OPS_CASES(OP, TYPE) \ default: \ printf("Invalid operation (%d)\n", OP); \ shmem_global_exit(1); \ } \ shmem_barrier_all(); \ if (remote != ~(TYPE)((1LLU << npes) - 1LLU)) { \ printf("PE %i observed error with TEST_SHMEM_AND(%s, %s)\n", \ mype, #OP, #TYPE); \ rc = EXIT_FAILURE; \ } \ } while (0) #else #define TEST_SHMEM_AND(OP, TYPE) #endif int main(int argc, char* argv[]) { shmem_init(); int rc = EXIT_SUCCESS; TEST_SHMEM_AND(AND, unsigned int); TEST_SHMEM_AND(AND, unsigned long); TEST_SHMEM_AND(AND, unsigned long long); TEST_SHMEM_AND(AND, int32_t); TEST_SHMEM_AND(AND, int64_t); TEST_SHMEM_AND(AND, uint32_t); TEST_SHMEM_AND(AND, uint64_t); TEST_SHMEM_AND(CTX_AND, unsigned int); TEST_SHMEM_AND(CTX_AND, unsigned long); TEST_SHMEM_AND(CTX_AND, unsigned long long); TEST_SHMEM_AND(CTX_AND, int32_t); TEST_SHMEM_AND(CTX_AND, int64_t); TEST_SHMEM_AND(CTX_AND, uint32_t); TEST_SHMEM_AND(CTX_AND, uint64_t); TEST_SHMEM_AND(FETCH_AND, unsigned int); TEST_SHMEM_AND(FETCH_AND, unsigned long); TEST_SHMEM_AND(FETCH_AND, unsigned long long); TEST_SHMEM_AND(FETCH_AND, int32_t); TEST_SHMEM_AND(FETCH_AND, int64_t); TEST_SHMEM_AND(FETCH_AND, uint32_t); TEST_SHMEM_AND(FETCH_AND, uint64_t); TEST_SHMEM_AND(CTX_FETCH_AND, unsigned int); TEST_SHMEM_AND(CTX_FETCH_AND, unsigned long); TEST_SHMEM_AND(CTX_FETCH_AND, unsigned long long); TEST_SHMEM_AND(CTX_FETCH_AND, int32_t); TEST_SHMEM_AND(CTX_FETCH_AND, int64_t); TEST_SHMEM_AND(CTX_FETCH_AND, uint32_t); TEST_SHMEM_AND(CTX_FETCH_AND, uint64_t); #ifdef ENABLE_SHMEMX_TESTS TEST_SHMEM_AND(FETCH_AND_NBI, unsigned int); TEST_SHMEM_AND(FETCH_AND_NBI, unsigned long); TEST_SHMEM_AND(FETCH_AND_NBI, unsigned long long); TEST_SHMEM_AND(FETCH_AND_NBI, int32_t); TEST_SHMEM_AND(FETCH_AND_NBI, int64_t); TEST_SHMEM_AND(FETCH_AND_NBI, uint32_t); TEST_SHMEM_AND(FETCH_AND_NBI, uint64_t); TEST_SHMEM_AND(CTX_FETCH_AND_NBI, unsigned int); TEST_SHMEM_AND(CTX_FETCH_AND_NBI, unsigned long); TEST_SHMEM_AND(CTX_FETCH_AND_NBI, unsigned long long); TEST_SHMEM_AND(CTX_FETCH_AND_NBI, int32_t); TEST_SHMEM_AND(CTX_FETCH_AND_NBI, int64_t); TEST_SHMEM_AND(CTX_FETCH_AND_NBI, uint32_t); TEST_SHMEM_AND(CTX_FETCH_AND_NBI, uint64_t); #endif shmem_finalize(); return rc; }
koz4k/soccer
CtrlLib/LineEdit.cpp
<gh_stars>1-10 #include "CtrlLib.h" namespace Upp { #define LLOG(x) // LOG(x) #define LTIMING(x) // RTIMING(x) LineEdit::LineEdit() { isdrag = false; nohbar = false; showtabs = false; tabsize = 4; font = CourierZ(12); SetFrame(ViewFrame()); sb.NoBox(); AddFrame(sb); sb.WhenScroll = THISBACK(Scroll); cutline = true; bordercolumn = -1; bordercolor = Null; overwrite = false; filter = NULL; showspaces = false; showlines = false; showreadonly = true; dorectsel = false; hline = Null; warnwhitespace = false; } LineEdit::~LineEdit() {} void LineEdit::MouseWheel(Point, int zdelta, dword keyflags) { if(keyflags & K_SHIFT) sb.WheelX(zdelta); else sb.WheelY(zdelta); } void LineEdit::Clear() { gcolumn = 0; TextCtrl::Clear(); sb.SetTotal(0, 0); sb.Set(0, 0); NewScrollPos(); PlaceCaret(0, false); } LineEdit& LineEdit::TabSize(int n) { tabsize = n; PlaceCaret0(GetColumnLine(cursor)); Refresh(); return *this; } LineEdit& LineEdit::BorderColumn(int col, Color c) { bordercolumn = col; bordercolor = c; Refresh(); return *this; } LineEdit& LineEdit::SetFont(Font f) { font = f; Layout(); TabSize(tabsize); SetSb(); return *this; } Size LineEdit::GetFontSize() const { FontInfo fi = font.Info(); return Size(max(fi['M'], fi['W']), fi.GetHeight()); } void LineEdit::SetRectSelection(int anchor, int cursor) { dorectsel = true; SetSelection(anchor, cursor); dorectsel = false; } void LineEdit::SetRectSelection(const Rect& rect) { SetRectSelection(GetGPos(rect.top, rect.left), GetGPos(rect.bottom, rect.right)); } Rect LineEdit::GetRectSelection() const { if(IsRectSelection()) { int sell, selh; GetSelection(sell, selh); Rect r(GetColumnLine(sell), GetColumnLine(selh)); if(r.left > r.right) Swap(r.left, r.right); return r; } return Null; } bool LineEdit::GetRectSelection(const Rect& rect, int line, int& l, int &h) { if(line >= rect.top && line <= rect.bottom) { l = GetGPos(line, rect.left); h = GetGPos(line, rect.right); return true; } return false; } int LineEdit::RemoveRectSelection() { Rect rect = GetRectSelection(); WString txt; for(int i = rect.top; i <= rect.bottom; i++) { int l, h; CacheLinePos(i); GetRectSelection(rect, i, l, h); WString s = GetWLine(i); s.Remove(l - GetPos(i), h - l); txt.Cat(s); txt.Cat('\n'); } int l = GetPos(rect.top); int h = GetPos(rect.bottom) + GetLineLength(rect.bottom); if(h < GetLength()) h++; Remove(l, h - l); Insert(l, txt); return GetGPos(rect.bottom, rect.left); } WString LineEdit::CopyRectSelection() { WString txt; Rect rect = GetRectSelection(); for(int i = rect.top; i <= rect.bottom; i++) { int l, h; CacheLinePos(i); int pos = GetPos(i); GetRectSelection(rect, i, l, h); txt.Cat(GetWLine(i).Mid(l - pos, h - l)); #ifdef PLATFORM_WIN32 txt.Cat('\r'); #endif txt.Cat('\n'); } return txt; } int LineEdit::PasteRectSelection(const WString& s) { Vector<WString> cl = Split(s, '\n', false); Rect rect = GetRectSelection(); int pos = cursor; int n = 0; for(int i = 0; i < cl.GetCount() && rect.top + i <= rect.bottom; i++) { int l, h; CacheLinePos(i); GetRectSelection(rect, i + rect.top, l, h); Remove(l, h - l); int nn = Insert(l, cl[i]); n += nn; pos = l + nn; } PlaceCaret(pos); return n; } void LineEdit::PasteColumn(const WString& text) { Vector<WString> cl = Split(text, '\n', false); if(cl.GetCount() && cl.Top().IsEmpty()) cl.Drop(); if(cl.GetCount() == 0) return; int pos; if(IsRectSelection()) { Rect t = GetRectSelection(); RemoveSelection(); Point p = t.TopLeft(); pos = cursor; for(int i = 0; i < t.bottom - t.top + 1; i++) { CacheLinePos(i + p.y); int l = GetGPos(i + p.y, p.x); pos = l + Insert(l, cl[i % cl.GetCount()]); } } else { RemoveSelection(); Point p = GetColumnLine(cursor); pos = cursor; for(int i = 0; i < cl.GetCount(); i++) { CacheLinePos(i + p.y); int li = p.y + i; if(li < line.GetCount()) { int l = GetGPos(i + p.y, p.x); pos = l + Insert(l, cl[i]); } else { Insert(GetLength(), cl[i] + "\n"); pos = GetLength(); } } } PlaceCaret(pos); } void LineEdit::PasteColumn() { WString w = ReadClipboardUnicodeText(); if(w.IsEmpty()) w = ReadClipboardText().ToWString(); PasteColumn(w); Action(); } bool sSortLineOrder(const WString& l1, const WString& l2) { return ToUpper(l1) < ToUpper(l2); } void LineEdit::Sort() { if(!IsRectSelection()) return; CopyRectSelection(); Rect rect = GetRectSelection(); Vector<WString> key; Vector<WString> ln; for(int i = rect.top; i <= rect.bottom; i++) { int l, h; GetRectSelection(rect, i, l, h); key.Add(GetW(l, h - l)); ln.Add(line[i]); } int sell = GetPos(rect.top); int selh = rect.bottom + 1 < line.GetCount() ? GetPos(rect.bottom + 1) : GetLength(); IndexSort(key, ln, sSortLineOrder); Remove(sell, selh - sell); Insert(sell, Join(ln, "\n")); } class sOptimizedRectRenderer { Draw& w; Rect cr; Color color; public: void DrawRect(const Rect& r, Color color); void DrawRect(int x, int y, int cx, int cy, Color color) { DrawRect(RectC(x, y, cx, cy), color); } void Flush(); sOptimizedRectRenderer(Draw& w) : w(w) { cr = Null; color = Null; } ~sOptimizedRectRenderer() { Flush(); } }; void sOptimizedRectRenderer::Flush() { LTIMING("RectFlush"); if(!IsNull(cr)) { w.DrawRect(cr, color); cr = Null; } } void sOptimizedRectRenderer::DrawRect(const Rect& r, Color c) { LTIMING("DrawRect"); if(cr.top == r.top && cr.bottom == r.bottom && cr.right == r.left && c == color) { cr.right = r.right; return; } Flush(); cr = r; color = c; } #if 1 // This is a more ambitious approach combining non-continual chunks of text, it is a bit faster... class sOptimizedTextRenderer { Draw& w; int y; struct Chrs : Moveable<Chrs> { Vector<int> x; WString text; }; VectorMap< Tuple2<Font, Color>, Chrs > cache; public: void DrawChar(int x, int y, int chr, int width, Font afont, Color acolor); void Flush(); sOptimizedTextRenderer(Draw& w) : w(w) { y = Null; } ~sOptimizedTextRenderer() { Flush(); } }; void sOptimizedTextRenderer::Flush() { if(cache.GetCount() == 0) return; LTIMING("Flush"); for(int i = 0; i < cache.GetCount(); i++) { Chrs& c = cache[i]; if(c.x.GetCount()) { Tuple2<Font, Color> fc = cache.GetKey(i); int x = c.x[0]; for(int i = 0; i < c.x.GetCount() - 1; i++) c.x[i] = c.x[i + 1] - c.x[i]; c.x.Top() = 0; w.DrawText(x, y, c.text, fc.a, fc.b, c.x); } } cache.Clear(); } void sOptimizedTextRenderer::DrawChar(int x, int _y, int chr, int width, Font font, Color color) { LTIMING("DrawChar"); if(y != _y) { Flush(); y = _y; } Chrs *c; { LTIMING("Map"); c = &cache.GetAdd(MakeTuple(font, color)); } if(c->x.GetCount() && c->x.Top() > x) { Flush(); c = &cache.GetAdd(MakeTuple(font, color)); } c->text.Cat(chr); c->x.Add(x); } #else class sOptimizedTextRenderer { Draw& w; int x, y; int xpos; Vector<int> dx; WString text; Font font; Color color; public: void DrawChar(int x, int y, int chr, int width, Font afont, Color acolor); void Flush(); sOptimizedTextRenderer(Draw& w) : w(w) { y = Null; } ~sOptimizedTextRenderer() { Flush(); } }; void sOptimizedTextRenderer::Flush() { if(text.GetCount() == 0) return; LTIMING("Flush"); w.DrawText(x, y, text, font, color, dx); y = Null; text.Clear(); dx.Clear(); } void sOptimizedTextRenderer::DrawChar(int _x, int _y, int chr, int width, Font _font, Color _color) { LTIMING("DrawChar"); if(y == _y && font == _font && color == _color && dx.GetCount() && _x >= xpos - dx.Top()) dx.Top() += _x - xpos; else { LTIMING("DrawChar flush"); Flush(); x = _x; y = _y; font = _font; color = _color; } dx.Add(width); text.Cat(chr); xpos = _x + width; } #endif void LineEdit::Paint0(Draw& w) { LTIMING("LineEdit::Paint0"); int sell, selh; GetSelection(sell, selh); if(!IsEnabled()) sell = selh = 0; Rect rect; bool rectsel = IsRectSelection(); if(IsRectSelection()) rect = GetRectSelection(); Size sz = GetSize(); Size fsz = GetFontSize(); Point sc = sb; int ll = min(line.GetCount(), sz.cy / fsz.cy + sc.y + 1); int y = 0; sc.y = minmax(sc.y, 0, line.GetCount() - 1); cpos = GetPos(sc.y); cline = sc.y; sell -= cpos; selh -= cpos; int pos = cpos; int fascent = font.Info().GetAscent(); int cursorline = GetLine(cursor); Highlight ih; ih.ink = color[IsShowEnabled() ? INK_NORMAL : INK_DISABLED]; ih.paper = color[IsReadOnly() && showreadonly || !IsShowEnabled() ? PAPER_READONLY : PAPER_NORMAL]; if(nobg) ih.paper = Null; ih.font = font; ih.chr = 0; for(int i = sc.y; i < ll; i++) { Color showcolor = color[WHITESPACE]; WString tx = line[i]; bool warn_whitespace = false; if(warnwhitespace && !IsSelection()) { int pos = GetCursor(); int linei = GetLinePos(pos); if(linei != i || pos < tx.GetCount()) { int wkind = 0; bool empty = true; for(const wchar *s = tx; *s; s++) { if(*s == '\t') { if(wkind == ' ') { warn_whitespace = true; break; } wkind = '\t'; } else if(*s == ' ') wkind = ' '; else if(*s > ' ') { empty = false; wkind = 0; } } if(wkind && !empty) warn_whitespace = true; if(warn_whitespace) showcolor = color[WARN_WHITESPACE]; } } bool do_highlight = tx.GetCount() < 100000; int len = tx.GetLength(); if(w.IsPainting(0, y, sz.cx, fsz.cy)) { LTIMING("PaintLine"); Vector<Highlight> hl; int ln; if(do_highlight) { hl.SetCount(len + 1, ih); for(int q = 0; q < tx.GetCount(); q++) hl[q].chr = tx[q]; LTIMING("HighlightLine"); HighlightLine(i, hl, pos); ln = hl.GetCount() - 1; } else ln = tx.GetCount(); int lgp = -1; for(int pass = 0; pass < 3; pass++) { int gp = 0; int scx = fsz.cx * sc.x; sOptimizedRectRenderer rw(w); if(ln >= 0) { int q = 0; int x = 0; int scx2 = scx - max(2, tabsize) * fsz.cx; while(q < ln && x < scx2) { // Skip part before left border wchar chr = do_highlight ? hl[q++].chr : tx[q++]; if(chr == '\t') { gp = (gp + tabsize) / tabsize * tabsize; x = fsz.cx * gp; } else if(IsCJKIdeograph(chr)) { x += 2 * fsz.cx; gp += 2; } else { x += fsz.cx; gp++; } } sOptimizedTextRenderer tw(w); while(q < ln) { if(q == tx.GetCount()) lgp = gp; Highlight h; if(do_highlight) h = hl[q]; else { h = ih; h.chr = tx[q]; } int pos = min(q, len); // Highligting can add chars at the end of line if(rectsel ? i >= rect.top && i <= rect.bottom && gp >= rect.left && gp < rect.right : pos >= sell && pos < selh) { h.paper = color[PAPER_SELECTED]; h.ink = color[INK_SELECTED]; } int x = gp * fsz.cx - scx; if(h.chr == '\t') { int ngp = (gp + tabsize) / tabsize * tabsize; int l = ngp - gp; LLOG("Highlight -> tab[" << q << "] paper = " << h.paper); if(pass == 0 && x >= -fsz.cy * tabsize) { rw.DrawRect(x, y, fsz.cx * l, fsz.cy, h.paper); if((showtabs || warn_whitespace) && h.paper != SColorHighlight && q < tx.GetLength()) { rw.DrawRect(x + 2, y + fsz.cy / 2, l * fsz.cx - 4, 1, showcolor); rw.DrawRect(ngp * fsz.cx - scx - 3, y + 3, 1, fsz.cy - 6, showcolor); } if(bordercolumn > 0 && bordercolumn >= gp && bordercolumn < gp + l) rw.DrawRect((bordercolumn - sc.x) * fsz.cx, y, 1, fsz.cy, bordercolor); } q++; gp = ngp; } else if(h.chr == ' ') { LLOG("Highlight -> space[" << q << "] paper = " << h.paper); if(pass == 0 && x >= -fsz.cy) { rw.DrawRect(x, y, fsz.cx, fsz.cy, h.paper); if((showspaces || warn_whitespace) && h.paper != SColorHighlight && q < tx.GetLength()) { int n = fsz.cy / 10 + 1; rw.DrawRect(x + fsz.cx / 2, y + fsz.cy / 2, n, n, showcolor); } if(bordercolumn > 0 && bordercolumn >= gp && bordercolumn < gp + 1) rw.DrawRect((bordercolumn - sc.x) * fsz.cx, y, 1, fsz.cy, bordercolor); } q++; gp++; } else { bool cjk = IsCJKIdeograph(h.chr); LLOG("Highlight -> paper[" << q << "] = " << h.paper); int xx = x + (gp + 1 + cjk) * fsz.cx; if(max(x, 0) < min(xx, sz.cx) && fsz.cx >= -fsz.cy) { if(pass == 0) { rw.DrawRect(x, y, (cjk + 1) * fsz.cx, fsz.cy, h.paper); if(bordercolumn > 0 && bordercolumn >= gp && bordercolumn < gp + 1 + cjk) rw.DrawRect((bordercolumn - sc.x) * fsz.cx, y, 1, fsz.cy, bordercolor); } if(pass == 1 && (h.flags & SPELLERROR)) rw.DrawRect(x, max(y, y + fsz.cy - Zy(1)), (cjk + 1) * fsz.cx, Zy(1), LtRed()); if(pass == 2) tw.DrawChar(x + (h.flags & SHIFT_L ? -fsz.cx / 6 : h.flags & SHIFT_R ? fsz.cx / 6 : 0), y + fascent - h.font.GetAscent(), h.chr, (cjk + 1) * fsz.cx, h.font, h.ink); } q++; gp += 1 + cjk; if(x > sz.cx) break; } } } if(pass == 0) { int gpx = gp * fsz.cx - scx; rw.DrawRect(gpx, y, sz.cx - gpx, fsz.cy, !rectsel && sell <= len && len < selh ? color[PAPER_SELECTED] : (do_highlight ? hl.Top() : ih).paper); if(bordercolumn > 0 && bordercolumn >= gp) rw.DrawRect((bordercolumn - sc.x) * fsz.cx, y, 1, fsz.cy, bordercolor); } if(pass == 0 && (showlines || warn_whitespace)) { int yy = 2 * fsz.cy / 3; int x = (lgp >= 0 ? lgp : gp) * fsz.cx - scx; rw.DrawRect(x, y + yy, fsz.cx / 2, 1, showcolor); if(fsz.cx > 2) rw.DrawRect(x + 1, y + yy - 1, 1, 3, showcolor); if(fsz.cx > 5) rw.DrawRect(x + 2, y + yy - 2, 1, 5, showcolor); rw.DrawRect(x + fsz.cx / 2, y + yy / 2, 1, yy - yy / 2, showcolor); } if(pass == 0 && !IsNull(hline) && sell == selh && i == cursorline) { rw.DrawRect(0, y, sz.cx, 1, hline); rw.DrawRect(0, y + fsz.cy - 1, sz.cx, 1, hline); } if(pass == 0 && rectsel && rect.left == rect.right && i >= rect.top && i <= rect.bottom) rw.DrawRect(rect.left * fsz.cx - scx, y, 2, fsz.cy, Blend(color[PAPER_SELECTED], color[PAPER_NORMAL])); } } y += fsz.cy; sell -= len + 1; selh -= len + 1; pos += len + 1; } w.DrawRect(0, y, sz.cx, sz.cy - y, color[IsReadOnly() && showreadonly || !IsShowEnabled() ? PAPER_READONLY : PAPER_NORMAL]); DrawTiles(w, DropCaret(), CtrlImg::checkers()); } void LineEdit::Paint(Draw& w) { Paint0(w); scroller.Set(sb); } struct LineEdit::RefreshDraw : public NilDraw { Ctrl *ctrl; bool (*chars)(int c); Size fsz; virtual void DrawTextOp(int x, int y, int angle, const wchar *text, Font, Color, int n, const int *dx) { if(dx) while(n > 0) { if((*chars)(*text)) ctrl->Refresh(x, y, fsz.cx, fsz.cy); text++; x += *dx++; n--; } } bool IsPaintingOp(const Rect& r) const { return true; } }; void LineEdit::RefreshChars(bool (*chars)(int c)) { RefreshDraw rw; rw.ctrl = this; rw.fsz = GetFontSize(); rw.chars = chars; Paint(rw); } void LineEdit::Layout() { Size sz = sb.GetReducedViewSize(); if(nohbar || isdrag) sz.cy = GetSize().cy; sb.SetPage(sz / GetFontSize()); SetHBar(); } int LineEdit::GetGPos(int ln, int cl) const { ln = minmax(ln, 0, line.GetCount() - 1); const String& stxt = line[ln].text; const char *s = stxt; const char *e = stxt.End(); const char *b = s; int gl = 0; int wpos = 0; while(s < e) { if(*s == '\t') gl = (gl + tabsize) / tabsize * tabsize; else if((byte)*s < 128) gl++; else { WString txt = FromUtf8(s, int(e - s)); const wchar *b = txt; const wchar *e = txt.End(); const wchar *s = b; while(s < e) { if(*s == '\t') gl = (gl + tabsize) / tabsize * tabsize; else gl += 1 + IsCJKIdeograph(*s); if(cl < gl) break; s++; } wpos = int(s - b); break; } if(cl < gl) break; s++; } return GetPos(ln, int(s - b) + wpos); } Point LineEdit::GetColumnLine(int pos) const { Point p; if(pos > total) pos = total; p.y = GetLinePos(pos); p.x = 0; WString txt = line[p.y]; const wchar *s = txt; while(pos--) { if(*s == '\t') p.x = (p.x + tabsize) / tabsize * tabsize; else p.x += 1 + IsCJKIdeograph(*s); s++; } return p; } Point LineEdit::GetIndexLine(int pos) const { Point p; if(pos > total) pos = total; p.y = GetLinePos(pos); p.x = minmax(pos, 0, line[p.y].GetLength()); return p; } int LineEdit::GetIndexLinePos(Point pos) const { if(pos.y < 0) return 0; if(pos.y >= GetLineCount()) return total; return GetPos(pos.y, minmax(pos.x, 0, line[pos.y].GetLength())); } void LineEdit::RefreshLine(int i) { Size sz = GetSize(); int fcy = GetFontSize().cy; Refresh(0, (i - sb.Get().y) * fcy, sz.cx, fcy); } Rect LineEdit::GetLineScreenRect(int line) const { int fcy = GetFontSize().cy; Rect r = RectC(0, (line - sb.Get().y) * fcy, GetSize().cx, fcy); r.Offset(GetScreenView().TopLeft()); return r; } void LineEdit::SetSb() { sb.SetTotalY(line.GetCount()); SetHBar(); } void LineEdit::NewScrollPos() {} void LineEdit::HighlightLine(int line, Vector<Highlight>& h, int pos) {} void LineEdit::AlignChar() { int c = GetCursor(); if(c == 0) return; Point pos = GetColumnLine(c); if(pos.x == 0) return; for(int d = 1; d <= pos.y && d < 100; d++) { int lny = pos.y - d; WString above = GetWLine(lny); int offset = GetGPos(lny, pos.x) - GetPos(lny); int end = offset; char ch = GetChar(c - 1); if(ch == ' ') { offset++; while(end < above.GetLength() && above[end] != ' ') end++; while(end < above.GetLength() && above[end] == ' ') end++; } else while(end < above.GetLength() && above[end] != ch) end++; if(end < above.GetLength()) { int count = end - offset + 1; WString s(' ', count); Insert(c - 1, s, true); SetCursor(c + count); return; } } } void LineEdit::PlaceCaret0(Point p) { Size fsz = GetFontSize(); p -= sb; caretpos = Point(p.x * fsz.cx, p.y * fsz.cy); if(overwrite) SetCaret(caretpos.x, caretpos.y + fsz.cy - 2, fsz.cx, 2); else SetCaret(caretpos.x, caretpos.y, 2, fsz.cy); } int LineEdit::PlaceCaretNoG(int newcursor, bool sel) { if(newcursor > total) newcursor = total; Point p = GetColumnLine(newcursor); if(sel) { if(anchor < 0) { anchor = cursor; } if(rectsel || rectsel != dorectsel) Refresh(); else RefreshLines(p.y, GetLine(cursor)); rectsel = dorectsel; } else { if(anchor >= 0) { if(rectsel || dorectsel) Refresh(); else RefreshLines(GetLine(cursor), GetLine(anchor)); anchor = -1; } rectsel = false; } RefreshLine(GetColumnLine(cursor).y); RefreshLine(p.y); cursor = newcursor; ScrollIntoCursor(); PlaceCaret0(p); SelectionChanged(); WhenSel(); if(IsAnySelection()) SetSelectionSource(ClipFmtsText()); return p.x; } void LineEdit::PlaceCaret(int newcursor, bool sel) { gcolumn = PlaceCaretNoG(newcursor, sel); } void LineEdit::TopCursor(int lines) { sb.SetY(max(0, GetLine(cursor) - lines)); } void LineEdit::CenterCursor() { int cy = sb.GetPage().cy; if(cy > 4) sb.SetY(max(min(GetLine(cursor) - cy / 2, line.GetCount() - cy), 0)); } void LineEdit::Scroll() { PlaceCaret0(GetColumnLine(cursor)); scroller.Scroll(*this, GetSize(), sb.Get(), GetFontSize()); SetHBar(); NewScrollPos(); } int LineEdit::GetMousePos(Point p) const { Size fsz = GetFontSize(); p = (p + fsz.cx / 2 + fsz * (Size)sb.Get()) / fsz; return GetGPos(p.y, p.x); } void LineEdit::LeftDown(Point p, dword flags) { mpos = GetMousePos(p); int l, h; if(GetSelection(l, h) && mpos >= l && mpos < h) { selclick = true; return; } dorectsel = flags & K_ALT; PlaceCaret(mpos, (flags & K_SHIFT) || dorectsel); dorectsel = false; SetFocus(); SetCapture(); } void LineEdit::LeftUp(Point p, dword flags) { if(!HasCapture() && selclick && !IsDragAndDropSource()) { mpos = GetMousePos(p); PlaceCaret(mpos, flags & K_SHIFT); SetFocus(); } selclick = false; ReleaseCapture(); } void LineEdit::RightDown(Point p, dword flags) { mpos = GetMousePos(p); SetFocus(); int l, h; GetSelection(l, h); if(!IsAnySelection() || !(mpos >= l && mpos < h)) PlaceCaret(mpos, false); MenuBar::Execute(WhenBar); } void LineEdit::LeftDouble(Point, dword) { int l, h; if(GetWordSelection(cursor, l, h)) SetSelection(l, h); } void LineEdit::LeftTriple(Point, dword) { int q = cursor; int i = GetLinePos(q); q = cursor - q; SetSelection(q, q + GetLineLength(i) + 1); } void LineEdit::MouseMove(Point p, dword flags) { if((flags & K_MOUSELEFT) && HasFocus() && HasCapture()) { int c = GetMousePos(p); dorectsel = flags & K_ALT; PlaceCaret(c, mpos != c || HasCapture()); dorectsel = false; } } void LineEdit::LeftRepeat(Point p, dword flags) { if(HasCapture()) { int c = GetMousePos(p); if(mpos != c) { dorectsel = flags & K_ALT; PlaceCaret(c, true); dorectsel = false; } } } Image LineEdit::CursorImage(Point, dword) { return Image::IBeam(); } void LineEdit::MoveUpDown(int n, bool sel) { int cl = cursor; int ln = GetLinePos(cl); ln = minmax(ln + n, 0, line.GetCount() - 1); PlaceCaretNoG(GetGPos(ln, gcolumn), sel); } void LineEdit::MoveLeft(bool sel) { if(cursor) PlaceCaret(cursor - 1, sel); } void LineEdit::MoveRight(bool sel) { if(cursor < total) PlaceCaret(cursor + 1, sel); } void LineEdit::MoveUp(bool sel) { MoveUpDown(-1, sel); } void LineEdit::MoveDown(bool sel) { MoveUpDown(1, sel); } void LineEdit::MovePage(int dir, bool sel) { int n = dir * max(GetSize().cy / GetFontSize().cy - 2, 2); sb.SetY(Point(sb).y + n); MoveUpDown(n, sel); } void LineEdit::MovePageUp(bool sel) { MovePage(-1, sel); } void LineEdit::MovePageDown(bool sel) { MovePage(1, sel); } inline bool sTabSpace(int c) { return c == '\t' || c == ' '; } void LineEdit::MoveHome(bool sel) { int cl = cursor; int li = GetLinePos(cl); int i = 0; WString l = line[li]; while(sTabSpace(l[i])) i++; PlaceCaret(GetPos(li, cl == i ? 0 : i), sel); } void LineEdit::MoveEnd(bool sel) { int i = GetLine(cursor); PlaceCaret(GetPos(i, line[i].GetLength()), sel); } void LineEdit::MoveTextBegin(bool sel) { PlaceCaret(0, sel); } void LineEdit::MoveTextEnd(bool sel) { PlaceCaret(total, sel); } bool LineEdit::InsertChar(dword key, int count, bool canow) { if(key == K_TAB && !processtab) return false; if(filter && key >= 32 && key < 65535) key = (*filter)(key); if(!IsReadOnly() && (key >= 32 && key < 65536 || key == '\t' || key == '\n' || key == K_ENTER && processenter || key == K_SHIFT_SPACE)) { if(key >= 128 && key < 65536 && (charset != CHARSET_UNICODE && charset != CHARSET_UTF8_BOM) && FromUnicode((wchar)key, charset) == DEFAULTCHAR) return true; if(!RemoveSelection() && overwrite && key != '\n' && key != K_ENTER && canow) { int q = cursor; int i = GetLinePos(q); if(q + count - 1 < GetLineLength(i)) Remove(cursor, count); } WString text(key == K_ENTER ? '\n' : key == K_SHIFT_SPACE ? ' ' : key, count); Insert(cursor, text, true); PlaceCaret(cursor + count); Action(); return true; } return false; } void LineEdit::DeleteChar() { if(IsReadOnly() || RemoveSelection()) { Action(); return; } if(cursor < total) { Remove(cursor, 1); Action(); } } void LineEdit::Backspace() { if(IsReadOnly() || RemoveSelection() || cursor == 0) return; MoveLeft(); DeleteChar(); Action(); } void LineEdit::DeleteLine() { int b, e; if(GetSelection(b, e) && GetLine(b) != GetLine(e)) { RemoveSelection(); return; } int i = GetLine(cursor); int p = GetPos(i); Remove(p, line[i].GetLength() + 1); PlaceCaret(p); Action(); } void LineEdit::CutLine() { if(IsReadOnly()) return; int b, e; if(GetSelection(b, e) && GetLine(b) != GetLine(e)) { Cut(); return; } int i = GetLine(cursor); int p = GetPos(i); WString txt = Get(p, line[i].GetLength() + 1).ToWString(); WriteClipboardUnicodeText(txt); AppendClipboardText(txt.ToString()); ClearSelection(); DeleteLine(); } void LineEdit::EditPos::Serialize(Stream& s) { int version = 0; s / version; s % sby % cursor; } LineEdit::EditPos LineEdit::GetEditPos() const { EditPos pos; pos.sby = sb.Get().y; pos.cursor = cursor; return pos; } void LineEdit::SetEditPos(const LineEdit::EditPos& pos) { sb.SetY(minmax(pos.sby, 0, line.GetCount() - 1)); SetCursor(pos.cursor); } void LineEdit::SetEditPosSb(const LineEdit::EditPos& pos) { SetCursor(pos.cursor); sb.SetY(minmax(pos.sby, 0, line.GetCount() - 1)); } void LineEdit::SetHBar() { int mpos = 0; if(!nohbar && !isdrag) { int m = min(sb.y + sb.GetPage().cy + 2, line.GetCount()); for(int i = sb.y; i < m; i++) { int pos = 0; WString l = line[i]; const wchar *s = l; const wchar *e = l.End(); while(s < e) { if(*s == '\t') pos = (pos + tabsize) / tabsize * tabsize; else pos += 1 + IsCJKIdeograph(*s); s++; } mpos = max(mpos, pos); } } sb.SetTotalX(mpos + 1); } void LineEdit::ScrollIntoCursor() { Point p = GetColumnLine(GetCursor()); sb.ScrollInto(p); SetHBar(); sb.ScrollInto(p); } bool LineEdit::Key(dword key, int count) { NextUndo(); switch(key) { case K_CTRL_UP: ScrollUp(); return true; case K_CTRL_DOWN: ScrollDown(); return true; case K_INSERT: OverWriteMode(!IsOverWriteMode()); break; } bool sel = key & K_SHIFT; dorectsel = key & K_ALT; dword k = key & ~K_SHIFT; if((key & (K_SHIFT|K_ALT)) == (K_SHIFT|K_ALT)) k &= ~K_ALT; switch(k) { case K_CTRL_LEFT: { PlaceCaret(GetPrevWord(cursor), sel); break; } case K_CTRL_RIGHT: { PlaceCaret(GetNextWord(cursor), sel); break; } case K_LEFT: MoveLeft(sel); break; case K_RIGHT: MoveRight(sel); break; case K_HOME: MoveHome(sel); break; case K_END: MoveEnd(sel); break; case K_UP: MoveUp(sel); break; case K_DOWN: MoveDown(sel); break; case K_PAGEUP: MovePageUp(sel); break; case K_PAGEDOWN: MovePageDown(sel); break; case K_CTRL_PAGEUP: case K_CTRL_HOME: MoveTextBegin(sel); break; case K_CTRL_PAGEDOWN: case K_CTRL_END: MoveTextEnd(sel); break; case K_CTRL_C: case K_CTRL_INSERT: Copy(); break; case K_CTRL_A: SelectAll(); break; default: dorectsel = false; if(IsReadOnly()) return MenuBar::Scan(WhenBar, key); switch(key) { case K_DELETE: DeleteChar(); break; case K_BACKSPACE: case K_SHIFT|K_BACKSPACE: Backspace(); break; case K_SHIFT_TAB: AlignChar(); break; case K_CTRL_Y: case K_CTRL_L: if(cutline) { CutLine(); break; } default: if(InsertChar(key, count, true)) return true; return MenuBar::Scan(WhenBar, key); } return true; } dorectsel = false; Sync(); return true; } void LineEdit::DragAndDrop(Point p, PasteClip& d) { if(IsReadOnly()) return; int c = GetMousePos(p); if(AcceptText(d)) { NextUndo(); int a = sb.y; int sell, selh; WString text = GetWString(d); if(GetSelection(sell, selh)) { if(c >= sell && c < selh) { if(!IsReadOnly()) RemoveSelection(); if(IsDragAndDropSource()) d.SetAction(DND_COPY); c = sell; } else if(d.GetAction() == DND_MOVE && IsDragAndDropSource()) { if(c > sell) c -= selh - sell; if(!IsReadOnly()) RemoveSelection(); d.SetAction(DND_COPY); } } int count = Insert(c, text); sb.y = a; SetFocus(); SetSelection(c, c + count); Action(); return; } if(!d.IsAccepted()) return; if(!isdrag) { isdrag = true; ScrollIntoCursor(); } Point dc = Null; if(c >= 0) dc = GetColumnLine(c); if(dc != dropcaret) { RefreshDropCaret(); dropcaret = dc; RefreshDropCaret(); } } Rect LineEdit::DropCaret() { if(IsNull(dropcaret)) return Rect(0, 0, 0, 0); Size fsz = GetFontSize(); Point p = dropcaret - sb; p = Point(p.x * fsz.cx, p.y * fsz.cy); return RectC(p.x, p.y, 1, fsz.cy); } void LineEdit::RefreshDropCaret() { Refresh(DropCaret()); } void LineEdit::DragRepeat(Point p) { sb.y = (int)sb.y + GetDragScroll(this, p, 1).y; } void LineEdit::DragLeave() { RefreshDropCaret(); dropcaret = Null; isdrag = false; Layout(); } void LineEdit::LeftDrag(Point p, dword flags) { int c = GetMousePos(p); int l, h; if(!HasCapture() && GetSelection(l, h) && c >= l && c < h) { WString sample = GetW(l, min(h - l, 3000)); Size sz = StdSampleSize(); ImageDraw iw(sz); iw.DrawRect(sz, Black()); iw.Alpha().DrawRect(sz, Black()); DrawTLText(iw.Alpha(), 0, 0, 9999, sample, CourierZ(10), White()); NextUndo(); if(DoDragAndDrop(ClipFmtsText(), iw) == DND_MOVE && !IsReadOnly()) { RemoveSelection(); Action(); } } } }
Masterlupo/EvilCraft
src/main/java/org/cyclops/evilcraft/core/recipe/type/RecipeSerializerBloodInfuserConfig.java
<reponame>Masterlupo/EvilCraft<filename>src/main/java/org/cyclops/evilcraft/core/recipe/type/RecipeSerializerBloodInfuserConfig.java package org.cyclops.evilcraft.core.recipe.type; import org.cyclops.cyclopscore.config.extendedconfig.RecipeConfig; import org.cyclops.evilcraft.EvilCraft; /** * Config for the blood infuser recipe serializer. * @author rubensworks * */ public class RecipeSerializerBloodInfuserConfig extends RecipeConfig<RecipeBloodInfuser> { public RecipeSerializerBloodInfuserConfig() { super( EvilCraft._instance, "blood_infuser", eConfig -> new RecipeSerializerBloodInfuser() ); } }
skylark-integration/skylark-dojox
dist/dojox/grid/enhanced/nls/it/Pagination.js
/** * dojox - A version of dojox.js framework that ported to running on skylarkjs. * @author Hudaokeji, Inc. * @version v0.9.0 * @link https://github.com/skylark-integration/dojox/ * @license MIT */ define({descTemplate:"${2} - ${3} di ${1} ${0}",firstTip:"Prima pagina",lastTip:"Ultima pagina",nextTip:"Pagina successiva",prevTip:"Pagina precedente",itemTitle:"elementi",singularItemTitle:"elemento",pageStepLabelTemplate:"Pagina ${0}",pageSizeLabelTemplate:"${0} elementi per pagina",allItemsLabelTemplate:"Tutti gli elementi",gotoButtonTitle:"Vai a pagina specifica",dialogTitle:"Vai a pagina",dialogIndication:"Specifica numero pagina",pageCountIndication:" (${0} pagine)",dialogConfirm:"Vai",dialogCancel:"Annulla",all:"Tutto"}); //# sourceMappingURL=../../../../sourcemaps/grid/enhanced/nls/it/Pagination.js.map
liexusong/fuchsia
garnet/examples/intl/wisdom/tests/intl_wisdom_test.cc
<filename>garnet/examples/intl/wisdom/tests/intl_wisdom_test.cc // Copyright 2018 The Fuchsia 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 <lib/fdio/directory.h> #include <lib/fdio/fd.h> #include <lib/fdio/fdio.h> #include <lib/sys/cpp/file_descriptor.h> #include <lib/sys/cpp/testing/test_with_environment.h> #include <stdint.h> #include <stdio.h> #include <unistd.h> #include <fstream> #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "src/lib/files/file.h" #include "src/lib/files/scoped_temp_dir.h" namespace intl_wisdom { using fuchsia::sys::ComponentControllerPtr; using fuchsia::sys::LaunchInfo; using sys::testing::TestWithEnvironment; // The C++ version of the wisdom client-server example. constexpr char kIntlWisdomClientPackage[] = "fuchsia-pkg://fuchsia.com/intl_wisdom#meta/intl_wisdom_client.cmx"; // The Rust version of the wisdom client-server example. constexpr char kIntlWisdomClientRustPackage[] = "fuchsia-pkg://fuchsia.com/intl_wisdom_rust#meta/intl_wisdom_client_rust.cmx"; // Integration test for IntlWisdomClient and IntlWisdomServer. // // Starts a client, which starts a server and asks it for wisdom. Compares the // entire STDOUT output of the client (including the server's response) to an // expected output file. class IntlWisdomTest : public TestWithEnvironment { protected: void SetUp() override { TestWithEnvironment::SetUp(); OpenNewOutFiles(); } void TearDown() override { CloseOutFiles(); TestWithEnvironment::TearDown(); } void OpenNewOutFiles() { ASSERT_TRUE(temp_dir_.NewTempFile(&out_file_path_)); out_file_ = std::fopen(out_file_path_.c_str(), "w"); ASSERT_TRUE(temp_dir_.NewTempFile(&err_file_path_)); err_file_ = std::fopen(err_file_path_.c_str(), "w"); } void CloseOutFiles() { if (out_file_ != nullptr) { std::fclose(out_file_); } if (err_file_ != nullptr) { std::fclose(err_file_); } } // Read the contents of the file at |path| into |contents|. static void ReadFile(const std::string& path, std::string& contents) { ASSERT_TRUE(files::ReadFileToString(path, &contents)) << "Could not read file " << path; } ComponentControllerPtr LaunchClientWithServer(const std::string& url) { LaunchInfo launch_info{ .url = url, .out = sys::CloneFileDescriptor(fileno(out_file_)), .err = sys::CloneFileDescriptor(fileno(err_file_)), .arguments = std::vector<std::string>({ "--timestamp=2018-11-01T12:34:56Z", "--timezone=America/Los_Angeles", }), }; ComponentControllerPtr controller; CreateComponentInCurrentEnvironment(std::move(launch_info), controller.NewRequest()); return controller; } const std::string& out_file_path() const { return out_file_path_; } const std::string& err_file_path() const { return err_file_path_; } // Syncs the files used for recording stdout and stderr. void SyncWrites() { fsync(fileno(out_file_)); fsync(fileno(err_file_)); } void RunWisdomClientAndServer(const std::string& package_url) { std::string expected_output; IntlWisdomTest::ReadFile("/pkg/data/golden-output.txt", expected_output); ComponentControllerPtr controller = LaunchClientWithServer(package_url); ASSERT_TRUE(RunComponentUntilTerminated(std::move(controller), nullptr)); // Ensures that the data we just wrote is available for subsequent reading // in the assertions. Not doing so can result in assertions not seeing // the just-written content. SyncWrites(); std::string actual_output; ReadFile(out_file_path(), actual_output); std::string stderr_output; ReadFile(err_file_path(), stderr_output); ASSERT_EQ(actual_output, expected_output) << "stdout:\n" << actual_output << "\n:stderr:\n" << stderr_output; } private: files::ScopedTempDir temp_dir_; std::string out_file_path_; std::string err_file_path_; FILE* out_file_ = nullptr; FILE* err_file_ = nullptr; }; TEST_F(IntlWisdomTest, RunWisdomClientAndServerCPP) { RunWisdomClientAndServer(kIntlWisdomClientPackage); } TEST_F(IntlWisdomTest, RunWisdomClientAndServerRust) { RunWisdomClientAndServer(kIntlWisdomClientRustPackage); } } // namespace intl_wisdom
wstong999/AliOS-Things
components/drivers/peripheral/adc/src/adc_dev.c
<reponame>wstong999/AliOS-Things /* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <poll.h> #include <aos/hal/adc.h> #include <vfsdev/adc_dev.h> #include <devicevfs/devicevfs.h> #ifdef CONFIG_ADC_NUM #define PLATFORM_ADC_NUM CONFIG_ADC_NUM #else #define PLATFORM_ADC_NUM 4 #endif #if (PLATFORM_ADC_NUM > 0) // ADC device node will be named with "/dev/adc<x>", where <x> is adc port id #define ADC_DEV_NAME_FORMAT "adc%d" typedef struct vfs_adc { int ref_cnt; adc_dev_t dev; } vfs_adc_t; int adc_device_ioctl (file_t *f, int cmd, unsigned long arg) { int ret = 0; io_adc_arg_t adc_arg; io_adc_arg_t *p_adc_arg = NULL; char *fname = f->node->i_name; vfs_adc_t *vd = (vfs_adc_t *)f->node->i_arg; adc_dev_t *adc_dev = &vd->dev; // arg is channel info ddkc_dbg("cmd:0x%x, arg:0x%lx\r\n", cmd, arg); switch (cmd) { case IOC_ADC_GET_VALUE: p_adc_arg = (io_adc_arg_t *)arg; BUG_ON_MSG(!p_adc_arg, "IOC_ADC_GET_VALUE - arg should not be NULL\r\n"); /* copy timeout config from user */ aos_ipc_copy(&adc_arg, p_adc_arg, sizeof(io_adc_arg_t)); ret = hal_adc_value_get(adc_dev, &adc_arg.value, adc_arg.timeout); /* copy value back to user */ aos_ipc_copy(p_adc_arg, &adc_arg, sizeof(io_adc_arg_t)); ddkc_info("IOC_ADC_GET_VALUE, adc_arg.value:%d, ret:%d\r\n", adc_arg.value, ret); break; case IOC_ADC_START: ddkc_dbg("IOC_ADC_START, arg:%ld\r\n", arg); adc_dev->config.sampling_cycle = arg; ret = vd->ref_cnt ? 0 : hal_adc_init(adc_dev); if (ret) { ddkc_err("%s starts failed, port:%d, ref_cnt:%d\r\n", fname, adc_dev->port, vd->ref_cnt); } else { vd->ref_cnt++; ddkc_dbg("%s starts success, port:%d, ref_cnt:%d\r\n", fname, adc_dev->port, vd->ref_cnt); } break; case IOC_ADC_STOP: vd->ref_cnt--; ret = vd->ref_cnt ? 0 : hal_adc_finalize(adc_dev); if (ret) { ddkc_err("%s stop failed, port:%d\r\n", fname, adc_dev->port); } else { ddkc_dbg("%s stop success, port:%d\r\n", fname, adc_dev->port); } break; default: ddkc_err("invalid cmd:%d\r\n", cmd); break; } return ret; } int adc_device_open (inode_t *node, file_t *f) { ddkc_info("device:%s open succeed\r\n", node->i_name); return 0; } int adc_device_close (file_t *f) { ddkc_info("device:%s close succeed\r\n", f->node->i_name); return 0; } /************************** device ****************************/ subsys_file_ops_t adc_device_fops = { .open = adc_device_open, .close = adc_device_close, .read = NULL, .write = NULL, .ioctl = adc_device_ioctl, .poll = NULL, }; int adc_device_init (struct u_platform_device *pdev) { // make sure 0 is returned if init operation success // or aos_dev_reg procedure will break and no device node will be registered ddkc_dbg("%s\r\n", __func__); return 0; } int adc_device_deinit (struct u_platform_device *pdev) { ddkc_dbg("%s\r\n", __func__); return 0; } int adc_device_pm (struct u_platform_device *pdev, u_pm_ops_t state) { ddkc_dbg("%s\r\n", __func__); return 0; } struct subsys_drv adc_device_drv = { .drv_name = "adc", .init = adc_device_init, .deinit = adc_device_deinit, .pm = adc_device_pm, }; struct subsys_dev *g_adc_device_array[PLATFORM_ADC_NUM]; int vfs_adc_drv_init (void) { int i = 0; int j = 0; int ret = 0; int node_name_len = 0; struct subsys_dev **ppsdev = NULL; ddkc_dbg("adc vfs driver init starts\r\n"); node_name_len = strlen(ADC_DEV_NAME_FORMAT) + 1; memset(g_adc_device_array, 0, sizeof(g_adc_device_array)); ppsdev = g_adc_device_array; for (i = 0; i < PLATFORM_ADC_NUM; i++) { vfs_adc_t *vd = malloc(sizeof(vfs_adc_t)); *ppsdev = malloc(sizeof(struct subsys_dev) + node_name_len); if (!(*ppsdev) || !vd) { ddkc_err("malloc failed, *ppsdev:%p, vd:%p\r\n", *ppsdev, vd); if (*ppsdev) { free(*ppsdev); *ppsdev = NULL; } if (vd) free(vd); goto err; } memset(*ppsdev, 0, sizeof(struct subsys_dev) + node_name_len); memset(vd, 0, sizeof(*vd)); // vfs_adc_t's port should be remained during the whole driver life vd->dev.port = i; (*ppsdev)->node_name = (char *)((*ppsdev) + 1); snprintf((*ppsdev)->node_name, node_name_len, ADC_DEV_NAME_FORMAT, i); ddkc_dbg("*ppsdev:%p, node_name:%s, (*ppsdev) + 1:%p, sizeof(struct subsys_dev):%d\r\n", *ppsdev, (*ppsdev)->node_name, (*ppsdev) + 1, sizeof(struct subsys_dev)); (*ppsdev)->permission = 0; // please refer to definitions in enum SUBSYS_BUS_TYPE (*ppsdev)->type = BUS_TYPE_PLATFORM; // user_data will be passed to open operation via node->i_arg (*ppsdev)->user_data = vd; ret = aos_dev_reg(*ppsdev, &adc_device_fops, &adc_device_drv); if (ret) { ddkc_err("aos_dev_reg for adc%d failed, ret:%d\r\n", i, ret); free(vd); free(*ppsdev); *ppsdev = NULL; goto err; } ppsdev++; } ddkc_dbg("adc vfs driver init finish, ret:%d\r\n", ret); return 0; err: ppsdev = g_adc_device_array; for (j = 0; j < i; j++) { // shall uninstall adc devices who are already registered if (*ppsdev) { aos_dev_unreg(*ppsdev); ddkc_info("free memory for adc%d\r\n", j); if ((*ppsdev)->user_data) free((*ppsdev)->user_data); free(*ppsdev); *ppsdev = NULL; } ppsdev++; } ddkc_err("adc vfs driver init failed, ret:%d\r\n", ret); return ret; } VFS_DRIVER_ENTRY(vfs_adc_drv_init) #endif
FRED5DON/KiwiVMWare
app/src/main/java/com/freddon/android/app/kiwivmware/tools/GsonUtils.java
package com.freddon.android.app.kiwivmware.tools; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import java.lang.reflect.Type; import java.util.Collection; /** * Created by fred on 2016/11/7. */ public class GsonUtils { public static <T> T parseJson(String str, Type type) { Gson gson = new Gson(); return gson.fromJson(str, type); } public static <T> T parseJson(String str, Class<T> type) { Gson gson = new Gson(); return gson.fromJson(str, type); } /** * 对象转换成json字符串 * * @param obj * @return */ public static String toJson(Object obj) { try { Gson gson = new Gson(); return gson.toJson(obj); } catch (Exception e) { return ""; } } public static JSONArray toJsonArray(Collection collection) { try { return new JSONArray(GsonUtils.toJson(collection)); } catch (JSONException e) { } return new JSONArray(); } }
JINSCOP/PConnect
pconnect-springcloud/bizsrvs/pconnect-todo/src/main/java/cn/bgenius/pconnect/todo/mapper/TTodoesStatusEnumMapper.java
package cn.bgenius.pconnect.todo.mapper; import cn.bgenius.pconnect.todo.entity.TTodoesStatusEnum; import tk.mybatis.mapper.common.Mapper; public interface TTodoesStatusEnumMapper extends Mapper<TTodoesStatusEnum> { }
ans-hub/wumpus_game
src/gui/widgets/widget_room.h
<reponame>ans-hub/wumpus_game // Package: wumpus_game (v0.9) // Description: https://github.com/ans-hub/wumpus_game // Author: <NAME>, 2017 // File: control widget represents interactive rooms on game the map #ifndef WIDGET_ROOM_H #define WIDGET_ROOM_H #include <map> #include <FL/Fl.H> #include <FL/Fl_PNG_Image.H> #include <FL/Fl_Button.H> #include "gui/images.h" #include "enums/enums.h" namespace wumpus_game { struct WidgetRoom : Fl_Button { using State = RoomState; using StateMap = std::map<State,Fl_Image*>; WidgetRoom(int num, int level, Images& images, int x, int y, int w, int h) : Fl_Button(x, y, w, h) , num_{num} , level_{level} , marked_{value() ? true : false} , locked_{false} , images_{} { images_[State::DARK] = images.GetRoomImage(State::DARK, level_); images_[State::LIGHT] = images.GetRoomImage(State::LIGHT, level_); images_[State::GATE] = images.GetRoomImage(State::GATE, level_); images_[State::GUIDE_OPENED] = images.GetRoomImage(State::GUIDE_OPENED, level_); images_[State::GUIDE_CLOSED] = images.GetRoomImage(State::GUIDE_CLOSED, level_); SetImage(State::DARK); SetDeimage(State::GATE); box(FL_NO_BOX); } int GetNum() const { return num_; } void SetImage(State state) { if (!locked_) image(images_[state]); } void SetDeimage(State state) { if (!locked_) deimage(images_[state]); } void SwitchOn() { value(1); } void SwitchOff() { value(0); } void LockImage() { locked_ = true; } void UnlockImage() { locked_ = false; } bool IsLockedImage() { return locked_; } private: int num_; int level_; bool marked_; bool locked_; StateMap images_; int handle(int) override; }; // Handle event on widget, used for determine event of middle button. // Other events such as right and left btn click is deteremine in controller // by callback function inline int WidgetRoom::handle(int event) { switch(event) { case FL_PUSH : if (Fl::event_button() == FL_MIDDLE_MOUSE && !locked_) { if (marked_) SetImage(State::DARK); else SetImage(State::LIGHT); marked_ = !marked_; } redraw(); do_callback(); Fl::pushed(nullptr); return Fl_Widget::handle(event); default : return Fl_Widget::handle(event); } } } // namespace wumpus_game #endif // WIDGET_ROOM_H
wiseants/Varins
Unmanaged/HVisionSystem/include/Utility/Rotate.h
<gh_stars>0 // Rotate.h: interface for the CRotate class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_ROTATE_H__A188B40D_51C5_43D1_8AC3_1E5E4D957337__INCLUDED_) #define AFX_ROTATE_H__A188B40D_51C5_43D1_8AC3_1E5E4D957337__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "UtilityClass.h" #include "dblPoint.h" #include "dblSize.h" #include "dblRect.h" UTILITYCLASS void Rotate(long& x, long& y, double angle); UTILITYCLASS void Rotate(double& x, double& y, double angle); UTILITYCLASS void Rotate(CdblPoint& point, double angle); UTILITYCLASS void Rotate(CdblPoint& point, CdblPoint ptCenter, double angle); UTILITYCLASS void Rotate(CPoint& point, double angle); UTILITYCLASS void Rotate(CPoint& point, CPoint ptCenter, double angle); UTILITYCLASS void Rotate(CdblSize& size, double angle); UTILITYCLASS void Rotate(CSize& size, double angle); UTILITYCLASS void Rotate(CdblRect& rect, double angle); UTILITYCLASS void Rotate(CdblRect& rect, const CdblPoint& centerPt, double angle); UTILITYCLASS void Rotate(CRect& rect, double angle); UTILITYCLASS void Rotate(CRect& rect, const CPoint& centerPt, double angle); UTILITYCLASS void Rotate(CRect& rect, CRect& rectParent, double angle); UTILITYCLASS void Rotate(CdblRect rect, double angle, CdblPoint pt[4]); UTILITYCLASS void Rotate(CdblRect rect, double angle, CPoint pt[4]); UTILITYCLASS void Rotate(CdblRect rect, CdblPoint centerPt, double angle, CdblPoint pt[4]); UTILITYCLASS void Rotate(CRect rect, CPoint centerPt, double angle, CPoint pt[4]); UTILITYCLASS CdblRect GetRealRect(const CdblRect& srcRect, double angle); UTILITYCLASS CRect GetRealRect(const CRect& srcRect, double angle); UTILITYCLASS BOOL IsRectAvailable(double angle); UTILITYCLASS void Rotate(CRect rect, double angle, CPoint pt[4]); UTILITYCLASS void RotateOffset(CdblRect& rect, const CdblPoint& centerPt, long angle); UTILITYCLASS void RotateOffset(CRect& rect, const CPoint& centerPt, long angle); #endif // !defined(AFX_ROTATE_H__A188B40D_51C5_43D1_8AC3_1E5E4D957337__INCLUDED_)
duranfatih/hmc-hmi-inbound-adapter
src/main/java/uk/gov/hmcts/reform/hmc/client/model/hmi/HearingDetailsRequest.java
package uk.gov.hmcts.reform.hmc.client.model.hmi; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.Valid; @Data @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class HearingDetailsRequest { @Valid private HearingResponse hearingResponse; @JsonProperty("err") @Valid private ErrorDetails errorDetails; }
sho25/karaf
bundle/core/src/main/java/org/apache/karaf/bundle/command/Headers.java
<reponame>sho25/karaf<gh_stars>0 begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|bundle operator|. name|command package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Comparator import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Dictionary import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Enumeration import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Iterator import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|TreeMap import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|felix operator|. name|utils operator|. name|manifest operator|. name|Attribute import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|felix operator|. name|utils operator|. name|manifest operator|. name|Clause import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|felix operator|. name|utils operator|. name|manifest operator|. name|Directive import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|felix operator|. name|utils operator|. name|manifest operator|. name|Parser import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|felix operator|. name|utils operator|. name|version operator|. name|VersionRange import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|felix operator|. name|utils operator|. name|version operator|. name|VersionTable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|api operator|. name|action operator|. name|Command import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|api operator|. name|action operator|. name|Option import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|api operator|. name|action operator|. name|lifecycle operator|. name|Reference import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|api operator|. name|action operator|. name|lifecycle operator|. name|Service import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|api operator|. name|console operator|. name|Terminal import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|support operator|. name|ShellUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|support operator|. name|ansi operator|. name|SimpleAnsi import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|Bundle import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|Constants import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|wiring operator|. name|BundleCapability import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|wiring operator|. name|BundleRevision import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|wiring operator|. name|BundleWiring import|; end_import begin_class annotation|@ name|Command argument_list|( name|scope operator|= literal|"bundle" argument_list|, name|name operator|= literal|"headers" argument_list|, name|description operator|= literal|"Displays OSGi headers of a given bundles." argument_list|) annotation|@ name|Service specifier|public class|class name|Headers extends|extends name|BundlesCommand block|{ specifier|protected specifier|final specifier|static name|String name|KARAF_PREFIX init|= literal|"Karaf-" decl_stmt|; specifier|protected specifier|final specifier|static name|String name|BUNDLE_PREFIX init|= literal|"Bundle-" decl_stmt|; specifier|protected specifier|final specifier|static name|String name|PACKAGE_SUFFFIX init|= literal|"-Package" decl_stmt|; specifier|protected specifier|final specifier|static name|String name|SERVICE_SUFFIX init|= literal|"-Service" decl_stmt|; specifier|protected specifier|final specifier|static name|String name|CAPABILITY_SUFFIX init|= literal|"-Capability" decl_stmt|; specifier|protected specifier|final specifier|static name|String name|IMPORT_PACKAGES_ATTRIB init|= literal|"Import-Package" decl_stmt|; specifier|protected specifier|final specifier|static name|String name|REQUIRE_BUNDLE_ATTRIB init|= literal|"Require-Bundle" decl_stmt|; annotation|@ name|Option argument_list|( name|name operator|= literal|"--indent" argument_list|, name|description operator|= literal|"Indentation method" argument_list|) name|int name|indent init|= operator|- literal|1 decl_stmt|; annotation|@ name|Option argument_list|( name|name operator|= literal|"--no-uses" argument_list|, name|description operator|= literal|"Print or not the Export-Package uses section" argument_list|) name|boolean name|noUses init|= literal|false decl_stmt|; annotation|@ name|Reference argument_list|( name|optional operator|= literal|true argument_list|) name|Terminal name|terminal decl_stmt|; annotation|@ name|Override specifier|protected name|void name|executeOnBundle parameter_list|( name|Bundle name|bundle parameter_list|) throws|throws name|Exception block|{ name|String name|title init|= name|ShellUtil operator|. name|getBundleName argument_list|( name|bundle argument_list|) decl_stmt|; name|System operator|. name|out operator|. name|println argument_list|( literal|"\n" operator|+ name|title argument_list|) expr_stmt|; name|System operator|. name|out operator|. name|println argument_list|( name|ShellUtil operator|. name|getUnderlineString argument_list|( name|title argument_list|) argument_list|) expr_stmt|; if|if condition|( name|indent operator|== literal|0 condition|) block|{ name|Dictionary argument_list|< name|String argument_list|, name|String argument_list|> name|dict init|= name|bundle operator|. name|getHeaders argument_list|() decl_stmt|; name|Enumeration argument_list|< name|String argument_list|> name|keys init|= name|dict operator|. name|keys argument_list|() decl_stmt|; while|while condition|( name|keys operator|. name|hasMoreElements argument_list|() condition|) block|{ name|Object name|k init|= name|keys operator|. name|nextElement argument_list|() decl_stmt|; name|Object name|v init|= name|dict operator|. name|get argument_list|( name|k argument_list|) decl_stmt|; name|System operator|. name|out operator|. name|println argument_list|( name|k operator|+ literal|" = " operator|+ name|ShellUtil operator|. name|getValueString argument_list|( name|v argument_list|) argument_list|) expr_stmt|; block|} block|} else|else block|{ name|System operator|. name|out operator|. name|println argument_list|( name|generateFormattedOutput argument_list|( name|bundle argument_list|) argument_list|) expr_stmt|; block|} block|} specifier|protected name|String name|generateFormattedOutput parameter_list|( name|Bundle name|bundle parameter_list|) block|{ name|StringBuilder name|output init|= operator|new name|StringBuilder argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|Object argument_list|> name|otherAttribs init|= operator|new name|TreeMap argument_list|<> argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|Object argument_list|> name|karafAttribs init|= operator|new name|TreeMap argument_list|<> argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|Object argument_list|> name|bundleAttribs init|= operator|new name|TreeMap argument_list|<> argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|Object argument_list|> name|serviceAttribs init|= operator|new name|TreeMap argument_list|<> argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|Object argument_list|> name|packagesAttribs init|= operator|new name|TreeMap argument_list|<> argument_list|() decl_stmt|; name|Dictionary argument_list|< name|String argument_list|, name|String argument_list|> name|dict init|= name|bundle operator|. name|getHeaders argument_list|() decl_stmt|; name|Enumeration argument_list|< name|String argument_list|> name|keys init|= name|dict operator|. name|keys argument_list|() decl_stmt|; comment|// do an initial loop and separate the attributes in different groups while|while condition|( name|keys operator|. name|hasMoreElements argument_list|() condition|) block|{ name|String name|k init|= name|keys operator|. name|nextElement argument_list|() decl_stmt|; name|Object name|v init|= name|dict operator|. name|get argument_list|( name|k argument_list|) decl_stmt|; if|if condition|( name|k operator|. name|startsWith argument_list|( name|KARAF_PREFIX argument_list|) condition|) block|{ comment|// starts with Karaf-xxx name|karafAttribs operator|. name|put argument_list|( name|k argument_list|, name|v argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|k operator|. name|startsWith argument_list|( name|BUNDLE_PREFIX argument_list|) condition|) block|{ comment|// starts with Bundle-xxx name|bundleAttribs operator|. name|put argument_list|( name|k argument_list|, name|v argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|k operator|. name|endsWith argument_list|( name|SERVICE_SUFFIX argument_list|) operator||| name|k operator|. name|endsWith argument_list|( name|CAPABILITY_SUFFIX argument_list|) condition|) block|{ comment|// ends with xxx-Service name|serviceAttribs operator|. name|put argument_list|( name|k argument_list|, name|v argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|k operator|. name|endsWith argument_list|( name|PACKAGE_SUFFFIX argument_list|) condition|) block|{ comment|// ends with xxx-Package name|packagesAttribs operator|. name|put argument_list|( name|k argument_list|, name|v argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|k operator|. name|endsWith argument_list|( name|REQUIRE_BUNDLE_ATTRIB argument_list|) condition|) block|{ comment|// require bundle statement name|packagesAttribs operator|. name|put argument_list|( name|k argument_list|, name|v argument_list|) expr_stmt|; block|} else|else block|{ comment|// the remaining attribs name|otherAttribs operator|. name|put argument_list|( name|k argument_list|, name|v argument_list|) expr_stmt|; block|} block|} comment|// we will display the formatted result like this: comment|// Bundle-Name (ID) comment|// ----------------------- comment|// all other attributes comment|// comment|// all Karaf attributes comment|// comment|// all Bundle attributes comment|// comment|// all Service attributes comment|// comment|// all Package attributes name|Iterator argument_list|< name|Map operator|. name|Entry argument_list|< name|String argument_list|, name|Object argument_list|> argument_list|> name|it init|= name|otherAttribs operator|. name|entrySet argument_list|() operator|. name|iterator argument_list|() decl_stmt|; while|while condition|( name|it operator|. name|hasNext argument_list|() condition|) block|{ name|Map operator|. name|Entry argument_list|< name|String argument_list|, name|Object argument_list|> name|e init|= name|it operator|. name|next argument_list|() decl_stmt|; name|output operator|. name|append argument_list|( name|String operator|. name|format argument_list|( literal|"%s = %s\n" argument_list|, name|e operator|. name|getKey argument_list|() argument_list|, name|ShellUtil operator|. name|getValueString argument_list|( name|e operator|. name|getValue argument_list|() argument_list|) argument_list|) argument_list|) expr_stmt|; block|} if|if condition|( name|otherAttribs operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ name|output operator|. name|append argument_list|( literal|'\n' argument_list|) expr_stmt|; block|} name|it operator|= name|karafAttribs operator|. name|entrySet argument_list|() operator|. name|iterator argument_list|() expr_stmt|; while|while condition|( name|it operator|. name|hasNext argument_list|() condition|) block|{ name|Map operator|. name|Entry argument_list|< name|String argument_list|, name|Object argument_list|> name|e init|= name|it operator|. name|next argument_list|() decl_stmt|; name|output operator|. name|append argument_list|( name|String operator|. name|format argument_list|( literal|"%s = %s\n" argument_list|, name|e operator|. name|getKey argument_list|() argument_list|, name|ShellUtil operator|. name|getValueString argument_list|( name|e operator|. name|getValue argument_list|() argument_list|) argument_list|) argument_list|) expr_stmt|; block|} if|if condition|( name|karafAttribs operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ name|output operator|. name|append argument_list|( literal|'\n' argument_list|) expr_stmt|; block|} name|it operator|= name|bundleAttribs operator|. name|entrySet argument_list|() operator|. name|iterator argument_list|() expr_stmt|; while|while condition|( name|it operator|. name|hasNext argument_list|() condition|) block|{ name|Map operator|. name|Entry argument_list|< name|String argument_list|, name|Object argument_list|> name|e init|= name|it operator|. name|next argument_list|() decl_stmt|; name|output operator|. name|append argument_list|( name|String operator|. name|format argument_list|( literal|"%s = %s\n" argument_list|, name|e operator|. name|getKey argument_list|() argument_list|, name|ShellUtil operator|. name|getValueString argument_list|( name|e operator|. name|getValue argument_list|() argument_list|) argument_list|) argument_list|) expr_stmt|; block|} if|if condition|( name|bundleAttribs operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ name|output operator|. name|append argument_list|( literal|'\n' argument_list|) expr_stmt|; block|} name|it operator|= name|serviceAttribs operator|. name|entrySet argument_list|() operator|. name|iterator argument_list|() expr_stmt|; while|while condition|( name|it operator|. name|hasNext argument_list|() condition|) block|{ name|Map operator|. name|Entry argument_list|< name|String argument_list|, name|Object argument_list|> name|e init|= name|it operator|. name|next argument_list|() decl_stmt|; name|output operator|. name|append argument_list|( name|e operator|. name|getKey argument_list|() argument_list|) expr_stmt|; name|output operator|. name|append argument_list|( literal|" = \n" argument_list|) expr_stmt|; name|formatHeader argument_list|( name|ShellUtil operator|. name|getValueString argument_list|( name|e operator|. name|getValue argument_list|() argument_list|) argument_list|, literal|null argument_list|, name|output argument_list|, name|indent argument_list|) expr_stmt|; name|output operator|. name|append argument_list|( literal|"\n" argument_list|) expr_stmt|; block|} if|if condition|( name|serviceAttribs operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ name|output operator|. name|append argument_list|( literal|'\n' argument_list|) expr_stmt|; block|} name|Map argument_list|< name|String argument_list|, name|ClauseFormatter argument_list|> name|formatters init|= operator|new name|HashMap argument_list|<> argument_list|() decl_stmt|; name|formatters operator|. name|put argument_list|( name|REQUIRE_BUNDLE_ATTRIB argument_list|, operator|new name|ClauseFormatter argument_list|() block|{ specifier|public name|void name|pre parameter_list|( name|Clause name|clause parameter_list|, name|StringBuilder name|output parameter_list|) block|{ name|boolean name|isSatisfied init|= name|checkBundle argument_list|( name|clause operator|. name|getName argument_list|() argument_list|, name|clause operator|. name|getAttribute argument_list|( literal|"bundle-version" argument_list|) argument_list|) decl_stmt|; name|output operator|. name|append argument_list|( name|isSatisfied condition|? name|SimpleAnsi operator|. name|COLOR_DEFAULT else|: name|SimpleAnsi operator|. name|COLOR_RED argument_list|) expr_stmt|; block|} specifier|public name|void name|post parameter_list|( name|Clause name|clause parameter_list|, name|StringBuilder name|output parameter_list|) block|{ name|output operator|. name|append argument_list|( name|SimpleAnsi operator|. name|RESET argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; name|formatters operator|. name|put argument_list|( name|IMPORT_PACKAGES_ATTRIB argument_list|, operator|new name|ClauseFormatter argument_list|() block|{ specifier|public name|void name|pre parameter_list|( name|Clause name|clause parameter_list|, name|StringBuilder name|output parameter_list|) block|{ name|boolean name|isSatisfied init|= name|checkPackage argument_list|( name|clause operator|. name|getName argument_list|() argument_list|, name|clause operator|. name|getAttribute argument_list|( literal|"version" argument_list|) argument_list|) decl_stmt|; name|boolean name|isOptional init|= literal|"optional" operator|. name|equals argument_list|( name|clause operator|. name|getDirective argument_list|( literal|"resolution" argument_list|) argument_list|) decl_stmt|; name|output operator|. name|append argument_list|( name|isSatisfied condition|? name|SimpleAnsi operator|. name|COLOR_DEFAULT else|: name|SimpleAnsi operator|. name|COLOR_RED argument_list|) expr_stmt|; name|output operator|. name|append argument_list|( name|isSatisfied operator||| name|isOptional condition|? name|SimpleAnsi operator|. name|INTENSITY_NORMAL else|: name|SimpleAnsi operator|. name|INTENSITY_BOLD argument_list|) expr_stmt|; block|} specifier|public name|void name|post parameter_list|( name|Clause name|clause parameter_list|, name|StringBuilder name|output parameter_list|) block|{ name|output operator|. name|append argument_list|( name|SimpleAnsi operator|. name|RESET argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; name|it operator|= name|packagesAttribs operator|. name|entrySet argument_list|() operator|. name|iterator argument_list|() expr_stmt|; while|while condition|( name|it operator|. name|hasNext argument_list|() condition|) block|{ name|Map operator|. name|Entry argument_list|< name|String argument_list|, name|Object argument_list|> name|e init|= name|it operator|. name|next argument_list|() decl_stmt|; name|output operator|. name|append argument_list|( name|e operator|. name|getKey argument_list|() argument_list|) expr_stmt|; name|output operator|. name|append argument_list|( literal|" = \n" argument_list|) expr_stmt|; name|formatHeader argument_list|( name|ShellUtil operator|. name|getValueString argument_list|( name|e operator|. name|getValue argument_list|() argument_list|) argument_list|, name|formatters operator|. name|get argument_list|( name|e operator|. name|getKey argument_list|() argument_list|) argument_list|, name|output argument_list|, name|indent argument_list|) expr_stmt|; name|output operator|. name|append argument_list|( literal|"\n" argument_list|) expr_stmt|; block|} if|if condition|( name|packagesAttribs operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ name|output operator|. name|append argument_list|( literal|'\n' argument_list|) expr_stmt|; block|} return|return name|output operator|. name|toString argument_list|() return|; block|} specifier|protected interface|interface name|ClauseFormatter block|{ name|void name|pre parameter_list|( name|Clause name|clause parameter_list|, name|StringBuilder name|output parameter_list|) function_decl|; name|void name|post parameter_list|( name|Clause name|clause parameter_list|, name|StringBuilder name|output parameter_list|) function_decl|; block|} specifier|protected name|void name|formatHeader parameter_list|( name|String name|header parameter_list|, name|ClauseFormatter name|formatter parameter_list|, name|StringBuilder name|builder parameter_list|, name|int name|indent parameter_list|) block|{ name|Clause index|[] name|clauses init|= name|Parser operator|. name|parseHeader argument_list|( name|header argument_list|) decl_stmt|; name|formatClauses argument_list|( name|clauses argument_list|, name|formatter argument_list|, name|builder argument_list|, name|indent argument_list|) expr_stmt|; block|} specifier|protected name|void name|formatClauses parameter_list|( name|Clause index|[] name|clauses parameter_list|, name|ClauseFormatter name|formatter parameter_list|, name|StringBuilder name|builder parameter_list|, name|int name|indent parameter_list|) block|{ name|boolean name|first init|= literal|true decl_stmt|; for|for control|( name|Clause name|clause range|: name|clauses control|) block|{ if|if condition|( name|first condition|) block|{ name|first operator|= literal|false expr_stmt|; block|} else|else block|{ name|builder operator|. name|append argument_list|( literal|",\n" argument_list|) expr_stmt|; block|} name|formatClause argument_list|( name|clause argument_list|, name|formatter argument_list|, name|builder argument_list|, name|indent argument_list|) expr_stmt|; block|} block|} specifier|protected name|void name|formatClause parameter_list|( name|Clause name|clause parameter_list|, name|ClauseFormatter name|formatter parameter_list|, name|StringBuilder name|builder parameter_list|, name|int name|indent parameter_list|) block|{ name|builder operator|. name|append argument_list|( literal|"\t" argument_list|) expr_stmt|; if|if condition|( name|formatter operator|!= literal|null condition|) block|{ name|formatter operator|. name|pre argument_list|( name|clause argument_list|, name|builder argument_list|) expr_stmt|; block|} name|formatClause argument_list|( name|clause argument_list|, name|builder argument_list|, name|indent argument_list|) expr_stmt|; if|if condition|( name|formatter operator|!= literal|null condition|) block|{ name|formatter operator|. name|post argument_list|( name|clause argument_list|, name|builder argument_list|) expr_stmt|; block|} block|} specifier|protected name|int name|getTermWidth parameter_list|() block|{ return|return name|terminal operator|!= literal|null condition|? name|terminal operator|. name|getWidth argument_list|() else|: literal|0 return|; block|} specifier|protected name|void name|formatClause parameter_list|( name|Clause name|clause parameter_list|, name|StringBuilder name|builder parameter_list|, name|int name|indent parameter_list|) block|{ if|if condition|( name|indent operator|< literal|0 condition|) block|{ if|if condition|( name|clause operator|. name|toString argument_list|() operator|. name|length argument_list|() operator|< name|getTermWidth argument_list|() operator|- literal|8 condition|) block|{ comment|// -8 for tabs name|indent operator|= literal|1 expr_stmt|; block|} else|else block|{ name|indent operator|= literal|3 expr_stmt|; block|} block|} name|String name|name init|= name|clause operator|. name|getName argument_list|() decl_stmt|; name|Directive index|[] name|directives init|= name|clause operator|. name|getDirectives argument_list|() decl_stmt|; name|Attribute index|[] name|attributes init|= name|clause operator|. name|getAttributes argument_list|() decl_stmt|; name|Arrays operator|. name|sort argument_list|( name|directives argument_list|, name|Comparator operator|. name|comparing argument_list|( name|Directive operator|:: name|getName argument_list|) argument_list|) expr_stmt|; name|Arrays operator|. name|sort argument_list|( name|attributes argument_list|, name|Comparator operator|. name|comparing argument_list|( name|Attribute operator|:: name|getName argument_list|) argument_list|) expr_stmt|; name|builder operator|. name|append argument_list|( name|name argument_list|) expr_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|directives operator|!= literal|null operator|&& name|i operator|< name|directives operator|. name|length condition|; name|i operator|++ control|) block|{ if|if condition|( name|noUses operator|&& name|directives index|[ name|i index|] operator|. name|getName argument_list|() operator|. name|equalsIgnoreCase argument_list|( literal|"uses" argument_list|) condition|) block|{ continue|continue; block|} name|builder operator|. name|append argument_list|( literal|";" argument_list|) expr_stmt|; if|if condition|( name|indent operator|> literal|1 condition|) block|{ name|builder operator|. name|append argument_list|( literal|"\n\t\t" argument_list|) expr_stmt|; block|} name|builder operator|. name|append argument_list|( name|directives index|[ name|i index|] operator|. name|getName argument_list|() argument_list|) operator|. name|append argument_list|( literal|":=" argument_list|) expr_stmt|; name|String name|v init|= name|directives index|[ name|i index|] operator|. name|getValue argument_list|() decl_stmt|; if|if condition|( name|v operator|. name|contains argument_list|( literal|"," argument_list|) condition|) block|{ if|if condition|( name|indent operator|> literal|2 operator|&& name|v operator|. name|length argument_list|() operator|> literal|20 condition|) block|{ name|v operator|= name|v operator|. name|replace argument_list|( literal|"," argument_list|, literal|",\n\t\t\t" argument_list|) expr_stmt|; block|} name|builder operator|. name|append argument_list|( literal|"\"" argument_list|) operator|. name|append argument_list|( name|v argument_list|) operator|. name|append argument_list|( literal|"\"" argument_list|) expr_stmt|; block|} else|else block|{ name|builder operator|. name|append argument_list|( name|v argument_list|) expr_stmt|; block|} block|} for|for control|( name|int name|i init|= literal|0 init|; name|attributes operator|!= literal|null operator|&& name|i operator|< name|attributes operator|. name|length condition|; name|i operator|++ control|) block|{ name|builder operator|. name|append argument_list|( literal|";" argument_list|) expr_stmt|; if|if condition|( name|indent operator|> literal|1 condition|) block|{ name|builder operator|. name|append argument_list|( literal|"\n\t\t" argument_list|) expr_stmt|; block|} name|builder operator|. name|append argument_list|( name|attributes index|[ name|i index|] operator|. name|getName argument_list|() argument_list|) operator|. name|append argument_list|( literal|"=" argument_list|) expr_stmt|; name|String name|v init|= name|attributes index|[ name|i index|] operator|. name|getValue argument_list|() decl_stmt|; if|if condition|( name|v operator|. name|contains argument_list|( literal|"," argument_list|) condition|) block|{ if|if condition|( name|indent operator|> literal|2 operator|&& name|v operator|. name|length argument_list|() operator|> literal|20 condition|) block|{ name|v operator|= name|v operator|. name|replace argument_list|( literal|"," argument_list|, literal|",\n\t\t\t" argument_list|) expr_stmt|; block|} name|builder operator|. name|append argument_list|( literal|"\"" argument_list|) operator|. name|append argument_list|( name|v argument_list|) operator|. name|append argument_list|( literal|"\"" argument_list|) expr_stmt|; block|} else|else block|{ name|builder operator|. name|append argument_list|( name|v argument_list|) expr_stmt|; block|} block|} block|} specifier|private name|boolean name|checkBundle parameter_list|( name|String name|bundleName parameter_list|, name|String name|version parameter_list|) block|{ name|VersionRange name|vr init|= name|VersionRange operator|. name|parseVersionRange argument_list|( name|version argument_list|) decl_stmt|; name|Bundle index|[] name|bundles init|= name|bundleContext operator|. name|getBundles argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; operator|( name|bundles operator|!= literal|null operator|) operator|&& operator|( name|i operator|< name|bundles operator|. name|length operator|) condition|; name|i operator|++ control|) block|{ name|String name|sym init|= name|bundles index|[ name|i index|] operator|. name|getSymbolicName argument_list|() decl_stmt|; if|if condition|( operator|( name|sym operator|!= literal|null operator|) operator|&& name|sym operator|. name|equals argument_list|( name|bundleName argument_list|) condition|) block|{ if|if condition|( name|vr operator|. name|contains argument_list|( name|bundles index|[ name|i index|] operator|. name|getVersion argument_list|() argument_list|) condition|) block|{ return|return literal|true return|; block|} block|} block|} return|return literal|false return|; block|} specifier|private name|boolean name|checkPackage parameter_list|( name|String name|packageName parameter_list|, name|String name|version parameter_list|) block|{ name|VersionRange name|range init|= name|VersionRange operator|. name|parseVersionRange argument_list|( name|version argument_list|) decl_stmt|; name|Bundle index|[] name|bundles init|= name|bundleContext operator|. name|getBundles argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; operator|( name|bundles operator|!= literal|null operator|) operator|&& operator|( name|i operator|< name|bundles operator|. name|length operator|) condition|; name|i operator|++ control|) block|{ name|BundleWiring name|wiring init|= name|bundles index|[ name|i index|] operator|. name|adapt argument_list|( name|BundleWiring operator|. name|class argument_list|) decl_stmt|; name|List argument_list|< name|BundleCapability argument_list|> name|caps init|= name|wiring operator|!= literal|null condition|? name|wiring operator|. name|getCapabilities argument_list|( name|BundleRevision operator|. name|PACKAGE_NAMESPACE argument_list|) else|: literal|null decl_stmt|; if|if condition|( name|caps operator|!= literal|null condition|) block|{ for|for control|( name|BundleCapability name|cap range|: name|caps control|) block|{ name|String name|n init|= name|getAttribute argument_list|( name|cap argument_list|, name|BundleRevision operator|. name|PACKAGE_NAMESPACE argument_list|) decl_stmt|; name|String name|v init|= name|getAttribute argument_list|( name|cap argument_list|, name|Constants operator|. name|VERSION_ATTRIBUTE argument_list|) decl_stmt|; if|if condition|( name|packageName operator|. name|equals argument_list|( name|n argument_list|) operator|&& name|range operator|. name|contains argument_list|( name|VersionTable operator|. name|getVersion argument_list|( name|v argument_list|) argument_list|) condition|) block|{ return|return literal|true return|; block|} block|} block|} block|} return|return literal|false return|; block|} specifier|private name|String name|getAttribute parameter_list|( name|BundleCapability name|cap parameter_list|, name|String name|name parameter_list|) block|{ name|Object name|obj init|= name|cap operator|. name|getAttributes argument_list|() operator|. name|get argument_list|( name|name argument_list|) decl_stmt|; return|return name|obj operator|!= literal|null condition|? name|obj operator|. name|toString argument_list|() else|: literal|null return|; block|} block|} end_class end_unit
cajunc2/dev80
src/main/java/org/cajunc2/dev80/newui/menu/EditMenu.java
<filename>src/main/java/org/cajunc2/dev80/newui/menu/EditMenu.java package org.cajunc2.dev80.newui.menu; import java.awt.AWTEvent; import java.awt.event.InputEvent; import javax.swing.FocusManager; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import org.cajunc2.dev80.newui.EditorWindow; import org.cajunc2.dev80.newui.project.ProjectWindow; class EditMenu extends JMenu { private static final long serialVersionUID = 1L; public EditMenu(EditorWindow editorWindow, ProjectWindow projectWindow) { super("Edit"); JMenuItem undoItem = new JMenuItem("Undo"); undoItem.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.META_DOWN_MASK)); add(undoItem); JMenuItem redoItem = new JMenuItem("Redo"); redoItem.setAccelerator( KeyStroke.getKeyStroke('Z', InputEvent.META_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); add(redoItem); addSeparator(); JMenuItem cutItem = new JMenuItem("Cut"); cutItem.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.META_DOWN_MASK)); add(cutItem); JMenuItem copyItem = new JMenuItem("Copy"); copyItem.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.META_DOWN_MASK)); add(copyItem); JMenuItem pasteItem = new JMenuItem("Paste"); pasteItem.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.META_DOWN_MASK)); add(pasteItem); JMenuItem selectAllItem = new JMenuItem("Select All"); selectAllItem.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.META_DOWN_MASK)); selectAllItem.addActionListener(evt -> { AWTEvent event = new SelectAllEvent(); FocusManager.getCurrentManager().getActiveWindow().dispatchEvent(event); }); add(selectAllItem); } private static class SelectAllEvent extends AWTEvent { private static final long serialVersionUID = 1L; public SelectAllEvent() { super(null, 0); } } }
wrcold520/mcourse
microcourse/src/main/java/com/mcourse/frame/utils/date/DatePattern.java
<reponame>wrcold520/mcourse package com.mcourse.frame.utils.date; import java.util.ArrayList; import java.util.List; /** * 日期时间格式枚举 * * @Title * @Description * * @Created Assassin * @DateTime 2017/06/30 10:07:32 */ public enum DatePattern { // 日期时间格式 /** 【日期时间】空格符号 yyyy MM dd HH:mm:ss **/ DATETIME_BLANK("yyyy MM dd HH:mm:ss"), /** 【日期时间】短横线符号 yyyy-MM-dd HH:mm:ss **/ DATETIME_DASH("yyyy-MM-dd HH:mm:ss"), /** 【日期时间】斜杠符号 yyyy/MM/dd HH:mm:ss **/ DATETIME_SLASH("yyyy/MM/dd HH:mm:ss"), /** 【日期时间】无符号 yyyyMMddHHmmss **/ DATETIME_NOSYMBOL("yyyyMMddHHmmss"), // 日期格式 /** 【日期】空格符号 yyyy MM dd **/ DATE_BLANK("yyyy MM dd"), /** 【日期】短横线符号 yyyy-MM-dd **/ DATE_DASH("yyyy-MM-dd"), /** 【日期】斜杠符号 yyyy/MM/dd **/ DATE_SLASH("yyyy/MM/dd"), /** 【日期】无符号 yyyyMMdd **/ DATE_NOSYMBOL("yyyyMMdd"), // 时间格式 /** 【时间】冒号符号 HH:mm:ss **/ TIME_COLON("HH:mm:ss"), /** 【时间】 无符号HHmmss **/ TIME_NOSYMBOL("HHmmss"); /** 日期时间格式的集合 **/ private static List<DatePattern> datetimePatternList = new ArrayList<DatePattern>(); /** 日期格式的集合 **/ private static List<DatePattern> datePatternList = new ArrayList<DatePattern>(); /** 日期格式的集合 **/ private static List<DatePattern> timePatternList = new ArrayList<DatePattern>(); static { datetimePatternList.add(DatePattern.DATETIME_BLANK); datetimePatternList.add(DatePattern.DATETIME_DASH); datetimePatternList.add(DatePattern.DATETIME_NOSYMBOL); datetimePatternList.add(DatePattern.DATETIME_SLASH); datePatternList.add(DatePattern.DATE_BLANK); datePatternList.add(DatePattern.DATE_DASH); datePatternList.add(DatePattern.DATE_NOSYMBOL); datePatternList.add(DatePattern.DATE_SLASH); timePatternList.add(DatePattern.TIME_COLON); timePatternList.add(DatePattern.TIME_NOSYMBOL); } private String patternStr; private DatePattern(String patternStr) { this.patternStr = patternStr; } /** * 获取格式的字符串 * * @return */ public String getPatternStr() { return patternStr; } public void setPatternStr(String patternStr) { this.patternStr = patternStr; } public static List<DatePattern> getDatetimePatternList() { return datetimePatternList; } public static List<DatePattern> getDatePatternList() { return datePatternList; } public static List<DatePattern> getTimePatternList() { return timePatternList; } }
RobertPaasche/git4c
confluence-plugin/src/main/resources/js/flag-compat.js
//AJS Compat var AJSC = {} AJSC.flag = function (data) { if (AJS.flag) { AJS.flag(data) } else { require(['aui/flag'], function(flag) { flag(data); }) } }
raychorn/svn_molten-magma
molten-trunk/molten5_withgrid/app/models/solution_relevancy.rb
<gh_stars>0 class SolutionRelevancy < ActiveRecord::Base set_primary_key "id" #------------------ # VALIDATIONS #------------------ validates_presence_of :rating_value_one, :rating_value_two, :rating_value_three, :rating_value_four, :view_value, :update_value #------------------ # CLASS METHODS #------------------ # Sends missing methods to the first record. def self.method_missing(meth, *args, &block) if self.new.respond_to?(meth) raise "The relevancy setting does not exist for solutions. Please create it." unless rel = find(:first) rel.send(meth) else super end end end
luisriverag/verus-desktop
routes/api/utils/auth/rpcAuth.js
/* Copyright (c) 2019, <NAME> <<EMAIL>> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ const crypto = require('crypto') function generateSalt (size) { const buf = crypto.randomBytes(size) const salt = buf.toString('hex') return salt } function generateRpcPassword () { const buf = crypto.randomBytes(32) const password = Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '') return password } function passwordToHmac (salt, password) { const hmac = crypto.createHmac('sha256', salt) hmac.update(password) return hmac.digest('hex') } module.exports = { generateSalt, generateRpcPassword, passwordToHmac }
lazylester/RescueRails
spec/tasks/adoptapet_sync_spec.rb
require 'rails_helper' require_relative '../helpers/rspec_matchers' describe 'adoptapet_sync:export_upload', type: :task do describe 'inclusion of photos in the csv' do 5.times do |i| let("photo#{i}"){ FactoryBot.build(:photo, updated_at: DateTime.new(2018,1,i+1)) } end let(:foster) { FactoryBot.create(:foster, region: "VA") } let!(:dog) { FactoryBot.create(:dog, status: 'adoptable', foster_id: foster.id, photos_attributes: [photo0,photo1,photo2,photo3,photo4].map(&:attributes)) } let!(:rake){ task.execute } let(:recent_photos){ Dog.first.photos.sort_by{|photo| photo.updated_at}.reverse[0..3]} let(:photo_urls){ recent_photos.map{|photo| photo.photo.url(:large)} } let(:csv) { CSV.read( '/tmp/adoptapet/pets_VA.csv' ) } it "should include most recent four photos for a dog" do csv_photos = csv.first[16..19] # just confirming recent_photos are the ones we want to upload # expect most recent first expect(recent_photos.map(&:updated_at)).to be_sorted(:descending) expect(csv_photos).to eq photo_urls end end describe 'inclusion of dogs by status' do let(:foster) { FactoryBot.create(:foster, region: "VA") } Dog::STATUSES.each do |status| dog_type = status.gsub(/\s/,'_')+'_dog' let!(dog_type){ FactoryBot.create(:dog, status: status, foster_id: foster.id) } end let!(:rake){ task.execute } let(:csv) { CSV.read( '/tmp/adoptapet/pets_VA.csv' ) } it 'should include only adoptable, adoption pending and coming soon dogs' do included_ids = csv.map{|row| row[0]} expect(csv.map{|row| row[0]}).to match_array [adoptable_dog.id, adoption_pending_dog.id, coming_soon_dog.id].map(&:to_s) end end describe 'inclusion of dogs by location of foster' do let(:va_foster) { FactoryBot.create(:foster, region: "VA") } let(:ca_foster) { FactoryBot.create(:foster, region: "CA") } let!(:va_dog){ FactoryBot.create(:dog, status: 'adoptable', foster_id: va_foster.id) } let!(:ca_dog){ FactoryBot.create(:dog, status: 'adoptable', foster_id: ca_foster.id) } let!(:rake){ task.execute } let(:csv) { CSV.read( '/tmp/adoptapet/pets_VA.csv' ) } it 'should include only adoptable, adoption pending and coming soon dogs' do included_ids = csv.map{|row| row[0]} expect(csv.map{|row| row[0]}).to match_array [va_dog.id].map(&:to_s) end end end
USSDlover/abp-sam-nestjs
node_modules/ts-morph/dist/errors/classes/ArgumentNullOrWhitespaceError.js
<reponame>USSDlover/abp-sam-nestjs "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ArgumentError_1 = require("./ArgumentError"); class ArgumentNullOrWhitespaceError extends ArgumentError_1.ArgumentError { /** @private */ constructor(argName) { super(argName, "Cannot be null or whitespace.", ArgumentNullOrWhitespaceError.prototype); } } exports.ArgumentNullOrWhitespaceError = ArgumentNullOrWhitespaceError;
Abolitionist-Project/QM-Java
fluxtream-web/src/main/webapp/static/js/jquery.shorten-1.0.0.js
<filename>fluxtream-web/src/main/webapp/static/js/jquery.shorten-1.0.0.js ;(function ($) { //var $c = console; var _native = false, is_canvasTextSupported, measureContext, // canvas context or table cell measureText, // function that measures text width info_identifier = "shorten-info", options_identifier = "shorten-options"; $.fn.shorten = function() { var userOptions = {}, args = arguments, // for better minification func = args.callee; // dito; and shorter than $.fn.shorten if ( args.length ) { if ( args[0].constructor == Object ) { userOptions = args[0]; } else if ( args[0] == "options" ) { return $(this).eq(0).data(options_identifier); } else { userOptions = { width: parseInt(args[0]), tail: args[1] }; } } this.css("visibility","hidden"); // Hide the element(s) while manipulating them // apply options vs. defaults var options = $.extend({}, func.defaults, userOptions); /** * HERE WE GO! **/ return this.each(function () { var $this = $(this), text = $this.text(), numChars = text.length, targetWidth, tailText = $("<span/>").html(options.tail).text(), // convert html to text tailWidth, info = { shortened: false, textOverflow: false }; if ($this.css("float") != "none") { targetWidth = options.width || $this.width(); // this let's correctly shorten text in floats, but fucks up the rest } else { targetWidth = options.width || $this.parent().width(); } if (targetWidth < 0) { // jQuery versions < 1.4.4 return negative values for .width() if display:none is used. //$c.log("nonsense target width ", targetWidth); return true; } $this.data(options_identifier, options); // for consistency with the text-overflow method (which requires these properties), but not actually neccessary. this.style.display = "block"; //this.style.overflow = "hidden"; // firefox: a floated li will cause the ul to have a "bottom padding" if this is set. this.style.whiteSpace = "nowrap"; // decide on a method for measuring text width if ( is_canvasTextSupported ) { //$c.log("canvas"); measureContext = measureText_initCanvas.call( this ); measureText = measureText_canvas; } else { //$c.log("table") measureContext = measureText_initTable.call( this ); measureText = measureText_table; } var origLength = measureText.call( this, text, measureContext ); if ( options.tooltip ) { this.setAttribute("title", text); } if ( origLength < targetWidth ) { //$c.log("nothing to do"); $this.text( text ); this.style.visibility = "visible"; $this.data(info_identifier, info); return true; } /** * If browser implements text-overflow:ellipsis in CSS and tail is &hellip;/Unicode 8230/(…), use it! * In this case we're doing the measurement above to determine if we need the tooltip. **/ if ( func._native && !userOptions.width ) { //$c.log("css ellipsis"); var rendered_tail = $("<span>"+options.tail+"</span>").text(); // render tail to find out if it's the ellipsis character. if ( rendered_tail.length == 1 && rendered_tail.charCodeAt(0) == 8230 ) { $this.text( text ); // the following three properties are needed for text-overflow to work (tested in Chrome). // for consistency now I need to set this everywhere... which probably interferes with users' layout... //this.style.whiteSpace = "nowrap"; this.style.overflow = "hidden"; //this.style.display = "block"; this.style[func._native] = "ellipsis"; this.style.visibility = "visible"; info.shortened = true; info.textOverflow = "ellipsis"; $this.data(info_identifier, info); return true; } } tailWidth = measureText.call( this, tailText, measureContext ); // convert html to text and measure it targetWidth = targetWidth - tailWidth; //$c.log(text +" + "+ tailText); /** * Before we start removing characters one by one, let's try to be more intelligent about this: * If the original string is longer than targetWidth by at least 15% (for safety), then shorten it * to targetWidth + 15% (and re-measure for safety). If the resulting text still is too long (as expected), * use that for further shortening. Else use the original text. This saves a lot of time for text that is * much longer than the desired width. */ var safeGuess = targetWidth * 1.15; // add 15% to targetWidth for safety before making the cut. if ( origLength - safeGuess > 0 ) { // if it's safe to cut, do it. var cut_ratio = safeGuess / origLength, num_guessText_chars = Math.ceil( numChars * cut_ratio ), // looking good: shorten and measure guessText = text.substring(0, num_guessText_chars), guessTextLength = measureText.call( this, guessText, measureContext ); //$c.info("safe guess: remove " + (numChars - num_guessText_chars) +" chars"); if ( guessTextLength > targetWidth ) { // make sure it's not too short! text = guessText; numChars = text.length; } } // Remove characters one by one until text width <= targetWidth //var count = 0; do { numChars--; text = text.substring(0, numChars); //count++; } while ( measureText.call( this, text, measureContext ) >= targetWidth ); $this.html( $.trim( $("<span/>").text(text).html() ) + options.tail ); this.style.visibility = "visible"; //$c.info(count + " normal truncating cycles...") //$c.log("----------------------------------------------------------------------"); info.shortened = true; $this.data(info_identifier, info); return true; }); return true; }; var css = document.documentElement.style; if ( "textOverflow" in css ) { _native = "textOverflow"; } else if ( "OTextOverflow" in css ) { _native = "OTextOverflow"; } // test for canvas support if ( typeof Modernizr != 'undefined' && Modernizr.canvastext ) { // if Modernizr has tested for this already use that. is_canvasTextSupported = Modernizr.canvastext; } else { var canvas = document.createElement("canvas"); is_canvasTextSupported = !!(canvas.getContext && canvas.getContext("2d") && (typeof canvas.getContext("2d").fillText === 'function')); } $.fn.shorten._is_canvasTextSupported = is_canvasTextSupported; $.fn.shorten._native = _native; function measureText_initCanvas() { var $this = $(this); var canvas = document.createElement("canvas"); //scanvas.setAttribute("width", 500); canvas.setAttribute("height", 40); ctx = canvas.getContext("2d"); $this.html( canvas ); /* the rounding is experimental. it fixes a problem with a font size specified as 0.7em which resulted in a computed size of 11.2px. without rounding the measured font was too small. even with rounding the result differs slightly from the table method's results. */ // Get the current text style. This string uses the same syntax as the CSS font specifier. The ordering matters! ctx.font = $this.css("font-style") +" "+ $this.css("font-variant") +" "+ $this.css("font-weight") +" "+ Math.ceil(parseFloat($this.css("font-size"))) +"px "+ $this.css("font-family"); return ctx; } // measurement using canvas function measureText_canvas( text, ctx ) { //ctx.fillStyle = "red"; ctx.fillRect (0, 0, 500, 40); //ctx.fillStyle = "black"; ctx.fillText(text, 0, 12); return ctx.measureText(text).width; // crucial, fast but called too often }; function measureText_initTable() { var css = "padding:0; margin:0; border:none; font:inherit;"; var $table = $('<table style="'+ css +'width:auto;zoom:1;position:absolute;"><tr style="'+ css +'"><td style="'+ css +'white-space:nowrap;"></td></tr></table>'); $td = $("td", $table); $(this).html( $table ); return $td; }; // measurement using table function measureText_table( text, $td ) { $td.text( text ); return $td.width(); // crucial but expensive }; $.fn.shorten.defaults = { tail: "&hellip;", tooltip: true }; })(jQuery);
uizaio/uiza-sdk-player-android
corebase/src/main/java/vn/loitp/restapi/uiza/model/v2/getplayerinfo/PlayerConfig.java
<reponame>uizaio/uiza-sdk-player-android package vn.loitp.restapi.uiza.model.v2.getplayerinfo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class PlayerConfig { @SerializedName("setting") @Expose private Setting setting; @SerializedName("styling") @Expose private Styling styling; @SerializedName("socialSharing") @Expose private SocialSharing socialSharing; @SerializedName("endscreen") @Expose private Endscreen endscreen; public Setting getSetting() { return setting; } public void setSetting(Setting setting) { this.setting = setting; } public Styling getStyling() { return styling; } public void setStyling(Styling styling) { this.styling = styling; } public SocialSharing getSocialSharing() { return socialSharing; } public void setSocialSharing(SocialSharing socialSharing) { this.socialSharing = socialSharing; } public Endscreen getEndscreen() { return endscreen; } public void setEndscreen(Endscreen endscreen) { this.endscreen = endscreen; } }
lukewarlow/WP-ClientProject
app/src/main/java/com/nsa/teamtwo/welshpharmacy/data/pharmacy/Pharmacy.java
<filename>app/src/main/java/com/nsa/teamtwo/welshpharmacy/data/pharmacy/Pharmacy.java package com.nsa.teamtwo.welshpharmacy.data.pharmacy; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import android.util.Pair; import com.google.android.gms.maps.model.LatLng; import com.nsa.teamtwo.welshpharmacy.R; import com.nsa.teamtwo.welshpharmacy.data.DayOfTheWeek; import com.nsa.teamtwo.welshpharmacy.util.Util; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; public class Pharmacy implements Parcelable { private String name; private LatLng location; private HashMap<DayOfTheWeek, OpeningTime> openingTimes; private String phoneNumber; private boolean welshAvailable; private List<Service> services; public Pharmacy(String name, double lat, double lng, HashMap<DayOfTheWeek, OpeningTime> openingTimes, String phoneNumber, boolean welshAvailable) { this.name = name; this.location = new LatLng(lat, lng); this.openingTimes = openingTimes; this.phoneNumber = phoneNumber; this.welshAvailable = welshAvailable; services = new ArrayList<>(); } @SuppressWarnings("unchecked") public Pharmacy(Parcel in) { name = in.readString(); location = in.readParcelable(LatLng.class.getClassLoader()); openingTimes = (HashMap<DayOfTheWeek, OpeningTime>) in.readSerializable(); phoneNumber = in.readString(); welshAvailable = (Boolean) in.readSerializable(); services = new ArrayList<>(); in.readList(services, Service.class.getClassLoader()); } public String getName() { return name; } public LatLng getLocation() { return location; } public OpeningTime getOpeningTime(DayOfTheWeek dayOfWeek) { return openingTimes.get(dayOfWeek); } public Pair<String, OpeningTime> getNextOpeningTime(Context context) { Calendar calendar = Calendar.getInstance(); String today = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(calendar.getTime()).toUpperCase(); while (true) { String day = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(calendar.getTime()).toUpperCase(); if (day.equals(today)) { if (Util.getCurrentTimeAsDouble() < getOpeningTime(DayOfTheWeek.valueOf(today)).getClosingTime()) { return new Pair<>(context.getString(R.string.today), getOpeningTime(DayOfTheWeek.valueOf(day))); } } else if (willOpen(DayOfTheWeek.valueOf(day))) { if (Util.systemLanguageIsWelsh(context)) { return new Pair<>(Util.getDayInWelsh(day).toLowerCase(), getOpeningTime(DayOfTheWeek.valueOf(day))); } else { return new Pair<>(day.toLowerCase(), getOpeningTime(DayOfTheWeek.valueOf(day))); } } calendar.add(Calendar.DAY_OF_YEAR, 1); } } public boolean willOpen(DayOfTheWeek dayOfTheWeek) { double openingTime = getOpeningTime(dayOfTheWeek).getOpeningTime(); double closingTime = getOpeningTime(dayOfTheWeek).getClosingTime(); return openingTime != closingTime; } public boolean isOpenNow() { String today = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(new Date()).toUpperCase(); double openingTime = openingTimes.get(DayOfTheWeek.valueOf(today)).getOpeningTime(); double closingTime = openingTimes.get(DayOfTheWeek.valueOf(today)).getClosingTime(); double currentTime = Util.getCurrentTimeAsDouble(); if (openingTime == closingTime) { return false; } else { return currentTime > openingTime && currentTime < closingTime; } } public String getPhoneNumber() { return phoneNumber; } public Boolean isWelshAvailable() { return welshAvailable; } public void addService(Service service) { if (!services.contains(service)) { services.add(service); } else { Log.d("Pharmacy", service.getEnglishName() + " already added to pharmacy."); } } public Boolean doesService(Service service) { return services.contains(service); } public List<Service> getServices() { return services; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeParcelable(location, flags); dest.writeSerializable(openingTimes); dest.writeString(phoneNumber); dest.writeSerializable(welshAvailable); dest.writeList(services); } public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { @Override public Pharmacy createFromParcel(Parcel source) { return new Pharmacy(source); } @Override public Pharmacy[] newArray(int size) { return new Pharmacy[size]; } }; }
TeamGrainPigeon/Arknights-Mod
src/main/java/arknights/entity/model/WModel.java
package arknights.entity.model; public class WModel extends WomanModel { public WModel(float modelSize) { super(modelSize); } }
ZeusWPI/gamification
db/migrate/20141104172317_create_commits.rb
<filename>db/migrate/20141104172317_create_commits.rb class CreateCommits < ActiveRecord::Migration def change create_table :commits do |t| t.references :coder, index: true t.references :repository, index: true t.string :sha, null: false t.integer :additions, null: false, default: 0 t.integer :deletions, null: false, default: 0 t.timestamp :date, null: false, index: true t.timestamps end add_index :commits, [:repository_id, :sha], unique: true end end
sabahkhaliq/yoti
src/doc_scan_service/session/retrieve/watchlist.screening.report.response.js
<reponame>sabahkhaliq/yoti 'use strict'; const WatchlistReportResponse = require('./watchlist.report.response'); const WatchlistScreeningSummaryResponse = require('./watchlist.screening.summary.response'); class WatchlistScreeningReportResponse extends WatchlistReportResponse { constructor(report) { super(report); if (report.watchlist_summary) { this.watchListSummary = new WatchlistScreeningSummaryResponse(report.watchlist_summary); } } /** * * @return {WatchlistScreeningSummaryResponse} */ getWatchlistSummary() { return this.watchListSummary; } } module.exports = WatchlistScreeningReportResponse;
AREA44/competitive-programming
UVa-OnlineJudge/UVa280_Vetex.cpp
<reponame>AREA44/competitive-programming<gh_stars>0 /* UVa - 280 - Vertex * https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=216 */ //nhatnguyendrgs (c) 2015 #include "iostream" #include "stdio.h" #include "stdlib.h" #include "string" #include "string.h" #include "algorithm" #include "math.h" #include "vector" #include "map" #include "queue" #include "stack" #include "deque" #include "set" using namespace std; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; const int inf = 1e9; const int MaxN = 1e2; const int base = 1e9+7; #define DFS_WHITE -1 #define DFS_BLACK 1 int n,q,u,v; vector<vi> Adj; vi dfs_num; void dfs(int u){ for(int j=0;j<Adj[u].size();j++){ int v=Adj[u][j]; if(dfs_num[v]==DFS_WHITE){ dfs_num[v]=DFS_BLACK; dfs(v); } } } queue<int> Q; int main(){ while(1){ scanf("%d",&n); if(n==0) break; Adj.assign(n+4,vi()); while(1){ scanf("%d",&u); if(u==0) break; while(1){ scanf("%d",&v); if(v==0) break; Adj[u].push_back(v); } } scanf("%d",&q); for(int i=1;i<=q;i++){ scanf("%d",&u); dfs_num.assign(n+4,DFS_WHITE); dfs(u); for(int i=1;i<=n;i++){ if(dfs_num[i]==DFS_WHITE) Q.push(i); } if(Q.size()==0) printf("0\n"); else{ printf("%d ",Q.size()); while(Q.size()>1){ printf("%d ", Q.front()); Q.pop(); } printf("%d\n",Q.front()); Q.pop(); } } } return 0; }
SebastianWeberKamp/KAMP
bundles/Toometa/toometa.relations.tests/src/relations/tests/RelationTypeTest.java
/** */ package relations.tests; import junit.framework.TestCase; import junit.textui.TestRunner; import relations.RelationType; import relations.RelationsFactory; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Relation Type</b></em>'. * <!-- end-user-doc --> * @generated */ public class RelationTypeTest extends TestCase { /** * The fixture for this Relation Type test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected RelationType fixture = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(RelationTypeTest.class); } /** * Constructs a new Relation Type test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RelationTypeTest(String name) { super(name); } /** * Sets the fixture for this Relation Type test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void setFixture(RelationType fixture) { this.fixture = fixture; } /** * Returns the fixture for this Relation Type test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected RelationType getFixture() { return fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(RelationsFactory.eINSTANCE.createRelationType()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } } //RelationTypeTest
sdmiller/gtsam_pcl
gtsam/inference/tests/testSerializationInference.cpp
<filename>gtsam/inference/tests/testSerializationInference.cpp /* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: <NAME>, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file testSerializationInference.cpp * @brief * @author <NAME> * @date Feb 7, 2012 */ #include <gtsam/inference/IndexConditional.h> #include <gtsam/inference/SymbolicFactorGraph.h> #include <gtsam/inference/BayesTree.h> #include <gtsam/base/serializationTestHelpers.h> #include <CppUnitLite/TestHarness.h> using namespace std; using namespace gtsam; using namespace gtsam::serializationTestHelpers; /* ************************************************************************* */ TEST (Serialization, symbolic_graph) { // construct expected symbolic graph SymbolicFactorGraph sfg; sfg.push_factor(0); sfg.push_factor(0,1); sfg.push_factor(0,2); sfg.push_factor(2,1); EXPECT(equalsObj(sfg)); EXPECT(equalsXML(sfg)); } /* ************************************************************************* */ TEST (Serialization, symbolic_bn) { IndexConditional::shared_ptr x2(new IndexConditional(1, 2, 0)); IndexConditional::shared_ptr l1(new IndexConditional(2, 0)); IndexConditional::shared_ptr x1(new IndexConditional(0)); SymbolicBayesNet sbn; sbn.push_back(x2); sbn.push_back(l1); sbn.push_back(x1); EXPECT(equalsObj(sbn)); EXPECT(equalsXML(sbn)); } /* ************************************************************************* */ TEST (Serialization, symbolic_bayes_tree ) { typedef BayesTree<IndexConditional> SymbolicBayesTree; static const Index _X_=0, _T_=1, _S_=2, _E_=3, _L_=4, _B_=5; IndexConditional::shared_ptr B(new IndexConditional(_B_)), L(new IndexConditional(_L_, _B_)), E(new IndexConditional(_E_, _L_, _B_)), S(new IndexConditional(_S_, _L_, _B_)), T(new IndexConditional(_T_, _E_, _L_)), X(new IndexConditional(_X_, _E_)); // Bayes Tree for Asia example SymbolicBayesTree bayesTree; SymbolicBayesTree::insert(bayesTree, B); SymbolicBayesTree::insert(bayesTree, L); SymbolicBayesTree::insert(bayesTree, E); SymbolicBayesTree::insert(bayesTree, S); SymbolicBayesTree::insert(bayesTree, T); SymbolicBayesTree::insert(bayesTree, X); EXPECT(equalsObj(bayesTree)); EXPECT(equalsXML(bayesTree)); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); } /* ************************************************************************* */
npocmaka/Windows-Server-2003
printscan/faxsrv/util/security.cpp
<reponame>npocmaka/Windows-Server-2003 /*++ Copyright (c) 2000 Microsoft Corporation Module Name: Security.cpp Abstract: General fax server security utility functions Author: <NAME> (EranY) Feb, 2001 Revision History: --*/ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <tchar.h> #include <Accctrl.h> #include <Aclapi.h> #include "faxutil.h" #include "faxreg.h" #include "FaxUIConstants.h" HANDLE EnablePrivilege ( LPCTSTR lpctstrPrivName ) /*++ Routine name : EnablePrivilege Routine description: Enables a specific privilege in the current thread (or process) access token Author: <NAME> (EranY), Feb, 2001 Arguments: lpctstrPrivName [in] - Privilege to enable (e.g. SE_TAKE_OWNERSHIP_NAME) Return Value: INVALID_HANDLE_VALUE on failure (call GetLastError to get error code). On success, returns the handle which holds the thread/process priviledges before the change. The caller must call ReleasePrivilege() to restore the access token state and release the handle. --*/ { BOOL fResult; HANDLE hToken = INVALID_HANDLE_VALUE; HANDLE hOriginalThreadToken = INVALID_HANDLE_VALUE; LUID luidPriv; TOKEN_PRIVILEGES tp = {0}; DEBUG_FUNCTION_NAME( TEXT("EnablePrivileges")); Assert (lpctstrPrivName); // // Get the LUID of the privilege. // if (!LookupPrivilegeValue(NULL, lpctstrPrivName, &luidPriv)) { DebugPrintEx( DEBUG_ERR, _T("Failed to LookupPrivilegeValue. (ec: %ld)"), GetLastError ()); return INVALID_HANDLE_VALUE; } // // Initialize the Privileges Structure // tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; tp.Privileges[0].Luid = luidPriv; // // Open the Token // fResult = OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE, FALSE, &hToken); if (fResult) { // // Remember the thread token // hOriginalThreadToken = hToken; } else { fResult = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &hToken); } if (fResult) { HANDLE hNewToken; // // Duplicate that Token // fResult = DuplicateTokenEx(hToken, TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, NULL, // PSECURITY_ATTRIBUTES SecurityImpersonation, // SECURITY_IMPERSONATION_LEVEL TokenImpersonation, // TokenType &hNewToken); // Duplicate token if (fResult) { // // Add new privileges // fResult = AdjustTokenPrivileges(hNewToken, // TokenHandle FALSE, // DisableAllPrivileges &tp, // NewState 0, // BufferLength NULL, // PreviousState NULL); // ReturnLength if (fResult) { // // Begin impersonating with the new token // fResult = SetThreadToken(NULL, hNewToken); } CloseHandle(hNewToken); } } // // If something failed, don't return a token // if (!fResult) { hOriginalThreadToken = INVALID_HANDLE_VALUE; } if (INVALID_HANDLE_VALUE == hOriginalThreadToken) { // // Using the process token // if (INVALID_HANDLE_VALUE != hToken) { // // Close the original token if we aren't returning it // CloseHandle(hToken); } if (fResult) { // // If we succeeded, but there was no original thread token, // return NULL to indicate we need to do SetThreadToken(NULL, NULL) to release privs. // hOriginalThreadToken = NULL; } } return hOriginalThreadToken; } // EnablePrivilege void ReleasePrivilege( HANDLE hToken ) /*++ Routine name : ReleasePrivilege Routine description: Resets privileges to the state prior to the corresponding EnablePrivilege() call Author: <NAME> (EranY), Feb, 2001 Arguments: hToken [IN] - Return value from the corresponding EnablePrivilege() call Return Value: None. --*/ { DEBUG_FUNCTION_NAME( TEXT("ReleasePrivilege")); if (INVALID_HANDLE_VALUE != hToken) { if(!SetThreadToken(NULL, hToken)) { DebugPrintEx(DEBUG_ERR, TEXT("SetThreadToken() failed (ec: %ld)"), GetLastError()); } if (hToken) { if(!CloseHandle(hToken)) { DebugPrintEx(DEBUG_ERR, TEXT("CloseHandle() failed (ec: %ld)"), GetLastError()); } } } } // ReleasePrivilege DWORD EnableProcessPrivilege(LPCTSTR lpPrivilegeName) /*++ Routine name : EnableProcessPrivilege Routine description: Enables process privilege. Author: <NAME> (t-nicali) Mar, 2002 Arguments: lpPrivilegeName [in] - Pointer to a null-terminated string that specifies the name of the privilege, as defined in the Winnt.h header file. For example, this parameter could specify the constant SE_SECURITY_NAME, or its corresponding string, "SeSecurityPrivilege" Return Value: Standard Win32 error code. --*/ { HANDLE hToken = INVALID_HANDLE_VALUE; TOKEN_PRIVILEGES tp = {0}; LUID luidPriv; BOOL bRet; DWORD dwRet=ERROR_SUCCESS; DEBUG_FUNCTION_NAME( TEXT("EnableProcessPrivilege")); Assert(lpPrivilegeName); // // Get the LUID of the privilege. // if (!LookupPrivilegeValue(NULL, lpPrivilegeName, &luidPriv)) { dwRet = GetLastError(); DebugPrintEx( DEBUG_ERR, _T("Failed to LookupPrivilegeValue. (ec: %lu)"), dwRet); goto Exit; } // // Initialize the Privileges Structure // tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; tp.Privileges[0].Luid = luidPriv; // // Open process token // bRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken); if (FALSE == bRet) { // // Failed to OpenProcessToken // dwRet = GetLastError(); DebugPrintEx( DEBUG_ERR, TEXT("OpenProcessToken() failed: err = %lu"), dwRet); goto Exit; } // // Adjust the Token // bRet = AdjustTokenPrivileges(hToken, // TokenHandle FALSE, // DisableAllPrivileges &tp, // NewState 0, // BufferLength NULL, // PreviousState NULL); // ReturnLength if (FALSE == bRet) { // // Failed to OpenProcessToken // dwRet = GetLastError(); DebugPrintEx( DEBUG_ERR, TEXT("AdjustTokenPrivileges() failed: err = %lu"), dwRet); goto Exit; } Assert(ERROR_SUCCESS == dwRet); Exit: if(NULL != hToken) { if(!CloseHandle(hToken)) { DebugPrintEx( DEBUG_ERR, TEXT("CloseHandle() failed: err = %lu"), GetLastError()); } } return dwRet; }
samvantran/dcos-metrics
module/container_state_cache_impl.cpp
<filename>module/container_state_cache_impl.cpp #include "container_state_cache_impl.hpp" #include <stout/json.hpp> #include <stout/os.hpp> #include <stout/path.hpp> /* * dir format: * DIR/ * containers/ * container_id-0.json * container_id-1.json * container_id-2.json * ... * * file format in container jsons: * { "container_id": "container_id-0", * "statsd_host": "some_host", * "statsd_port": some_port } */ namespace { const std::string CONTAINER_CACHE_DIR("containers"); const std::string CONTAINER_ID_KEY("container_id"); const std::string HOST_KEY("statsd_host"); const std::string PORT_KEY("statsd_port"); /** * Avoid eg: * - malicious: "/example/path/" + "../../etc/shadow" * - nested: "/example/path/" + "valid-container-id/with-slash" * Solution: Just strip out all slashes from the name. */ std::string sanitized_filename(const mesos::ContainerID& container_id) { return strings::remove(container_id.value(), "/"); } } metrics::ContainerStateCacheImpl::ContainerStateCacheImpl(const mesos::Parameters& parameters) : config_state_dir(params::get_str(parameters, params::STATE_PATH_DIR, params::STATE_PATH_DIR_DEFAULT)), container_state_dir(path::join(config_state_dir, CONTAINER_CACHE_DIR)) { } const std::string& metrics::ContainerStateCacheImpl::path() const { return config_state_dir; } metrics::container_id_map<metrics::UDPEndpoint> metrics::ContainerStateCacheImpl::get_containers() { Try<std::list<std::string>> files = os::ls(container_state_dir); container_id_map<UDPEndpoint> map; if (files.isError()) { LOG(ERROR) << "Unable to list content of cache dir[" << container_state_dir << "]: " << files.error(); return map; } for (const std::string& filename : files.get()) { std::string pathstr(path::join(container_state_dir, filename)); Try<std::string> content = os::read(pathstr); if (content.isError()) { LOG(ERROR) << "Unable to read content of cache file[" << pathstr << "]: " << content.error(); continue; } Try<JSON::Object> content_json = JSON::parse<JSON::Object>(content.get()); if (content_json.isError()) { LOG(ERROR) << "Unable to parse JSON in cache file[" << pathstr << "] " << "content[" << content.get() << "]: " << content_json.error(); continue; } Result<JSON::String> container_id_json = content_json.get().find<JSON::String>(CONTAINER_ID_KEY); if (container_id_json.isError()) { LOG(ERROR) << "Unable to parse container id value in cache file[" << pathstr << "] " << "content[" << content.get() << "]: " << container_id_json.error(); continue; } else if (container_id_json.isNone()) { LOG(ERROR) << "Missing container_id value in cache file[" << pathstr << "] " << "content[" << content.get() << "]"; continue; } Result<JSON::String> host = content_json.get().find<JSON::String>(HOST_KEY); if (host.isError()) { LOG(ERROR) << "Unable to parse host value in cache file[" << pathstr << "] " << "content[" << content.get() << "]: " << host.error(); continue; } else if (host.isNone()) { LOG(ERROR) << "Missing host value in cache file[" << pathstr << "] " << "content[" << content.get() << "]"; continue; } Result<JSON::Number> port = content_json.get().find<JSON::Number>(PORT_KEY); if (port.isError()) { LOG(ERROR) << "Unable to parse port value in cache file[" << pathstr << "] " << "content[" << content.get() << "]: " << port.error(); continue; } else if (port.isNone()) { LOG(ERROR) << "Missing port value in cache file[" << pathstr << "] " << "content[" << content.get() << "]"; continue; } else if (port.get().as<long>() < 0) { LOG(ERROR) << "Port value in cache file[" << pathstr << "] " << "content[" << content.get() << "] must be non-negative"; continue; } mesos::ContainerID container_id; container_id.set_value(container_id_json.get().value); metrics::UDPEndpoint endpoint(host.get().value, port.get().as<size_t>()); LOG(INFO) << "Found container file[" << pathstr << "] with " << "container_id[" << container_id.value() << "] => " << "endpoint[" << endpoint.string() << "]"; map.insert(std::make_pair(container_id, endpoint)); } return map; } void metrics::ContainerStateCacheImpl::add_container( const mesos::ContainerID& container_id, const UDPEndpoint& endpoint) { if (!os::exists(container_state_dir)) { LOG(INFO) << "Creating new container state directory[" << container_state_dir << "]"; Try<Nothing> result = os::mkdir(container_state_dir); if (result.isError()) { LOG(ERROR) << "Failed to create container state directory[" << container_state_dir << "]: " << result.error(); return; } } std::string container_path = path::join(container_state_dir, sanitized_filename(container_id)); LOG(INFO) << "Writing container file[" << container_path << "] with " << "endpoint[" << endpoint.string() << "]"; JSON::Object json_obj; json_obj.values[CONTAINER_ID_KEY] = container_id.value(); json_obj.values[HOST_KEY] = endpoint.host; json_obj.values[PORT_KEY] = endpoint.port; Try<Nothing> result = os::write(container_path, stringify(json_obj)); } void metrics::ContainerStateCacheImpl::remove_container(const mesos::ContainerID& container_id) { std::string container_path = path::join(container_state_dir, sanitized_filename(container_id)); LOG(INFO) << "Removing container file[" << container_path << "]"; Try<Nothing> result = os::rm(container_path); if (result.isError()) { LOG(ERROR) << "Failed to remove container file[" << container_path << "]: " << result.error(); } }
Bosik927/DesignPatterns
Structural/src/main/java/com/github/bosik927/bridge/vehicle/workshops/control/AssembleWorkShop.java
package com.github.bosik927.bridge.vehicle.workshops.control; import com.github.bosik927.bridge.vehicle.vehicles.boundary.Vehicle; import com.github.bosik927.bridge.vehicle.workshops.boundary.WorkShop; import java.util.concurrent.TimeUnit; import static com.github.bosik927.bridge.vehicle.workshops.entity.WorkShopConstants.WORK_STATEMENT_PATTERN; public class AssembleWorkShop extends WorkShop { public AssembleWorkShop() { super(); } @Override public void work(Vehicle vehicle) { System.out.print("Assembling... "); long timeToTake = 200 * vehicle.minWorkTime(); try { TimeUnit.MILLISECONDS.sleep(timeToTake); } catch (InterruptedException exp) { // nothing to do for now. } System.out.printf(WORK_STATEMENT_PATTERN, timeToTake); } }
premisedata/spark
core/src/main/scala/spark/deploy/ExecutorState.scala
package spark.deploy private[spark] object ExecutorState extends Enumeration("LAUNCHING", "LOADING", "RUNNING", "KILLED", "FAILED", "LOST") { val LAUNCHING, LOADING, RUNNING, KILLED, FAILED, LOST = Value type ExecutorState = Value def isFinished(state: ExecutorState): Boolean = Seq(KILLED, FAILED, LOST).contains(state) }
cnelson87/GruntES6
grunt_tasks/handlebarslayouts.js
<gh_stars>0 /** * handlebarslayouts * Handlebars task to render Handlebars templates to HTML. */ module.exports = function (grunt) { return { options: { basePath: '<%= sourceHTML %>', partials: [ '<%= sourceHTML %>/_layouts/**/*.html', '<%= sourceHTML %>/_partials/**/*.html' ], modules: ['<%= sourceHTML %>/_helpers/**/*.js'], context: [ '<%= sourceHTML %>/_context/data.json', { 'appName': '<%= appName %>' } ] }, dev: { files: { '<%= devPath %>/*.html': ['<%= sourceHTML %>/*.html'], '<%= devPath %>/ajax-content/*.html': ['<%= sourceHTML %>/ajax-content/*.html'] } }, prod: { files: { '<%= prodPath %>/*.html': ['<%= sourceHTML %>/*.html'], '<%= prodPath %>/ajax-content/*.html': ['<%= sourceHTML %>/ajax-content/*.html'] } } }; };
PC-DOS/SEUCPP-OJ-KEYS
Contest 1003/F.cpp
<gh_stars>0 #include <iostream> #include <iomanip> using namespace std; int main(){ int iMonthSal; cin>>iMonthSal; double iTotal=iMonthSal*12.0-60000.0; double iTax; if (iTotal<=0){ cout<<0; return 0; } if (iTotal<=36000){ iTax=iTotal*0.03; } else if (iTotal > 36000 && iTotal <=144000){ iTax=36000.0*0.03+(iTotal-36000.0)*0.1; } else if (iTotal > 144000 && iTotal <=300000){ iTax=36000.0*0.03+(144000.0-36000.0)*0.1+(iTotal-144000.0)*0.2; } else if (iTotal > 300000 && iTotal <=420000){ iTax=36000.0*0.03+(144000.0-36000.0)*0.1+(300000.0-144000.0)*0.2+(iTotal-300000.0)*0.25; } else if (iTotal > 420000 && iTotal <=660000){ iTax=36000.0*0.03+(144000.0-36000.0)*0.1+(300000.0-144000.0)*0.2+(420000.0-300000.0)*0.25+(iTotal-420000.0)*0.3; } else if (iTotal > 660000 && iTotal <=960000){ iTax=36000.0*0.03+(144000.0-36000.0)*0.1+(300000.0-144000.0)*0.2+(420000.0-300000.0)*0.25+(660000.0-420000.0)*0.3+(iTotal-660000.0)*0.35; } else{ iTax=36000.0*0.03+(144000.0-36000.0)*0.1+(300000.0-144000.0)*0.2+(420000.0-300000.0)*0.25+(660000.0-420000.0)*0.3+(960000.0-660000.0)*0.35+(iTotal-960000.0)*0.45; } cout<<iTax; return 0; }
kelibst/fr-unitreview
src/components/Patients/PatientLogin.js
import React, { Component } from "react"; import { Button, Form } from "react-bootstrap"; import Icofont from "react-icofont"; import { connect } from "react-redux"; import { fetchPatient, loginPatientIn, } from "../../store/actions/PatientAction"; import ErrOrs from "../ErrOrs"; import Success from "../Success"; class PatientLogin extends Component { constructor(props) { super(props); this.state = { isSubmit: false, data: { email: "", }, }; } componentDidMount() { let jwtToken = localStorage.getItem("patJwt"); jwtToken = JSON.parse(jwtToken); const { fetchPatient, error } = this.props; jwtToken?.token?.length && fetchPatient(jwtToken); const { patient, history } = this.props; patient?.dates?.created_at?.length && jwtToken?.token?.length && history.push(`/client/dashboard`) } componentDidUpdate(prevProps, prevState) { const { patient, history, fetchPatient, error, success } = this.props; let jwtToken = localStorage.getItem("patJwt"); jwtToken = JSON.parse(jwtToken); const isNotEmpty = (obj) => Object.keys(obj).length !== 0; isNotEmpty(error) ? prevProps.error !== error && jwtToken?.exp && !patient?.dates?.created_at?.length && fetchPatient(jwtToken) : success.type === "login_success" && jwtToken?.exp && !patient && fetchPatient(jwtToken) patient?.dates?.created_at?.length && jwtToken?.token?.length && history.push(`/client/dashboard`) } render() { const { hospitalData } = this.props.hospital; const { loginPatientIn, success, error } = this.props; const handleChange = (e) => { const { id, value } = e.target; const { data } = this.state; this.setState({ ...this.state, data: { ...data, [id]: value, }, }); }; const handleSubmit = (e) => { e.preventDefault(); this.setState({ ...this.state, isSubmit: true }) const { data } = this.state; loginPatientIn(data); }; return ( <div className="login d-flex auth"> <div className="bg-light auth-header-cont col-md-4"> <h1 className="auth-head home-brand">{hospitalData?.body?.name}</h1> <div className="auth-header"> <div className="auth-header-title d-flex align-items-center"> <Icofont icon="address-book" className="auth-header-icon text-primary" /> <h4 className="fw-bold">Client Login</h4> </div> <p className="font-lg"> Welcome! <br></br> If you have recently been to{" "} {hospitalData?.body?.name}, Kindly login using your{" "} <span className="text-scuess">email</span> and tell us how we treated you. </p> <div className="form-footer"> {success?.type && <Success />} {error?.response && <ErrOrs />} </div> </div> </div> <div className="col-md-8 px-auto auth-form-cont bg-white"> <Form className="auth-form" onSubmit={handleSubmit}> <h6 className="fw-bold my-5">Login</h6> <Form.Group controlId="email" className="pb-3 my-2"> <Form.Control required type="email" className="py-2" placeholder="Enter email" onChange={handleChange} /> <Form.Text className="text-muted"> We will never share your email with anyone else. </Form.Text> </Form.Group> <Button className="auth-btn" type="submit"> Submit </Button> </Form> </div> </div> ); } } const mapStateToProps = (state) => ({ hospital: state.hospital, patient: state.patientsData.patient, success: state.success, error: state.errors.err, }); export default connect(mapStateToProps, { fetchPatient, loginPatientIn })( PatientLogin );
Balkerm/spring-data-examples
jpa/deferred/src/main/java/example/service/Customer595Service.java
package example.service; import example.repo.Customer595Repository; import org.springframework.stereotype.Service; @Service public class Customer595Service { public Customer595Service(Customer595Repository repo) {} }
jchn/preact-spectre
src/components/Grid/Container.js
/** @jsx h */ import { h } from 'preact' import PropTypes from 'prop-types' import { createComponent } from '../../utils' const GridClassModifiers = { size: size => `grid-${size}`, } const GridBase = createComponent('div', 'container', GridClassModifiers) const Grid = props => <GridBase {...props} /> Grid.propTypes = { size: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), } export default Grid
F-f-f-F/java-vk-bots-long-poll-api
src/main/java/api/longpoll/bots/model/response/stories/StoriesGetRepliesResult.java
<gh_stars>0 package api.longpoll.bots.model.response.stories; import api.longpoll.bots.model.objects.additional.StoriesFeedBlock; import api.longpoll.bots.model.response.ExtendedVkList; import api.longpoll.bots.model.response.GenericResult; /** * Response to <b>stories.getReplies</b> */ public class StoriesGetRepliesResult extends GenericResult<ExtendedVkList<StoriesFeedBlock>> { }
kaelgodlike/nentropy
multiraft/client/batch.go
<reponame>kaelgodlike/nentropy<gh_stars>0 // Copyright 2015 The Cockroach 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 client import ( "github.com/pkg/errors" "github.com/journeymidnight/nentropy/helper" "github.com/journeymidnight/nentropy/multiraft/multiraftbase" ) const ( raw = true notRaw = false ) // Batch provides for the parallel execution of a number of database // operations. Operations are added to the Batch and then the Batch is executed // via either DB.Run, Txn.Run or Txn.Commit. // // TODO(pmattis): Allow a timestamp to be specified which is applied to all // operations within the batch. type Batch struct { // Results contains an entry for each operation added to the batch. The order // of the results matches the order the operations were added to the // batch. For example: // // b := db.NewBatch() // b.Put("a", "1") // b.Put("b", "2") // _ = db.Run(b) // // string(b.Results[0].Rows[0].Key) == "a" // // string(b.Results[1].Rows[0].Key) == "b" Results []Result // The Header which will be used to send the resulting BatchRequest. // To be modified directly. Header multiraftbase.Header req multiraftbase.RequestUnion // Set when AddRawRequest is used, in which case using the "other" // operations renders the batch unusable. raw bool // Once received, the response from a successful batch. response *multiraftbase.BatchResponse // Once received, any error encountered sending the batch. pErr *multiraftbase.Error // We use pre-allocated buffers to avoid dynamic allocations for small batches. resultsBuf [8]Result rowsBuf []KeyValue rowsStaticBuf [8]KeyValue rowsStaticIdx int } // RawResponse returns the BatchResponse which was the result of a successful // execution of the batch, and nil otherwise. func (b *Batch) RawResponse() *multiraftbase.BatchResponse { return b.response } // MustPErr returns the structured error resulting from a failed execution of // the batch, asserting that that error is non-nil. func (b *Batch) MustPErr() *multiraftbase.Error { if b.pErr == nil { panic(errors.Errorf("expected non-nil pErr for batch %+v", b)) } return b.pErr } func (b *Batch) prepare() error { for _, r := range b.Results { if r.Err != nil { return r.Err } } return nil } func (b *Batch) initResult(calls, numRows int, raw bool, err error) { if err == nil && b.raw && !raw { err = errors.Errorf("must not use non-raw operations on a raw batch") } // TODO(tschottdorf): assert that calls is 0 or 1? r := Result{calls: calls, Err: err} if numRows > 0 { if b.rowsStaticIdx+numRows <= len(b.rowsStaticBuf) { r.Rows = b.rowsStaticBuf[b.rowsStaticIdx : b.rowsStaticIdx+numRows] b.rowsStaticIdx += numRows } else { // Most requests produce 0 (unknown) or 1 result rows, so optimize for // that case. switch numRows { case 1: // Use a buffer to batch allocate the result rows. if cap(b.rowsBuf)-len(b.rowsBuf) == 0 { const minSize = 16 const maxSize = 128 size := cap(b.rowsBuf) * 2 if size < minSize { size = minSize } else if size > maxSize { size = maxSize } b.rowsBuf = make([]KeyValue, 0, size) } pos := len(b.rowsBuf) r.Rows = b.rowsBuf[pos : pos+1 : pos+1] b.rowsBuf = b.rowsBuf[:pos+1] default: r.Rows = make([]KeyValue, numRows) } } } if b.Results == nil { b.Results = b.resultsBuf[:0] } b.Results = append(b.Results, r) } // fillResults walks through the results and updates them either with the // data or error which was the result of running the batch previously. func (b *Batch) fillResults() error { offset := 0 for i := range b.Results { result := &b.Results[i] for k := 0; k < result.calls; k++ { args := b.req.GetInner() var reply multiraftbase.Response // It's possible that result.Err was populated early, for example // when PutProto is called and the proto marshaling errored out. // In that case, we don't want to mutate this result's error // further. if result.Err == nil { // The outcome of each result is that of the batch as a whole. result.Err = b.pErr.GoError() if result.Err == nil { // For a successful request, load the reply to populate in // this pass. if b.response != nil { reply = b.response.Responses.GetInner() } else { helper.Panicln(5, errors.Errorf("not enough responses for calls: %+v, %+v", b.req, b.response)) } } } switch req := args.(type) { case *multiraftbase.GetRequest: row := &result.Rows[k] row.Key = []byte(req.Key) if result.Err == nil { //row.Value = reply.(*multiraftbase.GetResponse).Value getRes := b.response.Responses.GetValue().(*multiraftbase.GetResponse) row.Value = getRes.Value helper.Println(5, "sssssssss:", row.Value.RawBytes) } case *multiraftbase.PutRequest: row := &result.Rows[k] row.Key = []byte(req.Key) if result.Err == nil { row.Value = &req.Value } default: if result.Err == nil { result.Err = errors.Errorf("unsupported reply: %T for %T", reply, args) } } // Fill up the RangeInfos, in case we got any. if result.Err == nil && reply != nil { result.PgInfos = reply.Header().PgInfos } } offset += result.calls } for i := range b.Results { result := &b.Results[i] if result.Err != nil { return result.Err } } return nil } func (b *Batch) appendReq(req multiraftbase.Request) { b.req.MustSetInner(req) } // AddRawRequest adds the specified requests to the batch. No responses will // be allocated for them, and using any of the non-raw operations will result // in an error when running the batch. func (b *Batch) AddRawRequest(req multiraftbase.Request) { b.raw = true b.appendReq(req) b.initResult(1 /* calls */, 1, raw, nil) } // Get retrieves the value for a key. A new result will be appended to the // batch which will contain a single row. // // r, err := db.Get("a") // // string(r.Rows[0].Key) == "a" // // key can be either a byte slice or a string. func (b *Batch) Get(key multiraftbase.Key) { b.appendReq(multiraftbase.NewGet(key, 0, 0)) b.initResult(1, 1, notRaw, nil) } // Put sets the value for a key. // // A new result will be appended to the batch which will contain a single row // and Result.Err will indicate success or failure. // // key can be either a byte slice or a string. value can be any key type, a // proto.Message or any Go primitive type (bool, int, etc). func (b *Batch) Put(key multiraftbase.Key, value multiraftbase.Value) { b.appendReq(multiraftbase.NewPut(key, value)) b.initResult(1, 1, notRaw, nil) }
byxorna/nycmesh-tool
generated/go/uisp/models/site_update.go
<reponame>byxorna/nycmesh-tool // Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // SiteUpdate site update // // swagger:model SiteUpdate type SiteUpdate struct { // description // Required: true Description *SiteDescription1 `json:"description"` // id // Example: f7ac9cad-ea28-4390-93c8-7add010e8ee3 ID string `json:"id,omitempty"` // identification // Required: true Identification *SiteIdentificationDetail1 `json:"identification"` // notifications Notifications *SiteNotifications `json:"notifications,omitempty"` // qos Qos *SiteTrafficShaping1 `json:"qos,omitempty"` // ucrm Ucrm *SiteUcrmDescription `json:"ucrm,omitempty"` } // Validate validates this site update func (m *SiteUpdate) Validate(formats strfmt.Registry) error { var res []error if err := m.validateDescription(formats); err != nil { res = append(res, err) } if err := m.validateIdentification(formats); err != nil { res = append(res, err) } if err := m.validateNotifications(formats); err != nil { res = append(res, err) } if err := m.validateQos(formats); err != nil { res = append(res, err) } if err := m.validateUcrm(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *SiteUpdate) validateDescription(formats strfmt.Registry) error { if err := validate.Required("description", "body", m.Description); err != nil { return err } if m.Description != nil { if err := m.Description.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("description") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("description") } return err } } return nil } func (m *SiteUpdate) validateIdentification(formats strfmt.Registry) error { if err := validate.Required("identification", "body", m.Identification); err != nil { return err } if m.Identification != nil { if err := m.Identification.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("identification") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("identification") } return err } } return nil } func (m *SiteUpdate) validateNotifications(formats strfmt.Registry) error { if swag.IsZero(m.Notifications) { // not required return nil } if m.Notifications != nil { if err := m.Notifications.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("notifications") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("notifications") } return err } } return nil } func (m *SiteUpdate) validateQos(formats strfmt.Registry) error { if swag.IsZero(m.Qos) { // not required return nil } if m.Qos != nil { if err := m.Qos.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("qos") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("qos") } return err } } return nil } func (m *SiteUpdate) validateUcrm(formats strfmt.Registry) error { if swag.IsZero(m.Ucrm) { // not required return nil } if m.Ucrm != nil { if err := m.Ucrm.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("ucrm") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("ucrm") } return err } } return nil } // ContextValidate validate this site update based on the context it is used func (m *SiteUpdate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateDescription(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateIdentification(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateNotifications(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateQos(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateUcrm(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *SiteUpdate) contextValidateDescription(ctx context.Context, formats strfmt.Registry) error { if m.Description != nil { if err := m.Description.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("description") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("description") } return err } } return nil } func (m *SiteUpdate) contextValidateIdentification(ctx context.Context, formats strfmt.Registry) error { if m.Identification != nil { if err := m.Identification.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("identification") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("identification") } return err } } return nil } func (m *SiteUpdate) contextValidateNotifications(ctx context.Context, formats strfmt.Registry) error { if m.Notifications != nil { if err := m.Notifications.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("notifications") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("notifications") } return err } } return nil } func (m *SiteUpdate) contextValidateQos(ctx context.Context, formats strfmt.Registry) error { if m.Qos != nil { if err := m.Qos.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("qos") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("qos") } return err } } return nil } func (m *SiteUpdate) contextValidateUcrm(ctx context.Context, formats strfmt.Registry) error { if m.Ucrm != nil { if err := m.Ucrm.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("ucrm") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("ucrm") } return err } } return nil } // MarshalBinary interface implementation func (m *SiteUpdate) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *SiteUpdate) UnmarshalBinary(b []byte) error { var res SiteUpdate if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
icahoon/vocal
rtsp/rtspserver/RtspFileManager.hxx
#ifndef RtspFileManager_hxx #define RtspFileManager_hxx /* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. 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. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact <EMAIL>. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF 281421,000, NOR FOR ANY 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. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */ static const char* const RtspFileManager_hxx_version = "$Id: RtspFileManager.hxx,v 1.1 2004/05/01 04:15:23 greear Exp $"; #include "Sptr.hxx" #include "Data.hxx" #include "cpLog.h" #include <set> /** Maintins a list of files for access locking. Class doesn't check existance of file or acutally lock file on disk. Class is a singelton. This class doesn't use any mutex's so it's not multithread safe. */ class RtspFileManager { public: /** create a singelton object */ static RtspFileManager& instance(); /** destructor */ ~RtspFileManager(); /** frees the memory associated with singelton instance */ static void destroy(); /** adds a new file into manager @param filename name of new file to lock @return false on failure */ bool add( const Data& filename ); /** delete an existing file from manager @param filename name of file to unlock @return false on failure */ bool del( const Data& filename ); /** find if a file exists in manager @return true of exists */ bool find( const Data& filename ) const; private: /** constructor */ RtspFileManager(); /** singelton object */ static RtspFileManager* myInstance; /** set of locked filenames */ set<Data> myFilenameSet; protected: /** suppress copy constructor */ RtspFileManager( const RtspFileManager& ); /** suppress assignment operator */ RtspFileManager& operator=( const RtspFileManager& ); }; /* Local Variables: */ /* c-file-style: "stroustrup" */ /* indent-tabs-mode: nil */ /* c-file-offsets: ((access-label . -) (inclass . ++)) */ /* c-basic-offset: 4 */ /* End: */ #endif
GigahexHQ/jetprobe
project/BuildSettings.scala
<gh_stars>1-10 import sbt.Keys.{version, _} import sbt._ import com.typesafe.sbt.packager.Keys._ /** * @author Shad. */ object BuildSettings { lazy val basicSettings = Seq( organization := "com.jetprobe", resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots", version := "0.2.0-SNAPSHOT", scalaVersion := "2.12.2", crossScalaVersions := Seq("2.12.2", "2.11.8"), publishMavenStyle := true, scriptClasspath := Seq("*"), maintainer := "<NAME> <<EMAIL>>", packageSummary := "Jetprobe", homepage := Some(url("https://jetprobe.com")), scmInfo := Some(ScmInfo(url("https://github.com/jetprobe/jetprobe"), "<EMAIL>:jetprobe/jetprobe.git")), developers := List(Developer("amezng", "<NAME>", "<EMAIL>", url("https://github.com/amezng"))), licenses += ("Apache-2.0", url("http://www.apache.org/licenses/LICENSE-2.0")), pomIncludeRepository := (_ => false) ) }
andyyau520/uniclubdev
src/common/actions/routeActions.js
<gh_stars>10-100 import { push } from 'react-router-redux'; import { setCookie } from './cookieActions'; export const redirect = (path) => { return (dispatch) => { dispatch(setCookie('redirect', path)); dispatch(push(path)); }; };
zwergziege/tlaplus
tlatools/org.lamport.tlatools/test/tlc2/value/impl/TupleValueTest.java
/******************************************************************************* * Copyright (c) 2020 Microsoft Research. All rights reserved. * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ******************************************************************************/ package tlc2.value.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import tlc2.TLCGlobals; import tlc2.value.impl.IntervalValue; import tlc2.value.impl.SetOfTuplesValue; import tlc2.value.impl.TupleValue; import tlc2.value.impl.IntValue; import tlc2.value.impl.StringValue; import tlc2.value.impl.Value; import util.Assert; public class TupleValueTest { @Test public void testErrorMessages() { Value elems[] = {new StringValue("A")}; final TupleValue tupVal = new TupleValue(elems); try{ tupVal.apply(IntValue.gen(2), 0); } catch(Assert.TLCRuntimeException ex){ assertTrue(ex.getMessage().contains("Attempted to access index 2 of tuple\n<<\"A\">>\nwhich is out of bounds")); } try{ tupVal.apply(new StringValue("a"), 0); } catch(Assert.TLCRuntimeException ex){ assertTrue(ex.getMessage().contains("Attempted to access tuple at a non integral index: \"a\"")); } try{ tupVal.select(new StringValue("a")); } catch(Assert.TLCRuntimeException ex){ assertTrue(ex.getMessage().contains("Attempted to access tuple at a non integral index: \"a\"")); } try{ Value args[] = {new StringValue("arg1"), new StringValue("arg2")}; tupVal.apply(args, 0); } catch(Assert.TLCRuntimeException ex){ assertTrue(ex.getMessage().contains("Attempted to access tuple with 2 arguments when it expects 1.")); } } }
frederic-tingaud-sonarsource/xania
src/DescriptorList.hpp
#pragma once #include "Char.hpp" #include "Descriptor.hpp" #include "DescriptorFilter.hpp" #include <range/v3/view/filter.hpp> #include <range/v3/view/transform.hpp> #include <unordered_map> class DescriptorList { // We hand out pointers to Descriptors, so this structure must be address-stable. std::unordered_map<uint32_t, Descriptor> descriptors_; public: // Return all descriptors, including those in the process of logging in. [[nodiscard]] auto all() const noexcept { return descriptors_ | ranges::views::transform([](auto &pr) -> const Descriptor & { return pr.second; }); } [[nodiscard]] auto all() noexcept { return descriptors_ | ranges::views::transform([](auto &pr) -> Descriptor & { return pr.second; }); } // Return all descriptors for characters in the "playing" state. [[nodiscard]] auto playing() const noexcept { return all() | DescriptorFilter::playing(); } // Return all descriptors for playing characters, skipping the given character. [[nodiscard]] auto all_but(const Char &ch) const noexcept { return playing() | DescriptorFilter::except(ch); } // Return all descriptors for playing characters who are visible to the given character, including the character // themselves. [[nodiscard]] auto all_visible_to(const Char &ch) const noexcept { return playing() | DescriptorFilter::visible_to(ch); } // Return all descriptors for playing characters who can see the given character. [[nodiscard]] auto all_who_can_see(const Char &ch) const noexcept { return all_but(ch) | DescriptorFilter::can_see(ch); } // Try and find a descriptor by channel id. Descriptor *find_by_channel(uint32_t channel_id); // Create a new descriptor associated with the given channel. Fails if the channel is a duplicate. // The returned descriptor is owned by the list, and will remain valid until the descriptor is closed and // reap_closed is called. Descriptor *create(uint32_t channel_id); // Recover resources used by closed sockets. void reap_closed(); }; DescriptorList &descriptors();
AdvancedVEXLibrary/Advanced-VEX-Library
vex/include/avl_circlearea.h
<reponame>AdvancedVEXLibrary/Advanced-VEX-Library #pragma once #ifndef _AVL_CIRCLEAREA_H_ #define _AVL_CIRCLEAREA_H_ #include <math.h> float avl_circlearea(const float radius) { return M_PI * radius * radius; } #endif // _AVL_CIRCLEAREA_H_
SoftwareEngineeringToolDemos/type-inference
inference-framework/checker-framework/checkers/inference-tests/ajtests/p/TreeMap_KeyIterator.java
<reponame>SoftwareEngineeringToolDemos/type-inference /** * */ package p; import checkers.inference.aj.quals.*; /*internal*/class TreeMap_KeyIterator extends TreeMap_PrivateEntryIterator { public TreeMap_KeyIterator(/*@Aliased*/ TreeMap tm/*M=this.I*/){ super(tm); } public Object next() { return nextEntry().getKey(); } }
Cyberdog52/torenta
src/main/java/ch/andreskonrad/torenta/tmdb/service/TmdbService.java
<reponame>Cyberdog52/torenta package ch.andreskonrad.torenta.tmdb.service; import ch.andreskonrad.torenta.CustomCacheConfig; import ch.andreskonrad.torenta.tmdb.dto.TmdbEpisodeDto; import ch.andreskonrad.torenta.tmdb.dto.TmdbSearchResultDto; import ch.andreskonrad.torenta.tmdb.dto.TmdbSeasonDto; import ch.andreskonrad.torenta.tmdb.dto.TmdbSeriesDetailDto; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; @Service @CacheConfig(cacheNames={CustomCacheConfig.TMDB_CACHE_NAME}) public class TmdbService { @Value("${ch.andreskonrad.torenta.tmdb.service.key}") private String apiKey; private final String host = "api.themoviedb.org"; private final String scheme = "https"; private static final RequestThrottler requestThrottler = new RequestThrottler(9, 1000); @Cacheable public TmdbSearchResultDto search(String searchString) { String jsonStringResponse = searchRequest(searchString); try { return new ObjectMapper().readValue(jsonStringResponse, TmdbSearchResultDto.class); } catch (Exception e) { e.printStackTrace(); return null; } } @Cacheable public TmdbSeriesDetailDto get(int id) { String jsonStringResponse = detailRequest(id); try { return new ObjectMapper().readValue(jsonStringResponse, TmdbSeriesDetailDto.class); } catch (Exception e) { e.printStackTrace(); return null; } } @Cacheable public TmdbEpisodeDto[] getEpisodes(int seriesId, int season_number) { String jsonStringResponse = seasonRequest(seriesId, season_number); try { return new ObjectMapper() .readValue(jsonStringResponse, TmdbSeasonDto.class) .getEpisodes(); } catch (Throwable t) { t.printStackTrace(); return new TmdbEpisodeDto[0]; } } private String detailRequest(int id) { return httpGet(getDefaultComponentsBuilder() .path("/3/tv/" + String.valueOf(id)) .build() .encode() .toUri()); } private String searchRequest(String searchString) { return httpGet(getDefaultComponentsBuilder() .path("/3/search/tv") .queryParam("query", searchString.toLowerCase()) .queryParam("page", "1") .build() .encode() .toUri()); } private UriComponentsBuilder getDefaultComponentsBuilder() { return UriComponentsBuilder.newInstance() .scheme(scheme) .host(host) .queryParam("api_key", apiKey) .queryParam("language", "en-US"); } private String httpGet(URI uri) { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(uri) .setHeader("User-Agent", "Java 11 HttpClient Bot") .build(); try { requestThrottler.throttle(); return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body(); } catch (Exception e) { e.printStackTrace(); return null; } } private String seasonRequest(int seriesId, int season_number) { return httpGet(getDefaultComponentsBuilder() .path("/3/tv/" + String.valueOf(seriesId) + "/season/" + String.valueOf(season_number)) .build() .encode() .toUri()); } }
IIP-Sogang/Audio-Visual-Speech-Recognition
SCTK/src/rfilter1/rfilter1.c
<reponame>IIP-Sogang/Audio-Visual-Speech-Recognition /* EXPORT VERSION OF: */ /* rfilter1.c - filter that applies a rule set. */ /* This version recognizes a context-sensitive rule formalism. */ /* */ /* Synopsis: rfilter1 fname_rules (db_level) < file1 > file2 */ /* Process: Applies rules in file <fname_rules> to STDIN, writing */ /* result to STDOUT. */ /* Rules in general are of the form A => B / C __ D */ /* command-line parameters: */ /* par # contents */ /* 1 fname_rules (name of file holding rules) */ /* 2* db_level (level of de-bug printf's to do) */ /* (if db_level = 1, prints no. of hits for each rule,stderr) */ /* (*=optional) */ /* */ /* Modified 11/8/96 by WMF to: */ /* - increase input buffer size */ /* - provide a warning error message if input seems truncated */ /* - free all allocated memory on program exit */ /* - recognize a header record in the rules file that specifies */ /* case insensitivity for the matching parts of a rule */ /* - recognize optional left & right contexts in a rule */ /* - use a left-corner indexing scheme for speed */ /*******************************************************************/ /* standard compile environment files: */ #include "include/stdcenvp.h" int main(int argc, char **argv) {char *proc = "RFILTER1 Ver. 2.0"; time_t t_sec; Char rxf[LONG_LINE], *fname_rules = &rxf[0]; #define MAX_INPUT_REC 100000 Char pax[MAX_INPUT_REC], *pa = &pax[0]; Char pbx[MAX_INPUT_REC], *pb = &pbx[0]; Char *path = ""; int err; int *perr = &err; RULESET2 rset_data, *rset = &rset_data; /* code */ t_sec = time(&t_sec); /* ANSI, Turbo C */ pdb = strcpy(pdb,"*DB: "); if (argc < 2) {fprintf(stdout,"*ERR: no command-line parameters were given.\n"); fprintf(stdout," %s synopsis:\n",proc); fprintf(stdout," rfilter1 rule_file_name (db_level) < in_file > out_file\n"); return 2; } fname_rules = argv[1]; if (argc > 2) db_level = atoi(argv[2]); else db_level = 0; get_rules2(rset, path, fname_rules, perr); if (*perr > 0) {fprintf(stdout,"; *ERR: Get_rules2 returned err code =%d\n",*perr); return 3; } if (db_level > 1) printf("%s No. of rules = %d\n",pdb,rset->nrules); if (db_level > 2) {printf("%s *DB: the rules are:\n",pdb); dump_rules2(rset); } /* exercise the rules */ while (fgets(pa,MAX_INPUT_REC,stdin) != NULL) {if (*(pa + strlen(pa) - 1) != '\n') {fprintf(stderr,"*WARNING:%s: rec w/o newline char,",proc); fprintf(stderr," probably truncated.\n Line is:'%s'\n",pa); } if (db_level > 1) printf("%s pa=%s",pdb,pa); pb = strcpy(pb,""); pb = apply_rules2(pb,pa,rset,perr); if (db_level > 1) printf("%s pb=%s",pdb,pb); if (*perr == 0) fprintf(stdout,"%s",pb); else {fprintf(stderr,"*ERR: apply_rules2 returns perr=%d\n",*perr); return 4; } } if (db_level > 0) {fprintf(stderr, "%s *DB: At end of run, the rules (with val1= no. of hits) are:\n",pdb); dump_rules3(rset,stderr); } free_rules2(rset); return 0; } /* end main */ /* copies of functions from libraries: */ #include "include/aprules2.c" #include "include/drules2.c" #include "include/drules3.c" #include "include/frules2.c" #include "include/grules2.c" #include "include/dbpkg1.c" #include "include/pltrimf.c" #include "include/expenv.c" #include "include/strdup2.c" #include "include/boolpr1.c" #include "include/ss_len.c" #include "include/mfname1.c" #include "include/prtrim.c" #include "include/strncmpi.c" #include "include/calloc2.c" #include "include/prtrim2.c" #include "include/mupper.c" #include "include/valdata.c" #include "include/ss_to_s.c" #include "include/remcomm.c" #include "include/atobool.c" #include "include/gcomflag.c" #include "include/textlen.c" #include "include/del_eol.c" #include "include/frstr1.c" #include "include/sstok2.c" #include "include/fatalerr.c" #include "include/strcutr.c" #include "include/str_eq.c" #include "include/pltrim.c" #include "include/strcmpi.c"
pfalcon/llvmpy
llpython/phi_injector.py
#! /usr/bin/env python # ______________________________________________________________________ from .bytecode_visitor import BytecodeFlowVisitor, BenignBytecodeVisitorMixin # ______________________________________________________________________ synthetic_opname = [] synthetic_opmap = {} def def_synth_op (opname): global synthetic_opname, synthetic_opmap ret_val = -(len(synthetic_opname) + 1) synthetic_opname.insert(0, opname) synthetic_opmap[opname] = ret_val return ret_val REF_ARG = def_synth_op('REF_ARG') BUILD_PHI = def_synth_op('BUILD_PHI') DEFINITION = def_synth_op('DEFINITION') REF_DEF = def_synth_op('REF_DEF') # ______________________________________________________________________ class PhiInjector (BenignBytecodeVisitorMixin, BytecodeFlowVisitor): '''Transformer responsible for modifying a bytecode flow, removing LOAD_FAST and STORE_FAST opcodes, and replacing them with a static single assignment (SSA) representation. In order to support SSA, PhiInjector adds the following synthetic opcodes to transformed flows: * REF_ARG: Specifically reference an incomming argument value. * BUILD_PHI: Build a phi node to disambiguate between several possible definitions at a control flow join. * DEFINITION: Unique value definition indexed by the "arg" field in the tuple. * REF_DEF: Reference a specific value definition.''' def visit_cfg (self, cfg, nargs = 0, *args, **kws): self.cfg = cfg ret_val = self.visit(cfg.blocks, nargs) del self.cfg return ret_val def visit (self, flow, nargs = 0, *args, **kws): self.nargs = nargs self.definitions = [] self.phis = [] self.prev_blocks = [] self.blocks_locals = dict((block, {}) for block in self.cfg.blocks.keys()) ret_val = super(PhiInjector, self).visit(flow, *args, **kws) for block, _, _, args, _ in self.phis: local = args.pop() reaching_definitions = self.cfg.reaching_definitions[block] for prev in reaching_definitions.keys(): if 0 in self.cfg.blocks_reaching[prev]: args.append((prev, REF_DEF, 'REF_DEF', self.blocks_locals[prev][local], ())) args.sort() del self.blocks_locals del self.prev_blocks del self.phis del self.definitions del self.nargs return ret_val def add_definition (self, index, local, arg): definition_index = len(self.definitions) definition = (index, DEFINITION, 'DEFINITION', definition_index, (arg,)) self.definitions.append(definition) self.blocks_locals[self.block][local] = definition_index return definition def add_phi (self, index, local): ret_val = (index, BUILD_PHI, 'BUILD_PHI', [local], ()) self.phis.append(ret_val) return ret_val def enter_block (self, block): ret_val = False self.block = block if block == 0: if self.nargs > 0: ret_val = [self.add_definition(-1, arg, (-1, REF_ARG, 'REF_ARG', arg, ())) for arg in range(self.nargs)] else: ret_val = True elif 0 in self.cfg.blocks_reaching[block]: ret_val = True prev_block_locals = None for pred_block in self.cfg.blocks_in[block]: if pred_block in self.prev_blocks: prev_block_locals = self.blocks_locals[pred_block] break assert prev_block_locals is not None, "Internal translation error" self.blocks_locals[block] = prev_block_locals.copy() phis_needed = self.cfg.phi_needed(block) if phis_needed: ret_val = [self.add_definition(block, local, self.add_phi(block, local)) for local in phis_needed] return ret_val def exit_block (self, block): if 0 in self.cfg.blocks_reaching[block]: self.prev_blocks.append(block) del self.block def op_STORE_FAST (self, i, op, arg, *args, **kws): assert len(args) == 1 return [self.add_definition(i, arg, args[0])] def op_LOAD_FAST (self, i, op, arg, *args, **kws): return [(i, REF_DEF, 'REF_DEF', self.blocks_locals[self.block][arg], args)] # ______________________________________________________________________ def inject_phis (func): '''Given a Python function, return a bytecode flow object that has been transformed by a fresh PhiInjector instance.''' import byte_control, byte_flow argcount = byte_control.opcode_util.get_code_object(func).co_argcount cfg = byte_control.build_cfg(func) cfg.blocks = byte_flow.BytecodeFlowBuilder().visit_cfg(cfg) return PhiInjector().visit_cfg(cfg, argcount) # ______________________________________________________________________ # Main (self-test) routine def main (*args): import pprint from tests import llfuncs if not args: args = ('doslice',) for arg in args: pprint.pprint(inject_phis(getattr(llfuncs, arg))) # ______________________________________________________________________ if __name__ == "__main__": import sys main(*sys.argv[1:]) # ______________________________________________________________________ # End of phi_injector.py
eserial/eserial
src/main/java/hu/elte/eserial/annotation/enumeration/IncludeMatcher.java
<gh_stars>1-10 package hu.elte.eserial.annotation.enumeration; import hu.elte.eserial.annotation.IncludeMatching; /** * Used by the {@link IncludeMatching} annotation.<br> * {@link IncludeMatcher#NOT_NULL} makes an object's null values ignored when serializing,<br> * {@link IncludeMatcher#NOT_EMPTY} makes an object's empty values ignored. */ public enum IncludeMatcher { NOT_NULL, NOT_EMPTY }
wybrandvdmeer/functionalsql
src/functionalsql/functions/Report.java
package functionalsql.functions; import functionalsql.Function; import functionalsql.consumer.TableOrColumnConsumer; import java.util.ArrayList; import java.util.List; import static functionalsql.FunctionalSQLCompiler.ERR_SELECT_ALREADY_DEFINED; /** * Syntax: (sum|max|min)( summation_column | nummerical_constant , field1 , table.field2 , ... ) * */ public class Report extends Function { private final String function; private List<String> columns = new ArrayList<>(); private String reportFunction = null; public Report(String function) { this.function = function; build(new TableOrColumnConsumer(this, token -> reportFunction = token).singleValue().mandatory()); build(new TableOrColumnConsumer(this, token -> columns.add(token))); } public void execute() throws Exception { if (!getCompiler().getStatement().isVirginSelectClause()) { getCompiler().syntaxError(ERR_SELECT_ALREADY_DEFINED, getCompiler().getStatement().getSelectClause()); } /* If anything else, then it is a program error. */ assert ("SUM".equals(function) || "MAX".equals(function) || "MIN".equals(function)); String selectClause = "SELECT"; String groupByClause=null; if (columns.size() > 0) { groupByClause = "GROUP BY"; } for (int idx = 0; idx < columns.size(); idx++) { selectClause += " " + columns.get(idx); groupByClause += " " + columns.get(idx); if (idx < columns.size() - 1) { selectClause += ","; groupByClause += ","; } } getCompiler().getStatement().setGroupByClause(groupByClause); getCompiler().getStatement().setSelectClause( selectClause + String.format("%s %s( %s )", columns.size() > 0 ? "," : "", function, reportFunction)); } }
shpi0/MyRemoteBackUp
common/src/main/java/files/FileType.java
package files; public enum FileType { FILE, FOLDER }
vsomnath/graphretro
seq_graph_retro/data/collate_fns.py
import torch from rdkit import Chem import networkx as nx from seq_graph_retro.molgraph.mol_features import get_atom_features, get_bond_features from seq_graph_retro.molgraph.mol_features import BOND_FDIM, ATOM_FDIM, BOND_TYPES from seq_graph_retro.utils.torch import create_pad_tensor from typing import Any, List, Dict, Tuple def prepare_lg_labels(lg_dict: Dict, lg_data: List) -> torch.Tensor: """Prepare leaving group tensors. Parameters ---------- lg_dict: Dict Dictionary containing leaving groups to indices map lg_data: List List of lists containing the leaving groups """ pad_idx, unk_idx = lg_dict["<pad>"], lg_dict["<unk>"] lg_labels = [[lg_dict.get(lg_group, unk_idx) for lg_group in labels] for labels in lg_data] lengths = [len(lg) for lg in lg_labels] labels = torch.full(size=(len(lg_labels), max(lengths)), fill_value=pad_idx, dtype=torch.long) for i, lgs in enumerate(lg_labels): labels[i, :len(lgs)] = torch.tensor(lgs) return labels, lengths def pack_graph_feats(graph_batch: List[Any], directed: bool, use_rxn_class: bool = False, return_graphs: bool = False) -> Tuple[torch.Tensor, List[Tuple[int]]]: """Prepare graph tensors. Parameters ---------- graph_batch: List[Any], Batch of graph objects. Should have attributes G_dir, G_undir directed: bool, Whether to prepare tensors for directed message passing use_rxn_class: bool, default False, Whether to use reaction class as additional input return_graphs: bool, default False, Whether to return the graphs """ if directed: fnode = [get_atom_features(Chem.Atom("*"), use_rxn_class=use_rxn_class, rxn_class=0)] fmess = [[0,0] + [0] * BOND_FDIM] agraph, bgraph = [[]], [[]] atoms_in_bonds = [[]] atom_scope, bond_scope = [], [] edge_dict = {} all_G = [] for bid, graph in enumerate(graph_batch): mol = graph.mol assert mol.GetNumAtoms() == len(graph.G_dir) atom_offset = len(fnode) bond_offset = len(atoms_in_bonds) bond_to_tuple = {bond.GetIdx(): tuple(sorted((bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()))) for bond in mol.GetBonds()} tuple_to_bond = {val: key for key, val in bond_to_tuple.items()} atom_scope.append(graph.update_atom_scope(atom_offset)) bond_scope.append(graph.update_bond_scope(bond_offset)) G = nx.convert_node_labels_to_integers(graph.G_dir, first_label=atom_offset) all_G.append(G) fnode.extend( [None for v in G.nodes] ) for v, attr in G.nodes(data='label'): G.nodes[v]['batch_id'] = bid fnode[v] = get_atom_features(mol.GetAtomWithIdx(v-atom_offset), use_rxn_class=use_rxn_class, rxn_class=graph.rxn_class) agraph.append([]) bond_comp = [None for _ in range(mol.GetNumBonds())] for u, v, attr in G.edges(data='label'): bond_feat = get_bond_features(mol.GetBondBetweenAtoms(u-atom_offset, v-atom_offset)).tolist() bond = sorted([u, v]) mess_vec = [u, v] + bond_feat if [v, u] not in bond_comp: idx_to_add = tuple_to_bond[(u-atom_offset, v-atom_offset)] bond_comp[idx_to_add] = [u, v] fmess.append(mess_vec) edge_dict[(u, v)] = eid = len(edge_dict) + 1 G[u][v]['mess_idx'] = eid agraph[v].append(eid) bgraph.append([]) atoms_in_bonds.extend(bond_comp) for u, v in G.edges: eid = edge_dict[(u, v)] for w in G.predecessors(u): if w == v: continue bgraph[eid].append( edge_dict[(w, u)] ) fnode = torch.tensor(fnode, dtype=torch.float) fmess = torch.tensor(fmess, dtype=torch.float) atoms_in_bonds = create_pad_tensor(atoms_in_bonds).long() agraph = create_pad_tensor(agraph) bgraph = create_pad_tensor(bgraph) graph_tensors = (fnode, fmess, agraph, bgraph, atoms_in_bonds) scopes = (atom_scope, bond_scope) if return_graphs: return graph_tensors, scopes, nx.union_all(all_G) else: return graph_tensors, scopes else: afeat = [get_atom_features(Chem.Atom("*"), use_rxn_class=use_rxn_class, rxn_class=0)] bfeat = [[0] * BOND_FDIM] atoms_in_bonds = [[]] agraph, bgraph = [[]], [[]] atom_scope = [] bond_scope = [] edge_dict = {} all_G = [] for bid, graph in enumerate(graph_batch): mol = graph.mol assert mol.GetNumAtoms() == len(graph.G_undir) atom_offset = len(afeat) bond_offset = len(bfeat) atom_scope.append(graph.update_atom_scope(atom_offset)) bond_scope.append(graph.update_bond_scope(bond_offset)) G = nx.convert_node_labels_to_integers(graph.G_undir, first_label=atom_offset) all_G.append(G) afeat.extend( [None for v in G.nodes] ) for v, attr in G.nodes(data='label'): G.nodes[v]['batch_id'] = bid afeat[v] = get_atom_features(mol.GetAtomWithIdx(v-atom_offset), use_rxn_class=use_rxn_class, rxn_class=graph.rxn_class) agraph.append([]) bgraph.append([]) for u, v, attr in G.edges(data='label'): bond_feat = get_bond_features(mol.GetBondBetweenAtoms(u-atom_offset, v-atom_offset)).tolist() bfeat.append(bond_feat) atoms_in_bonds.append([u, v]) edge_dict[(u, v)] = eid = len(edge_dict) + 1 G[u][v]['mess_idx'] = eid agraph[v].append(u) agraph[u].append(v) bgraph[u].append(eid) bgraph[v].append(eid) afeat = torch.tensor(afeat, dtype=torch.float) bfeat = torch.tensor(bfeat, dtype=torch.float) atoms_in_bonds = create_pad_tensor(atoms_in_bonds).long() agraph = create_pad_tensor(agraph) bgraph = create_pad_tensor(bgraph) graph_tensors = (afeat, bfeat, agraph, bgraph, atoms_in_bonds) scopes = (atom_scope, bond_scope) if return_graphs: return graph_tensors, scopes, nx.union_all(all_G) else: return graph_tensors, scopes def tensorize_bond_graphs(graph_batch, directed: bool, use_rxn_class: False, return_graphs: bool = False): if directed: edge_dict = {} fnode = [[0] * BOND_FDIM] if use_rxn_class: fmess = [[0, 0] + [0] * (ATOM_FDIM + 10) + [0] + [0] * 2 * (BOND_FDIM - 1)] else: fmess = [[0, 0] + [0] * ATOM_FDIM + [0] + [0] * 2 * (BOND_FDIM - 1)] agraph, bgraph = [[]], [[]] scope = [] for bid, graph in enumerate(graph_batch): mol = graph.mol assert mol.GetNumAtoms() == len(graph.G_undir) offset = len(fnode) bond_graph = nx.line_graph(graph.G_undir) bond_graph = nx.to_directed(bond_graph) fnode.extend([None for v in bond_graph.nodes]) scope.append((offset, mol.GetNumBonds())) ri = mol.GetRingInfo() bond_rings = ri.BondRings() bond_to_tuple = {bond.GetIdx(): tuple(sorted((bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()))) for bond in mol.GetBonds()} tuple_to_bond = {val: key for key, val in bond_to_tuple.items()} for u in bond_graph.nodes(): agraph.append([]) atom_idx_a, atom_idx_b = u bond_idx = tuple_to_bond[u] + offset fnode[bond_idx] = get_bond_features(mol.GetBondBetweenAtoms(atom_idx_a, atom_idx_b)).tolist() for u, v in bond_graph.edges(): edge_dict[(u, v)] = eid = len(edge_dict) + 1 bond_idx_u = tuple_to_bond[tuple(sorted(u))] + offset bond_idx_v = tuple_to_bond[tuple(sorted(v))] + offset common_atom_idx = set(u).intersection(set(v)) incommon_ring = 0 for ring in bond_rings: if (bond_idx_u-offset) in ring and (bond_idx_v-offset) in ring: incommon_ring = 1 break common_atom = mol.GetAtomWithIdx(list(common_atom_idx)[0]) edge_feats = get_atom_features(common_atom, use_rxn_class=use_rxn_class, rxn_class=graph.rxn_class) + [incommon_ring] atom_idx_a, atom_idx_b = u atom_idx_c, atom_idx_d = v bond_u = mol.GetBondBetweenAtoms(atom_idx_a, atom_idx_b) bond_v = mol.GetBondBetweenAtoms(atom_idx_c, atom_idx_d) bt_u, bt_v = bond_u.GetBondType(), bond_v.GetBondType() conj_u, conj_v = bond_u.GetIsConjugated(), bond_v.GetIsConjugated() sorted_u, sorted_v = sorted([bt_u, bt_v]) feats_u = [float(sorted_u == bond_type) for bond_type in BOND_TYPES[1:]] feats_v = [float(sorted_v == bond_type) for bond_type in BOND_TYPES[1:]] edge_feats.extend(feats_u) edge_feats.extend(feats_v) edge_feats.extend(sorted([conj_u, conj_v])) mess_vec = [bond_idx_u, bond_idx_v] + edge_feats fmess.append(mess_vec) agraph[bond_idx_v].append(eid) bgraph.append([]) for u, v in bond_graph.edges(): eid = edge_dict[(u, v)] for w in bond_graph.predecessors(u): if w == v: continue bgraph[eid].append(edge_dict[(w, u)]) fnode = torch.tensor(fnode, dtype=torch.float) fmess = torch.tensor(fmess, dtype=torch.float) agraph = create_pad_tensor(agraph) bgraph = create_pad_tensor(bgraph) graph_tensors = (fnode, fmess, agraph, bgraph, None) return graph_tensors, scope
FliesenUI/FliesenUI
src/com/bright_side_it/fliesenui/screendefinition/model/ResourceDefinitionProblem.java
<gh_stars>1-10 package com.bright_side_it.fliesenui.screendefinition.model; public class ResourceDefinitionProblem { public enum ProblemType { WIDGET_TABLE_UNKNOWN_DTO_SPECIFIED, WIDGET_TABLE_NO_FIELD_IN_DTO_SPECIFIED, WIDGET_TABLE_DTO_TYPE_UNKNOWN, WIDGET_TABLE_UNKNOWN_DTO_FIELD , WIDGET_TABLE_DTO_BASIC_TYPE_WITH_NESTED_TYPE, WIDGET_TABLE_DTO_SUB_TYPE_UNKNOWN, WIDGET_TABLE_DTO_IS_NOT_A_LIST, WIDGET_TABLE_ITEM_DTO_FIELD_UNKNOWN , WIDGET_TABLE_ID_DTO_FIELD_DOES_NOT_EXIST, WIDGET_TABLE_ID_DTO_FIELD_HAS_WRONG_TYPE, WIDGET_TABLE_ITEM_FIELD_HAS_WRONG_TYPE, ID_PROBLEM_ID_EMPTY , ID_PROBLEM_ID_DOES_NOT_START_WITH_LOWER_CHAR, ID_PROBLEM_ID_CONTAINS_WRONG_CHAR, ID_PROBLEM_ID_USED_MULTIPLE_TIMES, BAR_PROBLEM_SUM_NOT_100 , BASIC_WIDGET_UNKNOWN_TYPE, WIDGET_TABLE_NO_COLUMNS, SPACE_WIDGET_MISSING_HEIGHT, SPACE_WIDGET_HEIGHT_TOO_SMALL, TEXT_FIELD_WIDGET_UNEXPECTED_HEIGHT , BASIC_WIDGET_MISSING_ATTRIBUTE, BASIC_WIDGET_UNEXPECTED_ATTRIBUTE, WIDGET_TABLE_WRONG_SIZE, WIDGET_TABLE_WRONG_TOTAL_COLUMN_SIZE, CELL_WRONG_COLOR_VALUE , EVENT_PARAMETER_UNKNOWN_DTO, EVENT_PARAMETER_UNKNOWN_NO_DTO_AND_NO_WIDGET, EVENT_PARAMETER_UNKNOWN_WIDGET, EVENT_PARAMETER_MISSING_WIDGET_PROPERTY , CELL_WRONG_HEIGHT, WIDGET_TABLE_WRONG_HEIGHT, WRONG_XML_NODE_NAME, INVALID_XML_DATA, WIDGET_TABLE_COLUMN_WITHOUT_ITEMS, WIDGET_TABLE_ITEM_MISSING_ID , LABEL_WIDGET_MISSING_ID, WIDGET_TABLE_NO_DTO_SPECIFIED, WIDGET_TABLE_ID_DTO_FIELD_IS_MISSING, EVENT_PARAMETER_WRONG_WIDGET_TYPE_REFERENCED , EVENT_PARAMETER_WRONG_WIDGET_PROPERTY, LABEL_WIDGET_UNEXPECTED_STYLE, BUTTON_WIDGET_UNEXPECTED_STYLE, PLUGIN_INSTANCE_UNKNOWN_TYPE, PLUGIN_INSTANCE_MISSING_ID , PLUGIN_PARAMETER_UNEXPECTED, PLUGIN_PARAMETER_MISSING, EVENT_PARAMETER_UNKNOWN_PLUGIN_INSTANCE, EVENT_PARAMETER_UNKNOWN_PLUGIN_DEFINITION , EVENT_PARAMETER_UNKNOWN_PLUGIN_VARIABLE, IMAGE_SOURCE_IMAGE_RESOURCE_UNKNOWN, IMAGE_SOURCE_UNKNOWN_FORMAT, IMAGE_SOUCE_MULTIPLE_LOCATIONS , IMAGE_SOUCE_MISSING_LOCATION, IMAGE_SOUCE_MISSING_FORMAT, IMAGE_ASSET_DUPLICATE_ID, IMAGE_SOURCE_WRONG_WIDTH, IMAGE_SOURCE_WRONG_HEIGHT , WIDGET_TABLE_ITEM_UNEXPECTED_TEXT, WIDGET_TABLE_ITEM_UNEXPECTED_TEXT_DTO_FIELD, WIDGET_TABLE_ITEM_MISSING_IMAGE_SOURCE , BASIC_WIDGET_WITH_IMAGE_SOURCE_IS_MISSING_ID, UNEXPECTED_XML_ATTRIBUTE, WIDGET_TABLE_ITEM_IMAGE_DTO_FIELD_HAS_WRONG_TYPE , SCREEN_DEFINITION_UNKNOWN_PARAMETER_DTO, SCREEN_DEFINITION_UNKNOWN_DTO_TYPE, PROJECT_CONTAINS_NO_SCREENS, PROJECT_START_SCREEN_MISSING , PROJECT_START_SCREEN_UNKNOWN, EVENT_HANDLER_SCREEN_PARAMETER_DTO_WITHOUT_SCREEN_PARAMETER, EVENT_HANDLER_SCREEN_TO_OPEN_UNKNOWN , EVENT_HANDLER_MISSING_PARAMETER_DTO, EVENT_HANDLER_WRONG_PARAMETER_DTO_TYPE, EVENT_HANDLER_UNKNOWN_CONTAINER, EVENT_CONTAINER_UNEXPECTED_TYPE , EVENT_HANDLER_SCREEN_TO_OPEN_AND_URL_TO_OPEN, TIMER_INTERVAL_TOO_SHORT, SElECT_BOX_NO_DTO_SPECIFIED, SELECT_BOX_UNKNOWN_DTO_SPECIFIED , SELECT_BOX_NO_FIELD_IN_DTO_SPECIFIED, SELECT_BOX_DTO_TYPE_UNKNOWN, SELECT_BOX_UNKNOWN_DTO_FIELD, SELECT_BOXDTO_BASIC_TYPE_WITH_NESTED_TYPE , SELECT_BOX_DTO_SUB_TYPE_UNKNOWN, SELECT_BOX_DTO_IS_NOT_A_LIST, SELECT_BOX_ID_DTO_FIELD_IS_MISSING, SELECT_BOX_LABEL_DTO_FIELD_IS_MISSING , SELECT_BOX_ID_DTO_FIELD_DOES_NOT_EXIST, SELECT_BOX_ID_DTO_FIELD_HAS_WRONG_TYPE, SELECT_BOX_LABEL_DTO_FIELD_DOES_NOT_EXIST , SELECT_BOX_LABEL_DTO_FIELD_HAS_WRONG_TYPE, CELL_INVISIBLE_WITHOUT_ID, LAYOUT_CONTAINER_INVISIBLE_WITHOUT_ID, LAYOUT_BAR_INVISIBLE_WITHOUT_ID, DTO_NO_FIELDS , DTO_FIELD_TYPE_UNKNOWN, BAR_PROBLEM_EMPTY_BAR, PROJECT_CONTAINS_NO_OUTPUTS, PROJECT_DEFINITION_COULD_NOT_READ_CHILD_NODES, PROJECT_OUTPUT_UNKNOWN_FLAVOR , PROJECT_OUTPUT_MISSING_SOURCE_DIR_PATH, PROJECT_OUTPUT_UNEXPECTED_ANDROID_PROJECT_PATH, PROJECT_OUTPUT_MISSING_ANDROID_PROJECT_PATH , PROJECT_OUTPUT_UNEXPECTED_SOURCE_DIR_PATH, SELECT_BOX_SELECTED_ID_DTO_FIELD_DOES_NOT_EXIST, BASIC_WIDGET_TEXT_DTO_FIELD_DOES_NOT_EXIST , SHARED_REPLY_INTERFACE_ID_USED_MULTIPLE_TIMES, SHARED_REPLY_INTERFACE_COULD_NOT_READ_CHILD_NODES, SHARED_REPLY_INTERFACE_NO_SCREENS_DEFINED , SHARED_REPLY_INTERFACE_UNKNOWN_SCREEN, SHARED_REPLY_INTERFACE_SCREEN_OCCURS_MULTIPLE_TIMES, SCREEN_DEFINITION_MULTIPLE_EVENT_LISTENERS_OF_SAME_TYPE , EVENT_HANDLER_BUTTON_TO_CLICK_DOES_NOT_EXIST, EVENT_HANDLER_BUTTON_TO_CLICK_IS_NOT_A_BUTTON, EVENT_HANDLER_TYPE_ENTER_FOR_NON_TEXT_FIELD , EVENT_HANDLER_TYPE_CLICK_FOR_NON_BUTTON, BASIC_WIDGET_LABEL_TEXT_STRING_RESOURCE_DOES_NOT_EXIST, BASIC_WIDGET_TEXT_STRING_RESOURCE_DOES_NOT_EXIST , WIDGET_TABLE_ITEM_TEXT_STRING_RESOURCE_DOES_NOT_EXIST, WIDGET_TABLE_COLUMN_TEXT_STRING_RESOURCE_DOES_NOT_EXIST, STRING_RESOURCE_NAME_CONTAINS_WRONG_CHAR , STRING_RESOURCE_NAME_OCCURES_MULTIPLE_TIMES, STRING_RESOURCE_NAME_DOES_NOT_OCCUR_IN_DEFAULT_LANGUAGE, EVENT_LISTENER_KEY_CHAR_TOO_LONG , EVENT_LISTENER_CHAR_USED_MULTIPLE_TIMES, EVENT_LISTENER_DIFFERENT_PARAMETERS, STRING_RESOURCE_DEFAULT_LANGUAGE_MISSING_WHILE_OTHER_LANGUAGE_IS_PROVIDED , EVENT_LISTENER_KEY_CODE_UNKNOWN, EVENT_LISTENER_NEITHER_CHAR_NOR_KEY_CODE, EVENT_LISTENER_CHAR_, EVENT_LISTENER_CHAR_AND_CODE_SPECIFIED , EVENT_LISTENER_CHAR_NOT_UPPER_CASE, EVENT_LISTENER_KEY_PRESS_WITH_CONTROL, EVENT_PARAMETER_WRONG_CHECKED_ROW_IDS_REQUIRED_ROW_CHECKBOXES , COLOR_PALETTE_COULD_NOT_READ_CHILD_NODES, COLOR_PALETTE_UNKNOWN_SHADE, COLOR_PALETTE_MISSING_COLOR, COLOR_PALETTE_WRONG_COLOR_VALUE , COLOR_PALETTE_SHADE_MULTIPLE_OCCURENCES, COLOR_PALETTE_COULD_NOT_READ_SHADE, PROJECT_UNKNOWN_COLOR_PALETTE, COLOR_PALETTE_DEFAULT_PALETTE_ID_USED , COLOR_PALETTE_UNKNOWN_PALETTE_EXTENDED, CELL_HEADLINE_WITHOUT_ID, CELL_SUBHEAD_WITHOUT_ID, LAYOUT_CONTAINER_BORDER_LAYOUT_IN_SUB_CONTAINER , LAYOUT_CONTAINER_BORDER_LAYOUT_WITHOUT_SIZES, LAYOUT_BAR_POSITION_MISSING_IN_BORDER_LAYOUT, LAYOUT_BAR_POSITION_BUT_NO_BORDER_LAYOUT , LAYOUT_BAR_DUBLICATE_POSITION, LAYOUT_CONTAINER_MISSING_BOTTOM_SIZE, LAYOUT_CONTAINER_MISSING_TOP_SIZE, LAYOUT_CONTAINER_MISSING_LEFT_SIZE , LAYOUT_CONTAINER_MISSING_RIGHT_SIZE, CALLBACK_METHOD_NAME_USED_MULTIPLE_TIMES, CALLBACK_METHOD_NAME_EMPTY, CALLBACK_METHOD_NAME_WRONG , CALLBACK_METHOD_PARAMETER_NAME_WRONG, CALLBACK_METHOD_PARAMETER_NAME_USED_MULTIPLE_TIMES, CALLBACK_METHOD_PARAMETER_TYPE_MISSING , CALLBACK_METHOD_PARAMETER_TYPE_UNKNOWN } private String message; private NodePath nodePath; private String attribute; private ProblemType type; public ProblemType getType() { return type; } public void setType(ProblemType type) { this.type = type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public NodePath getNodePath() { return nodePath; } public void setNodePath(NodePath nodePath) { this.nodePath = nodePath; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } }
brunobarbosagoncalves/chama-front-test
src/services/errorHandler.js
<reponame>brunobarbosagoncalves/chama-front-test import errorHandlerApi from 'api/errorHandler' export default async (error = {}, ref = '') => errorHandlerApi.post(`/?ref=${ref}`, JSON.stringify(error))
nolledge/circe-derivation
modules/annotations/shared/src/test/scala/io/circe/derivation/annotations/JsonCodecCustomSpec.scala
<gh_stars>0 package io.circe.derivation.annotations import io.circe._ import io.circe.parser._ import io.circe.syntax._ import org.scalatest._ object CustomJsonCodecSpecSamples { @JsonCodec case class Person( @JsonKey("n") name: String, @JsonNoDefault @JsonKey("a") age: Int = 0, optional: Option[String] = None ) @JsonCodec case class RemoveEmptyPerson( optional: Option[String] = None, values: List[String] = Nil, valuesSet: Set[String] = Set.empty[String], obj: Json = Json.obj() ) @JsonCodec case class Group(name: String, team: Map[String, Person]) } class CustomJsonCodecSpec extends WordSpec with Matchers { import CustomJsonCodecSpecSamples._ implicit val printer = Printer.noSpaces.copy(dropNullValues = true) "CustomJsonCodec" should { io.circe.Decoder "correct generate json" in { val p1 = Person("andrea") p1.asJson.pretty(printer) should be("{\"n\":\"andrea\"}") parse("""{"n":"andrea"}""").right.get.as[Person] should be(Right(p1)) } "remove empty values" in { val p1 = RemoveEmptyPerson() p1.asJson.pretty(printer) should be( """{"values":[],"valuesSet":[],"obj":{}}""" ) val p2 = RemoveEmptyPerson(values = List("a")) p2.asJson.pretty(printer) should be( """{"values":["a"],"valuesSet":[],"obj":{}}""" ) parse("""{}""").right.get.as[RemoveEmptyPerson] should be(Right(p1)) } "manage map" in { val g1 = Group("name", Map("peter" -> Person("Peter", 18))) g1.asJson.pretty(printer) should be( """{"name":"name","team":{"peter":{"n":"Peter","a":18}}}""" ) } } }
mattcarlotta/SJSITAPP-SSR
e2e/integration/mail/viewall.mail.spec.js
context("Staff View Mail Page", () => { before(() => { cy.exec("npm run seed:stage"); }); beforeEach(() => { cy.request("POST", "/api/signin", { email: "<EMAIL>", password: "password", }); cy.reload(); cy.visit("/employee/mail/viewall?page=1"); }); after(() => { cy.exec("npm run drop:stage"); }); it("displays the mail table", () => { cy.get(".ant-table-wrapper").should("have.length", 1); }); it("filters the mail table", () => { cy.get(".ant-pagination-total-text").contains("6 items"); cy.get("button#status").click(); cy.get(".ant-select").click(); cy.get("li[role=option]").eq(1).click(); cy.get(".ant-pagination-total-text").contains("3 items"); cy.get("button#clear-filters").click(); cy.get(".ant-pagination-total-text").contains("6 items"); }); it("deletes an email", () => { cy.get("[data-test=table-actions]").eq(2).click({ force: true }); cy.get("[data-test=delete-item]").click(); cy.get(".ant-popover-buttons").find("button").eq(1).click(); cy.get("[data-test=toast-message]") .should("have.length", 1) .and("have.text", "Successfully deleted the email."); }); it("resends an email", () => { cy.get(".ant-table-row") .eq(1) .find("[data-status=sent]") .should("have.length", 1); cy.get("[data-test=table-actions]").eq(1).click({ force: true }); cy.get("[data-test=send-mail]").click(); cy.get(".ant-table-row") .eq(1) .find("[data-status=unsent]") .should("have.length", 1); cy.get("[data-test=toast-message]") .should("have.length", 1) .and("have.text", "That email will be resent shortly."); }); it("deletes multiple emails", () => { cy.get("input[type=checkbox]").then(e => { const elements = e.map((_, el) => Cypress.$(el)); cy.wrap(elements[2]).click(); cy.wrap(elements[3]).click(); }); cy.get("[data-test=table-actions]").eq(2).click({ force: true }); cy.get("[data-test=delete-many-items]").click(); cy.get(".ant-popover-buttons").find("button").eq(1).click(); cy.get("[data-test=toast-message]") .should("have.length", 1) .and("have.text", "Successfully deleted the mail."); }); it("navigates to a Send Mail page", () => { cy.get(".send-mail").click(); cy.url().should("contain", "/employee/mail/create"); cy.get("form").should("have.length", 1); }); it("navigates to an Edit Mail page", () => { cy.get("[data-test=table-actions]").first().click({ force: true }); cy.get("[data-test=edit-location]").click(); cy.url().should("contain", "/employee/mail/edit"); cy.get("form").should("have.length", 1); }); });
russells-crockpot/roll-with-it
tests/parsing/test_loops.py
<filename>tests/parsing/test_loops.py # pylint: disable=missing-docstring,unused-import,no-member from .util import create_scripttest_func test_until_do = create_scripttest_func('until_do') test_restart = create_scripttest_func('restart') test_for_every = create_scripttest_func('for_every')
jmhong-simulation/LithopiaOpen
Engine/Geometry/RAY.h
// The Lithopia project initiated by <NAME> for 3D Printing Community. // Copyright (c) 2015 <NAME> - All Rights Reserved. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. #pragma once #include "../GENERIC_DEFINITIONS.h" class RAY { public: TV origin_; TV direction_; T t_end_; public: RAY(const TV& _origin, const TV& _direction, const T& _t_end) : origin_(_origin), direction_(_direction), t_end_(_t_end) {} RAY(const TV& _start, const TV& _end) // : origin_(_start), t_end_((_end - _start).GetMagnitude()), direction_((_end-_start)/t_end_) { origin_ = _start; t_end_ = (_end - _start).getMagnitude(); direction_ = (_end - _start) / t_end_; } const T GetSphereIntersection(const TV& center, const T& radius) const; const TV GetPosition(const T& t) const; const bool CheckTriangleIntersection(const TV& tri_v0, const TV& tri_v1, const TV& tri_v2, const RAY& segment) const; };
yixuan-wei/PersonalEngine
Code/Engine/Math/Vec4.cpp
#include "Engine/Math/Vec4.hpp" #include "Engine/Math/Vec3.hpp" #include "Engine/Math/Vec2.hpp" ////////////////////////////////////////////////////////////////////////// Vec4::Vec4( const Vec4& copyFrom ) :x(copyFrom.x) ,y(copyFrom.y) ,z(copyFrom.z) ,w(copyFrom.w) { } ////////////////////////////////////////////////////////////////////////// Vec4::Vec4( float initialX, float initialY, float initialZ, float initialW ) :x(initialX) ,y(initialY) ,z(initialZ) ,w(initialW) { } ////////////////////////////////////////////////////////////////////////// Vec4::Vec4(Vec3 const& copyFrom, float initialW /*= 0.f*/) :x(copyFrom.x) ,y(copyFrom.y) ,z(copyFrom.z) ,w(initialW) { } ////////////////////////////////////////////////////////////////////////// float Vec4::GetLengthSquared() const { return x * x + y * y + z * z + w * w; } ////////////////////////////////////////////////////////////////////////// Vec3 Vec4::GetXYZ() const { return Vec3(x, y, z); } ////////////////////////////////////////////////////////////////////////// Vec2 Vec4::GetXY() const { return Vec2(x, y); } ////////////////////////////////////////////////////////////////////////// bool Vec4::operator!=( const Vec4& compare ) const { if( x != compare.x || y != compare.y || z != compare.z || w != compare.w ) return true; return false; } ////////////////////////////////////////////////////////////////////////// bool Vec4::operator==( const Vec4& compare ) const { if( x == compare.x && y == compare.y && z == compare.z && w == compare.w ) return true; return false; } ////////////////////////////////////////////////////////////////////////// const Vec4 Vec4::operator+( const Vec4& vecToAdd ) const { return Vec4( x + vecToAdd.x, y + vecToAdd.y, z + vecToAdd.z, w + vecToAdd.w ); } ////////////////////////////////////////////////////////////////////////// const Vec4 Vec4::operator-( const Vec4& vecToSubstract ) const { return Vec4( x - vecToSubstract.x, y - vecToSubstract.y, z - vecToSubstract.z, w - vecToSubstract.w ); } ////////////////////////////////////////////////////////////////////////// const Vec4 Vec4::operator-() const { return Vec4( -x, -y, -z, -w ); } ////////////////////////////////////////////////////////////////////////// void Vec4::operator/=( const float uniformDivisor ) { if( uniformDivisor == 0.f ) return; float scale = 1.f / uniformDivisor; x *= scale; y *= scale; z *= scale; w *= scale; } ////////////////////////////////////////////////////////////////////////// void Vec4::operator=( const Vec4& copyFrom ) { x = copyFrom.x; y = copyFrom.y; z = copyFrom.z; w = copyFrom.w; } ////////////////////////////////////////////////////////////////////////// void Vec4::operator*=( const float uniformScale ) { x *= uniformScale; y *= uniformScale; z *= uniformScale; w *= uniformScale; } ////////////////////////////////////////////////////////////////////////// const Vec4 Vec4::operator*( float uniformScale ) const { return Vec4( x * uniformScale, y * uniformScale, z * uniformScale, w * uniformScale ); } ////////////////////////////////////////////////////////////////////////// const Vec4 Vec4::operator*( const Vec4& vecToMultiply ) const { return Vec4(x * vecToMultiply.x, y * vecToMultiply.y, z * vecToMultiply.z, w * vecToMultiply.w); } ////////////////////////////////////////////////////////////////////////// const Vec4 Vec4::operator/( float inverseScale ) const { if( inverseScale == 0.f ) return Vec4( x, y, z, w ); float scale = 1.f / inverseScale; return Vec4( x * scale, y * scale, z * scale, w * scale ); } ////////////////////////////////////////////////////////////////////////// void Vec4::operator-=( const Vec4& vecToSubstract ) { x -= vecToSubstract.x; y -= vecToSubstract.y; z -= vecToSubstract.z; w -= vecToSubstract.w; } ////////////////////////////////////////////////////////////////////////// void Vec4::operator+=( const Vec4& vecToAdd ) { x += vecToAdd.x; y += vecToAdd.y; z += vecToAdd.z; w += vecToAdd.w; } ////////////////////////////////////////////////////////////////////////// const Vec4 operator*( float uniformScale, const Vec4& vecToScale ) { return Vec4( uniformScale * vecToScale.x, uniformScale * vecToScale.y, uniformScale * vecToScale.z, uniformScale * vecToScale.w ); }
HairLee/MyElcomMain
app/src/main/java/com/elcom/myelcom/view/ui/activity/SettingActivity.java
<reponame>HairLee/MyElcomMain package com.elcom.myelcom.view.ui.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.elcom.myelcom.R; import com.elcom.myelcom.core.base.BaseActivity; import com.elcom.myelcom.databinding.ActivitySettingBinding; import com.elcom.myelcom.model.api.response.Support; import com.elcom.myelcom.util.PreferUtils; import com.elcom.myelcom.util.Toaster; import com.elcom.myelcom.view.ui.LoginActivity; import com.elcom.myelcom.viewmodel.SettingViewModel; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.users.QBUsers; public class SettingActivity extends BaseActivity<SettingViewModel,ActivitySettingBinding> implements View.OnClickListener { private SettingViewModel viewModel; private TextView tvEmail; @Override protected Class<SettingViewModel> getViewModel() { return SettingViewModel.class; } @Override protected void onCreate(Bundle instance, SettingViewModel viewModel, ActivitySettingBinding binding) { this.viewModel = viewModel; findViewById(R.id.rlPassword).setOnClickListener(this); findViewById(R.id.tvLogout).setOnClickListener(this); findViewById(R.id.imvBack).setOnClickListener(this); findViewById(R.id.rlNotification).setOnClickListener(this); tvEmail = findViewById(R.id.tvEmail); tvEmail.setText(PreferUtils.getEmail(this)); viewModel.logout().observe(this, jsonElementRestData -> { hideProgressDialog(); if (jsonElementRestData.status_code == 200){ PreferUtils.setToken(this,""); Intent intent = new Intent(SettingActivity.this,LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } else { Toaster.longToast(jsonElementRestData.message); } } ); viewModel.getSupport().observe(this, supportRestData -> { if(supportRestData != null && supportRestData.data != null){ Support support = supportRestData.data; binding.tvSupport.setText(support.getBuilding_techniques()); binding.tvItSupport.setText(support.getSupport_it()); binding.tvCofee.setText(support.getBlackbox_coffee()); } }); } @Override protected int getLayoutResId() { return R.layout.activity_setting; } public static void start(Context context) { Intent starter = new Intent(context, SettingActivity.class); context.startActivity(starter); } private void logout(){ showProgressDialog(); QBUsers.signOut().performAsync(new QBEntityCallback<Void>() { @Override public void onSuccess(Void aVoid, Bundle bundle) { } @Override public void onError(QBResponseException e) { showProgressDialog(); } }); viewModel.setRequest(PreferUtils.getToken(SettingActivity.this)); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.rlPassword: SettingChangePwActivity.start(this); break; case R.id.tvLogout: logout(); break; case R.id.imvBack: onBackPressed(); break; case R.id.rlNotification: NotificationActivity.start(this); break; } } }
13939094104/Gtokrn
app/src/main/java/vdsMain/clue/LastWeekClueItem.java
<gh_stars>1-10 package vdsMain.clue; import generic.keyid.CTxDestinationFactory; import generic.io.StreamWriter; import generic.serialized.SeriableData; import vdsMain.CTxDestination; import java.io.IOException; import java.math.BigInteger; //bju public class LastWeekClueItem extends SeriableData { /* renamed from: a */ public CTxDestination f11808a; /* renamed from: b */ public BigInteger f11809b; /* renamed from: c */ public double f11810c = 0.0d; public void writeSerialData(StreamWriter streamWriter) throws IOException { this.f11808a.writeTypeAndData(streamWriter); streamWriter.writeUInt64(this.f11809b); streamWriter.writeDouble(this.f11810c); } public void onDecodeSerialData() throws IOException { this.f11808a = CTxDestinationFactory.m910a((SeriableData) this); this.f11809b = readUInt64(); this.f11810c = readDouble(); } }
YunuSahin/sdk
src/org.scn.community.utils/res/PdfPrint/aps/PdfPrintPropertyPage.js
<reponame>YunuSahin/sdk sap.designstudio.sdk.PropertyPage.subclass("org.scn.community.utils.PdfPrintPropertyPage", function() { var that = this; this.init = function() { $("#select").change(function() { that.firePropertiesChanged(["pdfMethod"]); return false; }); }; this.pdfMethod = function(value) { if (value === undefined) { return $("#select").val(); } else { $("#select").val(value); } }; });
r-dgreen/DashTable
dashtable/data2rst/merge_all_cells.py
<reponame>r-dgreen/DashTable from .cell import get_merge_direction from .cell import merge_cells def merge_all_cells(cells): """ Loop through list of cells and piece them together one by one Parameters ---------- cells : list of dashtable.data2rst.Cell Returns ------- grid_table : str The final grid table """ current = 0 while len(cells) > 1: count = 0 while count < len(cells): cell1 = cells[current] cell2 = cells[count] merge_direction = get_merge_direction(cell1, cell2) if not merge_direction == "NONE": merge_cells(cell1, cell2, merge_direction) if current > count: current -= 1 cells.pop(count) else: count += 1 current += 1 if current >= len(cells): current = 0 return cells[0].text
untoldwind/trustless-gtk3
main.go
package main import ( "context" "fmt" "os" "path/filepath" "time" "github.com/davecgh/go-spew/spew" "github.com/leanovate/microtools/logging" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/untoldwind/amintk/gtk" "github.com/untoldwind/trustless-gtk3/state" "github.com/untoldwind/trustless-gtk3/ui" "github.com/untoldwind/trustless/config" "github.com/untoldwind/trustless/daemon" "github.com/untoldwind/trustless/secrets" "github.com/untoldwind/trustless/secrets/pgp" "github.com/untoldwind/trustless/secrets/remote" ) var rootCommand = &cobra.Command{ Use: "Trustless GTK3", Short: "GTK3 frontend of trustless", Run: run, } var cmdSettings config.Settings var cfgFile string var startDaemon bool func showError(err error) { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error()) if cmdSettings.Debug { fmt.Fprintln(os.Stderr) spew.Fdump(os.Stderr, err) } os.Exit(1) } func init() { cobra.MousetrapHelpText = "" cobra.OnInitialize(initConfig) rootCommand.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default ./trustless.toml, $HOME/.trustless/trustless.toml") rootCommand.PersistentFlags().String("node-id", "", "ID of this node") rootCommand.PersistentFlags().String("store-url", "", "URL of the store to open (only file:// URLs are supported)") rootCommand.PersistentFlags().String("store-scheme", "openpgp", "Storage scheme (openpgp, openpgp+scrypt)") rootCommand.PersistentFlags().String("log-file", "", "Log to file instead stdout") rootCommand.PersistentFlags().String("log-format", "text", "Log format to use (test, json, logstash)") rootCommand.PersistentFlags().Bool("debug", false, "Enable debug information") rootCommand.PersistentFlags().Duration("unlock-timeout", 5*time.Minute, "AUtomatic lock timeout") rootCommand.PersistentFlags().Bool("unlock-timeout-hard", false, "Enable hard timeout") rootCommand.PersistentFlags().BoolVar(&startDaemon, "daemon", false, "Start daemon") viper.BindPFlags(rootCommand.PersistentFlags()) } func initConfig() { viper.SetEnvPrefix("TRUSTLESS") viper.AutomaticEnv() if err := viper.Unmarshal(&cmdSettings); err != nil { showError(err) } if cmdSettings.Debug { fmt.Fprintln(os.Stderr, "---- Settings [snip]----") spew.Fdump(os.Stderr, cmdSettings) fmt.Fprintln(os.Stderr, "---- Settings [snap] ----") } } func createLogger() logging.Logger { loggingOptions := logging.Options{ Backend: "simple", LogFile: cmdSettings.LogFile, LogFormat: cmdSettings.LogFormat, Level: logging.Info, } if cmdSettings.Debug { loggingOptions.Level = logging.Debug } return logging.NewLogger(loggingOptions). WithContext(map[string]interface{}{"process": "trustless-gtk3"}) } func readConfig() (*config.Settings, error) { var settings config.Settings if cfgFile != "" { viper.SetConfigFile(cfgFile) } else { home, err := homedir.Dir() if err != nil { showError(err) } viper.AddConfigPath(".") viper.AddConfigPath(home) viper.AddConfigPath(filepath.Join(home, ".config")) viper.SetConfigName("trustless") } if err := viper.ReadInConfig(); err != nil { if err := writeDefaultConfig(); err != nil { return nil, err } } if err := viper.Unmarshal(&settings); err != nil { return nil, err } if settings.Debug { fmt.Fprintln(os.Stderr, "---- Settings [snip]----") spew.Fdump(os.Stderr, settings) fmt.Fprintln(os.Stderr, "---- Settings [snap] ----") } return &settings, nil } func writeDefaultConfig() error { if viper.GetString("store-url") == "" { viper.Set("store-url", config.DefaultStoreURL()) } if viper.GetString("node-id") == "" { nodeId, err := config.GenerateNodeID() if err != nil { return err } viper.Set("node-id", nodeId) } home, err := homedir.Dir() if err != nil { showError(err) } os.MkdirAll(filepath.Join(home, ".config"), 0700) return viper.WriteConfigAs(filepath.Join(home, ".config", "trustless.toml")) } func run(cmd *cobra.Command, args []string) { gtk.Init(nil) logger := createLogger() var secrets secrets.Secrets if remote.RemoteAvailable(logger) { logger.Info("Use remote store") secrets = remote.NewRemoteSecrets(logger) } else { logger.Info("Starting own daemon") settings, err := readConfig() if err != nil { showError(err) } scrypted := false switch settings.StoreScheme { case "openpgp+scrypt": scrypted = true } secrets, err = pgp.NewPGPSecrets(settings.StoreURL, scrypted, settings.NodeID, 4096, settings.UnlockTimeout, settings.UnlockTimeoutHard, logger) if err != nil { showError(err) } defer secrets.Lock(context.Background()) if startDaemon { daemon := daemon.NewDaemon(secrets, logger) if err := daemon.Start(); err != nil { showError(err) } defer daemon.Stop() } } store, err := state.NewStore(secrets, logger) if err != nil { logger.ErrorErr(err) showError(err) } window, err := ui.NewMainWindow(store, logger) if err != nil { logger.ErrorErr(err) showError(err) } window.ShowAll() gtk.Main() } func main() { if err := rootCommand.Execute(); err != nil { showError(err) } }
cbFabian/Ceiba-Drogueria
microservicio/aplicacion/src/main/java/com/ceiba/pedido/comando/fabrica/FabricaPedido.java
package com.ceiba.pedido.comando.fabrica; import com.ceiba.pedido.modelo.entidad.Pedido; import org.springframework.stereotype.Component; import com.ceiba.pedido.comando.ComandoPedido; import java.text.SimpleDateFormat; import java.util.Date; @Component public class FabricaPedido { public Pedido crear(ComandoPedido comandoPedido) { Date fecha; try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); fecha = sdf.parse(comandoPedido.getFecha()); } catch (Exception ex) { fecha = null; } return new Pedido( comandoPedido.getId(), fecha, comandoPedido.getDomicilio(), comandoPedido.getLstProductos() ); } }
simonzabrocki/Anticipe
data/indicator/ME2/__init__.py
from data.indicator.ME2.preprocess import config
ai2cm/fv3gfs-util
tests/conftest.py
import pytest import fv3gfs.util import numpy as np try: import gt4py except ModuleNotFoundError: gt4py = None try: import cupy except ModuleNotFoundError: cupy = None @pytest.fixture(params=["numpy", "cupy", "gt4py_numpy", "gt4py_cupy"]) def backend(request): if cupy is None and request.param.endswith("cupy"): if request.config.getoption("--gpu-only"): raise ModuleNotFoundError("cupy must be installed to run gpu tests") else: pytest.skip("cupy is not available for GPU backend") elif gt4py is None and request.param.startswith("gt4py"): pytest.skip("gt4py backend is not available") elif request.config.getoption("--gpu-only") and not request.param.endswith("cupy"): pytest.skip("running gpu tests only") else: return request.param @pytest.fixture def fast(pytestconfig): return pytestconfig.getoption("--fast") @pytest.fixture def numpy(backend): if backend == "numpy": return np elif backend == "cupy": return cupy elif backend.startswith("gt4py"): if backend.endswith("numpy"): return fv3gfs.util.testing.gt4py_numpy elif backend.endswith("cupy"): return fv3gfs.util.testing.gt4py_cupy else: raise NotImplementedError() def pytest_addoption(parser): parser.addoption( "--gpu-only", action="store_true", default=False, help="only run gpu tests" ) parser.addoption( "--fast", action="store_true", default=False, help="run a limited suite of tests which completes quickly", ) def pytest_configure(config): config.addinivalue_line("markers", "cpu_only: mark test as not using a gpu") def pytest_collection_modifyitems(config, items): if config.getoption("--gpu-only"): skip_cpu_only = pytest.mark.skip(reason="running gpu tests only") for item in items: if "cpu_only" in item.keywords: item.add_marker(skip_cpu_only)
mfernba/rGWB
rGWB/csmsetop_procedges.c
// // csmsetop_procedges.c // rGWB // // Created by <NAME> on 22/5/17. // Copyright © 2017 <NAME>. All rights reserved. // #include "csmsetop_procedges.inl" #include "csmarrayc.h" #include "csmbbox.inl" #include "csmdebug.inl" #include "csmedge.inl" #include "csmedge.tli" #include "csmeuler_lmev.inl" #include "csmface.inl" #include "csmhashtb.inl" #include "csmhashtb2id.inl" #include "csmhedge.inl" #include "csmid.inl" #include "csmmath.inl" #include "csmmath.tli" #include "csmopbas.inl" #include "csmsetop.tli" #include "csmsetop_vtxfacc.inl" #include "csmsetop_vtxvtx.inl" #include "csmsolid.inl" #include "csmtolerance.inl" #include "csmvertex.inl" #include "csmvertex.tli" #ifdef RGWB_STANDALONE_DISTRIBUTABLE #include "csmassert.inl" #include "csmmem.inl" #include "csmstring.inl" #else #include "cyassert.h" #include "cypespy.h" #include "copiafor.h" #endif enum i_intersection_position_t { i_INTERSECTION_POSITION_AT_EDGE_VERTEX, i_INTERSECTION_POSITION_AT_EDGE_INTERIOR }; enum i_type_edge_intersection_t { i_TYPE_EDGE_INTERSECTION_VERTEX, i_TYPE_EDGE_INTERSECTION_INTERIOR_EDGE, i_TYPE_EDGE_INTERSECTION_INTERIOR_FACE }; struct i_edge_intersection_t { unsigned long intersection_id; CSMBOOL generate_intersection; enum i_intersection_position_t intersection_position_at_edge; struct csmvertex_t *edge_vertex; double x_edge_interior, y_edge_interior, z_edge_interior; double t_absolute_intersection_on_edge; struct csmface_t *face; enum i_type_edge_intersection_t edge_intersection_at_face; struct csmvertex_t *hit_vertex_at_face; struct csmhedge_t *hit_hedge_at_face; double x_edge_interior_hedge_at_face, y_edge_interior_hedge_at_face, z_edge_interior_hedge_at_face; double tolerance_equal_coords; }; struct i_optimized_edge_data_t { struct csmvertex_t *vertex_pos, *vertex_neg; unsigned long edge_id; double x1, y1, z1, x2, y2, z2; double length; }; /* struct i_inters_vertex_t { struct csmvertex_t *vertex; struct csmhashtb(csmvertex_t) *overlapped_vertexs; }; */ csmArrayStruct(i_edge_intersection_t); // ------------------------------------------------------------------------------------------ CONSTRUCTOR(static struct i_edge_intersection_t *, i_create_edge_intersection, ( unsigned long intersection_id, CSMBOOL generate_intersection, enum i_intersection_position_t intersection_position_at_edge, struct csmvertex_t *edge_vertex, double x_edge_interior, double y_edge_interior, double z_edge_interior, double t_absolute_intersection_on_edge, struct csmface_t *face, enum i_type_edge_intersection_t edge_intersection_at_face, struct csmvertex_t *hit_vertex_at_face, struct csmhedge_t *hit_hedge_at_face, double x_edge_interior_hedge_at_face, double y_edge_interior_hedge_at_face, double z_edge_interior_hedge_at_face, double tolerance_equal_coords)) { struct i_edge_intersection_t *edge_intersection; edge_intersection = MALLOC(struct i_edge_intersection_t); edge_intersection->intersection_id = intersection_id; edge_intersection->generate_intersection = generate_intersection; edge_intersection->intersection_position_at_edge = intersection_position_at_edge; edge_intersection->edge_vertex = edge_vertex; edge_intersection->x_edge_interior = x_edge_interior; edge_intersection->y_edge_interior = y_edge_interior; edge_intersection->z_edge_interior = z_edge_interior; edge_intersection->t_absolute_intersection_on_edge = t_absolute_intersection_on_edge; edge_intersection->face = face; edge_intersection->edge_intersection_at_face = edge_intersection_at_face; edge_intersection->hit_vertex_at_face = hit_vertex_at_face; edge_intersection->hit_hedge_at_face = hit_hedge_at_face; edge_intersection->x_edge_interior_hedge_at_face = x_edge_interior_hedge_at_face; edge_intersection->y_edge_interior_hedge_at_face = y_edge_interior_hedge_at_face; edge_intersection->z_edge_interior_hedge_at_face = z_edge_interior_hedge_at_face; edge_intersection->tolerance_equal_coords = tolerance_equal_coords; return edge_intersection; } // ------------------------------------------------------------------------------------------ static void i_free_edge_intersection(struct i_edge_intersection_t **edge_intersection) { assert_no_null(edge_intersection); assert_no_null(*edge_intersection); FREE_PP(edge_intersection, struct i_edge_intersection_t); } /* // ------------------------------------------------------------------------------------------ CONSTRUCTOR(static struct i_inters_vertex_t *, i_new_inters_vertex, (struct csmvertex_t *vertex, struct csmhashtb(csmvertex_t) **overlapped_vertexs)) { struct i_inters_vertex_t *inters_vertex; inters_vertex = MALLOC(struct i_inters_vertex_t); inters_vertex->vertex = vertex; inters_vertex->overlapped_vertexs = ASSIGN_POINTER_PP_NOT_NULL(overlapped_vertexs, struct csmhashtb(csmvertex_t)); return inters_vertex; } // ------------------------------------------------------------------------------------------ static void i_free_inters_vertex(struct i_inters_vertex_t **inters_vertex) { assert_no_null(inters_vertex); assert_no_null(*inters_vertex); csmhashtb_free(&(*inters_vertex)->overlapped_vertexs, csmvertex_t, NULL); FREE_PP(inters_vertex, struct i_inters_vertex_t); } // ------------------------------------------------------------------------------------------ CONSTRUCTOR(static struct i_inters_vertex_t *, i_new_inters_vertex_empty, (struct csmvertex_t *vertex)) { struct csmhashtb(csmvertex_t) *overlapped_vertexs; overlapped_vertexs = csmhashtb_create_empty(csmvertex_t); return i_new_inters_vertex(vertex, &overlapped_vertexs); } // ------------------------------------------------------------------------------------------ CONSTRUCTOR(static struct csmhashtb(i_inters_vertex_t) *, i_new_inters_vertex_table, (void)) { return csmhashtb_create_empty(i_inters_vertex_t); } */ // ------------------------------------------------------------------------------------------ static void i_append_new_vv_inters( unsigned long intersection_id, struct csmvertex_t *vertex_a, struct csmvertex_t *vertex_b, CSMBOOL is_A_vs_B, csmArrayStruct(csmsetop_vtxvtx_inters_t) *vv_intersections, double tolerance_equal_coords, CSMBOOL *did_add_intersection) { assert_no_null(did_add_intersection); assert(csmvertex_equal_coords(vertex_a, vertex_b, 2. * tolerance_equal_coords) == CSMTRUE); if (csmvertex_has_mask_attrib(vertex_a, CSMVERTEX_MASK_SETOP_COMMON_VERTEX) == CSMTRUE) { //assert(csmvertex_has_mask_attrib(vertex_b, CSMVERTEX_MASK_SETOP_COMMON_VERTEX) == CSMTRUE); *did_add_intersection = CSMFALSE; } else { struct csmsetop_vtxvtx_inters_t *vv_inters; *did_add_intersection = CSMTRUE; csmvertex_set_mask_attrib(vertex_a, CSMVERTEX_MASK_SETOP_COMMON_VERTEX); csmvertex_set_mask_attrib(vertex_b, CSMVERTEX_MASK_SETOP_COMMON_VERTEX); if (is_A_vs_B == CSMTRUE) vv_inters = csmsetop_vtxvtx_create_inters(intersection_id, vertex_a, vertex_b); else vv_inters = csmsetop_vtxvtx_create_inters(intersection_id, vertex_b, vertex_a); csmarrayc_append_element_st(vv_intersections, vv_inters, csmsetop_vtxvtx_inters_t); } } // ------------------------------------------------------------------------------------------ static void i_append_common_vertices_solid_A_on_solid_B( struct csmsolid_t *solid_A, struct csmsolid_t *solid_B, const struct csmtolerance_t *tolerances, unsigned long *id_new_intersection, csmArrayStruct(csmsetop_vtxvtx_inters_t) *vv_intersections, CSMBOOL *did_find_non_manifold_operand_solid) { double tolerance; struct csmhashtb_iterator(csmvertex_t) *vertex_iterator_A; assert_no_null(did_find_non_manifold_operand_solid); *did_find_non_manifold_operand_solid = CSMFALSE; tolerance = csmtolerance_equal_coords(tolerances); vertex_iterator_A = csmsolid_vertex_iterator(solid_A); while (csmhashtb_has_next(vertex_iterator_A, csmvertex_t) == CSMTRUE) { struct csmvertex_t *vertex_A, *vertex_B; csmhashtb_next_pair(vertex_iterator_A, NULL, &vertex_A, csmvertex_t); if (csmvertex_has_mask_attrib(vertex_A, CSMVERTEX_MASK_SETOP_COMMON_VERTEX) == CSMFALSE && csmsolid_contains_vertex_in_same_coordinates_as_given(solid_B, vertex_A, tolerance, &vertex_B) == CSMTRUE) { if (csmvertex_has_mask_attrib(vertex_B, CSMVERTEX_MASK_SETOP_COMMON_VERTEX) == CSMFALSE) { unsigned long intersection_id; CSMBOOL is_A_vs_B; CSMBOOL did_add_intersection; intersection_id = csmid_new_id(id_new_intersection, NULL); is_A_vs_B = CSMTRUE; i_append_new_vv_inters(intersection_id, vertex_A, vertex_B, is_A_vs_B, vv_intersections, tolerance, &did_add_intersection); assert(did_add_intersection == CSMTRUE); if (csmdebug_debug_enabled() == CSMTRUE) { char *description; double x, y, z; csmvertex_get_coords(vertex_A, &x, &y, &z); description = copiafor_codigo5("EQ VV (%g, %g, %g) %lu %lu", x, y, z, csmvertex_id(vertex_A), csmvertex_id(vertex_B)); csmdebug_append_debug_point(x, y, z, &description); csmdebug_print_debug_info("-->Coincident vertices: (%lu, %lu)\n", csmvertex_id(vertex_A), csmvertex_id(vertex_B)); } } else { *did_find_non_manifold_operand_solid = CSMTRUE; break; } } } csmhashtb_free_iterator(&vertex_iterator_A, csmvertex_t); } // ------------------------------------------------------------------------------------------ static void i_append_common_vertices_solid_A_and_B_not_previously_found( struct csmsolid_t *solid_A, struct csmsolid_t *solid_B, const struct csmtolerance_t *tolerances, unsigned long *id_new_intersection, csmArrayStruct(csmsetop_vtxvtx_inters_t) *vv_intersections, CSMBOOL *did_find_non_manifold_operand_solid_A, CSMBOOL *did_find_non_manifold_operand_solid_B) { i_append_common_vertices_solid_A_on_solid_B(solid_A, solid_B, tolerances, id_new_intersection, vv_intersections, did_find_non_manifold_operand_solid_A); i_append_common_vertices_solid_A_on_solid_B(solid_B, solid_A, tolerances, id_new_intersection, vv_intersections, did_find_non_manifold_operand_solid_B); } // ------------------------------------------------------------------------------------------ static CSMBOOL i_equal_edge_intersection(const struct i_edge_intersection_t *edge_intersection1, const struct i_edge_intersection_t *edge_intersection2) { assert_no_null(edge_intersection1); assert_no_null(edge_intersection2); assert(edge_intersection1->tolerance_equal_coords == edge_intersection2->tolerance_equal_coords); return csmmath_equal_coords( edge_intersection1->x_edge_interior, edge_intersection1->y_edge_interior, edge_intersection1->z_edge_interior, edge_intersection2->x_edge_interior, edge_intersection2->y_edge_interior, edge_intersection2->z_edge_interior, edge_intersection1->tolerance_equal_coords); } // ------------------------------------------------------------------------------------------ static void i_append_new_edge_intersection( enum i_intersection_position_t intersection_position_at_edge, struct csmvertex_t *edge_vertex, double x_edge_interior, double y_edge_interior, double z_edge_interior, double t_absolute_intersection_on_edge, struct csmface_t *face, enum csmmath_containment_point_loop_t type_of_containment_at_face, struct csmvertex_t *hit_vertex_at_face, struct csmhedge_t *hit_hedge_at_face, double x_edge_interior_hedge_at_face, double y_edge_interior_hedge_at_face, double z_edge_interior_hedge_at_face, const struct csmtolerance_t *tolerances, unsigned long *id_new_intersection, csmArrayStruct(i_edge_intersection_t) *edge_intersections) { CSMBOOL generate_intersection; enum i_type_edge_intersection_t edge_intersection_at_face; struct i_edge_intersection_t *edge_intersection; unsigned long intersection_id; double tolerance_equal_coords; generate_intersection = CSMTRUE; switch (type_of_containment_at_face) { case CSMMATH_CONTAINMENT_POINT_LOOP_INTERIOR: { assert(hit_vertex_at_face == NULL); assert(hit_hedge_at_face == NULL); edge_intersection_at_face = i_TYPE_EDGE_INTERSECTION_INTERIOR_FACE; break; } case CSMMATH_CONTAINMENT_POINT_LOOP_ON_VERTEX: { assert(hit_vertex_at_face != NULL); edge_intersection_at_face = i_TYPE_EDGE_INTERSECTION_VERTEX; break; } case CSMMATH_CONTAINMENT_POINT_LOOP_ON_HEDGE: { assert(hit_hedge_at_face != NULL); edge_intersection_at_face = i_TYPE_EDGE_INTERSECTION_INTERIOR_EDGE; break; } default_error(); } intersection_id = csmid_new_id(id_new_intersection, NULL); tolerance_equal_coords = csmtolerance_equal_coords(tolerances); edge_intersection = i_create_edge_intersection( intersection_id, generate_intersection, intersection_position_at_edge, edge_vertex, x_edge_interior, y_edge_interior, z_edge_interior, t_absolute_intersection_on_edge, face, edge_intersection_at_face, hit_vertex_at_face, hit_hedge_at_face, x_edge_interior_hedge_at_face, y_edge_interior_hedge_at_face, z_edge_interior_hedge_at_face, tolerance_equal_coords); if (csmarrayc_contains_element_st( edge_intersections, i_edge_intersection_t, edge_intersection, struct i_edge_intersection_t, i_equal_edge_intersection, NULL) == CSMTRUE) { i_free_edge_intersection(&edge_intersection); } else { csmarrayc_append_element_st(edge_intersections, edge_intersection, i_edge_intersection_t); } } // ------------------------------------------------------------------------------------------ static void i_intersection_coords_at_hedge( enum csmmath_containment_point_loop_t type_of_containment_at_face, struct csmhedge_t *hedge, double t_relative_to_hit_hedge_at_face, double *x, double *y, double *z) { assert_no_null(x); assert_no_null(y); assert_no_null(z); switch (type_of_containment_at_face) { case CSMMATH_CONTAINMENT_POINT_LOOP_ON_HEDGE: { struct csmhedge_t *hedge_next; double x1, y1, z1, x2, y2, z2; csmvertex_get_coords(csmhedge_vertex(hedge), &x1, &y1, &z1); hedge_next = csmhedge_next(hedge); csmvertex_get_coords(csmhedge_vertex(hedge_next), &x2, &y2, &z2); *x = x1 + (x2 - x1) * t_relative_to_hit_hedge_at_face; *y = y1 + (y2 - y1) * t_relative_to_hit_hedge_at_face; *z = z1 + (z2 - z1) * t_relative_to_hit_hedge_at_face; break; } case CSMMATH_CONTAINMENT_POINT_LOOP_ON_VERTEX: case CSMMATH_CONTAINMENT_POINT_LOOP_INTERIOR: *x = 0.; *y = 0.; *z = 0.; break; default_error(); } } // ------------------------------------------------------------------------------------------ static void i_append_intersection_between_vertex_A_and_face_B( struct csmvertex_t *vertex, struct csmface_t *face_B, double t_absolute_vertex_on_edge, const struct csmtolerance_t *tolerances, unsigned long *id_new_intersection, csmArrayStruct(i_edge_intersection_t) *edge_intersections) { enum csmmath_containment_point_loop_t type_of_containment_at_face; struct csmvertex_t *hit_vertex_at_face; struct csmhedge_t *hit_hedge_at_face; double t_relative_to_hit_hedge_at_face; hit_vertex_at_face = NULL; hit_hedge_at_face = NULL; if (csmface_contains_vertex( face_B, vertex, tolerances, &type_of_containment_at_face, &hit_vertex_at_face, &hit_hedge_at_face, &t_relative_to_hit_hedge_at_face) == CSMTRUE) { enum i_intersection_position_t intersection_position_at_edge; double x_edge_interior, y_edge_interior, z_edge_interior; double x_edge_interior_hedge_at_face, y_edge_interior_hedge_at_face, z_edge_interior_hedge_at_face; intersection_position_at_edge = i_INTERSECTION_POSITION_AT_EDGE_VERTEX; csmvertex_get_coords(vertex, &x_edge_interior, &y_edge_interior, &z_edge_interior); i_intersection_coords_at_hedge( type_of_containment_at_face, hit_hedge_at_face, t_relative_to_hit_hedge_at_face, &x_edge_interior_hedge_at_face, &y_edge_interior_hedge_at_face, &z_edge_interior_hedge_at_face); i_append_new_edge_intersection( intersection_position_at_edge, vertex, x_edge_interior, y_edge_interior, z_edge_interior, t_absolute_vertex_on_edge, face_B, type_of_containment_at_face, hit_vertex_at_face, hit_hedge_at_face, x_edge_interior_hedge_at_face, y_edge_interior_hedge_at_face, z_edge_interior_hedge_at_face, tolerances, id_new_intersection, edge_intersections); } } // ------------------------------------------------------------------------------------------ static void i_append_intersections_between_A_edge_and_B_face( const struct i_optimized_edge_data_t *optimized_edge_data, struct csmface_t *face_B, const struct csmtolerance_t *tolerances, unsigned long *id_new_intersection, csmArrayStruct(i_edge_intersection_t) *edge_intersections) { assert_no_null(optimized_edge_data); if (csmface_should_analyze_intersections_with_segment( face_B, optimized_edge_data->x1, optimized_edge_data->y1, optimized_edge_data->z1, optimized_edge_data->x2, optimized_edge_data->y2, optimized_edge_data->z2) == CSMTRUE) { enum csmcompare_t classification_vertex_pos, classification_vertex_neg; classification_vertex_pos = csmface_classify_vertex_relative_to_face(face_B, optimized_edge_data->vertex_pos); classification_vertex_neg = csmface_classify_vertex_relative_to_face(face_B, optimized_edge_data->vertex_neg); if (classification_vertex_pos == CSMCOMPARE_EQUAL || classification_vertex_neg == CSMCOMPARE_EQUAL) { if (classification_vertex_pos == CSMCOMPARE_EQUAL) { i_append_intersection_between_vertex_A_and_face_B( optimized_edge_data->vertex_pos, face_B, 0., tolerances, id_new_intersection, edge_intersections); } if (classification_vertex_neg == CSMCOMPARE_EQUAL) { i_append_intersection_between_vertex_A_and_face_B( optimized_edge_data->vertex_neg, face_B, optimized_edge_data->length, tolerances, id_new_intersection, edge_intersections); } } else { double x_inters, y_inters, z_inters, t; if (csmface_exists_intersection_between_line_and_face_plane( face_B, optimized_edge_data->x1, optimized_edge_data->y1, optimized_edge_data->z1, optimized_edge_data->x2, optimized_edge_data->y2, optimized_edge_data->z2, &x_inters, &y_inters, &z_inters, &t) == CSMTRUE) { enum csmmath_containment_point_loop_t type_of_containment_at_face; struct csmvertex_t *hit_vertex_at_face; struct csmhedge_t *hit_hedge_at_face; double t_relative_to_hit_hedge_at_face; hit_vertex_at_face = NULL; hit_hedge_at_face = NULL; if (csmface_contains_point( face_B, x_inters, y_inters, z_inters, tolerances, &type_of_containment_at_face, &hit_vertex_at_face, &hit_hedge_at_face, &t_relative_to_hit_hedge_at_face) == CSMTRUE) { enum i_intersection_position_t intersection_position_at_edge; struct csmvertex_t *edge_vertex; double x_edge_interior_hedge_at_face, y_edge_interior_hedge_at_face, z_edge_interior_hedge_at_face; double tolerance_equal_coords; tolerance_equal_coords = csmtolerance_equal_coords(tolerances); if (csmmath_equal_coords( optimized_edge_data->x1, optimized_edge_data->y1, optimized_edge_data->z1, x_inters, y_inters, z_inters, tolerance_equal_coords) == CSMTRUE) { intersection_position_at_edge = i_INTERSECTION_POSITION_AT_EDGE_VERTEX; edge_vertex = optimized_edge_data->vertex_pos; csmvertex_get_coords(optimized_edge_data->vertex_pos, &x_inters, &y_inters, &z_inters); t = 0.; } else if (csmmath_equal_coords( optimized_edge_data->x2, optimized_edge_data->y2, optimized_edge_data->z2, x_inters, y_inters, z_inters, tolerance_equal_coords) == CSMTRUE) { intersection_position_at_edge = i_INTERSECTION_POSITION_AT_EDGE_VERTEX; edge_vertex = optimized_edge_data->vertex_neg; csmvertex_get_coords(optimized_edge_data->vertex_neg, &x_inters, &y_inters, &z_inters); t = 1.; } else { intersection_position_at_edge = i_INTERSECTION_POSITION_AT_EDGE_INTERIOR; edge_vertex = NULL; } i_intersection_coords_at_hedge( type_of_containment_at_face, hit_hedge_at_face, t_relative_to_hit_hedge_at_face, &x_edge_interior_hedge_at_face, &y_edge_interior_hedge_at_face, &z_edge_interior_hedge_at_face); i_append_new_edge_intersection( intersection_position_at_edge, edge_vertex, x_inters, y_inters, z_inters, t * optimized_edge_data->length, face_B, type_of_containment_at_face, hit_vertex_at_face, hit_hedge_at_face, x_edge_interior_hedge_at_face, y_edge_interior_hedge_at_face, z_edge_interior_hedge_at_face, tolerances, id_new_intersection, edge_intersections); } } } } } // ------------------------------------------------------------------------------------------ static enum csmcompare_t i_compara_edge_intersection( const struct i_edge_intersection_t *edge_intersection1, const struct i_edge_intersection_t *edge_intersection2) { double tolerance; assert_no_null(edge_intersection1); assert_no_null(edge_intersection2); tolerance = 1.e-9; return csmmath_compare_doubles(edge_intersection1->t_absolute_intersection_on_edge, edge_intersection2->t_absolute_intersection_on_edge, tolerance); } // ------------------------------------------------------------------------------------------ static void i_append_new_vf_inters( unsigned long intersection_id, struct csmvertex_t *vertex_a, struct csmface_t *face_b, struct csmhashtb2id(csmsetop_vtxfacc_inters_t) *vertex_face_neighborhood, CSMBOOL *added) { unsigned long vertex_id, face_id; assert_no_null(added); vertex_id = csmvertex_id(vertex_a); face_id = csmface_id(face_b); if (csmhashtb2id_contains_id(vertex_face_neighborhood, csmsetop_vtxfacc_inters_t, vertex_id, face_id, NULL) == CSMTRUE) { *added = CSMFALSE; } else { struct csmsetop_vtxfacc_inters_t *vf_inters; vf_inters = csmsetop_vtxfacc_create_inters(intersection_id, vertex_a, face_b); csmhashtb2id_add_item(vertex_face_neighborhood, vertex_id, face_id, vf_inters, csmsetop_vtxfacc_inters_t); *added = CSMTRUE; } } // ------------------------------------------------------------------------------------------ static void i_discard_invalid_intersections(csmArrayStruct(i_edge_intersection_t) *edge_intersecctions) { unsigned long i, num_intersections; num_intersections = csmarrayc_count_st(edge_intersecctions, i_edge_intersection_t); assert(num_intersections > 0); for (i = 0; i < num_intersections; i++) { struct i_edge_intersection_t *edge_intersection_i; edge_intersection_i = csmarrayc_get_st(edge_intersecctions, i, i_edge_intersection_t); assert_no_null(edge_intersection_i); if (edge_intersection_i->generate_intersection == CSMTRUE && edge_intersection_i->edge_intersection_at_face == i_TYPE_EDGE_INTERSECTION_INTERIOR_FACE) { unsigned long j; for (j = 0; j < num_intersections; j++) { if (i != j) { const struct i_edge_intersection_t *edge_intersection_j; edge_intersection_j = csmarrayc_get_const_st(edge_intersecctions, j, i_edge_intersection_t); assert_no_null(edge_intersection_j); if (edge_intersection_j->generate_intersection == CSMTRUE && edge_intersection_j->edge_intersection_at_face == i_TYPE_EDGE_INTERSECTION_INTERIOR_EDGE) { struct csmedge_t *edge_j; struct csmhedge_t *he1_j, *he2_j; edge_j = csmhedge_edge(edge_intersection_j->hit_hedge_at_face); he1_j = csmedge_hedge_lado(edge_j, CSMEDGE_HEDGE_SIDE_POS); he2_j = csmedge_hedge_lado(edge_j, CSMEDGE_HEDGE_SIDE_NEG); if (csmopbas_face_from_hedge(he1_j) == edge_intersection_i->face || csmopbas_face_from_hedge(he2_j) == edge_intersection_i->face) { edge_intersection_i->generate_intersection = CSMFALSE; break; } } } } } } } // ------------------------------------------------------------------------------------------ static void i_update_splitted_hedge_on_intersections( const csmArrayStruct(i_edge_intersection_t) *edge_intersecctions, unsigned long start_idx, struct csmhedge_t *hit_hedge_at_face_to_replace, struct csmedge_t *hit_edge_at_face_replacement) { unsigned long i, num_intersections; struct csmedge_t *hit_edge_at_face_to_replace; struct csmhedge_t *mate_hit_hedge_at_face_to_replace; num_intersections = csmarrayc_count_st(edge_intersecctions, i_edge_intersection_t); assert(num_intersections > 0); hit_edge_at_face_to_replace = csmhedge_edge(hit_hedge_at_face_to_replace); mate_hit_hedge_at_face_to_replace = csmopbas_mate(hit_hedge_at_face_to_replace); for (i = start_idx; i < num_intersections; i++) { struct i_edge_intersection_t *edge_intersection; edge_intersection = csmarrayc_get_st(edge_intersecctions, i, i_edge_intersection_t); assert_no_null(edge_intersection); switch (edge_intersection->edge_intersection_at_face) { case i_TYPE_EDGE_INTERSECTION_INTERIOR_EDGE: if (edge_intersection->hit_hedge_at_face == hit_hedge_at_face_to_replace || edge_intersection->hit_hedge_at_face == mate_hit_hedge_at_face_to_replace) { double x1_esplit, y1_esplit, z1_esplit, x2_esplit, y2_esplit, z2_esplit; csmedge_vertex_coordinates( hit_edge_at_face_to_replace, &x1_esplit, &y1_esplit, &z1_esplit, NULL, &x2_esplit, &y2_esplit, &z2_esplit, NULL); if (csmmath_is_point_in_segment3D( edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior, x1_esplit, y1_esplit, z1_esplit, x2_esplit, y2_esplit, z2_esplit, edge_intersection->tolerance_equal_coords, NULL) == CSMFALSE) { struct csmhedge_t *he_replacement; csmedge_vertex_coordinates( hit_edge_at_face_replacement, &x1_esplit, &y1_esplit, &z1_esplit, NULL, &x2_esplit, &y2_esplit, &z2_esplit, NULL); assert(csmmath_is_point_in_segment3D( edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior, x1_esplit, y1_esplit, z1_esplit, x2_esplit, y2_esplit, z2_esplit, edge_intersection->tolerance_equal_coords, NULL) == CSMTRUE); he_replacement = csmedge_hedge_lado(hit_edge_at_face_replacement, CSMEDGE_HEDGE_SIDE_POS); if (csmhedge_next(edge_intersection->hit_hedge_at_face) == he_replacement || csmhedge_prev(edge_intersection->hit_hedge_at_face) == he_replacement) { edge_intersection->hit_hedge_at_face = he_replacement; } else { he_replacement = csmedge_hedge_lado(hit_edge_at_face_replacement, CSMEDGE_HEDGE_SIDE_NEG); assert(csmhedge_next(edge_intersection->hit_hedge_at_face) == he_replacement || csmhedge_prev(edge_intersection->hit_hedge_at_face) == he_replacement); } assert(hit_hedge_at_face_to_replace != he_replacement); edge_intersection->hit_hedge_at_face = he_replacement; } } break; case i_TYPE_EDGE_INTERSECTION_VERTEX: case i_TYPE_EDGE_INTERSECTION_INTERIOR_FACE: break; default_error(); } } } // ------------------------------------------------------------------------------------------ static void i_process_edge_intersections( struct csmedge_t *original_edge, csmArrayStruct(i_edge_intersection_t) *edge_intersecctions, CSMBOOL is_A_vs_B, csmArrayStruct(csmsetop_vtxvtx_inters_t) *vv_intersections, struct csmhashtb2id(csmsetop_vtxfacc_inters_t) *vertex_face_neighborhood, CSMBOOL *did_find_non_manifold_operand_update) { unsigned long i, num_intersections; struct csmedge_t *edge_to_split; num_intersections = csmarrayc_count_st(edge_intersecctions, i_edge_intersection_t); assert(num_intersections > 0); assert_no_null(did_find_non_manifold_operand_update); assert(*did_find_non_manifold_operand_update == CSMFALSE); if (csmdebug_debug_enabled() == CSMTRUE) { double x1, y1, z1, x2, y2, z2; unsigned long id_vertex1, id_vertex2; csmedge_vertex_coordinates(original_edge, &x1, &y1, &z1, &id_vertex1, &x2, &y2, &z2, &id_vertex2); csmdebug_print_debug_info("\n"); csmdebug_print_debug_info("Edge: %lu. [%lu](%lf, %lf, %lf) -> [%lu](%lf, %lf, %lf)\n", csmedge_id(original_edge), id_vertex1, x1, y1, z1, id_vertex2, x2, y2, z2); csmdebug_print_debug_info("No. intersections: %lu\n", num_intersections); } edge_to_split = original_edge; for (i = 0; i < num_intersections && *did_find_non_manifold_operand_update == CSMFALSE; i++) { const struct i_edge_intersection_t *edge_intersection; edge_intersection = csmarrayc_get_const_st(edge_intersecctions, i, i_edge_intersection_t); assert_no_null(edge_intersection); if (edge_intersection->generate_intersection == CSMTRUE) { struct csmvertex_t *edge_vertex_intersection; if (csmdebug_debug_enabled() == CSMTRUE) { double A, B, C, D; csmface_face_equation(edge_intersection->face, &A, &B, &C, &D); csmdebug_print_debug_info("Intersection with face: %lu, Eq: (%lf, %lf, %lf, %lf)\n", csmface_id(edge_intersection->face), A, B, C, D); } switch (edge_intersection->intersection_position_at_edge) { case i_INTERSECTION_POSITION_AT_EDGE_VERTEX: { if (csmdebug_debug_enabled() == CSMTRUE) { double x, y, z; csmvertex_get_coords(edge_intersection->edge_vertex, &x, &y, &z); csmdebug_print_debug_info("Intersection at vertex: %lu (%lf, %lf, %lf)\n", csmvertex_id(edge_intersection->edge_vertex), x, y, z); csmdebug_print_debug_info("-->NOTHING DONE\n"); } edge_vertex_intersection = edge_intersection->edge_vertex; break; } case i_INTERSECTION_POSITION_AT_EDGE_INTERIOR: { struct csmhedge_t *hedge_pos, *hedge_neg; struct csmhedge_t *hedge_pos_next; struct csmvertex_t *new_vertex; struct csmedge_t *new_edge; { double x1_esplit, y1_esplit, z1_esplit, x2_esplit, y2_esplit, z2_esplit; csmedge_vertex_coordinates(edge_to_split, &x1_esplit, &y1_esplit, &z1_esplit, NULL, &x2_esplit, &y2_esplit, &z2_esplit, NULL); assert(csmmath_equal_coords( x1_esplit, y1_esplit, z1_esplit, edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior, edge_intersection->tolerance_equal_coords) == CSMFALSE); assert(csmmath_equal_coords( x2_esplit, y2_esplit, z2_esplit, edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior, edge_intersection->tolerance_equal_coords) == CSMFALSE); assert(csmmath_is_point_in_segment3D( edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior, x1_esplit, y1_esplit, z1_esplit, x2_esplit, y2_esplit, z2_esplit, edge_intersection->tolerance_equal_coords, NULL) == CSMTRUE); } hedge_pos = csmedge_hedge_lado(edge_to_split, CSMEDGE_HEDGE_SIDE_POS); hedge_pos_next = csmhedge_next(hedge_pos); hedge_neg = csmedge_hedge_lado(edge_to_split, CSMEDGE_HEDGE_SIDE_NEG); csmeuler_lmev( hedge_neg, hedge_pos_next, edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior, &new_vertex, &new_edge, NULL, NULL); if (csmdebug_debug_enabled() == CSMTRUE) { char *description; csmdebug_print_debug_info("Intersection at inner point: (%lf, %lf, %lf)\n", edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior); csmdebug_print_debug_info("-->Created new vertex: %lu\n", csmvertex_id(new_vertex)); description = copiafor_codigo4("IE %lu (%.3g, %.3g, %.3g)", csmvertex_id(new_vertex), edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior); csmdebug_append_debug_point(edge_intersection->x_edge_interior, edge_intersection->y_edge_interior, edge_intersection->z_edge_interior, &description); } edge_vertex_intersection = new_vertex; edge_to_split = new_edge; break; } default_error(); } switch (edge_intersection->edge_intersection_at_face) { case i_TYPE_EDGE_INTERSECTION_VERTEX: { CSMBOOL did_add_intersection; i_append_new_vv_inters( edge_intersection->intersection_id, edge_vertex_intersection, edge_intersection->hit_vertex_at_face, is_A_vs_B, vv_intersections, edge_intersection->tolerance_equal_coords, &did_add_intersection); if (did_add_intersection == CSMTRUE && csmdebug_debug_enabled() == CSMTRUE) { csmdebug_print_debug_info("Intersection at face vertex: %lu\n", csmvertex_id(edge_intersection->hit_vertex_at_face)); csmdebug_print_debug_info("Added VV intersection (%lu, %lu)\n", csmvertex_id(edge_vertex_intersection), csmvertex_id(edge_intersection->hit_vertex_at_face)); } break; } case i_TYPE_EDGE_INTERSECTION_INTERIOR_EDGE: { struct csmhedge_t *hit_hedge_at_face_next, *mate_hit_hedge; struct csmvertex_t *new_vertex_on_hit_hedge; struct csmedge_t *new_edge_other_solid; CSMBOOL did_add_intersection; if (csmdebug_debug_enabled() == CSMTRUE) csmdebug_print_debug_info("Intersection at face hedge: %lu\n", csmhedge_id(edge_intersection->hit_hedge_at_face)); { struct csmedge_t *edge_to_split_other_solid; double x1_esplit, y1_esplit, z1_esplit, x2_esplit, y2_esplit, z2_esplit; edge_to_split_other_solid = csmhedge_edge(edge_intersection->hit_hedge_at_face); csmedge_vertex_coordinates(edge_to_split_other_solid, &x1_esplit, &y1_esplit, &z1_esplit, NULL, &x2_esplit, &y2_esplit, &z2_esplit, NULL); assert(csmmath_is_point_in_segment3D( edge_intersection->x_edge_interior_hedge_at_face, edge_intersection->y_edge_interior_hedge_at_face, edge_intersection->z_edge_interior_hedge_at_face, x1_esplit, y1_esplit, z1_esplit, x2_esplit, y2_esplit, z2_esplit, edge_intersection->tolerance_equal_coords, NULL) == CSMTRUE); } hit_hedge_at_face_next = csmhedge_next(edge_intersection->hit_hedge_at_face); mate_hit_hedge = csmopbas_mate(edge_intersection->hit_hedge_at_face); csmeuler_lmev( mate_hit_hedge, hit_hedge_at_face_next, edge_intersection->x_edge_interior_hedge_at_face, edge_intersection->y_edge_interior_hedge_at_face, edge_intersection->z_edge_interior_hedge_at_face, &new_vertex_on_hit_hedge, &new_edge_other_solid, NULL, NULL); i_update_splitted_hedge_on_intersections( edge_intersecctions, i + 1, edge_intersection->hit_hedge_at_face, new_edge_other_solid); if (csmdebug_debug_enabled() == CSMTRUE) { char *description; csmdebug_print_debug_info("-->Splitted hedge, new vertex: %lu\n", csmvertex_id(new_vertex_on_hit_hedge)); csmedge_print_debug_info(new_edge_other_solid, CSMTRUE); csmdebug_print_debug_info("Added VV intersection (%lu, %lu)\n", csmvertex_id(edge_vertex_intersection), csmvertex_id(new_vertex_on_hit_hedge)); description = copiafor_codigo4( "IE-F %lu (%.3g, %.3g, %.3g)", csmvertex_id(new_vertex_on_hit_hedge), edge_intersection->x_edge_interior_hedge_at_face, edge_intersection->y_edge_interior_hedge_at_face, edge_intersection->z_edge_interior_hedge_at_face); csmdebug_append_debug_point( edge_intersection->x_edge_interior_hedge_at_face, edge_intersection->y_edge_interior_hedge_at_face, edge_intersection->z_edge_interior_hedge_at_face, &description); } i_append_new_vv_inters(edge_intersection->intersection_id, edge_vertex_intersection, new_vertex_on_hit_hedge, is_A_vs_B, vv_intersections, edge_intersection->tolerance_equal_coords, &did_add_intersection); if (did_add_intersection == CSMFALSE) *did_find_non_manifold_operand_update = CSMTRUE; break; } case i_TYPE_EDGE_INTERSECTION_INTERIOR_FACE: { CSMBOOL added; i_append_new_vf_inters(edge_intersection->intersection_id, edge_vertex_intersection, edge_intersection->face, vertex_face_neighborhood, &added); if (added == CSMTRUE && csmdebug_debug_enabled() == CSMTRUE) { char *description; double x_edge_intersection, y_edge_intersection, z_edge_intersection; csmvertex_get_coords(edge_vertex_intersection, &x_edge_intersection, &y_edge_intersection, &z_edge_intersection); csmdebug_print_debug_info(" Intersection at interior of face\n"); description = copiafor_codigo4( "VF %lu (%.3g, %.3g, %.3g)", csmvertex_id(edge_vertex_intersection), x_edge_intersection, y_edge_intersection, z_edge_intersection); csmdebug_append_debug_point(x_edge_intersection, y_edge_intersection, z_edge_intersection, &description); } break; } default_error(); } csmdebug_print_debug_info("\n"); } } } // ------------------------------------------------------------------------------------------ static void i_generate_intersections_edge_with_solid_faces( struct csmedge_t *edge_A, struct csmsolid_t *solid_B, const struct csmtolerance_t *tolerances, CSMBOOL is_A_vs_B, unsigned long *id_new_intersection, csmArrayStruct(csmsetop_vtxvtx_inters_t) *vv_intersections, struct csmhashtb2id(csmsetop_vtxfacc_inters_t) *vertex_face_neighborhood, CSMBOOL *did_find_non_manifold_operand_update) { struct i_optimized_edge_data_t optimized_edge_data; struct csmhedge_t *hedge_pos, *hedge_neg; const struct csmbbox_t *solid_b_bbox; assert_no_null(did_find_non_manifold_operand_update); assert(*did_find_non_manifold_operand_update == CSMFALSE); optimized_edge_data.edge_id = csmedge_id(edge_A); hedge_pos = csmedge_hedge_lado(edge_A, CSMEDGE_HEDGE_SIDE_POS); optimized_edge_data.vertex_pos = csmhedge_vertex(hedge_pos); csmvertex_get_coords(optimized_edge_data.vertex_pos, &optimized_edge_data.x1, &optimized_edge_data.y1, &optimized_edge_data.z1); hedge_neg = csmedge_hedge_lado(edge_A, CSMEDGE_HEDGE_SIDE_NEG); optimized_edge_data.vertex_neg = csmhedge_vertex(hedge_neg); csmvertex_get_coords(optimized_edge_data.vertex_neg, &optimized_edge_data.x2, &optimized_edge_data.y2, &optimized_edge_data.z2); solid_b_bbox = csmsolid_get_bbox(solid_B); if (csmbbox_intersects_with_segment( solid_b_bbox, optimized_edge_data.x1, optimized_edge_data.y1, optimized_edge_data.z1, optimized_edge_data.x2, optimized_edge_data.y2, optimized_edge_data.z2) == CSMTRUE) { csmArrayStruct(i_edge_intersection_t) *edge_intersecctions; struct csmhashtb_iterator(csmface_t) *face_iterator_B; optimized_edge_data.length = csmmath_distance_3D( optimized_edge_data.x1, optimized_edge_data.y1, optimized_edge_data.z1, optimized_edge_data.x2, optimized_edge_data.y2, optimized_edge_data.z2); edge_intersecctions = csmarrayc_new_st_array(0, i_edge_intersection_t); face_iterator_B = csmsolid_face_iterator(solid_B); while (csmhashtb_has_next(face_iterator_B, csmface_t) == CSMTRUE) { struct csmface_t *face_B; csmhashtb_next_pair(face_iterator_B, NULL, &face_B, csmface_t); i_append_intersections_between_A_edge_and_B_face( &optimized_edge_data, face_B, tolerances, id_new_intersection, edge_intersecctions); } if (csmarrayc_count_st(edge_intersecctions, i_edge_intersection_t) > 0) { csmarrayc_qsort_st(edge_intersecctions, i_edge_intersection_t, i_compara_edge_intersection); i_discard_invalid_intersections(edge_intersecctions); i_process_edge_intersections(edge_A, edge_intersecctions, is_A_vs_B, vv_intersections, vertex_face_neighborhood, did_find_non_manifold_operand_update); } csmhashtb_free_iterator(&face_iterator_B, csmface_t); csmarrayc_free_st(&edge_intersecctions, i_edge_intersection_t, i_free_edge_intersection); } } // ------------------------------------------------------------------------------------------ static void i_generate_edge_intersections_solid_A_with_solid_B( struct csmsolid_t *solid_A, struct csmsolid_t *solid_B, const struct csmtolerance_t *tolerances, CSMBOOL is_A_vs_B, unsigned long *id_new_intersection, csmArrayStruct(csmsetop_vtxvtx_inters_t) *vv_intersections, struct csmhashtb2id(csmsetop_vtxfacc_inters_t) *vertex_face_neighborhood, CSMBOOL *did_find_non_manifold_operand_update) { struct csmhashtb_iterator(csmedge_t) *edge_iterator_A; assert_no_null(did_find_non_manifold_operand_update); edge_iterator_A = csmsolid_edge_iterator(solid_A); while (csmhashtb_has_next(edge_iterator_A, csmedge_t) == CSMTRUE && *did_find_non_manifold_operand_update == CSMFALSE) { struct csmedge_t *edge_A; csmhashtb_next_pair(edge_iterator_A, NULL, &edge_A, csmedge_t); i_generate_intersections_edge_with_solid_faces( edge_A, solid_B, tolerances, is_A_vs_B, id_new_intersection, vv_intersections, vertex_face_neighborhood, did_find_non_manifold_operand_update); } csmhashtb_free_iterator(&edge_iterator_A, csmedge_t); } // ------------------------------------------------------------------------------------------ void csmsetop_procedges_generate_intersections_on_both_solids( struct csmsolid_t *solid_A, struct csmsolid_t *solid_B, const struct csmtolerance_t *tolerances, csmArrayStruct(csmsetop_vtxvtx_inters_t) **vv_intersections, csmArrayStruct(csmsetop_vtxfacc_inters_t) **vf_intersections_A, csmArrayStruct(csmsetop_vtxfacc_inters_t) **vf_intersections_B, CSMBOOL *did_find_non_manifold_operand) { csmArrayStruct(csmsetop_vtxvtx_inters_t) *vv_intersections_loc; struct csmhashtb2id(csmsetop_vtxfacc_inters_t) *hashtb_vf_intersections_A_loc, *hashtb_vf_intersections_B_loc; CSMBOOL did_find_non_manifold_operand_solid_A, did_find_non_manifold_operand_solid_B; unsigned long id_new_intersection; CSMBOOL is_A_vs_B; assert_no_null(vv_intersections); assert_no_null(vf_intersections_A); assert_no_null(vf_intersections_B); assert_no_null(did_find_non_manifold_operand); vv_intersections_loc = csmarrayc_new_st_array(0, csmsetop_vtxvtx_inters_t); hashtb_vf_intersections_A_loc = csmhashtb2id_create_empty(csmsetop_vtxfacc_inters_t); hashtb_vf_intersections_B_loc = csmhashtb2id_create_empty(csmsetop_vtxfacc_inters_t); id_new_intersection = 0; csmdebug_begin_context("csmsetop_procedges_generate_intersections_on_both_solids"); { csmdebug_begin_context("Intersections A vs B"); { csmdebug_clear_debug_points(); is_A_vs_B = CSMTRUE; did_find_non_manifold_operand_solid_A = CSMFALSE; i_generate_edge_intersections_solid_A_with_solid_B( solid_A, solid_B, tolerances, is_A_vs_B, &id_new_intersection, vv_intersections_loc, hashtb_vf_intersections_A_loc, &did_find_non_manifold_operand_solid_A); csmsolid_print_debug(solid_A, CSMTRUE); csmsolid_print_debug(solid_B, CSMTRUE); } csmdebug_end_context(); //csmdebug_show_viewer(); if (did_find_non_manifold_operand_solid_A == CSMFALSE) { csmdebug_begin_context("Intersections B vs A"); { csmdebug_clear_debug_points(); is_A_vs_B = CSMFALSE; did_find_non_manifold_operand_solid_B = CSMFALSE; i_generate_edge_intersections_solid_A_with_solid_B( solid_B, solid_A, tolerances, is_A_vs_B, &id_new_intersection, vv_intersections_loc, hashtb_vf_intersections_B_loc, &did_find_non_manifold_operand_solid_B); csmsolid_print_debug(solid_A, CSMTRUE); csmsolid_print_debug(solid_B, CSMTRUE); } csmdebug_end_context(); } else { did_find_non_manifold_operand_solid_B = CSMFALSE; } //csmdebug_show_viewer(); if (did_find_non_manifold_operand_solid_A == CSMFALSE && did_find_non_manifold_operand_solid_B == CSMFALSE) { i_append_common_vertices_solid_A_and_B_not_previously_found( solid_A, solid_B, tolerances, &id_new_intersection, vv_intersections_loc, &did_find_non_manifold_operand_solid_A, &did_find_non_manifold_operand_solid_B); } } csmdebug_end_context(); *vv_intersections = vv_intersections_loc; *vf_intersections_A = csmhashtb2id_convert_to_array(hashtb_vf_intersections_A_loc, csmsetop_vtxfacc_inters_t); *vf_intersections_B = csmhashtb2id_convert_to_array(hashtb_vf_intersections_B_loc, csmsetop_vtxfacc_inters_t); *did_find_non_manifold_operand = IS_TRUE(did_find_non_manifold_operand_solid_A == CSMTRUE || did_find_non_manifold_operand_solid_B == CSMTRUE); csmhashtb2id_free(&hashtb_vf_intersections_A_loc, csmsetop_vtxfacc_inters_t, NULL); csmhashtb2id_free(&hashtb_vf_intersections_B_loc, csmsetop_vtxfacc_inters_t, NULL); }
ReDEnergy/OpenGL4.5-GameEngine
GameProject/Source/Editor/Windows/Interface/CustomWidget.cpp
#include "CustomWidget.h" #include <iostream> #include <QtWidgets/QBoxLayout> #include <QtCore/QFile> #include <QIcon> #include <Editor/Config/QtConfig.h> using namespace std; static unsigned int windowNumber = 0; CustomWidget::CustomWidget(QBoxLayout::Direction direction) { SetIcon("colorwheel.png"); qtLayout = new QBoxLayout(direction); qtLayout->setMargin(0); qtLayout->setSpacing(5); qtLayout->setContentsMargins(0, 0, 0, 0); this->setLayout(qtLayout); styleSheet = ""; } void CustomWidget::Init() { } void CustomWidget::Show() { show(); } void CustomWidget::Hide() { hide(); } void CustomWidget::Toggle() { isVisible() ? hide() : show(); } void CustomWidget::AddWidget(QWidget * widget) { if (widget) qtLayout->addWidget(widget); } void CustomWidget::RemoveWidget(QWidget * widget) { if (widget) { qtLayout->removeWidget(widget); widget->setParent(nullptr); } } void CustomWidget::DetachFromParent() { QWidget *widgetParent = (QWidget*)parent(); if (widgetParent) { widgetParent->layout()->removeWidget(this); this->setParent(nullptr); } } void CustomWidget::SetAsToolWindow() { setWindowFlags(Qt::WindowType::Tool | Qt::WindowType::WindowStaysOnTopHint); } void CustomWidget::SetIcon(const char * fileName) { setWindowIcon(*QtConfig::GetIcon(fileName)); } void CustomWidget::SetStyleID(const char * ID) { setObjectName(ID); } void CustomWidget::ReloadStyleSheet() { if (styleSheet.size()) LoadStyleSheet(styleSheet.c_str()); } void CustomWidget::LoadStyleSheet(const char* file) { styleSheet = file; QtConfig::SetWidgetStyleSheet(this, file); }
openDSME/CometOS
src/communication/dsme/helper/DSMEMessageBuffer.cc
/* * CometOS --- a component-based, extensible, tiny operating system * for wireless networks * * Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology * 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 Institute 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 INSTITUTE 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 INSTITUTE 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 "DSMEMessageBuffer.h" using namespace cometos; namespace dsme { DSMEMessageBuffer::DSMEMessageBuffer() : front(buffer), back(buffer + BUFFERSIZE - 1) { for (uint16_t i = 0; i < BUFFERSIZE; i++) { AirframePtr frame = make_checked<Airframe>(); airframeStack.push(frame); } for (uint16_t i = 0; i < BUFFERSIZE - 1; i++) { buffer[i].next = &(buffer[i + 1]); } buffer[BUFFERSIZE - 1].next = nullptr; } DSMEMessageBuffer::~DSMEMessageBuffer() { while(airframeStack.getSize() != 0) { AirframePtr p = airframeStack.top(); airframeStack.top().reset(); airframeStack.pop(); p.delete_object(); } } DSMEMessage* DSMEMessageBuffer::aquire() { DSMEMessageBufferElement *element = nullptr; if (front == nullptr) { ASSERT(false); return nullptr; } palExec_atomicBegin(); { element = front; front = front->next; element->message.prepare(airframeStack.top()); airframeStack.top().reset(); airframeStack.pop(); } palExec_atomicEnd(); return &(element->message); } DSMEMessage* DSMEMessageBuffer::aquire(cometos::AirframePtr frame) { DSMEMessageBufferElement *element = nullptr; if (front == nullptr) { ASSERT(false); return nullptr; } palExec_atomicBegin(); { element = front; front = front->next; element->message.prepare(frame); } palExec_atomicEnd(); return &(element->message); } void DSMEMessageBuffer::release(DSMEMessage* message) { if (message == nullptr) { return; } ASSERT(!message->frame || message->frame.unique()); palExec_atomicBegin(); { AirframePtr frame = message->decapsulateFrame(); if(!airframeStack.isFull()) { if(!frame) { frame = make_checked<Airframe>(); // = make_checked<Airframe>(); // the Airframe was decapsulated before } else { frame->clear(); frame->removeAll(); } bool result = airframeStack.push(frame); ASSERT(result); } else if(frame) { frame.delete_object(); // the stack is full anyway } } palExec_atomicEnd(); DSMEMessageBufferElement *element = (DSMEMessageBufferElement*) message; palExec_atomicBegin(); { back->next = element; back = element; if (front == nullptr) { front = element; } } palExec_atomicEnd(); return; } }
modem888/thai2transformers
thai2transformers/conf.py
from enum import Enum class Task(Enum): MULTICLASS_CLS = 'multiclass_classification' MULTILABEL_CLS = 'multilabel_classification'
fmhess/libpoet
test/exception_test.cpp
<reponame>fmhess/libpoet<filename>test/exception_test.cpp<gh_stars>1-10 // Copyright (C) <NAME> 2007 // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/assert.hpp> #include <iostream> #include <poet/active_function.hpp> #include <stdexcept> void throw_runtime_error() { std::cerr << __FUNCTION__ << std::endl; throw std::runtime_error("this std::runtime_error exception was transported to a future."); } int throw_logic_error() { std::cerr << __FUNCTION__ << std::endl; throw std::logic_error("this std::logic_error exception was transported to a future."); return 0; } int throw_out_of_range() { std::cerr << __FUNCTION__ << std::endl; throw std::out_of_range("this std::out_of_range exception was transported to a future."); return 0; } class custom_exception: public std::exception { public: custom_exception() {} virtual ~custom_exception() throw() {} virtual const char * what() const throw() {return "custom_exception";} }; void throw_unknown_exception() { std::cerr << __FUNCTION__ << std::endl; throw custom_exception(); } struct unknown { int value; }; void throw_really_unknown() { std::cerr << __FUNCTION__ << std::endl; throw unknown(); } int main() { { poet::active_function<void ()> thrower(&throw_runtime_error); poet::future<void> result = thrower(); try { result.get(); BOOST_ASSERT(false); } catch(const std::runtime_error &err) { std::cerr << "caught exception: " << err.what() << std::endl; } catch(...) { BOOST_ASSERT(false); } } { poet::active_function<int ()> thrower(&throw_logic_error); poet::future<int> result = thrower(); try { int retval = result; BOOST_ASSERT(false); std::cout << "retval is " << retval << std::endl; } catch(const std::logic_error &err) { std::cerr << "caught exception: " << err.what() << std::endl; } catch(...) { BOOST_ASSERT(false); } } { poet::active_function<int ()> thrower(&throw_out_of_range); poet::future<int> result = thrower(); try { int retval = result.get(); BOOST_ASSERT(false); std::cout << "retval is " << retval << std::endl; } catch(const std::out_of_range &err) { std::cerr << "caught exception: " << err.what() << std::endl; } catch(...) { BOOST_ASSERT(false); } } // throw an exception derived from std::exception { poet::active_function<void ()> thrower(&throw_unknown_exception); poet::future<void> result = thrower(); try { result.get(); BOOST_ASSERT(false); } catch(const poet::unknown_exception &err) { std::cerr << "caught exception: " << err.what() << std::endl; } catch(...) { BOOST_ASSERT(false); } } // throw completely unknown exception { poet::active_function<void ()> thrower(&throw_really_unknown); poet::future<void> result = thrower(); try { result.get(); BOOST_ASSERT(false); } catch(const poet::unknown_exception &err) { std::cerr << "caught exception: " << err.what() << std::endl; } catch(...) { BOOST_ASSERT(false); } } return 0; }
chenk-iguazio/ui
src/components/FeatureSetsPanel/FeatureSetsPanelView.js
<filename>src/components/FeatureSetsPanel/FeatureSetsPanelView.js import React from 'react' import PropTypes from 'prop-types' import Accordion from '../../common/Accordion/Accordion' import ErrorMessage from '../../common/ErrorMessage/ErrorMessage' import Button from '../../common/Button/Button' import FeatureSetsPanelTitle from './FeatureSetsPanelTitle/FeatureSetsPanelTitle' import FeatureSetsPanelDataSource from './FeatureSetsPanelDataSource/FeatureSetsPanelDataSource' import FeatureSetsPanelSchema from './FeatureSetsPanelSchema/FeatureSetsPanelSchema' import FeatureSetsPanelTargetStore from './FeatureSetsPanelTargetStore/FeatureSetsPanelTargetStore' import Loader from '../../common/Loader/Loader' import ConfirmDialog from '../../common/ConfirmDialog/ConfirmDialog' import PanelCredentialsAccessKey from '../../elements/PanelCredentialsAccessKey/PanelCredentialsAccessKey' import { PRIMARY_BUTTON, SECONDARY_BUTTON, TERTIARY_BUTTON } from '../../constants' import { ReactComponent as Arrow } from '../../images/arrow.svg' import './featureSetsPanel.scss' const FeatureSetsPanelView = ({ accessKeyRequired, closePanel, confirmDialog, error, featureStore, handleSave, handleSaveOnClick, loading, project, removeFeatureStoreError, setConfirmDialog, setNewFeatureSetCredentialsAccessKey, setValidation, validation }) => { return ( <div className="new-item-side-panel-container"> <div className="feature-set-panel new-item-side-panel"> {loading && <Loader />} {confirmDialog && ( <ConfirmDialog closePopUp={() => setConfirmDialog(null)} confirmButton={{ handler: handleSave, label: 'Okay', variant: PRIMARY_BUTTON }} message="Note that data will be ingested to the feature set without any transformation and therefore you won't be able to add a transformation graph unless you delete the data first." /> )} <FeatureSetsPanelTitle closePanel={closePanel} isNameValid={validation.isNameValid} setNameValid={setValidation} /> <div className="new-item-side-panel__body"> <Accordion accordionClassName="new-item-side-panel__accordion" icon={<Arrow />} iconClassName="new-item-side-panel__expand-icon" openByDefault > <FeatureSetsPanelDataSource project={project} setValidation={setValidation} validation={validation} /> </Accordion> <Accordion accordionClassName="new-item-side-panel__accordion" icon={<Arrow />} iconClassName="new-item-side-panel__expand-icon" openByDefault > <FeatureSetsPanelSchema setValidation={setValidation} validation={validation} /> </Accordion> <Accordion accordionClassName="new-item-side-panel__accordion" icon={<Arrow />} iconClassName="new-item-side-panel__expand-icon" openByDefault > <FeatureSetsPanelTargetStore setValidation={setValidation} validation={validation} /> </Accordion> <PanelCredentialsAccessKey credentialsAccessKey={ featureStore.newFeatureSet.credentials.access_key } required={accessKeyRequired} setCredentialsAccessKey={setNewFeatureSetCredentialsAccessKey} setValidation={setValidation} validation={validation} /> <div className="new-item-side-panel__buttons-container"> {error && ( <ErrorMessage closeError={() => { if (error) { removeFeatureStoreError() } }} message={error} /> )} <Button variant={TERTIARY_BUTTON} label="Cancel" className="pop-up-dialog__btn_cancel" onClick={closePanel} /> <Button variant={SECONDARY_BUTTON} label="Save" onClick={() => handleSaveOnClick(false)} /> <Button className="btn_start-ingestion" label="Save and ingest" onClick={() => handleSaveOnClick(true)} variant={SECONDARY_BUTTON} /> </div> </div> </div> </div> ) } FeatureSetsPanelView.defaultProps = { confirmDialog: null, defaultData: null, error: false } FeatureSetsPanelView.propTypes = { accessKeyRequired: PropTypes.bool.isRequired, closePanel: PropTypes.func.isRequired, confirmDialog: PropTypes.shape({ action: PropTypes.string.isRequired }), error: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]), featureStore: PropTypes.shape({}).isRequired, handleSave: PropTypes.func.isRequired, handleSaveOnClick: PropTypes.func.isRequired, loading: PropTypes.bool.isRequired, project: PropTypes.string.isRequired, removeFeatureStoreError: PropTypes.func.isRequired, setConfirmDialog: PropTypes.func.isRequired, setNewFeatureSetCredentialsAccessKey: PropTypes.func.isRequired, setValidation: PropTypes.func.isRequired, validation: PropTypes.shape({}).isRequired } export default FeatureSetsPanelView
consulo/consulo-github
src/main/java/org/jetbrains/plugins/github/util/GithubAuthData.java
<reponame>consulo/consulo-github<filename>src/main/java/org/jetbrains/plugins/github/util/GithubAuthData.java /* * Copyright 2000-2013 JetBrains s.r.o. * * 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.jetbrains.plugins.github.util; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.plugins.github.api.GithubApiUtil; /** * Container for authentication data: * - host * - login * - login/password pair * or * - OAuth2 access token * * @author <NAME> */ public class GithubAuthData { public enum AuthType { BASIC, TOKEN, ANONYMOUS } @Nonnull private final AuthType myAuthType; @Nonnull private final String myHost; @Nullable private final BasicAuth myBasicAuth; @Nullable private final TokenAuth myTokenAuth; private final boolean myUseProxy; private GithubAuthData(@Nonnull AuthType authType, @Nonnull String host, @Nullable BasicAuth basicAuth, @Nullable TokenAuth tokenAuth, boolean useProxy) { myAuthType = authType; myHost = host; myBasicAuth = basicAuth; myTokenAuth = tokenAuth; myUseProxy = useProxy; } public static GithubAuthData createAnonymous() { return createAnonymous(GithubApiUtil.DEFAULT_GITHUB_HOST); } public static GithubAuthData createAnonymous(@Nonnull String host) { return new GithubAuthData(AuthType.ANONYMOUS, host, null, null, true); } public static GithubAuthData createBasicAuth(@Nonnull String host, @Nonnull String login, @Nonnull String password) { return new GithubAuthData(AuthType.BASIC, host, new BasicAuth(login, password), null, true); } public static GithubAuthData createTokenAuth(@Nonnull String host, @Nonnull String token) { return new GithubAuthData(AuthType.TOKEN, host, null, new TokenAuth(token), true); } public static GithubAuthData createTokenAuth(@Nonnull String host, @Nonnull String token, boolean useProxy) { return new GithubAuthData(AuthType.TOKEN, host, null, new TokenAuth(token), useProxy); } @Nonnull public AuthType getAuthType() { return myAuthType; } @Nonnull public String getHost() { return myHost; } @Nullable public BasicAuth getBasicAuth() { return myBasicAuth; } @Nullable public TokenAuth getTokenAuth() { return myTokenAuth; } public boolean isUseProxy() { return myUseProxy; } public static class BasicAuth { @Nonnull private final String myLogin; @Nonnull private final String myPassword; private BasicAuth(@Nonnull String login, @Nonnull String password) { myLogin = login; myPassword = password; } @Nonnull public String getLogin() { return myLogin; } @Nonnull public String getPassword() { return <PASSWORD>; } } public static class TokenAuth { @Nonnull private final String myToken; private TokenAuth(@Nonnull String token) { myToken = token; } @Nonnull public String getToken() { return myToken; } } }
RomaKoks/druid
extensions-core/google-extensions/src/main/java/org/apache/druid/data/input/google/GoogleCloudStorageInputSource.java
<reponame>RomaKoks/druid /* * 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.data.input.google; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.api.services.storage.model.StorageObject; import org.apache.druid.data.input.InputEntity; import org.apache.druid.data.input.InputFileAttribute; import org.apache.druid.data.input.InputSplit; import org.apache.druid.data.input.SplitHintSpec; import org.apache.druid.data.input.impl.CloudObjectInputSource; import org.apache.druid.data.input.impl.CloudObjectLocation; import org.apache.druid.data.input.impl.SplittableInputSource; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.storage.google.GoogleInputDataConfig; import org.apache.druid.storage.google.GoogleStorage; import org.apache.druid.storage.google.GoogleStorageDruidModule; import org.apache.druid.storage.google.GoogleUtils; import org.apache.druid.utils.Streams; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.math.BigInteger; import java.net.URI; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class GoogleCloudStorageInputSource extends CloudObjectInputSource { private static final Logger LOG = new Logger(GoogleCloudStorageInputSource.class); private final GoogleStorage storage; private final GoogleInputDataConfig inputDataConfig; @JsonCreator public GoogleCloudStorageInputSource( @JacksonInject GoogleStorage storage, @JacksonInject GoogleInputDataConfig inputDataConfig, @JsonProperty("uris") @Nullable List<URI> uris, @JsonProperty("prefixes") @Nullable List<URI> prefixes, @JsonProperty("objects") @Nullable List<CloudObjectLocation> objects ) { super(GoogleStorageDruidModule.SCHEME_GS, uris, prefixes, objects); this.storage = storage; this.inputDataConfig = inputDataConfig; } @Override protected InputEntity createEntity(CloudObjectLocation location) { return new GoogleCloudStorageEntity(storage, location); } @Override protected Stream<InputSplit<List<CloudObjectLocation>>> getPrefixesSplitStream(@Nonnull SplitHintSpec splitHintSpec) { final Iterator<List<StorageObject>> splitIterator = splitHintSpec.split( storageObjectIterable().iterator(), storageObject -> { final BigInteger sizeInBigInteger = storageObject.getSize(); long sizeInLong; if (sizeInBigInteger == null) { sizeInLong = Long.MAX_VALUE; } else { try { sizeInLong = sizeInBigInteger.longValueExact(); } catch (ArithmeticException e) { LOG.warn( e, "The object [%s, %s] has a size [%s] out of the range of the long type. " + "The max long value will be used for its size instead.", storageObject.getBucket(), storageObject.getName(), sizeInBigInteger ); sizeInLong = Long.MAX_VALUE; } } return new InputFileAttribute(sizeInLong); } ); return Streams.sequentialStreamFrom(splitIterator) .map(objects -> objects.stream().map(this::byteSourceFromStorageObject).collect(Collectors.toList())) .map(InputSplit::new); } @Override public SplittableInputSource<List<CloudObjectLocation>> withSplit(InputSplit<List<CloudObjectLocation>> split) { return new GoogleCloudStorageInputSource(storage, inputDataConfig, null, null, split.get()); } private CloudObjectLocation byteSourceFromStorageObject(final StorageObject storageObject) { return GoogleUtils.objectToCloudObjectLocation(storageObject); } private Iterable<StorageObject> storageObjectIterable() { return () -> GoogleUtils.lazyFetchingStorageObjectsIterator( storage, getPrefixes().iterator(), inputDataConfig.getMaxListingLength() ); } @Override public String toString() { return "GoogleCloudStorageInputSource{" + "uris=" + getUris() + ", prefixes=" + getPrefixes() + ", objects=" + getObjects() + '}'; } }
towardsautonomy/towardsautonomy.github.com
tapl/doc/search/enums_1.js
var searchData= [ ['resultcode',['ResultCode',['../namespacetapl.html#a196ce1d5bf399fc26f03797e6a8d03ff',1,'tapl']]] ];
michaelBenin/node-startup
apps/home/home_view.js
'use strict'; var Backbone = require('backbone'); var $ = require('jquery'); var _ = require('lodash'); var stateManager = require('../../browser/js/services/state_manager'); var config = require('../../browser/js/config'); var template = require('./home.hbs'); var Handlebars = require('hbsfy/runtime'); Handlebars.registerPartial('home_sub', require('./home_sub.hbs')); var collectionViewOn = stateManager.collectionViewOn; var collectionViewOff = stateManager.collectionViewOff; var subView = require('./home_sub_view'); var LinksCollection = require('../../browser/js/models/links_collection'); var View = Backbone.View.extend({ bootstrapData: function() { this.setElement($('main.main')); var context = this.$el.find('section').attr('data-context'); if (context) { var model = JSON.parse(this.$el.find('section').attr('data-context')); this.collection = new LinksCollection(model.list); } }, onCollections: function() { var elements = this.$el.find('ul').children('li'); this.subviews = collectionViewOn(subView, elements, this.collection); }, off: function() { collectionViewOff(this.subviews); this.subviews = undefined; this.undelegateEvents(this.adaptive_events[this.currentDevice]); }, on: function() { var base = this.adaptive_events.base; var device = this.adaptive_events[stateManager.getDevice()]; //TODO Conditional delegate events with enquire for phone, tablet, desktop this.currentDevice = stateManager.getDevice(); this.delegateEvents(_.extend({}, base, device)); this.onCollections(); return this; }, currentDevice: null, adaptive_events: { base: { 'click .home': function(e) { } }, mobile: { 'click .home': function(e) { window.alert('mobile events bound home_logged_out view: ' + e.currentTarget); } }, tablet: { 'click .home': function(e) { window.alert('tablet events bound home_logged_out view: ' + e.currentTarget); } }, desktop: { 'click .home': function(e) { this.collection.fetch().then(function(data) { window.alert(data); }).catch(function(error) { window.alert(error); }); } } }, render: function() { this.setElement($('main.main')); var model = { title: 'testing it', content: 'test', list: [{ title: 'test', url: 'http://linkwaylive.com' }, { title: 'test2', url: 'http://test.com' }] }; var context = _.extend({}, config, model); this.collection = new LinksCollection(model.list); this .on() .$el .stop() .hide() .empty() .append(template(context)) .fadeIn(); this.onCollections(); Backbone.history.navigate(''); }, toString: function() { return 'home'; } }); module.exports = new View();
LaudateCorpus1/RosettaCodeData
Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-2.scala
object FindTheLastSundayOfEachMonth extends App { def lastSundaysOf(year: Int) = (1 to 12).map{month => import java.time._; import java.time.temporal.TemporalAdjusters._ LocalDate.of(year, month, 1).`with`(lastDayOfMonth).`with`(previousOrSame(DayOfWeek.SUNDAY))} val year = args.headOption.map(_.toInt).getOrElse(java.time.LocalDate.now.getYear) println(lastSundaysOf(year) mkString "\n") }
Ivan-sh/Orienteer
src/main/java/ru/ydn/orienteer/components/properties/LinksCollectionViewPanel.java
<reponame>Ivan-sh/Orienteer package ru.ydn.orienteer.components.properties; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import ru.ydn.orienteer.CustomAttributes; import ru.ydn.orienteer.components.ODocumentPageLink; import ru.ydn.orienteer.components.commands.CreateODocumentCommand; import ru.ydn.orienteer.components.commands.DeleteODocumentCommand; import ru.ydn.orienteer.components.commands.ReleaseODocumentCommand; import ru.ydn.orienteer.components.commands.SelectODocumentCommand; import ru.ydn.orienteer.components.table.CheckBoxColumn; import ru.ydn.orienteer.components.table.OEntityColumn; import ru.ydn.orienteer.components.table.OrienteerDataTable; import ru.ydn.orienteer.model.DynamicPropertyValueModel; import ru.ydn.orienteer.services.IOClassIntrospector; import ru.ydn.wicket.wicketorientdb.model.OPropertyModel; import ru.ydn.wicket.wicketorientdb.model.OPropertyNamingModel; import ru.ydn.wicket.wicketorientdb.model.OQueryDataProvider; import ru.ydn.wicket.wicketorientdb.utils.ODocumentORIDConverter; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.record.impl.ODocument; public class LinksCollectionViewPanel<T extends OIdentifiable, M extends Collection<T>> extends GenericPanel<M> { private static final long serialVersionUID = 1L; @Inject private IOClassIntrospector oClassIntrospector; public LinksCollectionViewPanel(String id, IModel<ODocument> documentModel, OProperty property) { super(id, new DynamicPropertyValueModel<M>(documentModel, new OPropertyModel(property))); OQueryDataProvider<ODocument> provider = oClassIntrospector.prepareDataProviderForProperty(property, documentModel); List<IColumn<ODocument, String>> columns = new ArrayList<IColumn<ODocument,String>>(); columns.add(new OEntityColumn<ODocument>(property.getLinkedClass())); OrienteerDataTable<ODocument, String> table = new OrienteerDataTable<ODocument, String>("links", columns, provider, 10); table.getHeadersToolbar().setVisibilityAllowed(false); table.getNoRecordsToolbar().setVisibilityAllowed(false); add(table); } }
jacadcaps/webkitty
Source/WebCore/platform/graphics/FloatPoint3D.h
/* Copyright (C) 2004, 2005, 2006 <NAME> <<EMAIL>> 2004, 2005 <NAME> <<EMAIL>> 2005 <NAME> <<EMAIL>> 2010 <NAME> <<EMAIL>> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License aint with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FloatPoint3D_h #define FloatPoint3D_h #include "FloatPoint.h" namespace WebCore { class FloatPoint3D { public: FloatPoint3D() = default; FloatPoint3D(float x, float y, float z) : m_x(x) , m_y(y) , m_z(z) { } FloatPoint3D(const FloatPoint& p) : m_x(p.x()) , m_y(p.y()) { } float x() const { return m_x; } void setX(float x) { m_x = x; } float y() const { return m_y; } void setY(float y) { m_y = y; } FloatPoint xy() const { return { m_x, m_y }; } void setXY(FloatPoint p) { m_x = p.x(); m_y = p.y(); } float z() const { return m_z; } void setZ(float z) { m_z = z; } void set(float x, float y, float z) { m_x = x; m_y = y; m_z = z; } void move(float dx, float dy, float dz = 0) { m_x += dx; m_y += dy; m_z += dz; } void scale(float sx, float sy, float sz) { m_x *= sx; m_y *= sy; m_z *= sz; } bool isZero() const { return !m_x && !m_y && !m_z; } void normalize(); float dot(const FloatPoint3D& a) const { return m_x * a.x() + m_y * a.y() + m_z * a.z(); } // Sets this FloatPoint3D to the cross product of the passed two. // It is safe for "this" to be the same as either or both of the // arguments. void cross(const FloatPoint3D& a, const FloatPoint3D& b) { float x = a.y() * b.z() - a.z() * b.y(); float y = a.z() * b.x() - a.x() * b.z(); float z = a.x() * b.y() - a.y() * b.x(); m_x = x; m_y = y; m_z = z; } // Convenience function returning "this cross point" as a // stack-allocated result. FloatPoint3D cross(const FloatPoint3D& point) const { FloatPoint3D result; result.cross(*this, point); return result; } float lengthSquared() const { return this->dot(*this); } float length() const { return std::hypot(m_x, m_y, m_z); } float distanceTo(const FloatPoint3D& a) const; private: float m_x { 0 }; float m_y { 0 }; float m_z { 0 }; }; inline FloatPoint3D& operator +=(FloatPoint3D& a, const FloatPoint3D& b) { a.move(b.x(), b.y(), b.z()); return a; } inline FloatPoint3D& operator +=(FloatPoint3D& a, const FloatPoint& b) { a.move(b.x(), b.y()); return a; } inline FloatPoint3D& operator -=(FloatPoint3D& a, const FloatPoint3D& b) { a.move(-b.x(), -b.y(), -b.z()); return a; } inline FloatPoint3D& operator -=(FloatPoint3D& a, const FloatPoint& b) { a.move(-b.x(), -b.y()); return a; } inline FloatPoint3D operator+(const FloatPoint3D& a, const FloatPoint3D& b) { return FloatPoint3D(a.x() + b.x(), a.y() + b.y(), a.z() + b.z()); } inline FloatPoint3D operator+(const FloatPoint3D& a, const FloatPoint& b) { return FloatPoint3D(a.x() + b.x(), a.y() + b.y(), a.z()); } inline FloatPoint3D operator-(const FloatPoint3D& a, const FloatPoint3D& b) { return FloatPoint3D(a.x() - b.x(), a.y() - b.y(), a.z() - b.z()); } inline FloatPoint3D operator-(const FloatPoint3D& a, const FloatPoint& b) { return FloatPoint3D(a.x() - b.x(), a.y() - b.y(), a.z()); } inline bool operator==(const FloatPoint3D& a, const FloatPoint3D& b) { return a.x() == b.x() && a.y() == b.y() && a.z() == b.z(); } inline bool operator!=(const FloatPoint3D& a, const FloatPoint3D& b) { return a.x() != b.x() || a.y() != b.y() || a.z() != b.z(); } inline float operator*(const FloatPoint3D& a, const FloatPoint3D& b) { // dot product return a.dot(b); } inline FloatPoint3D operator*(float k, const FloatPoint3D& v) { return FloatPoint3D(k * v.x(), k * v.y(), k * v.z()); } inline FloatPoint3D operator*(const FloatPoint3D& v, float k) { return FloatPoint3D(k * v.x(), k * v.y(), k * v.z()); } inline float FloatPoint3D::distanceTo(const FloatPoint3D& a) const { return (*this - a).length(); } WEBCORE_EXPORT WTF::TextStream& operator<<(WTF::TextStream&, const FloatPoint3D&); } // namespace WebCore #endif // FloatPoint3D_h
zmatez/WNDev1.14.4
src/main/java/com/matez/wildnature/world/gen/structures/nature/woods/pine/thin_pine2.java
<gh_stars>1-10 package com.matez.wildnature.world.gen.structures.nature.woods.pine; import com.matez.wildnature.world.gen.structures.nature.SchemFeature; import net.minecraft.util.math.BlockPos; import java.util.Set; public class thin_pine2 extends SchemFeature { public thin_pine2() { super(); this.terrainIncrease = 1; } @Override public Set<BlockPos> setBlocks() { Block(0, 17, -3, "wildnature:pine_leaves[distance=7,persistent=true,stage=1]"); Block(0, 12, -2, "wildnature:pine_leaves[distance=7,persistent=true,stage=4]"); Block(-1, 16, -2, "wildnature:pine_leaves[distance=7,persistent=true,stage=1]"); Block(0, 16, -2, "wildnature:spruce_branch[down=false,east=true,north=false,south=true,up=true,waterlogged=false,west=true]"); Block(1, 16, -2, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(0, 17, -2, "wildnature:spruce_branch[down=true,east=false,north=true,south=false,up=true,waterlogged=false,west=false]"); Block(0, 18, -2, "wildnature:pine_leaves[distance=7,persistent=true,stage=1]"); Block(0, 7, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=3]"); Block(-1, 11, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=3]"); Block(0, 11, -1, "wildnature:spruce_branch[down=false,east=true,north=false,south=true,up=true,waterlogged=false,west=true]"); Block(1, 11, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=3]"); Block(0, 12, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=1]"); Block(-2, 15, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(-1, 16, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=2]"); Block(0, 16, -1, "wildnature:spruce_branch[down=false,east=false,north=true,south=true,up=false,waterlogged=false,west=true]"); Block(1, 17, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=2]"); Block(0, 18, -1, "wildnature:pine_leaves[distance=7,persistent=true,stage=4]"); Block(0, 1, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(0, 2, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(0, 3, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(0, 4, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(0, 5, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(0, 6, 0, "wildnature:spruce_branch[down=true,east=true,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(1, 6, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(0, 7, 0, "wildnature:spruce_branch[down=true,east=false,north=true,south=false,up=true,waterlogged=false,west=false]"); Block(0, 8, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(-1, 9, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(0, 9, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=true,up=true,waterlogged=false,west=true]"); Block(0, 10, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(0, 11, 0, "wildnature:spruce_branch[down=true,east=false,north=true,south=false,up=true,waterlogged=false,west=false]"); Block(-1, 12, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=4]"); Block(0, 12, 0, "wildnature:spruce_branch[down=true,east=false,north=true,south=true,up=true,waterlogged=false,west=true]"); Block(0, 13, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=true,up=true,waterlogged=false,west=false]"); Block(0, 14, 0, "wildnature:spruce_branch[down=true,east=true,north=false,south=false,up=true,waterlogged=false,west=false]"); Block(1, 14, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=4]"); Block(-2, 15, 0, "wildnature:spruce_branch[down=false,east=true,north=true,south=false,up=true,waterlogged=false,west=false]"); Block(-1, 15, 0, "wildnature:spruce_branch[down=false,east=true,north=false,south=true,up=false,waterlogged=false,west=true]"); Block(0, 15, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=true]"); Block(-3, 16, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(-2, 16, 0, "wildnature:spruce_branch[down=true,east=false,north=false,south=false,up=true,waterlogged=false,west=true]"); Block(0, 16, 0, "wildnature:spruce_branch[down=true,east=true,north=true,south=false,up=true,waterlogged=false,west=false]"); Block(1, 16, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=5]"); Block(-2, 17, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(-1, 17, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=5]"); Block(0, 17, 0, "wildnature:spruce_branch[down=true,east=true,north=false,south=true,up=true,waterlogged=false,west=true]"); Block(1, 17, 0, "wildnature:spruce_branch[down=true,east=false,north=true,south=true,up=false,waterlogged=false,west=true]"); Block(0, 18, 0, "wildnature:spruce_branch[down=true,east=false,north=true,south=true,up=true,waterlogged=false,west=false]"); Block(0, 19, 0, "wildnature:pine_leaves[distance=7,persistent=true,stage=4]"); Block(0, 9, 1, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(0, 12, 1, "wildnature:spruce_branch[down=false,east=true,north=true,south=true,up=true,waterlogged=false,west=false]"); Block(1, 12, 1, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(0, 13, 1, "wildnature:pine_leaves[distance=7,persistent=true,stage=4]"); Block(-1, 15, 1, "wildnature:pine_leaves[distance=7,persistent=true,stage=5]"); Block(0, 17, 1, "wildnature:spruce_branch[down=false,east=true,north=true,south=false,up=true,waterlogged=false,west=false]"); Block(1, 17, 1, "wildnature:pine_leaves[distance=7,persistent=true,stage=6]"); Block(0, 18, 1, "wildnature:pine_leaves[distance=7,persistent=true,stage=4]"); Block(0, 12, 2, "wildnature:pine_leaves[distance=7,persistent=true,stage=3]"); // wildnature mod // created by matez // all rights reserved // http://bit.ly/wildnature-mod return super.setBlocks(); } }
realDaiwei/thinking-in-code
thinking-in-netty/src/main/java/daiwei/atguigu/rpc/RpcClientTestMain.java
<reponame>realDaiwei/thinking-in-code package daiwei.atguigu.rpc; import daiwei.atguigu.rpc.client.RpcNettyClient; import daiwei.atguigu.rpc.common.HelloService; import daiwei.atguigu.rpc.common.HelloServiceImpl; /** * Created by Daiwei on 2021/2/27 */ public class RpcClientTestMain { private static final String PROVIDER_NAME = "HelloService#hello#"; public static void main(String... args) { RpcNettyClient nettyClient = new RpcNettyClient("127.0.0.1", 8808); HelloService bean = (HelloService) nettyClient.getBean(HelloService.class, PROVIDER_NAME); String res = bean.hello("daiwei"); System.out.println(res); } }
ducis/operating-system-labs
sr/lsri/lib/libsys/read_tsc_64.c
#include "sysutil.h" #include <minix/u64.h> #include <minix/syslib.h> /* Utility function to work directly with u64_t * By <NAME> */ PUBLIC void read_tsc_64(t) u64_t* t; { u32_t lo, hi; read_tsc (&hi, &lo); *t = make64 (lo, hi); }
fgrid/iso20022
ResponseType1Choice.go
<filename>ResponseType1Choice.go<gh_stars>10-100 package iso20022 // Choice between a response type code and a proprietary code. type ResponseType1Choice struct { // Provides a margin call response type using an ISO 20022 code. Code *MarginCallResponse1Code `xml:"Cd"` // Provides a margin call response type using a proprietary code. Proprietary *GenericIdentification30 `xml:"Prtry"` } func (r *ResponseType1Choice) SetCode(value string) { r.Code = (*MarginCallResponse1Code)(&value) } func (r *ResponseType1Choice) AddProprietary() *GenericIdentification30 { r.Proprietary = new(GenericIdentification30) return r.Proprietary }
huaweicloud/huaweicloud-sdk-java-v3
services/classroom/src/main/java/com/huaweicloud/sdk/classroom/v3/model/JudgementCaseResult.java
package com.huaweicloud.sdk.classroom.v3.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** 用例运行结果信息 */ public class JudgementCaseResult { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "output") private String output; /** 用例运行结果状态: judgeout判题类型对应:pass(用例比对成功)、failed(用例比对失败); * caseout判题类型对应:success(用例运行成功)、error(用例运行失败);run_timeout(用例运行超时) */ public static final class CaseStatusEnum { /** Enum PASS for value: "pass" */ public static final CaseStatusEnum PASS = new CaseStatusEnum("pass"); /** Enum FAILED for value: "failed" */ public static final CaseStatusEnum FAILED = new CaseStatusEnum("failed"); /** Enum SUCCESS for value: "success" */ public static final CaseStatusEnum SUCCESS = new CaseStatusEnum("success"); /** Enum ERROR for value: "error" */ public static final CaseStatusEnum ERROR = new CaseStatusEnum("error"); /** Enum RUN_TIMEOUT for value: "run_timeout" */ public static final CaseStatusEnum RUN_TIMEOUT = new CaseStatusEnum("run_timeout"); private static final Map<String, CaseStatusEnum> STATIC_FIELDS = createStaticFields(); private static Map<String, CaseStatusEnum> createStaticFields() { Map<String, CaseStatusEnum> map = new HashMap<>(); map.put("pass", PASS); map.put("failed", FAILED); map.put("success", SUCCESS); map.put("error", ERROR); map.put("run_timeout", RUN_TIMEOUT); return Collections.unmodifiableMap(map); } private String value; CaseStatusEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static CaseStatusEnum fromValue(String value) { if (value == null) { return null; } CaseStatusEnum result = STATIC_FIELDS.get(value); if (result == null) { result = new CaseStatusEnum(value); } return result; } public static CaseStatusEnum valueOf(String value) { if (value == null) { return null; } CaseStatusEnum result = STATIC_FIELDS.get(value); if (result != null) { return result; } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } @Override public boolean equals(Object obj) { if (obj instanceof CaseStatusEnum) { return this.value.equals(((CaseStatusEnum) obj).value); } return false; } @Override public int hashCode() { return this.value.hashCode(); } } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "case_status") private CaseStatusEnum caseStatus; public JudgementCaseResult withOutput(String output) { this.output = output; return this; } /** 用例实际运行结果输出 * * @return output */ public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } public JudgementCaseResult withCaseStatus(CaseStatusEnum caseStatus) { this.caseStatus = caseStatus; return this; } /** 用例运行结果状态: judgeout判题类型对应:pass(用例比对成功)、failed(用例比对失败); * caseout判题类型对应:success(用例运行成功)、error(用例运行失败);run_timeout(用例运行超时) * * @return caseStatus */ public CaseStatusEnum getCaseStatus() { return caseStatus; } public void setCaseStatus(CaseStatusEnum caseStatus) { this.caseStatus = caseStatus; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JudgementCaseResult judgementCaseResult = (JudgementCaseResult) o; return Objects.equals(this.output, judgementCaseResult.output) && Objects.equals(this.caseStatus, judgementCaseResult.caseStatus); } @Override public int hashCode() { return Objects.hash(output, caseStatus); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class JudgementCaseResult {\n"); sb.append(" output: ").append(toIndentedString(output)).append("\n"); sb.append(" caseStatus: ").append(toIndentedString(caseStatus)).append("\n"); sb.append("}"); return sb.toString(); } /** Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
AsyncMC/Mojang-API-Libs
generated-sources/objc/mojang-sessions/OpenAPIClient/Api/OAIBansApi.h
#import <Foundation/Foundation.h> #import "OAIApi.h" /** * Mojang Session API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2020-06-05 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ @interface OAIBansApi: NSObject <OAIApi> extern NSString* kOAIBansApiErrorDomain; extern NSInteger kOAIBansApiMissingParamErrorCode; -(instancetype) initWithApiClient:(OAIApiClient *)apiClient NS_DESIGNATED_INITIALIZER; /// A list of SHA1 hashes of banned servers /// Returns a list of SHA1 hashes used to check server addresses against when the client tries to connect. Clients check the lowercase name, using the ISO-8859-1 charset, against this list. They will also attempt to check subdomains, replacing each level with a *. Specifically, it splits based off of the . in the domain, goes through each section removing one at a time. For instance, for mc.example.com, it would try mc.example.com, *.example.com, and *.com. With IP addresses (verified by having 4 split sections, with each section being a valid integer between 0 and 255, inclusive) substitution starts from the end, so for 192.168.0.1, it would try 192.168.0.1, 192.168.0.*, 192.168.*, and 192.*. This check is done by the bootstrap class in netty. The default netty class is overridden by one in the com.mojang:netty dependency loaded by the launcher. This allows it to affect any version that used netty (1.7+) /// /// /// code:200 message:"A list of SHA1 hashes, one hash per line" /// /// @return NSString* -(NSURLSessionTask*) getBlockedServerHashesWithCompletionHandler: (void (^)(NSString* output, NSError* error)) handler; @end
ElsevierSoftwareX/SOFTX-D-22-00045
src/backend/restful/institution/node/get-all.go
<reponame>ElsevierSoftwareX/SOFTX-D-22-00045<filename>src/backend/restful/institution/node/get-all.go package node import ( "net/http" "backend/env" "github.com/gin-gonic/gin" ) //GetAll is used to list all nodes. It is exported as RESTful endpoint via URL /restful/node/get-all. func GetAll(c *gin.Context) { var id []Nodes var err error err = env.Db().Find(&id).Error if err != nil { c.String(http.StatusInternalServerError, "node/get-all: Error while querying database.") return } c.JSON(http.StatusOK, id) }
LKG/lore
lore-core/src/main/java/im/heart/core/utils/DateUtilsEx.java
package im.heart.core.utils; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; /** * * @author gg * @desc扩展日期工具类 */ public class DateUtilsEx extends DateUtils { protected static final Logger logger = LoggerFactory.getLogger(DateUtilsEx.class); public final static String DATE_PATTERN = "yyyy-MM-dd"; public final static String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; /** * * 判断是否为yyyy-MM-dd 日期格式 兼容 yyyy-MM-dd HH:mm:ss * @param str * @return */ public static boolean isValidDate(String str) { return isValidDate(str,DATE_PATTERN); } /** * * 判断是否为指定日期格式 * @param str * @param dateFormat * @return */ public static boolean isValidDate(String str,String dateFormat) { try { SimpleDateFormat format = new SimpleDateFormat(dateFormat); format.parse(str); return true; } catch (ParseException e) { logger.debug(e.getStackTrace()[0].getMethodName(), e); } return false; } /** * * 判断是否为yyyy-MM-dd HH:mm:ss 日期格式 * @param str * @return */ public static boolean isValidDatetime(String str) { return isValidDate(str,TIME_PATTERN); } /** * * 转换日期为XMLGregorianCalendar 格式 * @param date * @return */ public static XMLGregorianCalendar convertXMLGregorianCalendar(Date date) { if (date == null) { return null; } try { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); XMLGregorianCalendar gregorianCalendar = datatypeFactory.newXMLGregorianCalendar(cal); return gregorianCalendar; } catch (DatatypeConfigurationException e) { logger.error(e.getStackTrace()[0].getMethodName(), e); } return null; } /** * * 转换日期为字符串格式 * @param aDate * @param format * @return */ public static final String dateToString(Date aDate, String format) { String returnValue = ""; if (aDate != null) { SimpleDateFormat df = new SimpleDateFormat(format); returnValue = df.format(aDate); } return returnValue; } /** * * 转换日期为字符串格式 格式为yyyy-MM-dd * @param aDate * @return */ public static final String dateToString(Date aDate) { return dateToString(aDate, DATE_PATTERN); } /** * * 转换日期为字符串格式 格式为yyyy-MM-dd HH:mm:ss * @param aDate * @return */ public static final String timeToString(Date aDate) { return dateToString(aDate, TIME_PATTERN); } /** * * 字符串转换为日期类型 * @param strDate * @param format * @return * @throws ParseException */ public static final Date stringToDate(String strDate, String format) throws ParseException { Date date = null; try { SimpleDateFormat df = new SimpleDateFormat(format); date = df.parse(strDate); } catch (ParseException e) { logger.error(e.getStackTrace()[0].getMethodName(), e); throw new ParseException(e.getMessage(), e.getErrorOffset()); } return date; } /** * * 字符串转换为日期类型 默认格式为 yyyy-MM-dd * @param strDate * @return * @throws ParseException */ public static Date stringToDate(String strDate) throws ParseException { return stringToDate(strDate, DATE_PATTERN); } public static Date stringToDateTime(String strDate) throws ParseException { return stringToDate(strDate, TIME_PATTERN); } }
emmamcbryde/AuTuMN-1
autumn/core/runs/managed.py
from pathlib import Path from .remote import RemoteRunData from .utils import website_addr_for_run from .powerbi import ManagedPowerBI from .full import ManagedFullRun from .calibration.managed import ManagedCalibrationRun from autumn.core import db from autumn.core.utils.display import get_link class ManagedRun: def __init__(self, run_id, s3_client=None): self.run_id = run_id self.remote = RemoteRunData(run_id, s3_client) self.local_path = self.remote.local_path_run self.calibration = ManagedCalibrationRun(self) self.powerbi = ManagedPowerBI(self) self.full_run = ManagedFullRun(self) web_addr = website_addr_for_run(self.run_id) self.website_link = get_link(web_addr) def list_local(self, glob_str='*'): return list(self.local_path.rglob(glob_str)) def __repr__(self): return f"ManagedRun: {self.run_id}"
NeilRen/NeilRen4J
src/main/java/com/neilren/neilren4j/security/XssAndSqlHttpServletRequestWrapper.java
package com.neilren.neilren4j.security; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.util.regex.Pattern; /** * @author NeilRen * @version 1.0 * @ClassName XssAndSqlHttpServletRequestWrapper * @Description TODO * @Date 2018/8/7 21:24 */ public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper { HttpServletRequest orgRequest = null; public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) { super(request); orgRequest = request; } /** * 覆盖getParameter方法,将参数名和参数值都做xss & sql过滤。<br/> * 如果需要获得原始的值,则通过super.getParameterValues(name)来获取<br/> * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖 */ @Override public String getParameter(String name) { String value = super.getParameter(xssEncode(name)); if (value != null) { value = xssEncode(value); } return value; } /** * 覆盖getHeader方法,将参数名和参数值都做xss & sql过滤。<br/> * 如果需要获得原始的值,则通过super.getHeaders(name)来获取<br/> * getHeaderNames 也可能需要覆盖 */ @Override public String getHeader(String name) { String value = super.getHeader(xssEncode(name)); if (value != null) { value = xssEncode(value); } return value; } /** * 将容易引起xss & sql漏洞的半角字符直接替换成全角字符 * * @param s * @return */ private static String xssEncode(String s) { if (s == null || s.isEmpty()) { return s; } else { s = stripXSSAndSql(s); } StringBuilder sb = new StringBuilder(s.length() + 16); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '>': sb.append(">");// 转义大于号 break; case '<': sb.append("<");// 转义小于号 break; case '\'': sb.append("'");// 转义单引号 break; case '\"': sb.append(""");// 转义双引号 break; case '&': sb.append("&");// 转义& break; case '#': sb.append("#");// 转义# break; default: sb.append(c); break; } } return sb.toString(); } /** * 获取最原始的request * * @return */ public HttpServletRequest getOrgRequest() { return orgRequest; } /** * 获取最原始的request的静态方法 * * @return */ public static HttpServletRequest getOrgRequest(HttpServletRequest req) { if (req instanceof XssAndSqlHttpServletRequestWrapper) { return ((XssAndSqlHttpServletRequestWrapper) req).getOrgRequest(); } return req; } /** * 防止xss跨脚本攻击(替换,根据实际情况调整) */ public static String stripXSSAndSql(String value) { if (value != null) { // NOTE: It's highly recommended to use the ESAPI library and // uncomment the following line to // avoid encoded attacks. // value = ESAPI.encoder().canonicalize(value); // Avoid null characters /** value = value.replaceAll("", "");***/ // Avoid anything between script tags Pattern scriptPattern = Pattern.compile("<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything in a src="http://www.yihaomen.com/article/java/..." type of e-xpression scriptPattern = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome </script> tag scriptPattern = Pattern.compile("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome <script ...> tag scriptPattern = Pattern.compile("<[\r\n| | ]*script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid eval(...) expressions scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid e-xpression(...) expressions scriptPattern = Pattern.compile("e-xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid javascript:... expressions scriptPattern = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid vbscript:... expressions scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid onload= expressions scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); } return value; } }
catherinedevlin/just-enough-python
040-a-loop.py
batters = ['Alma', 'Connie', 'Sylvia'] for at_bat in batters: print(at_bat + ' at bat')
thangtyt/orama
core/custom_filters/pagination.js
"use strict"; /** Create pagination */ module.exports = function (env) { env.addFilter('pagination', function (totalPage, current_page, link) { link = link.replace(/\"(.*)\"\.\"(.*)\"/, '$1.$2'); if (totalPage > 1) { let start = parseInt(current_page) - 4; if (start < 1) { start = 1; } let end = parseInt(current_page) + 4; if (end > totalPage) { end = totalPage; } let html = '<div class="col-md-12">' + '<div class="dataTables_paginate paging_simple_numbers" id="sample_2_paginate">' + '<ul class="pagination pull-left">' + '<li class="paginate_button previous ' + (parseInt(current_page) == 1 ? "disabled" : "") + '" aria-controls="sample_2" tabindex="0" id="sample_2_previous">' + '<a class="page-link" href="' + (parseInt(current_page) == 1 ? "#" : link.replace('{page}', parseInt(current_page) - 1)) + '"><i class="fa fa-angle-left"></i></a></li>'; if (start > 1) { let url = link.replace('{page}', start - 1); html += '<li class="paginate_button" aria-controls="sample_2" tabindex="0"><a class="page-link" href="' + url + '">...</a></li>' } for (let i = start; i <= end; i++) { let url = link.replace('{page}', i); let active = parseInt(current_page) == i ? "active" : ""; html += '<li class="paginate_button ' + active + '" aria-controls="sample_2" tabindex="0"><a class="page-link" href="' + url + '">' + i + '</a></li>' } if (end < totalPage) { let url = link.replace('{page}', end + 1); html += '<li class="paginate_button" aria-controls="sample_2" tabindex="0"><a class="page-link" href="' + url + '">...</a></li>' } html += '<li class="paginate_button next ' + (current_page == totalPage ? 'disabled' : '') + '" aria-controls="sample_2" tabindex="0" id="sample_2_next"><a class="page-link" href="' + (parseInt(current_page) == totalPage ? "#" : link.replace('{page}', parseInt(current_page) + 1)) + '"><i class="fa fa-angle-right"></i></a></li>' + '</ul></div></div>'; return html; } else { return ''; } }); };
welovekpop/wlk.yt-client
lib/components/Username/WithCard.js
<reponame>welovekpop/wlk.yt-client "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _jsx2 = _interopRequireDefault(require("@babel/runtime/helpers/builtin/jsx")); var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _compose = _interopRequireDefault(require("recompose/compose")); var _withProps = _interopRequireDefault(require("recompose/withProps")); var _userCardable = _interopRequireDefault(require("../../utils/userCardable")); var _ = _interopRequireDefault(require("./")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var enhance = (0, _compose.default)((0, _userCardable.default)(), (0, _withProps.default)(function (props) { return { onUsernameClick: function onUsernameClick(event) { event.preventDefault(); props.openUserCard(props.user); } }; })); var UsernameWithCard = function UsernameWithCard(_ref) { var user = _ref.user, onUsernameClick = _ref.onUsernameClick; return (0, _jsx2.default)("button", { onClick: onUsernameClick }, void 0, (0, _jsx2.default)(_.default, { user: user })); }; UsernameWithCard.propTypes = process.env.NODE_ENV !== "production" ? { user: _propTypes.default.object.isRequired, onUsernameClick: _propTypes.default.func.isRequired } : {}; var _default = enhance(UsernameWithCard); exports.default = _default; //# sourceMappingURL=WithCard.js.map
EquityZen/SynapseFI-Python
synapse_pay_rest/tests/__init__.py
<reponame>EquityZen/SynapseFI-Python from .errors_tests import * from .http_client_tests import * from .client_tests import * from .api import * from .models import *
JoeFu/filemaker18helper
FMP_Help/pairs/pair64.js
<reponame>JoeFu/filemaker18helper var pairs = { "mod":{"\u8FD4":1,"(":1,"\u51FD":1} ,"\u8FD4":{"\u56DE":1} ,"\u56DE":{"\u67D0":1,"\u5269":1,"\u201C":1} ,"\u67D0":{"\u6570":1} ,"\u6570":{"\u5B57":1,"\u540E":1,"\u3002":1,")":1,"\u503C":1,"-\u6570":1,"\u8FD4":1,"\u4E3A":1,"\u8F6C":1,"\u4EE5":1,"\u201D":1,"\u002F12":1,",":1,";":1,"\u0022":1} ,"\u5B57":{"\u9664":1,";":1,"\u6BB5":1,"filemaker":1} ,"\u9664":{"\u4EE5":1,"\u6570":1} ,"\u4EE5":{"\u9664":1,"4":1,"\u53CA":1} ,"\u540E":{"\u6240":1} ,"\u6240":{"\u5F97":1} ,"\u5F97":{"\u7684":1} ,"\u7684":{"\u4F59":1,"\u5B57":1,"\u4E2A":1,"\u5C0F":1,"\u6708":1} ,"\u4F59":{"\u6570":1,"\u5355":1,"\u7684":1} ,"\u3002":{"mod":1,"\u8BA1":1,"\u8F6C":1,"\u5F53":1,"\u5C06":1} ,"(":{"\u6570":1,"210":1,"24":1,"\u6708":1} ,";":{"\u9664":1,"4":1,"12":1} ,")":{"\u6570":1,"\u8FD4":1,"&\u0022":1} ,"\u503C":{"-\u4EFB":1,"\u8868":1} ,"-\u4EFB":{"\u610F":1} ,"\u610F":{"\u6570":1} ,"\u8868":{"\u8FBE":1,"\u793A":1} ,"\u8FBE":{"\u5F0F":1} ,"\u5F0F":{"\u6216":1,"\u7684":1} ,"\u6216":{"\u5305":1,"\u66F4":1} ,"\u5305":{"\u542B":1} ,"\u542B":{"\u6570":1,"16":1,"31":1} ,"\u6BB5":{"\u9664":1,"\u6570":1,"\u4E2D":1} ,"-\u6570":{"\u503C":1} ,"filemaker":{"\u00A0":1} ,"\u00A0":{"pro":1} ,"pro":{"6.0":1} ,"6.0":{"\u6216":1} ,"\u66F4":{"\u4F4E":1} ,"\u4F4E":{"\u7248":1} ,"\u7248":{"\u672C":1} ,"\u672C":{"\u5728":1} ,"\u5728":{"\u8F6C":1} ,"\u8F6C":{"\u6362":1} ,"\u6362":{"\u5EA6":1,"\u65F6":1,"\u4E3A":1} ,"\u5EA6":{"\u91CF":1} ,"\u91CF":{"\u5355":1} ,"\u5355":{"\u4F4D":1} ,"\u4F4D":{"\uFF08":1,"\u7684":1} ,"\uFF08":{"\u5982":1} ,"\u5982":{"\u4ECE":1} ,"\u4ECE":{"\u5206":1,"24":1} ,"\u5206":{"\u949F":1,"\uFF0C":1} ,"\u949F":{"\u5230":1} ,"\u5230":{"\u5C0F":1,"12":1} ,"\u5C0F":{"\u65F6":1} ,"\u65F6":{"\uFF09":1,"\uFF0C":1,"\u95F4":1,"\u90E8":1,"\u8868":1,"\u65F6":1,"\uFF1A":1} ,"\uFF09":{"\u65F6":1} ,"\uFF0C":{"\u4F7F":1,"\u4F59":1,"\u4ECE":1,"7":1} ,"\u4F7F":{"\u7528":1} ,"\u7528":{"mod":1} ,"\u51FD":{"\u6570":1} ,"\u5269":{"\u4F59":1} ,"\u4E2A":{"\u6570":1,"\u6708":1} ,"\u8BA1":{"\u7B97":1} ,"\u7B97":{"210":1} ,"210":{"\u9664":1,";":1} ,"4":{"\uFF0C":1,")":1,"\u201D":1} ,"\u4E3A":{"2":1,"\u5E74":1} ,"2":{"\u3002":1,"\u201D":1,"\u5E74":1} ,"\u201C":{"2":1,"24":1,"4":1,"\u6708":1} ,"\u201D":{"\u3002":1,"\u5B57":1} ,"\u95F4":{"\u7684":1,"\u201D":1,";12":1} ,"\u90E8":{"\u5206":1} ,"24":{"\u5C0F":1} ,"\u793A":{"\u6CD5":1} ,"\u6CD5":{"\u5230":1,"\u3002":1} ,"12":{"\u5C0F":1,")":1} ,"\u5F53":{"\u201C":1} ,"\u4E2D":{"\u5305":1} ,"16":{"\u65F6":1} ,"\uFF1A":{"mod":1,"int":1} ,";12":{")":1} ,"\u5C06":{"\u6708":1} ,"\u6708":{"\u4EFD":1,"\u201D":1} ,"\u4EFD":{"\u6570":1} ,"\u5E74":{"\u6570":1,"\uFF0C":1} ,"\u53CA":{"\u5269":1} ,"31":{"\u65F6":1} ,"int":{"(":1} ,"\u002F12":{")":1} ,"&\u0022":{"\u5E74":1,"\u6708":1} ,",":{"\u0022":1} ,"\u0022":{"&mod":1,"\u8FD4":1} ,"&mod":{"(":1} ,"7":{"\u4E2A":1} } ;Search.control.loadWordPairs(pairs);
DeskproApps/salesforce
src/salesforce/apiObjects.js
<gh_stars>0 class ApiObject { /** * @param {String | Object} raw * @return {*} */ static parse(raw) { return typeof raw === 'string' ? JSON.parse(raw) : JSON.parse(JSON.stringify(raw)); } /** * @param {...*} props */ constructor({ ...props }) { this.props = { ...props }; } toJSON = () => { return JSON.parse(JSON.stringify(this.props)); }; /** * Returns a deep clone of this object * * @method * @return {Object} */ toJS = () => this.toJSON(); } /** * @param {SFObjectField} left * @param {SFObjectField} right */ export const equalFields = (left, right) => left.name === right.name; export function indexOf(item, list, equals) { let index = -1; for (const listItem of list) { if (equals(item, listItem)) { return index + 1 } } return index; } /** * @param {Array} left * @param {Array} right * @param {Function} equals * @return {Array} */ export function diff(left, right, equals) { const diff = []; for (const leftItem of left) { for (const rightItem of right) { if (!equals(leftItem, rightItem)) { diff.push(leftItem); break; } } } return diff; } export class ChildRelationship extends ApiObject { /** * @param {String | Object} js * @returns {ChildRelationship} */ static instance(js) { const data = ApiObject.parse(js); return new ChildRelationship(data) } /** * @type {string} */ get field() { return this.props.field; } /** * @type {string} */ get childSObject() { return this.props.childSObject; } } export class SFObject extends ApiObject { /** * @param {String | Object} js * @returns {SFObject} */ static instance(js) { const data = ApiObject.parse(js); return new SFObject(data) } /** * @param {String} name * @param {String} label * @param {...*} props */ constructor({ name, label, ...props }) { super({ name, label, ...props }); } /** * @type {string} */ get label() { return this.props.label; } /** * @type {string} */ get name() { return this.props.name; } } export class SFObjectField extends ApiObject { static TYPE_REF = 'reference'; static TYPE_STRING = 'string'; static TYPE_ID = 'id'; static TYPE_ADDRESS = 'address'; static TYPE_BOOL = 'boolean'; static TYPE_CURRENCY = 'currency'; static TYPE_DOUBLE = 'double'; static TYPE_INT = 'int'; static TYPE_PHONE = 'phone'; static TYPE_PICKLIST = 'picklist'; static TYPE_URL = 'url'; /** * @param {String|Object} js * @returns {SFObjectField} */ static instance(js) { const data = ApiObject.parse(js); return new SFObjectField(data) } /** * @param {string} name * @param {string} type * @param {string} label * @param {...*} props */ constructor({name, type, label,...props}) { super({name, type, label, ...props}); } /** * @type {string} */ get label() { return this.props.label; } /** * @type {string} */ get name() { return this.props.name; } /** * @type {string} */ get type() { return this.props.type; } /** * @type {bool} */ get nameField() { return this.props.nameField; } } export class SFObjectRelation extends ApiObject { static TYPE_FOREIGN_FIELD = 'field'; /** * @param {String|Object} js * @returns {SFObjectRelation} */ static instance(js) { const data = ApiObject.parse(js); return new SFObjectRelation(data); } /** * @type {string} */ get foreignField() { return this.props.field; } } export class SFObjectDescription extends ApiObject { get fields() { return this.props.fields; } get relations() { return this.props.relations; } } export class RelatedObject extends ApiObject { /** * @param {String | Object} js * @returns {RelatedObject} */ static instance(js) { const data = ApiObject.parse(js); return new RelatedObject(data) } /** * @param {array} fields * @param {...*} props */ constructor({fields, ...props}) { super(props); this.props.fields = fields || []; } addField(field) { let objectIndex = indexOf(field, this.props.fields, equalFields); if (objectIndex === -1) { this.props.fields.push(field); } } get fields() { return this.props.fields; } set fields(fields) { this.props.fields = fields; return this; } get name() { return this.props.childSObject; } get foreignField() { return this.props.field; } } class ProjectionAttributes extends ApiObject { /** * @param {String | Object} js * @returns {ProjectionAttributes} */ static instance(js) { const data = ApiObject.parse(js); return new ProjectionAttributes(data) } /** * @param {string} type * @param {string} url * @param [rest] */ constructor({ type, url, ...rest }) { super({ type, url, ...rest }); } /** * @type {string} */ get type() { return this.props.type; } /** * @type {string} */ get url() { return this.props.url; } } export class Projection extends ApiObject { /** * @param {String | Object} js * @returns {Projection} */ static instance(js) { const { attributes, ...fields } = ApiObject.parse(js); return new Projection({ attributes: ProjectionAttributes.instance(attributes), ...fields }) } /** * * @param {{type: string, url: string}} attributes * @param [rest] */ constructor({ attributes, ...rest }) { super({ attributes, fields: rest }); } toJSON = () => { const { attributes, fields } = this.props; return JSON.parse(JSON.stringify({ attributes, ...fields })); }; /** * @type {ProjectionAttributes} */ get attributes() { return this.props.attributes; } /** * @type {{}} */ get fields() { return this.props.fields; } } export class UserInfo extends ApiObject { /** * @param {String | Object} js * @returns {UserInfo} */ static instance(js) { const data = ApiObject.parse(js); return new UserInfo(data); } /** * @param {String} name * @param {String} nickname * @param {String} email * @param [rest] */ constructor({ name, nickname, email, ...rest }) { super({ name, nickname, email, ...rest }); } /** * @type {string} */ get name() { return this.props.name; } /** * @type {string} */ get nickname() { return this.props.nickname; } get email() { return this.props.email; } objectUrl = (id) => { return this.props.profile.replace(/\/[^/]+$/, `/${id}`); } } export class ApiVersion extends ApiObject { /** * @param {String | Object} js * @returns {ApiVersion} */ static instance(js) { const data = ApiObject.parse(js); return new ApiVersion(data); } /** * @param {String} name * @param {String} label * @param {String} url * @param [rest] */ constructor({ version, label, url, ...rest }) { super({ version, label, url, ...rest }); } /** * @type {string} */ get version() { return this.props.version; } /** * @type {string} */ get label() { return this.props.label; } /** * @return {*} */ get url() { return this.props.url; } }